{"version":3,"file":"index-CVFwJUd2.cjs","sources":["../node_modules/clsx/dist/clsx.mjs","../node_modules/class-variance-authority/dist/index.mjs","../src/components/Button/Button.tsx","../node_modules/tailwind-merge/dist/bundle-mjs.mjs","../src/components/ButtonGroup/ButtonGroup.tsx","../src/lib/utils.ts","../src/components/Input/Input.tsx","../src/components/Textarea/Textarea.tsx","../src/components/Checkbox/Checkbox.tsx","../node_modules/@radix-ui/primitive/dist/index.mjs","../node_modules/@radix-ui/react-compose-refs/dist/index.mjs","../node_modules/@radix-ui/react-context/dist/index.mjs","../node_modules/@radix-ui/react-primitive/node_modules/@radix-ui/react-slot/dist/index.mjs","../node_modules/@radix-ui/react-primitive/dist/index.mjs","../node_modules/@radix-ui/react-collection/node_modules/@radix-ui/react-slot/dist/index.mjs","../node_modules/@radix-ui/react-collection/dist/index.mjs","../node_modules/@radix-ui/react-use-layout-effect/dist/index.mjs","../node_modules/@radix-ui/react-id/dist/index.mjs","../node_modules/@radix-ui/react-use-callback-ref/dist/index.mjs","../node_modules/@radix-ui/react-use-controllable-state/dist/index.mjs","../node_modules/@radix-ui/react-direction/dist/index.mjs","../node_modules/@radix-ui/react-roving-focus/dist/index.mjs","../node_modules/@radix-ui/react-use-size/dist/index.mjs","../node_modules/@radix-ui/react-use-previous/dist/index.mjs","../node_modules/@radix-ui/react-presence/dist/index.mjs","../node_modules/@radix-ui/react-radio-group/dist/index.mjs","../src/components/Radio/Radio.tsx","../node_modules/@radix-ui/react-switch/dist/index.mjs","../src/components/Switch/Switch.tsx","../src/components/Avatar/Avatar.tsx","../src/components/Divider/Divider.tsx","../src/components/DescriptionList/DescriptionList.tsx","../node_modules/@heroicons/react/24/outline/esm/ArchiveBoxIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowDownTrayIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowLeftStartOnRectangleIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowLeftIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowPathIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowRightOnRectangleIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowUpTrayIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowUturnLeftIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowsPointingInIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowsPointingOutIcon.js","../node_modules/@heroicons/react/24/outline/esm/Bars3Icon.js","../node_modules/@heroicons/react/24/outline/esm/BellIcon.js","../node_modules/@heroicons/react/24/outline/esm/BuildingOffice2Icon.js","../node_modules/@heroicons/react/24/outline/esm/BuildingOfficeIcon.js","../node_modules/@heroicons/react/24/outline/esm/CalendarIcon.js","../node_modules/@heroicons/react/24/outline/esm/CheckCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/CheckIcon.js","../node_modules/@heroicons/react/24/outline/esm/ChevronDownIcon.js","../node_modules/@heroicons/react/24/outline/esm/ChevronLeftIcon.js","../node_modules/@heroicons/react/24/outline/esm/ChevronRightIcon.js","../node_modules/@heroicons/react/24/outline/esm/ClockIcon.js","../node_modules/@heroicons/react/24/outline/esm/CloudArrowUpIcon.js","../node_modules/@heroicons/react/24/outline/esm/ComputerDesktopIcon.js","../node_modules/@heroicons/react/24/outline/esm/CreditCardIcon.js","../node_modules/@heroicons/react/24/outline/esm/CubeIcon.js","../node_modules/@heroicons/react/24/outline/esm/DocumentArrowDownIcon.js","../node_modules/@heroicons/react/24/outline/esm/DocumentDuplicateIcon.js","../node_modules/@heroicons/react/24/outline/esm/DocumentTextIcon.js","../node_modules/@heroicons/react/24/outline/esm/DocumentIcon.js","../node_modules/@heroicons/react/24/outline/esm/EllipsisVerticalIcon.js","../node_modules/@heroicons/react/24/outline/esm/ExclamationCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/ExclamationTriangleIcon.js","../node_modules/@heroicons/react/24/outline/esm/EyeIcon.js","../node_modules/@heroicons/react/24/outline/esm/FilmIcon.js","../node_modules/@heroicons/react/24/outline/esm/FunnelIcon.js","../node_modules/@heroicons/react/24/outline/esm/GlobeAltIcon.js","../node_modules/@heroicons/react/24/outline/esm/InformationCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/LinkIcon.js","../node_modules/@heroicons/react/24/outline/esm/ListBulletIcon.js","../node_modules/@heroicons/react/24/outline/esm/LockClosedIcon.js","../node_modules/@heroicons/react/24/outline/esm/LockOpenIcon.js","../node_modules/@heroicons/react/24/outline/esm/MagnifyingGlassIcon.js","../node_modules/@heroicons/react/24/outline/esm/MinusCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/MoonIcon.js","../node_modules/@heroicons/react/24/outline/esm/MusicalNoteIcon.js","../node_modules/@heroicons/react/24/outline/esm/NoSymbolIcon.js","../node_modules/@heroicons/react/24/outline/esm/PencilSquareIcon.js","../node_modules/@heroicons/react/24/outline/esm/PencilIcon.js","../node_modules/@heroicons/react/24/outline/esm/PhotoIcon.js","../node_modules/@heroicons/react/24/outline/esm/PlusIcon.js","../node_modules/@heroicons/react/24/outline/esm/PrinterIcon.js","../node_modules/@heroicons/react/24/outline/esm/ShoppingBagIcon.js","../node_modules/@heroicons/react/24/outline/esm/ShoppingCartIcon.js","../node_modules/@heroicons/react/24/outline/esm/Squares2X2Icon.js","../node_modules/@heroicons/react/24/outline/esm/TrashIcon.js","../node_modules/@heroicons/react/24/outline/esm/UserIcon.js","../node_modules/@heroicons/react/24/outline/esm/XCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/XMarkIcon.js","../src/components/AlertDialog/AlertDialog.tsx","../src/components/Alert/Alert.tsx","../src/components/Badge/Badge.tsx","../src/components/Card/cn.ts","../src/components/Card/Card.tsx","../src/components/InputNumber/InputNumber.tsx","../src/components/NavigationRailItem/NavigationRailItem.tsx","../src/components/Dropdown/icons.tsx","../src/components/Dropdown/Dropdown.tsx","../src/components/DropdownItemCollapsible/icons.tsx","../src/components/DropdownItemCollapsible/DropdownItemCollapsible.tsx","../src/components/DropdownItemHeading/icons.tsx","../src/components/DropdownItemHeading/DropdownItemHeading.tsx","../src/components/Notification/Notification.tsx","../src/components/Pagination/icons.tsx","../src/components/Pagination/Pagination.tsx","../node_modules/@heroicons/react/20/solid/esm/CheckIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChevronLeftIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChevronRightIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChevronUpDownIcon.js","../node_modules/@heroicons/react/20/solid/esm/MagnifyingGlassIcon.js","../node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../node_modules/@floating-ui/react/dist/floating-ui.react.utils.mjs","../node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs","../node_modules/@floating-ui/react/dist/floating-ui.react.mjs","../src/components/LookupField/hooks/useFloatingDropdown.ts","../src/components/Select/Select.tsx","../src/components/NavigationRail/NavigationRail.tsx","../src/components/NavigationRailPanel/NavigationRailPanel.tsx","../src/components/NavigationRailTypes/icons.tsx","../src/components/NavigationRailTypes/NavigationRailTypes.tsx","../src/components/NavigationRailGroup/icons.tsx","../src/components/NavigationRailGroup/NavigationRailGroup.tsx","../src/components/Table/Table.tsx","../src/components/MatchModal/icons.tsx","../src/components/LanguageManagement/core/interpolate.ts","../src/components/LanguageManagement/engines/DefaultTranslationEngine.ts","../src/components/LanguageManagement/storage/languageStorage.ts","../src/components/LanguageManagement/core/TranslationProvider.tsx","../src/components/LanguageManagement/hooks/useTranslation.ts","../src/components/MasterDocument/i18nFactory.ts","../src/components/MatchModal/i18n.ts","../src/components/MatchModal/MatchModal.tsx","../src/components/Tabs/Tabs.tsx","../src/components/LanguageManagement/hooks/useLanguage.ts","../src/components/LanguageManagement/components/LanguageSelector.tsx","../src/components/LanguageManagement/services/languageService.ts","../src/components/Navbar/icons.tsx","../src/components/Navbar/Navbar.tsx","../src/components/NavigationBar/NavigationBar.tsx","../src/components/POSConvention/icons.tsx","../src/components/POSConvention/POSConvention.tsx","../src/components/POSLocationButton/icons.tsx","../src/components/POSLocationButton/POSLocationButton.tsx","../src/components/POSNumberButton/POSNumberButton.tsx","../src/components/POSProductButton/POSProductButton.tsx","../src/components/POSProductCard/icons.tsx","../src/components/POSProductCard/POSProductCard.tsx","../src/components/POSProductSidebarItems/icons.tsx","../src/components/POSProductSidebarItems/POSProductSidebarItems.tsx","../src/components/POSTable/POSTable.tsx","../src/audit/hooks/useAuditHistory.ts","../node_modules/react-loading-skeleton/dist/index.js","../node_modules/date-fns/constants.js","../node_modules/date-fns/constructFrom.js","../node_modules/date-fns/toDate.js","../node_modules/date-fns/_lib/defaultOptions.js","../node_modules/date-fns/startOfWeek.js","../node_modules/date-fns/startOfISOWeek.js","../node_modules/date-fns/getISOWeekYear.js","../node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js","../node_modules/date-fns/_lib/normalizeDates.js","../node_modules/date-fns/startOfDay.js","../node_modules/date-fns/differenceInCalendarDays.js","../node_modules/date-fns/startOfISOWeekYear.js","../node_modules/date-fns/isDate.js","../node_modules/date-fns/isValid.js","../node_modules/date-fns/startOfYear.js","../node_modules/date-fns/locale/en-US/_lib/formatDistance.js","../node_modules/date-fns/locale/_lib/buildFormatLongFn.js","../node_modules/date-fns/locale/en-US/_lib/formatLong.js","../node_modules/date-fns/locale/en-US/_lib/formatRelative.js","../node_modules/date-fns/locale/_lib/buildLocalizeFn.js","../node_modules/date-fns/locale/en-US/_lib/localize.js","../node_modules/date-fns/locale/_lib/buildMatchFn.js","../node_modules/date-fns/locale/_lib/buildMatchPatternFn.js","../node_modules/date-fns/locale/en-US/_lib/match.js","../node_modules/date-fns/locale/en-US.js","../node_modules/date-fns/getDayOfYear.js","../node_modules/date-fns/getISOWeek.js","../node_modules/date-fns/getWeekYear.js","../node_modules/date-fns/startOfWeekYear.js","../node_modules/date-fns/getWeek.js","../node_modules/date-fns/_lib/addLeadingZeros.js","../node_modules/date-fns/_lib/format/lightFormatters.js","../node_modules/date-fns/_lib/format/formatters.js","../node_modules/date-fns/_lib/format/longFormatters.js","../node_modules/date-fns/_lib/protectedTokens.js","../node_modules/date-fns/format.js","../node_modules/date-fns/locale/es/_lib/formatDistance.js","../node_modules/date-fns/locale/es/_lib/formatLong.js","../node_modules/date-fns/locale/es/_lib/formatRelative.js","../node_modules/date-fns/locale/es/_lib/localize.js","../node_modules/date-fns/locale/es/_lib/match.js","../node_modules/date-fns/locale/es.js","../src/audit/utils/formatAuditTimestamp.ts","../src/audit/components/AuditTimestamp.tsx","../src/audit/components/AuditTimeline.tsx","../src/audit/utils/formatAuditValue.ts","../src/audit/components/AuditEntryDetail.tsx","../src/audit/components/AuditHistoryPanel.tsx","../node_modules/zustand/esm/vanilla.mjs","../src/components/MasterPatternView/store/slices/listSlice.ts","../src/components/MasterPatternView/engine/fieldEngine.ts","../src/components/MasterPatternView/store/slices/formSlice.ts","../src/components/MasterPatternView/store/slices/filterSlice.ts","../src/components/MasterPatternView/store/slices/uiSlice.ts","../src/components/MasterPatternView/store/slices/overrideSlice.ts","../src/components/MasterPatternView/store/createMasterViewStore.ts","../src/components/MasterPatternView/store/MasterViewContext.tsx","../src/components/Toast/Toast.tsx","../src/components/Toast/ToastProvider.tsx","../src/components/MasterPatternView/components/InternalToastContainer.tsx","../src/components/MasterPatternView/hooks/useToast.ts","../src/components/MasterPatternView/components/toolbar/CompanySelector.tsx","../src/components/MasterPatternView/components/modals/CompanyEnableModal.tsx","../src/components/MasterPatternView/components/ConfigTableContent.tsx","../src/components/MasterPatternView/engine/permissionEngine.ts","../src/components/MasterPatternView/components/form/FormActionBar.tsx","../src/components/MasterPatternView/components/form/TabBar.tsx","../src/components/MasterPatternView/components/form/SidebarPanel.tsx","../src/components/MasterPatternView/components/form/ModalPanel.tsx","../src/components/MasterPatternView/components/form/PagePanel.tsx","../src/components/LookupField/utils/cn.ts","../src/components/LookupField/utils/templateInterpolation.ts","../src/components/LookupField/services/api.types.ts","../src/components/LookupField/utils/errorMessages.ts","../src/components/LookupField/utils/filterBuilder.ts","../src/components/LookupField/hooks/useDebouncedSearch.ts","../src/components/LookupField/hooks/useKeyboardNavigation.ts","../src/components/LookupField/hooks/useTranslationSafe.ts","../src/components/LookupField/hooks/useClickOutside.ts","../node_modules/@tanstack/virtual-core/dist/esm/utils.js","../node_modules/@tanstack/virtual-core/dist/esm/index.js","../node_modules/@tanstack/react-virtual/dist/esm/index.js","../src/components/LookupField/hooks/useVirtualList.ts","../src/components/LookupField/parts/SearchInput.tsx","../src/components/LookupField/parts/LiveRegion.tsx","../src/components/LookupField/parts/CreatePopup.tsx","../src/components/LookupField/LookupField.tsx","../src/components/MasterPatternView/engine/validationEngine.ts","../src/components/MasterPatternView/hooks/useMasterForm.ts","../src/components/MasterPatternView/components/MasterPatternViewCreateForm.tsx","../node_modules/prop-types/node_modules/react-is/cjs/react-is.production.min.js","../node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js","../node_modules/prop-types/node_modules/react-is/index.js","../node_modules/object-assign/index.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/prop-types/lib/has.js","../node_modules/prop-types/checkPropTypes.js","../node_modules/prop-types/factoryWithTypeCheckers.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/index.js","../node_modules/tslib/tslib.es6.mjs","../node_modules/file-selector/dist/es2015/file.js","../node_modules/file-selector/dist/es2015/file-selector.js","../node_modules/attr-accept/dist/es/index.js","../node_modules/react-dropzone/dist/es/utils/index.js","../node_modules/react-dropzone/dist/es/index.js","../src/components/FileUploader/FilePreview.tsx","../src/components/FileUploader/FileUploader.tsx","../src/components/MasterPatternView/components/form/fields/FieldRenderer.tsx","../src/components/MasterPatternView/components/form/fields/OverridableFieldWrapper.tsx","../src/components/MasterPatternView/components/form/BasicDataTab.tsx","../src/components/MasterPatternView/components/form/TabSection.tsx","../src/components/MasterPatternView/components/form/ContentTab.tsx","../src/components/MasterPatternView/components/form/MasterPatternViewForm.tsx","../src/components/MasterPatternView/hooks/useFieldEngine.ts","../src/components/MasterPatternView/components/toolbar/FilterPanel.tsx","../src/components/MasterPatternView/components/toolbar/ToolbarActions.tsx","../src/components/MasterPatternView/assets/nodata.svg","../src/components/MasterPatternView/components/list/EmptyState.tsx","../src/components/MasterPatternView/components/list/RowActions.tsx","../src/components/MasterPatternView/components/list/CompanyStatusBadge.tsx","../src/components/MasterPatternView/components/list/ListTable.tsx","../src/components/MasterPatternView/components/list/ListCard.tsx","../src/components/MasterPatternView/components/list/PaginationBar.tsx","../src/components/MasterPatternView/components/list/BatchBar.tsx","../src/components/MasterPatternView/components/modals/DirtyStateDialog.tsx","../src/components/MasterPatternView/components/modals/ChangeStatusModal.tsx","../src/components/MasterPatternView/components/modals/ConflictDialog.tsx","../src/components/MasterPatternView/components/modals/NotEnabledModal.tsx","../src/components/MasterPatternView/hooks/useMasterList.ts","../src/components/MasterPatternView/hooks/useChangeStatus.ts","../src/components/MasterPatternView/hooks/useSortState.ts","../src/components/MasterPatternView/hooks/useMasterPatternViewTranslation.ts","../src/components/MasterPatternView/i18n/internalTranslations.ts","../src/components/MasterPatternView/components/MasterPatternView.tsx","../src/components/MasterCrud/icons.tsx","../src/components/MasterCrud/MasterCrudTable.tsx","../src/components/LookupField/services/api.ts","../src/components/MasterCrud/CompanySelector.tsx","../src/components/DynamicEntities/core/logic/RuleEngine.ts","../src/components/DynamicEntities/core/api/fetcher.ts","../src/components/DynamicEntities/core/api/DynamicEntitiesHttpError.ts","../src/components/DynamicEntities/core/api/DynamicEntitiesApi.ts","../src/components/DynamicEntities/core/DynamicEntitiesProvider.tsx","../src/components/DynamicEntities/core/hooks/useDynamicEntitiesApi.ts","../src/components/DynamicEntities/core/hooks/useDynamicDefinition.ts","../src/components/DynamicEntities/core/types/DynamicField.types.ts","../src/components/DynamicEntities/ui/DynamicFieldRenderer.tsx","../src/components/DynamicEntities/ui/DynamicEntities.tsx","../src/components/DynamicEntities/admin/services/FeatureService.ts","../src/components/DynamicEntities/admin/services/useFeatureService.ts","../src/components/DynamicEntities/ui/DynamicEntityGrid.tsx","../src/components/DynamicEntities/ui/DynamicEntityMultiRecord.tsx","../src/components/LayoutContent/LayoutContent.tsx","../src/components/DynamicEntities/ui/DynamicFeatureOrchestrator.tsx","../src/components/MasterCrud/DynamicEntitiesRegistrationContext.ts","../src/components/MasterCrud/MasterCrudDynamicEntities.tsx","../src/components/FileUploaderGallery/FileUploaderGallery.types.ts","../src/components/FileUploaderGallery/FileUploaderGallery.tsx","../src/components/MasterCrud/FileGalleryRegistrationContext.ts","../src/components/MasterCrud/MasterCrudFileManager.tsx","../src/components/MasterCrud/MasterCrudForm.tsx","../src/components/MasterCrud/MasterCrudToolbar.tsx","../src/components/MasterCrud/MasterCRUDCard.tsx","../src/components/MasterCrud/MasterCrudAdvancedSearch.tsx","../src/components/MasterCrud/LinkModal.tsx","../src/components/Info/Info.tsx","../src/assets/nodata.svg","../src/components/MasterCrud/MasterCrudDetailSection.tsx","../src/components/MasterCrud/MasterPatternAdapter.ts","../src/components/MasterCrud/services/BulkDynamicEditService.ts","../src/components/MasterCrud/useBulkDynamicEdit.ts","../src/components/MasterCrud/MasterCrudBulkDynamicEditor.tsx","../src/components/MasterCrud/useMasterCrudTranslation.ts","../src/components/MasterCrud/MasterCrud.tsx","../src/components/LoginView/icons.tsx","../src/components/LoginView/LoginView.tsx","../src/components/SignUpView/icons.tsx","../src/components/SignUpView/SignUpView.tsx","../src/components/ParameterEditor/ParameterEditorSearchBar.tsx","../src/components/ParameterEditor/ParameterEditorScrollableTabs.tsx","../src/components/ParameterEditor/ParameterEditor.utils.ts","../src/components/ParameterEditor/ParameterEditorDynamicField.tsx","../src/components/ParameterEditor/ParameterEditorFieldList.tsx","../src/components/ParameterEditor/ParameterEditorConfirmPanel.tsx","../src/components/ParameterEditor/ParameterEditor.tsx","../src/components/Tree/parts/TreeCheckbox.tsx","../src/components/Tree/parts/TreeNode.tsx","../src/components/Tree/utils/treeOperations.ts","../src/components/Tree/hooks/useTree.ts","../src/components/Tree/Tree.tsx","../src/views/LayoutBase/LayoutBase.tsx","../src/views/ListView/icons.tsx","../src/views/ListView/ListView.tsx","../src/views/LoginView/icons.tsx","../src/views/LoginView/LoginView.tsx","../src/views/ProductsView/icons.tsx","../src/views/ProductsView/ProductsView.tsx","../src/views/RecoverPasswordView/icons.tsx","../src/views/RecoverPasswordView/RecoverPasswordView.tsx","../src/views/SignUpView/icons.tsx","../src/views/SignUpView/SignUpView.tsx","../src/views/TableLayoutView/icons.tsx","../src/views/TableLayoutView/TableLayoutView.tsx","../src/context/ThemeContext.tsx","../src/components/FileUploaderGallery/useFileUploaderGallery.ts","../src/components/FileUploaderGallery/FileUploaderGalleryGlobal.tsx","../src/components/DynamicEntities/admin/FeatureList.tsx","../node_modules/@dnd-kit/utilities/dist/utilities.esm.js","../node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js","../node_modules/@dnd-kit/core/dist/core.esm.js","../node_modules/@dnd-kit/sortable/dist/sortable.esm.js","../src/components/DynamicEntities/admin/FieldDesigner.tsx","../src/components/DynamicEntities/admin/FieldEditor.tsx","../src/components/DynamicEntities/admin/EntityEditor.tsx","../src/components/DynamicEntities/admin/FeatureEditor.tsx","../src/components/DynamicEntities/admin/CatalogManager.tsx","../src/components/DynamicEntities/admin/DynamicEntitiesAdmin.tsx","../src/components/GenericEntities/GenericEntityModal.tsx","../src/components/GenericEntities/GenericEntities.tsx","../src/components/ContactManager/i18n/defaultTranslations.ts","../src/components/ContactManager/i18n/mergeTranslations.ts","../src/components/ContactManager/providers/ContactServiceProvider.tsx","../src/components/ContactManager/types/enum.types.ts","../src/components/ContactManager/store/useContactStore.ts","../src/components/ContactManager/hooks/useMediaQuery.ts","../src/components/ContactManager/utils/tagColors.ts","../src/components/ContactManager/parts/contactGridUtils.ts","../src/components/ContactManager/parts/ContactGridSkeleton.tsx","../src/components/ContactManager/parts/ContactGridEmptyState.tsx","../src/components/ContactManager/parts/ContactRowActions.tsx","../src/components/ContactManager/parts/ResponsiveContactCard.tsx","../src/components/ContactManager/parts/ContactGrid.tsx","../src/components/ContactManager/schemas/contact.schema.ts","../node_modules/@radix-ui/react-use-escape-keydown/dist/index.mjs","../node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs","../node_modules/@radix-ui/react-focus-scope/dist/index.mjs","../node_modules/@radix-ui/react-portal/dist/index.mjs","../node_modules/@radix-ui/react-focus-guards/dist/index.mjs","../node_modules/react-remove-scroll-bar/dist/es2015/constants.js","../node_modules/use-callback-ref/dist/es2015/assignRef.js","../node_modules/use-callback-ref/dist/es2015/useRef.js","../node_modules/use-callback-ref/dist/es2015/useMergeRef.js","../node_modules/use-sidecar/dist/es2015/medium.js","../node_modules/use-sidecar/dist/es2015/exports.js","../node_modules/react-remove-scroll/dist/es2015/medium.js","../node_modules/react-remove-scroll/dist/es2015/UI.js","../node_modules/get-nonce/dist/es2015/index.js","../node_modules/react-style-singleton/dist/es2015/singleton.js","../node_modules/react-style-singleton/dist/es2015/hook.js","../node_modules/react-style-singleton/dist/es2015/component.js","../node_modules/react-remove-scroll-bar/dist/es2015/utils.js","../node_modules/react-remove-scroll-bar/dist/es2015/component.js","../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js","../node_modules/react-remove-scroll/dist/es2015/handleScroll.js","../node_modules/react-remove-scroll/dist/es2015/SideEffect.js","../node_modules/react-remove-scroll/dist/es2015/sidecar.js","../node_modules/react-remove-scroll/dist/es2015/Combination.js","../node_modules/aria-hidden/dist/es2015/index.js","../node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-slot/dist/index.mjs","../node_modules/@radix-ui/react-dialog/dist/index.mjs","../node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-slot/dist/index.mjs","../node_modules/@radix-ui/react-alert-dialog/dist/index.mjs","../node_modules/@radix-ui/react-arrow/dist/index.mjs","../node_modules/@radix-ui/react-popper/dist/index.mjs","../node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-slot/dist/index.mjs","../node_modules/@radix-ui/react-popover/dist/index.mjs","../src/components/ContactManager/utils/cn.ts","../src/components/ContactManager/ui/dialog.tsx","../src/components/ContactManager/parts/PillEmailInput.tsx","../src/components/ContactManager/parts/UseForDropdown.tsx","../src/components/ContactManager/ui/alert-dialog.tsx","../src/components/ContactManager/parts/DefaultConfirmationDialog.tsx","../src/components/ContactManager/parts/UnifiedPhoneInput.tsx","../src/components/ContactManager/parts/ContactModal.tsx","../src/components/ContactManager/parts/DeleteDefaultConfirmationDialog.tsx","../src/components/ContactManager/ContactManager.tsx","../src/components/ContactManager/i18n/englishTranslations.ts","../node_modules/comma-separated-tokens/index.js","../node_modules/estree-util-is-identifier-name/lib/index.js","../node_modules/hast-util-whitespace/lib/index.js","../node_modules/property-information/lib/util/schema.js","../node_modules/property-information/lib/util/merge.js","../node_modules/property-information/lib/normalize.js","../node_modules/property-information/lib/util/info.js","../node_modules/property-information/lib/util/types.js","../node_modules/property-information/lib/util/defined-info.js","../node_modules/property-information/lib/util/create.js","../node_modules/property-information/lib/aria.js","../node_modules/property-information/lib/util/case-sensitive-transform.js","../node_modules/property-information/lib/util/case-insensitive-transform.js","../node_modules/property-information/lib/html.js","../node_modules/property-information/lib/svg.js","../node_modules/property-information/lib/xlink.js","../node_modules/property-information/lib/xmlns.js","../node_modules/property-information/lib/xml.js","../node_modules/property-information/lib/hast-to-react.js","../node_modules/property-information/lib/find.js","../node_modules/property-information/index.js","../node_modules/space-separated-tokens/index.js","../node_modules/inline-style-parser/cjs/index.js","../node_modules/style-to-object/cjs/index.js","../node_modules/style-to-js/cjs/utilities.js","../node_modules/style-to-js/cjs/index.js","../node_modules/unist-util-position/lib/index.js","../node_modules/unist-util-stringify-position/lib/index.js","../node_modules/vfile-message/lib/index.js","../node_modules/hast-util-to-jsx-runtime/lib/index.js","../node_modules/html-url-attributes/lib/index.js","../node_modules/mdast-util-to-string/lib/index.js","../node_modules/decode-named-character-reference/index.dom.js","../node_modules/micromark-util-chunked/index.js","../node_modules/micromark-util-combine-extensions/index.js","../node_modules/micromark-util-decode-numeric-character-reference/index.js","../node_modules/micromark-util-normalize-identifier/index.js","../node_modules/micromark-util-character/index.js","../node_modules/micromark-util-sanitize-uri/index.js","../node_modules/micromark-factory-space/index.js","../node_modules/micromark/lib/initialize/content.js","../node_modules/micromark/lib/initialize/document.js","../node_modules/micromark-util-classify-character/index.js","../node_modules/micromark-util-resolve-all/index.js","../node_modules/micromark-core-commonmark/lib/attention.js","../node_modules/micromark-core-commonmark/lib/autolink.js","../node_modules/micromark-core-commonmark/lib/blank-line.js","../node_modules/micromark-core-commonmark/lib/block-quote.js","../node_modules/micromark-core-commonmark/lib/character-escape.js","../node_modules/micromark-core-commonmark/lib/character-reference.js","../node_modules/micromark-core-commonmark/lib/code-fenced.js","../node_modules/micromark-core-commonmark/lib/code-indented.js","../node_modules/micromark-core-commonmark/lib/code-text.js","../node_modules/micromark-util-subtokenize/lib/splice-buffer.js","../node_modules/micromark-util-subtokenize/index.js","../node_modules/micromark-core-commonmark/lib/content.js","../node_modules/micromark-factory-destination/index.js","../node_modules/micromark-factory-label/index.js","../node_modules/micromark-factory-title/index.js","../node_modules/micromark-factory-whitespace/index.js","../node_modules/micromark-core-commonmark/lib/definition.js","../node_modules/micromark-core-commonmark/lib/hard-break-escape.js","../node_modules/micromark-core-commonmark/lib/heading-atx.js","../node_modules/micromark-util-html-tag-name/index.js","../node_modules/micromark-core-commonmark/lib/html-flow.js","../node_modules/micromark-core-commonmark/lib/html-text.js","../node_modules/micromark-core-commonmark/lib/label-end.js","../node_modules/micromark-core-commonmark/lib/label-start-image.js","../node_modules/micromark-core-commonmark/lib/label-start-link.js","../node_modules/micromark-core-commonmark/lib/line-ending.js","../node_modules/micromark-core-commonmark/lib/thematic-break.js","../node_modules/micromark-core-commonmark/lib/list.js","../node_modules/micromark-core-commonmark/lib/setext-underline.js","../node_modules/micromark/lib/initialize/flow.js","../node_modules/micromark/lib/initialize/text.js","../node_modules/micromark/lib/constructs.js","../node_modules/micromark/lib/create-tokenizer.js","../node_modules/micromark/lib/parse.js","../node_modules/micromark/lib/postprocess.js","../node_modules/micromark/lib/preprocess.js","../node_modules/micromark-util-decode-string/index.js","../node_modules/mdast-util-from-markdown/lib/index.js","../node_modules/remark-parse/lib/index.js","../node_modules/mdast-util-to-hast/lib/handlers/blockquote.js","../node_modules/mdast-util-to-hast/lib/handlers/break.js","../node_modules/mdast-util-to-hast/lib/handlers/code.js","../node_modules/mdast-util-to-hast/lib/handlers/delete.js","../node_modules/mdast-util-to-hast/lib/handlers/emphasis.js","../node_modules/mdast-util-to-hast/lib/handlers/footnote-reference.js","../node_modules/mdast-util-to-hast/lib/handlers/heading.js","../node_modules/mdast-util-to-hast/lib/handlers/html.js","../node_modules/mdast-util-to-hast/lib/revert.js","../node_modules/mdast-util-to-hast/lib/handlers/image-reference.js","../node_modules/mdast-util-to-hast/lib/handlers/image.js","../node_modules/mdast-util-to-hast/lib/handlers/inline-code.js","../node_modules/mdast-util-to-hast/lib/handlers/link-reference.js","../node_modules/mdast-util-to-hast/lib/handlers/link.js","../node_modules/mdast-util-to-hast/lib/handlers/list-item.js","../node_modules/mdast-util-to-hast/lib/handlers/list.js","../node_modules/mdast-util-to-hast/lib/handlers/paragraph.js","../node_modules/mdast-util-to-hast/lib/handlers/root.js","../node_modules/mdast-util-to-hast/lib/handlers/strong.js","../node_modules/mdast-util-to-hast/lib/handlers/table.js","../node_modules/mdast-util-to-hast/lib/handlers/table-row.js","../node_modules/mdast-util-to-hast/lib/handlers/table-cell.js","../node_modules/trim-lines/index.js","../node_modules/mdast-util-to-hast/lib/handlers/text.js","../node_modules/mdast-util-to-hast/lib/handlers/thematic-break.js","../node_modules/mdast-util-to-hast/lib/handlers/index.js","../node_modules/@ungap/structured-clone/esm/types.js","../node_modules/@ungap/structured-clone/esm/deserialize.js","../node_modules/@ungap/structured-clone/esm/serialize.js","../node_modules/@ungap/structured-clone/esm/index.js","../node_modules/mdast-util-to-hast/lib/footer.js","../node_modules/unist-util-is/lib/index.js","../node_modules/unist-util-visit-parents/lib/index.js","../node_modules/unist-util-visit/lib/index.js","../node_modules/mdast-util-to-hast/lib/state.js","../node_modules/mdast-util-to-hast/lib/index.js","../node_modules/remark-rehype/lib/index.js","../node_modules/bail/index.js","../node_modules/extend/index.js","../node_modules/is-plain-obj/index.js","../node_modules/trough/lib/index.js","../node_modules/vfile/lib/minpath.browser.js","../node_modules/vfile/lib/minproc.browser.js","../node_modules/vfile/lib/minurl.shared.js","../node_modules/vfile/lib/minurl.browser.js","../node_modules/vfile/lib/index.js","../node_modules/unified/lib/callable-instance.js","../node_modules/unified/lib/index.js","../node_modules/react-markdown/lib/index.js","../node_modules/ccount/index.js","../node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp/index.js","../node_modules/mdast-util-find-and-replace/lib/index.js","../node_modules/mdast-util-gfm-autolink-literal/lib/index.js","../node_modules/mdast-util-gfm-footnote/lib/index.js","../node_modules/mdast-util-gfm-strikethrough/lib/index.js","../node_modules/markdown-table/index.js","../node_modules/mdast-util-to-markdown/lib/handle/blockquote.js","../node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js","../node_modules/mdast-util-to-markdown/lib/handle/break.js","../node_modules/longest-streak/index.js","../node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js","../node_modules/mdast-util-to-markdown/lib/util/check-fence.js","../node_modules/mdast-util-to-markdown/lib/handle/code.js","../node_modules/mdast-util-to-markdown/lib/util/check-quote.js","../node_modules/mdast-util-to-markdown/lib/handle/definition.js","../node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js","../node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js","../node_modules/mdast-util-to-markdown/lib/util/encode-info.js","../node_modules/mdast-util-to-markdown/lib/handle/emphasis.js","../node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js","../node_modules/mdast-util-to-markdown/lib/handle/heading.js","../node_modules/mdast-util-to-markdown/lib/handle/html.js","../node_modules/mdast-util-to-markdown/lib/handle/image.js","../node_modules/mdast-util-to-markdown/lib/handle/image-reference.js","../node_modules/mdast-util-to-markdown/lib/handle/inline-code.js","../node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js","../node_modules/mdast-util-to-markdown/lib/handle/link.js","../node_modules/mdast-util-to-markdown/lib/handle/link-reference.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js","../node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js","../node_modules/mdast-util-to-markdown/lib/util/check-rule.js","../node_modules/mdast-util-to-markdown/lib/handle/list.js","../node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js","../node_modules/mdast-util-to-markdown/lib/handle/list-item.js","../node_modules/mdast-util-to-markdown/lib/handle/paragraph.js","../node_modules/mdast-util-phrasing/lib/index.js","../node_modules/mdast-util-to-markdown/lib/handle/root.js","../node_modules/mdast-util-to-markdown/lib/util/check-strong.js","../node_modules/mdast-util-to-markdown/lib/handle/strong.js","../node_modules/mdast-util-to-markdown/lib/handle/text.js","../node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js","../node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js","../node_modules/mdast-util-to-markdown/lib/handle/index.js","../node_modules/mdast-util-gfm-table/lib/index.js","../node_modules/mdast-util-gfm-task-list-item/lib/index.js","../node_modules/mdast-util-gfm/lib/index.js","../node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js","../node_modules/micromark-extension-gfm-footnote/lib/syntax.js","../node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js","../node_modules/micromark-extension-gfm-table/lib/edit-map.js","../node_modules/micromark-extension-gfm-table/lib/infer.js","../node_modules/micromark-extension-gfm-table/lib/syntax.js","../node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js","../node_modules/micromark-extension-gfm/index.js","../node_modules/remark-gfm/lib/index.js","../src/components/ChatWidget/ChatMessage.tsx","../src/components/ChatWidget/ChatInput.tsx","../src/components/ChatWidget/QuickActions.tsx","../src/components/ChatWidget/ChatWindow.tsx","../src/components/ChatWidget/ChatWidget.types.ts","../src/components/ChatWidget/ChatWidget.tsx","../src/components/MasterDocument/components/loading/Loading.tsx","../src/components/MasterDocument/i18n.ts","../src/components/MasterDocument/components/loading/FieldLoadingIndicator.tsx","../src/components/MasterDocument/MoreOptionsMenu.tsx","../src/components/MasterDocument/StateBadge.tsx","../src/components/MasterDocument/icons.tsx","../src/components/MasterDocument/stateActionCanon.ts","../src/components/MasterDocument/ActionBar.tsx","../src/components/MasterDocument/ContextStrip.tsx","../node_modules/react-number-format/dist/react-number-format.es.js","../src/components/MasterDocument/fieldStyles.ts","../src/components/MasterDocument/LookupReadonlyValue.tsx","../src/components/MasterDocument/formatters.ts","../src/components/MasterDocument/fieldValidation.ts","../src/components/MasterDocument/FieldRenderer.tsx","../src/components/MasterDocument/fieldLock.ts","../src/components/MasterDocument/CanonTabsBar.tsx","../src/components/MasterDocument/lookupFilters.ts","../src/components/MasterDocument/HeaderRenderer.tsx","../src/components/MasterDocument/LineContextMenu.tsx","../src/components/MasterDocument/LineFulfillmentBadge.tsx","../src/components/MasterDocument/rowActionStyles.ts","../src/components/MasterDocument/LinesSection.tsx","../src/components/MasterDocument/FactBox.tsx","../src/components/MasterDocument/ContentLayout.tsx","../src/components/MasterDocument/fieldCondition.ts","../src/components/MasterDocument/commonTexts.ts","../src/components/MasterDocument/SerialPanel/i18n.ts","../src/components/MasterDocument/SerialPanel/SerialCapturePanel.tsx","../src/components/MasterDocument/DocumentModalList.tsx","../src/components/MasterDocument/SerialPanel/SerialSelectPanel.tsx","../src/components/MasterDocument/SerialPanel/SerialPanel.tsx","../src/components/MasterDocument/SerialPanel/hooks/useSerialPanel.ts","../src/components/MasterDocument/LineFormModal.tsx","../src/components/MasterDocument/ConflictModal.tsx","../src/components/MasterDocument/Skeletons.tsx","../src/components/MasterDocument/inlineActions.ts","../src/components/MasterDocument/CrossingSourceSelector.tsx","../src/components/MasterDocument/StaleDataBanner.tsx","../src/components/MasterDocument/CrossingClassMenu.tsx","../src/components/MasterDocument/PendingLinesPanel.tsx","../src/components/MasterDocument/DocumentTraceabilityTree.tsx","../src/components/MasterDocument/LineCloseModal.tsx","../src/components/MasterDocument/CrossingGenerateModal.tsx","../src/components/MasterDocument/LineTabsBar.tsx","../src/components/MasterDocument/LineTabsRegion.tsx","../src/components/MasterDocument/MasterDocument.tsx","../src/components/MasterDocument/DocumentDynamicEntities.tsx","../src/components/MasterDocument/smart/useDocumentDynamicEntities.ts","../src/components/MasterDocument/CurrencyPanel.tsx","../src/components/MasterDocument/CurrencySelectorModal.tsx","../src/components/MasterDocument/smart/useCreateFromSource.ts","../src/components/MasterDocument/CreateFromSourceModal.tsx","../src/components/MasterDocument/adapter/createDefaultAdapter.ts","../src/components/MasterDocument/provider/iconRegistry.ts","../src/components/MasterDocument/printing/MasterDocumentPrintModal.tsx","../src/components/MasterDocument/printing/MasterDocumentPrintProvider.tsx","../src/components/MasterDocument/audit/MasterDocumentAuditModal.tsx","../src/components/MasterDocument/audit/MasterDocumentAuditProvider.tsx","../src/components/MasterDocument/provider/MasterDocumentProvider.tsx","../src/components/MasterDocument/provider/MasterDocumentRefreshProvider.tsx","../src/components/MasterDocument/template/expressionEvaluator.ts","../src/components/MasterDocument/smart/conflictError.ts","../src/components/MasterDocument/smart/userFacingError.ts","../src/components/MasterDocument/smart/useMasterDocumentReducer.ts","../src/components/MasterDocument/smart/useFactBoxData.ts","../src/components/MasterDocument/smart/crossingFetch.ts","../src/components/MasterDocument/smart/useCrossing.ts","../src/components/MasterDocument/FactBoxTotals.tsx","../src/components/MasterDocument/FactBoxCfde.tsx","../src/components/MasterDocument/FactBoxPaymentTerms.tsx","../src/components/MasterDocument/FactBoxFinancial.tsx","../src/components/MasterDocument/FactBoxStatusHistory.tsx","../src/components/MasterDocument/smart/factBoxBuilder.tsx","../src/components/MasterDocument/smart/lineFieldVisibility.ts","../src/components/MasterDocument/LineActionFormModal.tsx","../src/components/MasterDocument/smart/lineActionGating.ts","../src/components/MasterDocument/lineStateAxis.ts","../src/components/MasterDocument/actionVisibility.ts","../src/components/MasterDocument/smart/SmartMasterDocument.tsx","../src/components/MasterDocument/DocumentList.tsx","../src/components/MasterDocument/wizardOptionLookup.ts","../src/components/MasterDocument/DocumentCreationWizard.tsx","../src/components/MasterDocument/BulkConversionProgress.tsx","../src/components/MasterDocument/BulkResultsSummary.tsx","../src/components/MasterDocument/smart/useBulkConversion.ts","../src/components/MasterDocument/smart/MasterDocumentPage.tsx","../src/components/MasterDocument/flexQueryInterop.ts","../src/components/MasterDocument/ApprovalBanner.tsx","../src/components/MasterDocument/MasterDocumentFormModal.tsx","../src/components/MasterDocument/GlobalDiscountControl.tsx","../src/components/MasterDocument/CrossDocumentPanel.tsx","../src/components/MasterDocument/SourceDocumentsFactBox.tsx","../src/components/MasterDocument/smart/useCrossDocuments.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/i18n.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/AdvanceStatusBadge.tsx","../src/components/MasterDocument/AdvanceApplicationsPanel/hooks/keys.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/hooks/useAvailableAdvances.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/types.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/hooks/useDocumentAdvanceApplications.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/hooks/useApplyAdvance.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/hooks/useRemoveAdvance.ts","../src/components/MasterDocument/AdvanceApplicationsPanel/ApplyAdvanceModal.tsx","../src/components/MasterDocument/AdvanceApplicationsPanel/AdvanceApplicationsPanel.tsx","../src/components/MasterDocument/InstallmentsPanel/i18n.ts","../src/components/MasterDocument/InstallmentsPanel/InstallmentManualBadge.tsx","../src/components/MasterDocument/InstallmentsPanel/RegenerateInstallmentsModal.tsx","../src/components/MasterDocument/InstallmentsPanel/hooks/keys.ts","../src/components/MasterDocument/InstallmentsPanel/types.ts","../src/components/MasterDocument/InstallmentsPanel/hooks/useInstallments.ts","../src/components/MasterDocument/InstallmentsPanel/hooks/useModifyInstallment.ts","../src/components/MasterDocument/InstallmentsPanel/hooks/useRegenerateInstallments.ts","../src/components/MasterDocument/InstallmentsPanel/InstallmentsPanel.tsx","../src/components/MasterDocument/WithholdingsPanel/i18n.ts","../src/components/MasterDocument/WithholdingsPanel/WithholdingOriginBadge.tsx","../src/components/MasterDocument/WithholdingsPanel/WithholdingTotalCell.tsx","../src/components/MasterDocument/WithholdingsPanel/WithholdingsActionBar.tsx","../src/components/MasterDocument/WithholdingsPanel/WithholdingFormDialog.tsx","../src/components/MasterDocument/WithholdingsPanel/hooks/keys.ts","../src/components/MasterDocument/WithholdingsPanel/types.ts","../src/components/MasterDocument/WithholdingsPanel/hooks/useWithholdings.ts","../src/components/MasterDocument/WithholdingsPanel/hooks/useAddManualWithholding.ts","../src/components/MasterDocument/WithholdingsPanel/hooks/useModifyWithholding.ts","../src/components/MasterDocument/WithholdingsPanel/hooks/useDeleteWithholding.ts","../src/components/MasterDocument/WithholdingsPanel/hooks/useRecalculateWithholdings.ts","../src/components/MasterDocument/WithholdingsPanel/hooks/useWithholdingCatalogs.ts","../src/components/MasterDocument/WithholdingsPanel/WithholdingsAddModal.tsx","../src/components/MasterDocument/WithholdingsPanel/WithholdingsEditModal.tsx","../src/components/MasterDocument/WithholdingsPanel/WithholdingsConfirmModal.tsx","../src/components/MasterDocument/WithholdingsPanel/WithholdingsPanel.tsx","../src/components/MasterDocument/FinancialInstrumentPanel/i18n.ts","../src/components/MasterDocument/FinancialInstrumentPanel/InstrumentTypeField.tsx","../src/components/MasterDocument/FinancialInstrumentPanel/FinancialInstrumentForm.tsx","../src/components/MasterDocument/FinancialInstrumentPanel/FinancialInstrumentConfirmModal.tsx","../src/components/MasterDocument/FinancialInstrumentPanel/hooks/keys.ts","../src/components/MasterDocument/FinancialInstrumentPanel/types.ts","../src/components/MasterDocument/FinancialInstrumentPanel/hooks/useFinancialInstrument.ts","../src/components/MasterDocument/FinancialInstrumentPanel/hooks/useCreateFinancialInstrument.ts","../src/components/MasterDocument/FinancialInstrumentPanel/hooks/useUpdateFinancialInstrument.ts","../src/components/MasterDocument/FinancialInstrumentPanel/hooks/useDeleteFinancialInstrument.ts","../src/components/MasterDocument/FinancialInstrumentPanel/hooks/useInstrumentTypes.ts","../src/components/MasterDocument/FinancialInstrumentPanel/FinancialInstrumentPanel.tsx","../src/components/MasterDocument/FinancialInstrumentPanel/format.ts","../src/components/MasterDocument/FinancialInstrumentPanel/FinancialInstrumentFactBox.tsx","../src/dashboard/i18n.ts","../src/dashboard/components/DashboardCompanySelector.tsx","../src/dashboard/api/dashboardCatalog.ts","../src/dashboard/api/dashboardLayout.ts","../node_modules/@ucast/core/dist/es6m/index.mjs","../node_modules/@ucast/mongo/dist/es6m/index.mjs","../node_modules/@ucast/js/dist/es6m/index.mjs","../node_modules/@ucast/mongo2js/dist/es6m/index.mjs","../node_modules/@casl/ability/dist/es6m/index.mjs","../src/dashboard/ability.ts","../src/dashboard/hooks/useWidgetEngine.ts","../src/components/DashboardEngine/hooks/useOptimisticLayout.ts","../src/dashboard/hooks/useDashboardLayout.ts","../node_modules/react-grid-layout/dist/chunk-76RTO6EO.mjs","../node_modules/react-grid-layout/dist/chunk-KDANGDDL.mjs","../node_modules/fast-equals/dist/fast-equals.esm.js","../node_modules/clsx/dist/clsx.js","../node_modules/react-draggable/build/cjs/utils/shims.js","../node_modules/react-draggable/build/cjs/utils/getPrefix.js","../node_modules/react-draggable/build/cjs/utils/domFns.js","../node_modules/react-draggable/build/cjs/utils/positionFns.js","../node_modules/react-draggable/build/cjs/utils/log.js","../node_modules/react-draggable/build/cjs/DraggableCore.js","../node_modules/react-draggable/build/cjs/Draggable.js","../node_modules/react-draggable/build/cjs/cjs.js","../node_modules/react-resizable/build/utils.js","../node_modules/react-resizable/build/propTypes.js","../node_modules/react-resizable/build/Resizable.js","../node_modules/react-resizable/build/ResizableBox.js","../node_modules/react-resizable/index.js","../node_modules/react-grid-layout/dist/chunk-WGL5FSZH.mjs","../src/components/DashboardEngine/components/WidthProviderHOC.tsx","../src/dashboard/utils/layoutMigration.ts","../src/dashboard/DashboardGrid.tsx","../src/dashboard/utils/widgetTypeConfig.ts","../src/dashboard/useDashboardContext.ts","../src/dashboard/utils/indicatorsCatalog.ts","../src/dashboard/components/WidgetBuilder/types.ts","../src/dashboard/components/WidgetBuilder/Step1DataSource.tsx","../src/dashboard/components/WidgetBuilder/Step2FieldMapping.tsx","../src/dashboard/components/WidgetBuilder/Step3PresentationType.tsx","../src/dashboard/components/WidgetBuilder/categories.ts","../src/dashboard/components/WidgetBuilder/Step4Appearance.tsx","../src/dashboard/components/WidgetBuilder/Step5Permissions.tsx","../src/dashboard/components/WidgetBuilder/WidgetBuilder.tsx","../src/dashboard/access/WidgetAccessDialog.tsx","../src/dashboard/components/WidgetManagerPanel.tsx","../src/dashboard/types.ts","../src/dashboard/utils/detectValueFields.ts","../src/dashboard/utils/resolveChartFields.ts","../src/dashboard/utils/chartColors.ts","../src/dashboard/components/FieldMappingPanel.tsx","../src/dashboard/components/WidgetCustomizationPanel.tsx","../src/components/DashboardEngine/utils/gridEngine.ts","../src/components/DashboardEngine/components/WidgetErrorBoundary.tsx","../src/dashboard/components/WidgetSkeletons.tsx","../src/dashboard/utils/skeletonShape.ts","../src/dashboard/utils/useReducedMotion.ts","../src/dashboard/utils/formatNumber.ts","../src/dashboard/api/dashboardProxy.ts","../src/dashboard/api/widgetEnvelope.ts","../src/dashboard/utils/widgetConfig.ts","../src/dashboard/WidgetWrapper.tsx","../src/dashboard/components/LazyWidget.tsx","../src/dashboard/DashboardContext.tsx","../src/dashboard/utils/usePresentationMode.ts","../src/dashboard/DashboardPage.tsx","../src/components/FormCacheSelector/FormCacheSelector.api.ts","../src/components/FormCacheSelector/FormCacheSelector.utils.ts","../src/components/FormCacheSelector/FormCacheSelector.schema.ts","../src/components/FormCacheSelector/FormCacheSelector.hooks.ts","../src/components/FormCacheSelector/lib/ui/popover.tsx","../node_modules/cmdk/dist/chunk-NZJY6EH4.mjs","../node_modules/cmdk/dist/index.mjs","../src/components/FormCacheSelector/lib/ui/command.tsx","../src/components/FormCacheSelector/subcomponents/CacheSelector.tsx","../src/components/FormCacheSelector/lib/ui/dialog.tsx","../src/components/FormCacheSelector/subcomponents/SaveDialog.tsx","../src/components/FormCacheSelector/subcomponents/RenameDialog.tsx","../src/components/FormCacheSelector/subcomponents/DeleteDialog.tsx","../src/components/FormCacheSelector/FormCacheSelector.tsx","../src/components/PanelCompany/icons.tsx","../src/components/PanelCompany/PanelCompany.tsx"],"sourcesContent":["function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","/**\n * Copyright 2022 Joe Bell. All rights reserved.\n *\n * This file is licensed to you under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */ import { clsx } from \"clsx\";\nconst falsyToString = (value)=>typeof value === \"boolean\" ? `${value}` : value === 0 ? \"0\" : value;\nexport const cx = clsx;\nexport const cva = (base, config)=>(props)=>{\n        var _config_compoundVariants;\n        if ((config === null || config === void 0 ? void 0 : config.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);\n        const { variants, defaultVariants } = config;\n        const getVariantClassNames = Object.keys(variants).map((variant)=>{\n            const variantProp = props === null || props === void 0 ? void 0 : props[variant];\n            const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];\n            if (variantProp === null) return null;\n            const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);\n            return variants[variant][variantKey];\n        });\n        const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param)=>{\n            let [key, value] = param;\n            if (value === undefined) {\n                return acc;\n            }\n            acc[key] = value;\n            return acc;\n        }, {});\n        const getCompoundVariantClassNames = config === null || config === void 0 ? void 0 : (_config_compoundVariants = config.compoundVariants) === null || _config_compoundVariants === void 0 ? void 0 : _config_compoundVariants.reduce((acc, param)=>{\n            let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param;\n            return Object.entries(compoundVariantOptions).every((param)=>{\n                let [key, value] = param;\n                return Array.isArray(value) ? value.includes({\n                    ...defaultVariants,\n                    ...propsWithoutUndefined\n                }[key]) : ({\n                    ...defaultVariants,\n                    ...propsWithoutUndefined\n                })[key] === value;\n            }) ? [\n                ...acc,\n                cvClass,\n                cvClassName\n            ] : acc;\n        }, []);\n        return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);\n    };\n\n","import React from 'react';\nimport type { ButtonProps, ButtonColor } from './Button.types';\nimport { cva } from 'class-variance-authority';\n\n// Using a simple cx function instead of an external utility\nconst cx = (...inputs: (string | undefined | null | false)[]) => {\n  return inputs.filter(Boolean).join(' ');\n};\n\nconst buttonVariants = cva(\n  [\n    'inline-flex items-center justify-center rounded-md font-medium whitespace-nowrap transition-all duration-150 cursor-pointer',\n    'focus:outline-hidden focus:ring-4 focus:ring-offset-2',\n    'disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none'\n  ],\n  {\n    variants: {\n      type: {\n        default: 'shadow-inner hover:brightness-110 dark:hover:brightness-90',\n        outline: 'bg-transparent border shadow-xs hover:brightness-98 dark:hover:brightness-102',\n        plain: 'bg-transparent border-transparent hover:brightness-98 dark:hover:brightness-102'\n      },\n      color: {\n        primary: '',\n        secondary: '',\n        tertiary: '',\n      },\n      size: {\n        xs: '',\n        sm: '',\n        base: '',\n        l: '',\n        xl: '',\n      },\n      iconOnly: {\n        true: '',\n        false: ''\n      },\n      fullWidth: {\n        true: 'w-full',\n        false: ''\n      }\n    },\n    compoundVariants: [\n      // Primary\n      { type: 'default',\n        color: 'primary',\n        // El `!` (important) en el fondo evita que un reset SIN capa del consumidor\n        // (p. ej. `button { background-color: transparent }`) gane a esta utilidad,\n        // que se emite dentro de `@layer utilities`. Sin él, el botón sale\n        // blanco-sobre-blanco en apps reales. Ver SBC-3886.\n        className: 'bg-primary-700! dark:bg-primary-200! text-primary-50 dark:text-primary-800 border-primary-600 dark:border-primary-300 focus:ring-primary-400 focus:ring-offset-primary-100 dark:focus:ring-primary-500/50 dark:focus:ring-offset-gray-900'\n      },\n      {\n        type: 'outline',\n        color: 'primary',\n        className: 'text-primary-700 dark:text-primary-400 border-primary-300 dark:border-primary-700 hover:bg-primary-100 dark:hover:bg-primary-950 focus:ring-primary-400 focus:ring-offset-primary-100 dark:focus:ring-primary-500/50 dark:focus:ring-offset-gray-900'\n      },\n      {\n        type: 'plain',\n        color: 'primary',\n        className: 'text-primary-700 dark:text-primary-400 hover:bg-primary-100 dark:hover:bg-primary-950 hover:border-primary-100 dark:hover:border-primary-950 focus:ring-primary-400 focus:ring-offset-primary-100 dark:focus:ring-primary-500/50 dark:focus:ring-offset-gray-900'\n      },\n\n      // Secondary\n      {\n        type: 'default',\n        color: 'secondary',\n        className: 'bg-secondary-950! dark:bg-secondary-400! text-secondary-50 dark:text-secondary-950 border-secondary-950 dark:border-secondary-400 focus:ring-secondary-400 focus:ring-offset-secondary-100 dark:focus:ring-secondary-500/50 dark:focus:ring-offset-gray-900' },\n      {\n        type: 'outline',\n        color: 'secondary',\n        className: 'text-secondary-950 dark:text-secondary-300 border-secondary-300 dark:border-secondary-700 hover:bg-secondary-100 dark:hover:bg-secondary-900 focus:ring-secondary-400 focus:ring-offset-secondary-100 dark:focus:ring-secondary-500/50 dark:focus:ring-offset-gray-900'\n      },\n      {\n        type: 'plain',\n        color: 'secondary',\n        className: 'text-secondary-950 dark:text-secondary-300 hover:bg-secondary-100 dark:hover:bg-secondary-900 hover:border-secondary-100 dark:hover:border-secondary-900 focus:ring-secondary-400 focus:ring-offset-secondary-100 dark:focus:ring-secondary-500/50 dark:focus:ring-offset-gray-900'\n      },\n\n      // Tertiary\n      {\n        type: 'default',\n        color: 'tertiary',\n        className: 'bg-tertiary-800! dark:bg-tertiary-400! text-tertiary-50 dark:text-tertiary-800 border-tertiary-800 dark:border-tertiary-800 focus:ring-tertiary-400 focus:ring-offset-tertiary-100 dark:focus:ring-tertiary-500/50 dark:focus:ring-offset-gray-900' },\n      {\n        type: 'outline',\n        color: 'tertiary',\n        className: 'text-tertiary-800 dark:text-tertiary-300 border-tertiary-300 dark:border-tertiary-700 hover:bg-tertiary-100 dark:hover:bg-tertiary-800 focus:ring-tertiary-400 focus:ring-offset-tertiary-100 dark:focus:ring-tertiary-500/50 dark:focus:ring-offset-gray-900' },\n      {\n        type: 'plain',\n        color: 'tertiary',\n        className: 'text-tertiary-800 dark:text-tertiary-300 hover:bg-tertiary-100 dark:hover:bg-tertiary-800 hover:border-tertiary-100 dark:hover:border-tertiary-800 focus:ring-tertiary-400 focus:ring-offset-tertiary-100 dark:focus:ring-tertiary-500/50 dark:focus:ring-offset-gray-900' },\n\n      // Sizes\n      { size: 'xs', iconOnly: false, className: 'h-7 px-2 gap-2 text-xs' },\n      { size: 'sm', iconOnly: false, className: 'h-8 px-2 gap-2 text-sm' },\n      { size: 'base', iconOnly: false, className: 'h-9 px-3 gap-2 text-base' },\n      { size: 'l', iconOnly: false, className: 'h-10 px-3 gap-3 text-lg' },\n      { size: 'xl', iconOnly: false, className: 'h-11 px-4 gap-3 text-xl' },\n\n      // Sizes for iconOnly\n      { size: 'xs', iconOnly: true, className: 'h-7 w-7' },\n      { size: 'sm', iconOnly: true, className: 'h-8 w-8' },\n      { size: 'base', iconOnly: true, className: 'h-9 w-9' },\n      { size: 'l', iconOnly: true, className: 'h-10 w-10' },\n      { size: 'xl', iconOnly: true, className: 'h-11 w-11' },\n    ],\n    defaultVariants: {\n      type: 'default',\n      color: 'primary',\n      size: 'base',\n      iconOnly: false,\n      fullWidth: false\n    }\n  }\n);\n\nconst iconSizeClasses = {\n  xs: 'w-4 h-4 shrink-0',\n  sm: 'w-4 h-4 shrink-0',\n  base: 'w-4 h-4 shrink-0',\n  l: 'w-4 h-4 shrink-0',\n  xl: 'w-4 h-4 shrink-0',\n};\n\nexport const Button: React.FC<ButtonProps> = ({\n  type = 'default',\n  color = 'primary',\n  size = 'base',\n  iconOnly = false,\n  leftIcon,\n  rightIcon,\n  children,\n  disabled = false,\n  className = '',\n  onClick,\n  htmlType = 'button',\n  fullWidth = false,\n  ariaLabel,\n  badge = false,\n  badgeCount,\n  ...rest\n}) => {\n  const renderIcon = (icon: React.ReactNode) => {\n    if (!icon) return null;\n    return (\n      <span className={`inline-flex items-center justify-center shrink-0 ${iconSizeClasses[size]}`}>\n        {icon}\n      </span>\n    );\n  };\n\n  const renderContent = () => {\n    if (iconOnly) {\n      return renderIcon(leftIcon);\n    }\n\n    return (\n      <>\n        {leftIcon && renderIcon(leftIcon)}\n        {children && <span className=\"truncate\">{children}</span>}\n        {rightIcon && renderIcon(rightIcon)}\n      </>\n    );\n  };\n\n  const renderBadge = () => {\n    if (!badge && badgeCount === undefined) return null;\n\n    if (badgeCount !== undefined) {\n      return (\n        <span\n          className={cx(\n            'absolute -top-1 -right-1 flex items-center justify-center',\n            'min-w-[16px] h-4 px-1 rounded-full text-[10px] font-medium leading-none',\n            'pointer-events-none',\n            'bg-red-700 dark:bg-red-100 text-red-50 dark:text-red-700'\n          )}\n          aria-label={`${badgeCount} notificaciones`}\n        >\n          {badgeCount > 99 ? '99+' : badgeCount}\n        </span>\n      );\n    }\n\n    return (\n      <span\n        className={cx(\n          'absolute -top-1 -right-1 w-2 h-2 rounded-full pointer-events-none',\n          'bg-red-700 dark:bg-red-100'\n        )}\n        aria-label=\"Notificación\"\n      />\n    );\n  };\n\n  return (\n    <button\n      type={htmlType}\n      className={cx(\n        buttonVariants({\n          type,\n          color,\n          size,\n          iconOnly,\n          fullWidth\n        }),\n        (badge || badgeCount !== undefined) ? 'relative' : false,\n        className\n      )}\n      disabled={disabled}\n      onClick={onClick}\n      aria-label={ariaLabel}\n      {...rest}\n    >\n      {renderContent()}\n      {renderBadge()}\n    </button>\n  );\n};","/**\n * Concatenates two arrays faster than the array spread operator.\n */\nconst concatArrays = (array1, array2) => {\n  // Pre-allocate for better V8 optimization\n  const combinedArray = new Array(array1.length + array2.length);\n  for (let i = 0; i < array1.length; i++) {\n    combinedArray[i] = array1[i];\n  }\n  for (let i = 0; i < array2.length; i++) {\n    combinedArray[array1.length + i] = array2[i];\n  }\n  return combinedArray;\n};\n\n// Factory function ensures consistent object shapes\nconst createClassValidatorObject = (classGroupId, validator) => ({\n  classGroupId,\n  validator\n});\n// Factory ensures consistent ClassPartObject shape\nconst createClassPartObject = (nextPart = new Map(), validators = null, classGroupId) => ({\n  nextPart,\n  validators,\n  classGroupId\n});\nconst CLASS_PART_SEPARATOR = '-';\nconst EMPTY_CONFLICTS = [];\n// I use two dots here because one dot is used as prefix for class groups in plugins\nconst ARBITRARY_PROPERTY_PREFIX = 'arbitrary..';\nconst createClassGroupUtils = config => {\n  const classMap = createClassMap(config);\n  const {\n    conflictingClassGroups,\n    conflictingClassGroupModifiers\n  } = config;\n  const getClassGroupId = className => {\n    if (className.startsWith('[') && className.endsWith(']')) {\n      return getGroupIdForArbitraryProperty(className);\n    }\n    const classParts = className.split(CLASS_PART_SEPARATOR);\n    // Classes like `-inset-1` produce an empty string as first classPart. We assume that classes for negative values are used correctly and skip it.\n    const startIndex = classParts[0] === '' && classParts.length > 1 ? 1 : 0;\n    return getGroupRecursive(classParts, startIndex, classMap);\n  };\n  const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => {\n    if (hasPostfixModifier) {\n      const modifierConflicts = conflictingClassGroupModifiers[classGroupId];\n      const baseConflicts = conflictingClassGroups[classGroupId];\n      if (modifierConflicts) {\n        if (baseConflicts) {\n          // Merge base conflicts with modifier conflicts\n          return concatArrays(baseConflicts, modifierConflicts);\n        }\n        // Only modifier conflicts\n        return modifierConflicts;\n      }\n      // Fall back to without postfix if no modifier conflicts\n      return baseConflicts || EMPTY_CONFLICTS;\n    }\n    return conflictingClassGroups[classGroupId] || EMPTY_CONFLICTS;\n  };\n  return {\n    getClassGroupId,\n    getConflictingClassGroupIds\n  };\n};\nconst getGroupRecursive = (classParts, startIndex, classPartObject) => {\n  const classPathsLength = classParts.length - startIndex;\n  if (classPathsLength === 0) {\n    return classPartObject.classGroupId;\n  }\n  const currentClassPart = classParts[startIndex];\n  const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);\n  if (nextClassPartObject) {\n    const result = getGroupRecursive(classParts, startIndex + 1, nextClassPartObject);\n    if (result) return result;\n  }\n  const validators = classPartObject.validators;\n  if (validators === null) {\n    return undefined;\n  }\n  // Build classRest string efficiently by joining from startIndex onwards\n  const classRest = startIndex === 0 ? classParts.join(CLASS_PART_SEPARATOR) : classParts.slice(startIndex).join(CLASS_PART_SEPARATOR);\n  const validatorsLength = validators.length;\n  for (let i = 0; i < validatorsLength; i++) {\n    const validatorObj = validators[i];\n    if (validatorObj.validator(classRest)) {\n      return validatorObj.classGroupId;\n    }\n  }\n  return undefined;\n};\n/**\n * Get the class group ID for an arbitrary property.\n *\n * @param className - The class name to get the group ID for. Is expected to be string starting with `[` and ending with `]`.\n */\nconst getGroupIdForArbitraryProperty = className => className.slice(1, -1).indexOf(':') === -1 ? undefined : (() => {\n  const content = className.slice(1, -1);\n  const colonIndex = content.indexOf(':');\n  const property = content.slice(0, colonIndex);\n  return property ? ARBITRARY_PROPERTY_PREFIX + property : undefined;\n})();\n/**\n * Exported for testing only\n */\nconst createClassMap = config => {\n  const {\n    theme,\n    classGroups\n  } = config;\n  return processClassGroups(classGroups, theme);\n};\n// Split into separate functions to maintain monomorphic call sites\nconst processClassGroups = (classGroups, theme) => {\n  const classMap = createClassPartObject();\n  for (const classGroupId in classGroups) {\n    const group = classGroups[classGroupId];\n    processClassesRecursively(group, classMap, classGroupId, theme);\n  }\n  return classMap;\n};\nconst processClassesRecursively = (classGroup, classPartObject, classGroupId, theme) => {\n  const len = classGroup.length;\n  for (let i = 0; i < len; i++) {\n    const classDefinition = classGroup[i];\n    processClassDefinition(classDefinition, classPartObject, classGroupId, theme);\n  }\n};\n// Split into separate functions for each type to maintain monomorphic call sites\nconst processClassDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n  if (typeof classDefinition === 'string') {\n    processStringDefinition(classDefinition, classPartObject, classGroupId);\n    return;\n  }\n  if (typeof classDefinition === 'function') {\n    processFunctionDefinition(classDefinition, classPartObject, classGroupId, theme);\n    return;\n  }\n  processObjectDefinition(classDefinition, classPartObject, classGroupId, theme);\n};\nconst processStringDefinition = (classDefinition, classPartObject, classGroupId) => {\n  const classPartObjectToEdit = classDefinition === '' ? classPartObject : getPart(classPartObject, classDefinition);\n  classPartObjectToEdit.classGroupId = classGroupId;\n};\nconst processFunctionDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n  if (isThemeGetter(classDefinition)) {\n    processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);\n    return;\n  }\n  if (classPartObject.validators === null) {\n    classPartObject.validators = [];\n  }\n  classPartObject.validators.push(createClassValidatorObject(classGroupId, classDefinition));\n};\nconst processObjectDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n  const entries = Object.entries(classDefinition);\n  const len = entries.length;\n  for (let i = 0; i < len; i++) {\n    const [key, value] = entries[i];\n    processClassesRecursively(value, getPart(classPartObject, key), classGroupId, theme);\n  }\n};\nconst getPart = (classPartObject, path) => {\n  let current = classPartObject;\n  const parts = path.split(CLASS_PART_SEPARATOR);\n  const len = parts.length;\n  for (let i = 0; i < len; i++) {\n    const part = parts[i];\n    let next = current.nextPart.get(part);\n    if (!next) {\n      next = createClassPartObject();\n      current.nextPart.set(part, next);\n    }\n    current = next;\n  }\n  return current;\n};\n// Type guard maintains monomorphic check\nconst isThemeGetter = func => 'isThemeGetter' in func && func.isThemeGetter === true;\n\n// LRU cache implementation using plain objects for simplicity\nconst createLruCache = maxCacheSize => {\n  if (maxCacheSize < 1) {\n    return {\n      get: () => undefined,\n      set: () => {}\n    };\n  }\n  let cacheSize = 0;\n  let cache = Object.create(null);\n  let previousCache = Object.create(null);\n  const update = (key, value) => {\n    cache[key] = value;\n    cacheSize++;\n    if (cacheSize > maxCacheSize) {\n      cacheSize = 0;\n      previousCache = cache;\n      cache = Object.create(null);\n    }\n  };\n  return {\n    get(key) {\n      let value = cache[key];\n      if (value !== undefined) {\n        return value;\n      }\n      if ((value = previousCache[key]) !== undefined) {\n        update(key, value);\n        return value;\n      }\n    },\n    set(key, value) {\n      if (key in cache) {\n        cache[key] = value;\n      } else {\n        update(key, value);\n      }\n    }\n  };\n};\nconst IMPORTANT_MODIFIER = '!';\nconst MODIFIER_SEPARATOR = ':';\nconst EMPTY_MODIFIERS = [];\n// Pre-allocated result object shape for consistency\nconst createResultObject = (modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition, isExternal) => ({\n  modifiers,\n  hasImportantModifier,\n  baseClassName,\n  maybePostfixModifierPosition,\n  isExternal\n});\nconst createParseClassName = config => {\n  const {\n    prefix,\n    experimentalParseClassName\n  } = config;\n  /**\n   * Parse class name into parts.\n   *\n   * Inspired by `splitAtTopLevelOnly` used in Tailwind CSS\n   * @see https://github.com/tailwindlabs/tailwindcss/blob/v3.2.2/src/util/splitAtTopLevelOnly.js\n   */\n  let parseClassName = className => {\n    // Use simple array with push for better performance\n    const modifiers = [];\n    let bracketDepth = 0;\n    let parenDepth = 0;\n    let modifierStart = 0;\n    let postfixModifierPosition;\n    const len = className.length;\n    for (let index = 0; index < len; index++) {\n      const currentCharacter = className[index];\n      if (bracketDepth === 0 && parenDepth === 0) {\n        if (currentCharacter === MODIFIER_SEPARATOR) {\n          modifiers.push(className.slice(modifierStart, index));\n          modifierStart = index + 1;\n          continue;\n        }\n        if (currentCharacter === '/') {\n          postfixModifierPosition = index;\n          continue;\n        }\n      }\n      if (currentCharacter === '[') bracketDepth++;else if (currentCharacter === ']') bracketDepth--;else if (currentCharacter === '(') parenDepth++;else if (currentCharacter === ')') parenDepth--;\n    }\n    const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.slice(modifierStart);\n    // Inline important modifier check\n    let baseClassName = baseClassNameWithImportantModifier;\n    let hasImportantModifier = false;\n    if (baseClassNameWithImportantModifier.endsWith(IMPORTANT_MODIFIER)) {\n      baseClassName = baseClassNameWithImportantModifier.slice(0, -1);\n      hasImportantModifier = true;\n    } else if (\n    /**\n     * In Tailwind CSS v3 the important modifier was at the start of the base class name. This is still supported for legacy reasons.\n     * @see https://github.com/dcastil/tailwind-merge/issues/513#issuecomment-2614029864\n     */\n    baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER)) {\n      baseClassName = baseClassNameWithImportantModifier.slice(1);\n      hasImportantModifier = true;\n    }\n    const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : undefined;\n    return createResultObject(modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition);\n  };\n  if (prefix) {\n    const fullPrefix = prefix + MODIFIER_SEPARATOR;\n    const parseClassNameOriginal = parseClassName;\n    parseClassName = className => className.startsWith(fullPrefix) ? parseClassNameOriginal(className.slice(fullPrefix.length)) : createResultObject(EMPTY_MODIFIERS, false, className, undefined, true);\n  }\n  if (experimentalParseClassName) {\n    const parseClassNameOriginal = parseClassName;\n    parseClassName = className => experimentalParseClassName({\n      className,\n      parseClassName: parseClassNameOriginal\n    });\n  }\n  return parseClassName;\n};\n\n/**\n * Sorts modifiers according to following schema:\n * - Predefined modifiers are sorted alphabetically\n * - When an arbitrary variant appears, it must be preserved which modifiers are before and after it\n */\nconst createSortModifiers = config => {\n  // Pre-compute weights for all known modifiers for O(1) comparison\n  const modifierWeights = new Map();\n  // Assign weights to sensitive modifiers (highest priority, but preserve order)\n  config.orderSensitiveModifiers.forEach((mod, index) => {\n    modifierWeights.set(mod, 1000000 + index); // High weights for sensitive mods\n  });\n  return modifiers => {\n    const result = [];\n    let currentSegment = [];\n    // Process modifiers in one pass\n    for (let i = 0; i < modifiers.length; i++) {\n      const modifier = modifiers[i];\n      // Check if modifier is sensitive (starts with '[' or in orderSensitiveModifiers)\n      const isArbitrary = modifier[0] === '[';\n      const isOrderSensitive = modifierWeights.has(modifier);\n      if (isArbitrary || isOrderSensitive) {\n        // Sort and flush current segment alphabetically\n        if (currentSegment.length > 0) {\n          currentSegment.sort();\n          result.push(...currentSegment);\n          currentSegment = [];\n        }\n        result.push(modifier);\n      } else {\n        // Regular modifier - add to current segment for batch sorting\n        currentSegment.push(modifier);\n      }\n    }\n    // Sort and add any remaining segment items\n    if (currentSegment.length > 0) {\n      currentSegment.sort();\n      result.push(...currentSegment);\n    }\n    return result;\n  };\n};\nconst createConfigUtils = config => ({\n  cache: createLruCache(config.cacheSize),\n  parseClassName: createParseClassName(config),\n  sortModifiers: createSortModifiers(config),\n  ...createClassGroupUtils(config)\n});\nconst SPLIT_CLASSES_REGEX = /\\s+/;\nconst mergeClassList = (classList, configUtils) => {\n  const {\n    parseClassName,\n    getClassGroupId,\n    getConflictingClassGroupIds,\n    sortModifiers\n  } = configUtils;\n  /**\n   * Set of classGroupIds in following format:\n   * `{importantModifier}{variantModifiers}{classGroupId}`\n   * @example 'float'\n   * @example 'hover:focus:bg-color'\n   * @example 'md:!pr'\n   */\n  const classGroupsInConflict = [];\n  const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);\n  let result = '';\n  for (let index = classNames.length - 1; index >= 0; index -= 1) {\n    const originalClassName = classNames[index];\n    const {\n      isExternal,\n      modifiers,\n      hasImportantModifier,\n      baseClassName,\n      maybePostfixModifierPosition\n    } = parseClassName(originalClassName);\n    if (isExternal) {\n      result = originalClassName + (result.length > 0 ? ' ' + result : result);\n      continue;\n    }\n    let hasPostfixModifier = !!maybePostfixModifierPosition;\n    let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);\n    if (!classGroupId) {\n      if (!hasPostfixModifier) {\n        // Not a Tailwind class\n        result = originalClassName + (result.length > 0 ? ' ' + result : result);\n        continue;\n      }\n      classGroupId = getClassGroupId(baseClassName);\n      if (!classGroupId) {\n        // Not a Tailwind class\n        result = originalClassName + (result.length > 0 ? ' ' + result : result);\n        continue;\n      }\n      hasPostfixModifier = false;\n    }\n    // Fast path: skip sorting for empty or single modifier\n    const variantModifier = modifiers.length === 0 ? '' : modifiers.length === 1 ? modifiers[0] : sortModifiers(modifiers).join(':');\n    const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;\n    const classId = modifierId + classGroupId;\n    if (classGroupsInConflict.indexOf(classId) > -1) {\n      // Tailwind class omitted due to conflict\n      continue;\n    }\n    classGroupsInConflict.push(classId);\n    const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);\n    for (let i = 0; i < conflictGroups.length; ++i) {\n      const group = conflictGroups[i];\n      classGroupsInConflict.push(modifierId + group);\n    }\n    // Tailwind class not in conflict\n    result = originalClassName + (result.length > 0 ? ' ' + result : result);\n  }\n  return result;\n};\n\n/**\n * The code in this file is copied from https://github.com/lukeed/clsx and modified to suit the needs of tailwind-merge better.\n *\n * Specifically:\n * - Runtime code from https://github.com/lukeed/clsx/blob/v1.2.1/src/index.js\n * - TypeScript types from https://github.com/lukeed/clsx/blob/v1.2.1/clsx.d.ts\n *\n * Original code has MIT license: Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n */\nconst twJoin = (...classLists) => {\n  let index = 0;\n  let argument;\n  let resolvedValue;\n  let string = '';\n  while (index < classLists.length) {\n    if (argument = classLists[index++]) {\n      if (resolvedValue = toValue(argument)) {\n        string && (string += ' ');\n        string += resolvedValue;\n      }\n    }\n  }\n  return string;\n};\nconst toValue = mix => {\n  // Fast path for strings\n  if (typeof mix === 'string') {\n    return mix;\n  }\n  let resolvedValue;\n  let string = '';\n  for (let k = 0; k < mix.length; k++) {\n    if (mix[k]) {\n      if (resolvedValue = toValue(mix[k])) {\n        string && (string += ' ');\n        string += resolvedValue;\n      }\n    }\n  }\n  return string;\n};\nconst createTailwindMerge = (createConfigFirst, ...createConfigRest) => {\n  let configUtils;\n  let cacheGet;\n  let cacheSet;\n  let functionToCall;\n  const initTailwindMerge = classList => {\n    const config = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());\n    configUtils = createConfigUtils(config);\n    cacheGet = configUtils.cache.get;\n    cacheSet = configUtils.cache.set;\n    functionToCall = tailwindMerge;\n    return tailwindMerge(classList);\n  };\n  const tailwindMerge = classList => {\n    const cachedResult = cacheGet(classList);\n    if (cachedResult) {\n      return cachedResult;\n    }\n    const result = mergeClassList(classList, configUtils);\n    cacheSet(classList, result);\n    return result;\n  };\n  functionToCall = initTailwindMerge;\n  return (...args) => functionToCall(twJoin(...args));\n};\nconst fallbackThemeArr = [];\nconst fromTheme = key => {\n  const themeGetter = theme => theme[key] || fallbackThemeArr;\n  themeGetter.isThemeGetter = true;\n  return themeGetter;\n};\nconst arbitraryValueRegex = /^\\[(?:(\\w[\\w-]*):)?(.+)\\]$/i;\nconst arbitraryVariableRegex = /^\\((?:(\\w[\\w-]*):)?(.+)\\)$/i;\nconst fractionRegex = /^\\d+\\/\\d+$/;\nconst tshirtUnitRegex = /^(\\d+(\\.\\d+)?)?(xs|sm|md|lg|xl)$/;\nconst lengthUnitRegex = /\\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\\b(calc|min|max|clamp)\\(.+\\)|^0$/;\nconst colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\\(.+\\)$/;\n// Shadow always begins with x and y offset separated by underscore optionally prepended by inset\nconst shadowRegex = /^(inset_)?-?((\\d+)?\\.?(\\d+)[a-z]+|0)_-?((\\d+)?\\.?(\\d+)[a-z]+|0)/;\nconst imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\\(.+\\)$/;\nconst isFraction = value => fractionRegex.test(value);\nconst isNumber = value => !!value && !Number.isNaN(Number(value));\nconst isInteger = value => !!value && Number.isInteger(Number(value));\nconst isPercent = value => value.endsWith('%') && isNumber(value.slice(0, -1));\nconst isTshirtSize = value => tshirtUnitRegex.test(value);\nconst isAny = () => true;\nconst isLengthOnly = value =>\n// `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.\n// For example, `hsl(0 0% 0%)` would be classified as a length without this check.\n// I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.\nlengthUnitRegex.test(value) && !colorFunctionRegex.test(value);\nconst isNever = () => false;\nconst isShadow = value => shadowRegex.test(value);\nconst isImage = value => imageRegex.test(value);\nconst isAnyNonArbitrary = value => !isArbitraryValue(value) && !isArbitraryVariable(value);\nconst isArbitrarySize = value => getIsArbitraryValue(value, isLabelSize, isNever);\nconst isArbitraryValue = value => arbitraryValueRegex.test(value);\nconst isArbitraryLength = value => getIsArbitraryValue(value, isLabelLength, isLengthOnly);\nconst isArbitraryNumber = value => getIsArbitraryValue(value, isLabelNumber, isNumber);\nconst isArbitraryPosition = value => getIsArbitraryValue(value, isLabelPosition, isNever);\nconst isArbitraryImage = value => getIsArbitraryValue(value, isLabelImage, isImage);\nconst isArbitraryShadow = value => getIsArbitraryValue(value, isLabelShadow, isShadow);\nconst isArbitraryVariable = value => arbitraryVariableRegex.test(value);\nconst isArbitraryVariableLength = value => getIsArbitraryVariable(value, isLabelLength);\nconst isArbitraryVariableFamilyName = value => getIsArbitraryVariable(value, isLabelFamilyName);\nconst isArbitraryVariablePosition = value => getIsArbitraryVariable(value, isLabelPosition);\nconst isArbitraryVariableSize = value => getIsArbitraryVariable(value, isLabelSize);\nconst isArbitraryVariableImage = value => getIsArbitraryVariable(value, isLabelImage);\nconst isArbitraryVariableShadow = value => getIsArbitraryVariable(value, isLabelShadow, true);\n// Helpers\nconst getIsArbitraryValue = (value, testLabel, testValue) => {\n  const result = arbitraryValueRegex.exec(value);\n  if (result) {\n    if (result[1]) {\n      return testLabel(result[1]);\n    }\n    return testValue(result[2]);\n  }\n  return false;\n};\nconst getIsArbitraryVariable = (value, testLabel, shouldMatchNoLabel = false) => {\n  const result = arbitraryVariableRegex.exec(value);\n  if (result) {\n    if (result[1]) {\n      return testLabel(result[1]);\n    }\n    return shouldMatchNoLabel;\n  }\n  return false;\n};\n// Labels\nconst isLabelPosition = label => label === 'position' || label === 'percentage';\nconst isLabelImage = label => label === 'image' || label === 'url';\nconst isLabelSize = label => label === 'length' || label === 'size' || label === 'bg-size';\nconst isLabelLength = label => label === 'length';\nconst isLabelNumber = label => label === 'number';\nconst isLabelFamilyName = label => label === 'family-name';\nconst isLabelShadow = label => label === 'shadow';\nconst validators = /*#__PURE__*/Object.defineProperty({\n  __proto__: null,\n  isAny,\n  isAnyNonArbitrary,\n  isArbitraryImage,\n  isArbitraryLength,\n  isArbitraryNumber,\n  isArbitraryPosition,\n  isArbitraryShadow,\n  isArbitrarySize,\n  isArbitraryValue,\n  isArbitraryVariable,\n  isArbitraryVariableFamilyName,\n  isArbitraryVariableImage,\n  isArbitraryVariableLength,\n  isArbitraryVariablePosition,\n  isArbitraryVariableShadow,\n  isArbitraryVariableSize,\n  isFraction,\n  isInteger,\n  isNumber,\n  isPercent,\n  isTshirtSize\n}, Symbol.toStringTag, {\n  value: 'Module'\n});\nconst getDefaultConfig = () => {\n  /**\n   * Theme getters for theme variable namespaces\n   * @see https://tailwindcss.com/docs/theme#theme-variable-namespaces\n   */\n  /***/\n  const themeColor = fromTheme('color');\n  const themeFont = fromTheme('font');\n  const themeText = fromTheme('text');\n  const themeFontWeight = fromTheme('font-weight');\n  const themeTracking = fromTheme('tracking');\n  const themeLeading = fromTheme('leading');\n  const themeBreakpoint = fromTheme('breakpoint');\n  const themeContainer = fromTheme('container');\n  const themeSpacing = fromTheme('spacing');\n  const themeRadius = fromTheme('radius');\n  const themeShadow = fromTheme('shadow');\n  const themeInsetShadow = fromTheme('inset-shadow');\n  const themeTextShadow = fromTheme('text-shadow');\n  const themeDropShadow = fromTheme('drop-shadow');\n  const themeBlur = fromTheme('blur');\n  const themePerspective = fromTheme('perspective');\n  const themeAspect = fromTheme('aspect');\n  const themeEase = fromTheme('ease');\n  const themeAnimate = fromTheme('animate');\n  /**\n   * Helpers to avoid repeating the same scales\n   *\n   * We use functions that create a new array every time they're called instead of static arrays.\n   * This ensures that users who modify any scale by mutating the array (e.g. with `array.push(element)`) don't accidentally mutate arrays in other parts of the config.\n   */\n  /***/\n  const scaleBreak = () => ['auto', 'avoid', 'all', 'avoid-page', 'page', 'left', 'right', 'column'];\n  const scalePosition = () => ['center', 'top', 'bottom', 'left', 'right', 'top-left',\n  // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n  'left-top', 'top-right',\n  // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n  'right-top', 'bottom-right',\n  // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n  'right-bottom', 'bottom-left',\n  // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n  'left-bottom'];\n  const scalePositionWithArbitrary = () => [...scalePosition(), isArbitraryVariable, isArbitraryValue];\n  const scaleOverflow = () => ['auto', 'hidden', 'clip', 'visible', 'scroll'];\n  const scaleOverscroll = () => ['auto', 'contain', 'none'];\n  const scaleUnambiguousSpacing = () => [isArbitraryVariable, isArbitraryValue, themeSpacing];\n  const scaleInset = () => [isFraction, 'full', 'auto', ...scaleUnambiguousSpacing()];\n  const scaleGridTemplateColsRows = () => [isInteger, 'none', 'subgrid', isArbitraryVariable, isArbitraryValue];\n  const scaleGridColRowStartAndEnd = () => ['auto', {\n    span: ['full', isInteger, isArbitraryVariable, isArbitraryValue]\n  }, isInteger, isArbitraryVariable, isArbitraryValue];\n  const scaleGridColRowStartOrEnd = () => [isInteger, 'auto', isArbitraryVariable, isArbitraryValue];\n  const scaleGridAutoColsRows = () => ['auto', 'min', 'max', 'fr', isArbitraryVariable, isArbitraryValue];\n  const scaleAlignPrimaryAxis = () => ['start', 'end', 'center', 'between', 'around', 'evenly', 'stretch', 'baseline', 'center-safe', 'end-safe'];\n  const scaleAlignSecondaryAxis = () => ['start', 'end', 'center', 'stretch', 'center-safe', 'end-safe'];\n  const scaleMargin = () => ['auto', ...scaleUnambiguousSpacing()];\n  const scaleSizing = () => [isFraction, 'auto', 'full', 'dvw', 'dvh', 'lvw', 'lvh', 'svw', 'svh', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n  const scaleColor = () => [themeColor, isArbitraryVariable, isArbitraryValue];\n  const scaleBgPosition = () => [...scalePosition(), isArbitraryVariablePosition, isArbitraryPosition, {\n    position: [isArbitraryVariable, isArbitraryValue]\n  }];\n  const scaleBgRepeat = () => ['no-repeat', {\n    repeat: ['', 'x', 'y', 'space', 'round']\n  }];\n  const scaleBgSize = () => ['auto', 'cover', 'contain', isArbitraryVariableSize, isArbitrarySize, {\n    size: [isArbitraryVariable, isArbitraryValue]\n  }];\n  const scaleGradientStopPosition = () => [isPercent, isArbitraryVariableLength, isArbitraryLength];\n  const scaleRadius = () => [\n  // Deprecated since Tailwind CSS v4.0.0\n  '', 'none', 'full', themeRadius, isArbitraryVariable, isArbitraryValue];\n  const scaleBorderWidth = () => ['', isNumber, isArbitraryVariableLength, isArbitraryLength];\n  const scaleLineStyle = () => ['solid', 'dashed', 'dotted', 'double'];\n  const scaleBlendMode = () => ['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'];\n  const scaleMaskImagePosition = () => [isNumber, isPercent, isArbitraryVariablePosition, isArbitraryPosition];\n  const scaleBlur = () => [\n  // Deprecated since Tailwind CSS v4.0.0\n  '', 'none', themeBlur, isArbitraryVariable, isArbitraryValue];\n  const scaleRotate = () => ['none', isNumber, isArbitraryVariable, isArbitraryValue];\n  const scaleScale = () => ['none', isNumber, isArbitraryVariable, isArbitraryValue];\n  const scaleSkew = () => [isNumber, isArbitraryVariable, isArbitraryValue];\n  const scaleTranslate = () => [isFraction, 'full', ...scaleUnambiguousSpacing()];\n  return {\n    cacheSize: 500,\n    theme: {\n      animate: ['spin', 'ping', 'pulse', 'bounce'],\n      aspect: ['video'],\n      blur: [isTshirtSize],\n      breakpoint: [isTshirtSize],\n      color: [isAny],\n      container: [isTshirtSize],\n      'drop-shadow': [isTshirtSize],\n      ease: ['in', 'out', 'in-out'],\n      font: [isAnyNonArbitrary],\n      'font-weight': ['thin', 'extralight', 'light', 'normal', 'medium', 'semibold', 'bold', 'extrabold', 'black'],\n      'inset-shadow': [isTshirtSize],\n      leading: ['none', 'tight', 'snug', 'normal', 'relaxed', 'loose'],\n      perspective: ['dramatic', 'near', 'normal', 'midrange', 'distant', 'none'],\n      radius: [isTshirtSize],\n      shadow: [isTshirtSize],\n      spacing: ['px', isNumber],\n      text: [isTshirtSize],\n      'text-shadow': [isTshirtSize],\n      tracking: ['tighter', 'tight', 'normal', 'wide', 'wider', 'widest']\n    },\n    classGroups: {\n      // --------------\n      // --- Layout ---\n      // --------------\n      /**\n       * Aspect Ratio\n       * @see https://tailwindcss.com/docs/aspect-ratio\n       */\n      aspect: [{\n        aspect: ['auto', 'square', isFraction, isArbitraryValue, isArbitraryVariable, themeAspect]\n      }],\n      /**\n       * Container\n       * @see https://tailwindcss.com/docs/container\n       * @deprecated since Tailwind CSS v4.0.0\n       */\n      container: ['container'],\n      /**\n       * Columns\n       * @see https://tailwindcss.com/docs/columns\n       */\n      columns: [{\n        columns: [isNumber, isArbitraryValue, isArbitraryVariable, themeContainer]\n      }],\n      /**\n       * Break After\n       * @see https://tailwindcss.com/docs/break-after\n       */\n      'break-after': [{\n        'break-after': scaleBreak()\n      }],\n      /**\n       * Break Before\n       * @see https://tailwindcss.com/docs/break-before\n       */\n      'break-before': [{\n        'break-before': scaleBreak()\n      }],\n      /**\n       * Break Inside\n       * @see https://tailwindcss.com/docs/break-inside\n       */\n      'break-inside': [{\n        'break-inside': ['auto', 'avoid', 'avoid-page', 'avoid-column']\n      }],\n      /**\n       * Box Decoration Break\n       * @see https://tailwindcss.com/docs/box-decoration-break\n       */\n      'box-decoration': [{\n        'box-decoration': ['slice', 'clone']\n      }],\n      /**\n       * Box Sizing\n       * @see https://tailwindcss.com/docs/box-sizing\n       */\n      box: [{\n        box: ['border', 'content']\n      }],\n      /**\n       * Display\n       * @see https://tailwindcss.com/docs/display\n       */\n      display: ['block', 'inline-block', 'inline', 'flex', 'inline-flex', 'table', 'inline-table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row-group', 'table-row', 'flow-root', 'grid', 'inline-grid', 'contents', 'list-item', 'hidden'],\n      /**\n       * Screen Reader Only\n       * @see https://tailwindcss.com/docs/display#screen-reader-only\n       */\n      sr: ['sr-only', 'not-sr-only'],\n      /**\n       * Floats\n       * @see https://tailwindcss.com/docs/float\n       */\n      float: [{\n        float: ['right', 'left', 'none', 'start', 'end']\n      }],\n      /**\n       * Clear\n       * @see https://tailwindcss.com/docs/clear\n       */\n      clear: [{\n        clear: ['left', 'right', 'both', 'none', 'start', 'end']\n      }],\n      /**\n       * Isolation\n       * @see https://tailwindcss.com/docs/isolation\n       */\n      isolation: ['isolate', 'isolation-auto'],\n      /**\n       * Object Fit\n       * @see https://tailwindcss.com/docs/object-fit\n       */\n      'object-fit': [{\n        object: ['contain', 'cover', 'fill', 'none', 'scale-down']\n      }],\n      /**\n       * Object Position\n       * @see https://tailwindcss.com/docs/object-position\n       */\n      'object-position': [{\n        object: scalePositionWithArbitrary()\n      }],\n      /**\n       * Overflow\n       * @see https://tailwindcss.com/docs/overflow\n       */\n      overflow: [{\n        overflow: scaleOverflow()\n      }],\n      /**\n       * Overflow X\n       * @see https://tailwindcss.com/docs/overflow\n       */\n      'overflow-x': [{\n        'overflow-x': scaleOverflow()\n      }],\n      /**\n       * Overflow Y\n       * @see https://tailwindcss.com/docs/overflow\n       */\n      'overflow-y': [{\n        'overflow-y': scaleOverflow()\n      }],\n      /**\n       * Overscroll Behavior\n       * @see https://tailwindcss.com/docs/overscroll-behavior\n       */\n      overscroll: [{\n        overscroll: scaleOverscroll()\n      }],\n      /**\n       * Overscroll Behavior X\n       * @see https://tailwindcss.com/docs/overscroll-behavior\n       */\n      'overscroll-x': [{\n        'overscroll-x': scaleOverscroll()\n      }],\n      /**\n       * Overscroll Behavior Y\n       * @see https://tailwindcss.com/docs/overscroll-behavior\n       */\n      'overscroll-y': [{\n        'overscroll-y': scaleOverscroll()\n      }],\n      /**\n       * Position\n       * @see https://tailwindcss.com/docs/position\n       */\n      position: ['static', 'fixed', 'absolute', 'relative', 'sticky'],\n      /**\n       * Top / Right / Bottom / Left\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      inset: [{\n        inset: scaleInset()\n      }],\n      /**\n       * Right / Left\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      'inset-x': [{\n        'inset-x': scaleInset()\n      }],\n      /**\n       * Top / Bottom\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      'inset-y': [{\n        'inset-y': scaleInset()\n      }],\n      /**\n       * Start\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      start: [{\n        start: scaleInset()\n      }],\n      /**\n       * End\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      end: [{\n        end: scaleInset()\n      }],\n      /**\n       * Top\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      top: [{\n        top: scaleInset()\n      }],\n      /**\n       * Right\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      right: [{\n        right: scaleInset()\n      }],\n      /**\n       * Bottom\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      bottom: [{\n        bottom: scaleInset()\n      }],\n      /**\n       * Left\n       * @see https://tailwindcss.com/docs/top-right-bottom-left\n       */\n      left: [{\n        left: scaleInset()\n      }],\n      /**\n       * Visibility\n       * @see https://tailwindcss.com/docs/visibility\n       */\n      visibility: ['visible', 'invisible', 'collapse'],\n      /**\n       * Z-Index\n       * @see https://tailwindcss.com/docs/z-index\n       */\n      z: [{\n        z: [isInteger, 'auto', isArbitraryVariable, isArbitraryValue]\n      }],\n      // ------------------------\n      // --- Flexbox and Grid ---\n      // ------------------------\n      /**\n       * Flex Basis\n       * @see https://tailwindcss.com/docs/flex-basis\n       */\n      basis: [{\n        basis: [isFraction, 'full', 'auto', themeContainer, ...scaleUnambiguousSpacing()]\n      }],\n      /**\n       * Flex Direction\n       * @see https://tailwindcss.com/docs/flex-direction\n       */\n      'flex-direction': [{\n        flex: ['row', 'row-reverse', 'col', 'col-reverse']\n      }],\n      /**\n       * Flex Wrap\n       * @see https://tailwindcss.com/docs/flex-wrap\n       */\n      'flex-wrap': [{\n        flex: ['nowrap', 'wrap', 'wrap-reverse']\n      }],\n      /**\n       * Flex\n       * @see https://tailwindcss.com/docs/flex\n       */\n      flex: [{\n        flex: [isNumber, isFraction, 'auto', 'initial', 'none', isArbitraryValue]\n      }],\n      /**\n       * Flex Grow\n       * @see https://tailwindcss.com/docs/flex-grow\n       */\n      grow: [{\n        grow: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Flex Shrink\n       * @see https://tailwindcss.com/docs/flex-shrink\n       */\n      shrink: [{\n        shrink: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Order\n       * @see https://tailwindcss.com/docs/order\n       */\n      order: [{\n        order: [isInteger, 'first', 'last', 'none', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Grid Template Columns\n       * @see https://tailwindcss.com/docs/grid-template-columns\n       */\n      'grid-cols': [{\n        'grid-cols': scaleGridTemplateColsRows()\n      }],\n      /**\n       * Grid Column Start / End\n       * @see https://tailwindcss.com/docs/grid-column\n       */\n      'col-start-end': [{\n        col: scaleGridColRowStartAndEnd()\n      }],\n      /**\n       * Grid Column Start\n       * @see https://tailwindcss.com/docs/grid-column\n       */\n      'col-start': [{\n        'col-start': scaleGridColRowStartOrEnd()\n      }],\n      /**\n       * Grid Column End\n       * @see https://tailwindcss.com/docs/grid-column\n       */\n      'col-end': [{\n        'col-end': scaleGridColRowStartOrEnd()\n      }],\n      /**\n       * Grid Template Rows\n       * @see https://tailwindcss.com/docs/grid-template-rows\n       */\n      'grid-rows': [{\n        'grid-rows': scaleGridTemplateColsRows()\n      }],\n      /**\n       * Grid Row Start / End\n       * @see https://tailwindcss.com/docs/grid-row\n       */\n      'row-start-end': [{\n        row: scaleGridColRowStartAndEnd()\n      }],\n      /**\n       * Grid Row Start\n       * @see https://tailwindcss.com/docs/grid-row\n       */\n      'row-start': [{\n        'row-start': scaleGridColRowStartOrEnd()\n      }],\n      /**\n       * Grid Row End\n       * @see https://tailwindcss.com/docs/grid-row\n       */\n      'row-end': [{\n        'row-end': scaleGridColRowStartOrEnd()\n      }],\n      /**\n       * Grid Auto Flow\n       * @see https://tailwindcss.com/docs/grid-auto-flow\n       */\n      'grid-flow': [{\n        'grid-flow': ['row', 'col', 'dense', 'row-dense', 'col-dense']\n      }],\n      /**\n       * Grid Auto Columns\n       * @see https://tailwindcss.com/docs/grid-auto-columns\n       */\n      'auto-cols': [{\n        'auto-cols': scaleGridAutoColsRows()\n      }],\n      /**\n       * Grid Auto Rows\n       * @see https://tailwindcss.com/docs/grid-auto-rows\n       */\n      'auto-rows': [{\n        'auto-rows': scaleGridAutoColsRows()\n      }],\n      /**\n       * Gap\n       * @see https://tailwindcss.com/docs/gap\n       */\n      gap: [{\n        gap: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Gap X\n       * @see https://tailwindcss.com/docs/gap\n       */\n      'gap-x': [{\n        'gap-x': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Gap Y\n       * @see https://tailwindcss.com/docs/gap\n       */\n      'gap-y': [{\n        'gap-y': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Justify Content\n       * @see https://tailwindcss.com/docs/justify-content\n       */\n      'justify-content': [{\n        justify: [...scaleAlignPrimaryAxis(), 'normal']\n      }],\n      /**\n       * Justify Items\n       * @see https://tailwindcss.com/docs/justify-items\n       */\n      'justify-items': [{\n        'justify-items': [...scaleAlignSecondaryAxis(), 'normal']\n      }],\n      /**\n       * Justify Self\n       * @see https://tailwindcss.com/docs/justify-self\n       */\n      'justify-self': [{\n        'justify-self': ['auto', ...scaleAlignSecondaryAxis()]\n      }],\n      /**\n       * Align Content\n       * @see https://tailwindcss.com/docs/align-content\n       */\n      'align-content': [{\n        content: ['normal', ...scaleAlignPrimaryAxis()]\n      }],\n      /**\n       * Align Items\n       * @see https://tailwindcss.com/docs/align-items\n       */\n      'align-items': [{\n        items: [...scaleAlignSecondaryAxis(), {\n          baseline: ['', 'last']\n        }]\n      }],\n      /**\n       * Align Self\n       * @see https://tailwindcss.com/docs/align-self\n       */\n      'align-self': [{\n        self: ['auto', ...scaleAlignSecondaryAxis(), {\n          baseline: ['', 'last']\n        }]\n      }],\n      /**\n       * Place Content\n       * @see https://tailwindcss.com/docs/place-content\n       */\n      'place-content': [{\n        'place-content': scaleAlignPrimaryAxis()\n      }],\n      /**\n       * Place Items\n       * @see https://tailwindcss.com/docs/place-items\n       */\n      'place-items': [{\n        'place-items': [...scaleAlignSecondaryAxis(), 'baseline']\n      }],\n      /**\n       * Place Self\n       * @see https://tailwindcss.com/docs/place-self\n       */\n      'place-self': [{\n        'place-self': ['auto', ...scaleAlignSecondaryAxis()]\n      }],\n      // Spacing\n      /**\n       * Padding\n       * @see https://tailwindcss.com/docs/padding\n       */\n      p: [{\n        p: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding X\n       * @see https://tailwindcss.com/docs/padding\n       */\n      px: [{\n        px: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding Y\n       * @see https://tailwindcss.com/docs/padding\n       */\n      py: [{\n        py: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding Start\n       * @see https://tailwindcss.com/docs/padding\n       */\n      ps: [{\n        ps: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding End\n       * @see https://tailwindcss.com/docs/padding\n       */\n      pe: [{\n        pe: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding Top\n       * @see https://tailwindcss.com/docs/padding\n       */\n      pt: [{\n        pt: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding Right\n       * @see https://tailwindcss.com/docs/padding\n       */\n      pr: [{\n        pr: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding Bottom\n       * @see https://tailwindcss.com/docs/padding\n       */\n      pb: [{\n        pb: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Padding Left\n       * @see https://tailwindcss.com/docs/padding\n       */\n      pl: [{\n        pl: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Margin\n       * @see https://tailwindcss.com/docs/margin\n       */\n      m: [{\n        m: scaleMargin()\n      }],\n      /**\n       * Margin X\n       * @see https://tailwindcss.com/docs/margin\n       */\n      mx: [{\n        mx: scaleMargin()\n      }],\n      /**\n       * Margin Y\n       * @see https://tailwindcss.com/docs/margin\n       */\n      my: [{\n        my: scaleMargin()\n      }],\n      /**\n       * Margin Start\n       * @see https://tailwindcss.com/docs/margin\n       */\n      ms: [{\n        ms: scaleMargin()\n      }],\n      /**\n       * Margin End\n       * @see https://tailwindcss.com/docs/margin\n       */\n      me: [{\n        me: scaleMargin()\n      }],\n      /**\n       * Margin Top\n       * @see https://tailwindcss.com/docs/margin\n       */\n      mt: [{\n        mt: scaleMargin()\n      }],\n      /**\n       * Margin Right\n       * @see https://tailwindcss.com/docs/margin\n       */\n      mr: [{\n        mr: scaleMargin()\n      }],\n      /**\n       * Margin Bottom\n       * @see https://tailwindcss.com/docs/margin\n       */\n      mb: [{\n        mb: scaleMargin()\n      }],\n      /**\n       * Margin Left\n       * @see https://tailwindcss.com/docs/margin\n       */\n      ml: [{\n        ml: scaleMargin()\n      }],\n      /**\n       * Space Between X\n       * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n       */\n      'space-x': [{\n        'space-x': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Space Between X Reverse\n       * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n       */\n      'space-x-reverse': ['space-x-reverse'],\n      /**\n       * Space Between Y\n       * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n       */\n      'space-y': [{\n        'space-y': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Space Between Y Reverse\n       * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n       */\n      'space-y-reverse': ['space-y-reverse'],\n      // --------------\n      // --- Sizing ---\n      // --------------\n      /**\n       * Size\n       * @see https://tailwindcss.com/docs/width#setting-both-width-and-height\n       */\n      size: [{\n        size: scaleSizing()\n      }],\n      /**\n       * Width\n       * @see https://tailwindcss.com/docs/width\n       */\n      w: [{\n        w: [themeContainer, 'screen', ...scaleSizing()]\n      }],\n      /**\n       * Min-Width\n       * @see https://tailwindcss.com/docs/min-width\n       */\n      'min-w': [{\n        'min-w': [themeContainer, 'screen', /** Deprecated. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n        'none', ...scaleSizing()]\n      }],\n      /**\n       * Max-Width\n       * @see https://tailwindcss.com/docs/max-width\n       */\n      'max-w': [{\n        'max-w': [themeContainer, 'screen', 'none', /** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n        'prose', /** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n        {\n          screen: [themeBreakpoint]\n        }, ...scaleSizing()]\n      }],\n      /**\n       * Height\n       * @see https://tailwindcss.com/docs/height\n       */\n      h: [{\n        h: ['screen', 'lh', ...scaleSizing()]\n      }],\n      /**\n       * Min-Height\n       * @see https://tailwindcss.com/docs/min-height\n       */\n      'min-h': [{\n        'min-h': ['screen', 'lh', 'none', ...scaleSizing()]\n      }],\n      /**\n       * Max-Height\n       * @see https://tailwindcss.com/docs/max-height\n       */\n      'max-h': [{\n        'max-h': ['screen', 'lh', ...scaleSizing()]\n      }],\n      // ------------------\n      // --- Typography ---\n      // ------------------\n      /**\n       * Font Size\n       * @see https://tailwindcss.com/docs/font-size\n       */\n      'font-size': [{\n        text: ['base', themeText, isArbitraryVariableLength, isArbitraryLength]\n      }],\n      /**\n       * Font Smoothing\n       * @see https://tailwindcss.com/docs/font-smoothing\n       */\n      'font-smoothing': ['antialiased', 'subpixel-antialiased'],\n      /**\n       * Font Style\n       * @see https://tailwindcss.com/docs/font-style\n       */\n      'font-style': ['italic', 'not-italic'],\n      /**\n       * Font Weight\n       * @see https://tailwindcss.com/docs/font-weight\n       */\n      'font-weight': [{\n        font: [themeFontWeight, isArbitraryVariable, isArbitraryNumber]\n      }],\n      /**\n       * Font Stretch\n       * @see https://tailwindcss.com/docs/font-stretch\n       */\n      'font-stretch': [{\n        'font-stretch': ['ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded', isPercent, isArbitraryValue]\n      }],\n      /**\n       * Font Family\n       * @see https://tailwindcss.com/docs/font-family\n       */\n      'font-family': [{\n        font: [isArbitraryVariableFamilyName, isArbitraryValue, themeFont]\n      }],\n      /**\n       * Font Variant Numeric\n       * @see https://tailwindcss.com/docs/font-variant-numeric\n       */\n      'fvn-normal': ['normal-nums'],\n      /**\n       * Font Variant Numeric\n       * @see https://tailwindcss.com/docs/font-variant-numeric\n       */\n      'fvn-ordinal': ['ordinal'],\n      /**\n       * Font Variant Numeric\n       * @see https://tailwindcss.com/docs/font-variant-numeric\n       */\n      'fvn-slashed-zero': ['slashed-zero'],\n      /**\n       * Font Variant Numeric\n       * @see https://tailwindcss.com/docs/font-variant-numeric\n       */\n      'fvn-figure': ['lining-nums', 'oldstyle-nums'],\n      /**\n       * Font Variant Numeric\n       * @see https://tailwindcss.com/docs/font-variant-numeric\n       */\n      'fvn-spacing': ['proportional-nums', 'tabular-nums'],\n      /**\n       * Font Variant Numeric\n       * @see https://tailwindcss.com/docs/font-variant-numeric\n       */\n      'fvn-fraction': ['diagonal-fractions', 'stacked-fractions'],\n      /**\n       * Letter Spacing\n       * @see https://tailwindcss.com/docs/letter-spacing\n       */\n      tracking: [{\n        tracking: [themeTracking, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Line Clamp\n       * @see https://tailwindcss.com/docs/line-clamp\n       */\n      'line-clamp': [{\n        'line-clamp': [isNumber, 'none', isArbitraryVariable, isArbitraryNumber]\n      }],\n      /**\n       * Line Height\n       * @see https://tailwindcss.com/docs/line-height\n       */\n      leading: [{\n        leading: [/** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n        themeLeading, ...scaleUnambiguousSpacing()]\n      }],\n      /**\n       * List Style Image\n       * @see https://tailwindcss.com/docs/list-style-image\n       */\n      'list-image': [{\n        'list-image': ['none', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * List Style Position\n       * @see https://tailwindcss.com/docs/list-style-position\n       */\n      'list-style-position': [{\n        list: ['inside', 'outside']\n      }],\n      /**\n       * List Style Type\n       * @see https://tailwindcss.com/docs/list-style-type\n       */\n      'list-style-type': [{\n        list: ['disc', 'decimal', 'none', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Text Alignment\n       * @see https://tailwindcss.com/docs/text-align\n       */\n      'text-alignment': [{\n        text: ['left', 'center', 'right', 'justify', 'start', 'end']\n      }],\n      /**\n       * Placeholder Color\n       * @deprecated since Tailwind CSS v3.0.0\n       * @see https://v3.tailwindcss.com/docs/placeholder-color\n       */\n      'placeholder-color': [{\n        placeholder: scaleColor()\n      }],\n      /**\n       * Text Color\n       * @see https://tailwindcss.com/docs/text-color\n       */\n      'text-color': [{\n        text: scaleColor()\n      }],\n      /**\n       * Text Decoration\n       * @see https://tailwindcss.com/docs/text-decoration\n       */\n      'text-decoration': ['underline', 'overline', 'line-through', 'no-underline'],\n      /**\n       * Text Decoration Style\n       * @see https://tailwindcss.com/docs/text-decoration-style\n       */\n      'text-decoration-style': [{\n        decoration: [...scaleLineStyle(), 'wavy']\n      }],\n      /**\n       * Text Decoration Thickness\n       * @see https://tailwindcss.com/docs/text-decoration-thickness\n       */\n      'text-decoration-thickness': [{\n        decoration: [isNumber, 'from-font', 'auto', isArbitraryVariable, isArbitraryLength]\n      }],\n      /**\n       * Text Decoration Color\n       * @see https://tailwindcss.com/docs/text-decoration-color\n       */\n      'text-decoration-color': [{\n        decoration: scaleColor()\n      }],\n      /**\n       * Text Underline Offset\n       * @see https://tailwindcss.com/docs/text-underline-offset\n       */\n      'underline-offset': [{\n        'underline-offset': [isNumber, 'auto', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Text Transform\n       * @see https://tailwindcss.com/docs/text-transform\n       */\n      'text-transform': ['uppercase', 'lowercase', 'capitalize', 'normal-case'],\n      /**\n       * Text Overflow\n       * @see https://tailwindcss.com/docs/text-overflow\n       */\n      'text-overflow': ['truncate', 'text-ellipsis', 'text-clip'],\n      /**\n       * Text Wrap\n       * @see https://tailwindcss.com/docs/text-wrap\n       */\n      'text-wrap': [{\n        text: ['wrap', 'nowrap', 'balance', 'pretty']\n      }],\n      /**\n       * Text Indent\n       * @see https://tailwindcss.com/docs/text-indent\n       */\n      indent: [{\n        indent: scaleUnambiguousSpacing()\n      }],\n      /**\n       * Vertical Alignment\n       * @see https://tailwindcss.com/docs/vertical-align\n       */\n      'vertical-align': [{\n        align: ['baseline', 'top', 'middle', 'bottom', 'text-top', 'text-bottom', 'sub', 'super', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Whitespace\n       * @see https://tailwindcss.com/docs/whitespace\n       */\n      whitespace: [{\n        whitespace: ['normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap', 'break-spaces']\n      }],\n      /**\n       * Word Break\n       * @see https://tailwindcss.com/docs/word-break\n       */\n      break: [{\n        break: ['normal', 'words', 'all', 'keep']\n      }],\n      /**\n       * Overflow Wrap\n       * @see https://tailwindcss.com/docs/overflow-wrap\n       */\n      wrap: [{\n        wrap: ['break-word', 'anywhere', 'normal']\n      }],\n      /**\n       * Hyphens\n       * @see https://tailwindcss.com/docs/hyphens\n       */\n      hyphens: [{\n        hyphens: ['none', 'manual', 'auto']\n      }],\n      /**\n       * Content\n       * @see https://tailwindcss.com/docs/content\n       */\n      content: [{\n        content: ['none', isArbitraryVariable, isArbitraryValue]\n      }],\n      // -------------------\n      // --- Backgrounds ---\n      // -------------------\n      /**\n       * Background Attachment\n       * @see https://tailwindcss.com/docs/background-attachment\n       */\n      'bg-attachment': [{\n        bg: ['fixed', 'local', 'scroll']\n      }],\n      /**\n       * Background Clip\n       * @see https://tailwindcss.com/docs/background-clip\n       */\n      'bg-clip': [{\n        'bg-clip': ['border', 'padding', 'content', 'text']\n      }],\n      /**\n       * Background Origin\n       * @see https://tailwindcss.com/docs/background-origin\n       */\n      'bg-origin': [{\n        'bg-origin': ['border', 'padding', 'content']\n      }],\n      /**\n       * Background Position\n       * @see https://tailwindcss.com/docs/background-position\n       */\n      'bg-position': [{\n        bg: scaleBgPosition()\n      }],\n      /**\n       * Background Repeat\n       * @see https://tailwindcss.com/docs/background-repeat\n       */\n      'bg-repeat': [{\n        bg: scaleBgRepeat()\n      }],\n      /**\n       * Background Size\n       * @see https://tailwindcss.com/docs/background-size\n       */\n      'bg-size': [{\n        bg: scaleBgSize()\n      }],\n      /**\n       * Background Image\n       * @see https://tailwindcss.com/docs/background-image\n       */\n      'bg-image': [{\n        bg: ['none', {\n          linear: [{\n            to: ['t', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl']\n          }, isInteger, isArbitraryVariable, isArbitraryValue],\n          radial: ['', isArbitraryVariable, isArbitraryValue],\n          conic: [isInteger, isArbitraryVariable, isArbitraryValue]\n        }, isArbitraryVariableImage, isArbitraryImage]\n      }],\n      /**\n       * Background Color\n       * @see https://tailwindcss.com/docs/background-color\n       */\n      'bg-color': [{\n        bg: scaleColor()\n      }],\n      /**\n       * Gradient Color Stops From Position\n       * @see https://tailwindcss.com/docs/gradient-color-stops\n       */\n      'gradient-from-pos': [{\n        from: scaleGradientStopPosition()\n      }],\n      /**\n       * Gradient Color Stops Via Position\n       * @see https://tailwindcss.com/docs/gradient-color-stops\n       */\n      'gradient-via-pos': [{\n        via: scaleGradientStopPosition()\n      }],\n      /**\n       * Gradient Color Stops To Position\n       * @see https://tailwindcss.com/docs/gradient-color-stops\n       */\n      'gradient-to-pos': [{\n        to: scaleGradientStopPosition()\n      }],\n      /**\n       * Gradient Color Stops From\n       * @see https://tailwindcss.com/docs/gradient-color-stops\n       */\n      'gradient-from': [{\n        from: scaleColor()\n      }],\n      /**\n       * Gradient Color Stops Via\n       * @see https://tailwindcss.com/docs/gradient-color-stops\n       */\n      'gradient-via': [{\n        via: scaleColor()\n      }],\n      /**\n       * Gradient Color Stops To\n       * @see https://tailwindcss.com/docs/gradient-color-stops\n       */\n      'gradient-to': [{\n        to: scaleColor()\n      }],\n      // ---------------\n      // --- Borders ---\n      // ---------------\n      /**\n       * Border Radius\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      rounded: [{\n        rounded: scaleRadius()\n      }],\n      /**\n       * Border Radius Start\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-s': [{\n        'rounded-s': scaleRadius()\n      }],\n      /**\n       * Border Radius End\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-e': [{\n        'rounded-e': scaleRadius()\n      }],\n      /**\n       * Border Radius Top\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-t': [{\n        'rounded-t': scaleRadius()\n      }],\n      /**\n       * Border Radius Right\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-r': [{\n        'rounded-r': scaleRadius()\n      }],\n      /**\n       * Border Radius Bottom\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-b': [{\n        'rounded-b': scaleRadius()\n      }],\n      /**\n       * Border Radius Left\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-l': [{\n        'rounded-l': scaleRadius()\n      }],\n      /**\n       * Border Radius Start Start\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-ss': [{\n        'rounded-ss': scaleRadius()\n      }],\n      /**\n       * Border Radius Start End\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-se': [{\n        'rounded-se': scaleRadius()\n      }],\n      /**\n       * Border Radius End End\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-ee': [{\n        'rounded-ee': scaleRadius()\n      }],\n      /**\n       * Border Radius End Start\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-es': [{\n        'rounded-es': scaleRadius()\n      }],\n      /**\n       * Border Radius Top Left\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-tl': [{\n        'rounded-tl': scaleRadius()\n      }],\n      /**\n       * Border Radius Top Right\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-tr': [{\n        'rounded-tr': scaleRadius()\n      }],\n      /**\n       * Border Radius Bottom Right\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-br': [{\n        'rounded-br': scaleRadius()\n      }],\n      /**\n       * Border Radius Bottom Left\n       * @see https://tailwindcss.com/docs/border-radius\n       */\n      'rounded-bl': [{\n        'rounded-bl': scaleRadius()\n      }],\n      /**\n       * Border Width\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w': [{\n        border: scaleBorderWidth()\n      }],\n      /**\n       * Border Width X\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-x': [{\n        'border-x': scaleBorderWidth()\n      }],\n      /**\n       * Border Width Y\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-y': [{\n        'border-y': scaleBorderWidth()\n      }],\n      /**\n       * Border Width Start\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-s': [{\n        'border-s': scaleBorderWidth()\n      }],\n      /**\n       * Border Width End\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-e': [{\n        'border-e': scaleBorderWidth()\n      }],\n      /**\n       * Border Width Top\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-t': [{\n        'border-t': scaleBorderWidth()\n      }],\n      /**\n       * Border Width Right\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-r': [{\n        'border-r': scaleBorderWidth()\n      }],\n      /**\n       * Border Width Bottom\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-b': [{\n        'border-b': scaleBorderWidth()\n      }],\n      /**\n       * Border Width Left\n       * @see https://tailwindcss.com/docs/border-width\n       */\n      'border-w-l': [{\n        'border-l': scaleBorderWidth()\n      }],\n      /**\n       * Divide Width X\n       * @see https://tailwindcss.com/docs/border-width#between-children\n       */\n      'divide-x': [{\n        'divide-x': scaleBorderWidth()\n      }],\n      /**\n       * Divide Width X Reverse\n       * @see https://tailwindcss.com/docs/border-width#between-children\n       */\n      'divide-x-reverse': ['divide-x-reverse'],\n      /**\n       * Divide Width Y\n       * @see https://tailwindcss.com/docs/border-width#between-children\n       */\n      'divide-y': [{\n        'divide-y': scaleBorderWidth()\n      }],\n      /**\n       * Divide Width Y Reverse\n       * @see https://tailwindcss.com/docs/border-width#between-children\n       */\n      'divide-y-reverse': ['divide-y-reverse'],\n      /**\n       * Border Style\n       * @see https://tailwindcss.com/docs/border-style\n       */\n      'border-style': [{\n        border: [...scaleLineStyle(), 'hidden', 'none']\n      }],\n      /**\n       * Divide Style\n       * @see https://tailwindcss.com/docs/border-style#setting-the-divider-style\n       */\n      'divide-style': [{\n        divide: [...scaleLineStyle(), 'hidden', 'none']\n      }],\n      /**\n       * Border Color\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color': [{\n        border: scaleColor()\n      }],\n      /**\n       * Border Color X\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-x': [{\n        'border-x': scaleColor()\n      }],\n      /**\n       * Border Color Y\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-y': [{\n        'border-y': scaleColor()\n      }],\n      /**\n       * Border Color S\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-s': [{\n        'border-s': scaleColor()\n      }],\n      /**\n       * Border Color E\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-e': [{\n        'border-e': scaleColor()\n      }],\n      /**\n       * Border Color Top\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-t': [{\n        'border-t': scaleColor()\n      }],\n      /**\n       * Border Color Right\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-r': [{\n        'border-r': scaleColor()\n      }],\n      /**\n       * Border Color Bottom\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-b': [{\n        'border-b': scaleColor()\n      }],\n      /**\n       * Border Color Left\n       * @see https://tailwindcss.com/docs/border-color\n       */\n      'border-color-l': [{\n        'border-l': scaleColor()\n      }],\n      /**\n       * Divide Color\n       * @see https://tailwindcss.com/docs/divide-color\n       */\n      'divide-color': [{\n        divide: scaleColor()\n      }],\n      /**\n       * Outline Style\n       * @see https://tailwindcss.com/docs/outline-style\n       */\n      'outline-style': [{\n        outline: [...scaleLineStyle(), 'none', 'hidden']\n      }],\n      /**\n       * Outline Offset\n       * @see https://tailwindcss.com/docs/outline-offset\n       */\n      'outline-offset': [{\n        'outline-offset': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Outline Width\n       * @see https://tailwindcss.com/docs/outline-width\n       */\n      'outline-w': [{\n        outline: ['', isNumber, isArbitraryVariableLength, isArbitraryLength]\n      }],\n      /**\n       * Outline Color\n       * @see https://tailwindcss.com/docs/outline-color\n       */\n      'outline-color': [{\n        outline: scaleColor()\n      }],\n      // ---------------\n      // --- Effects ---\n      // ---------------\n      /**\n       * Box Shadow\n       * @see https://tailwindcss.com/docs/box-shadow\n       */\n      shadow: [{\n        shadow: [\n        // Deprecated since Tailwind CSS v4.0.0\n        '', 'none', themeShadow, isArbitraryVariableShadow, isArbitraryShadow]\n      }],\n      /**\n       * Box Shadow Color\n       * @see https://tailwindcss.com/docs/box-shadow#setting-the-shadow-color\n       */\n      'shadow-color': [{\n        shadow: scaleColor()\n      }],\n      /**\n       * Inset Box Shadow\n       * @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-shadow\n       */\n      'inset-shadow': [{\n        'inset-shadow': ['none', themeInsetShadow, isArbitraryVariableShadow, isArbitraryShadow]\n      }],\n      /**\n       * Inset Box Shadow Color\n       * @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-shadow-color\n       */\n      'inset-shadow-color': [{\n        'inset-shadow': scaleColor()\n      }],\n      /**\n       * Ring Width\n       * @see https://tailwindcss.com/docs/box-shadow#adding-a-ring\n       */\n      'ring-w': [{\n        ring: scaleBorderWidth()\n      }],\n      /**\n       * Ring Width Inset\n       * @see https://v3.tailwindcss.com/docs/ring-width#inset-rings\n       * @deprecated since Tailwind CSS v4.0.0\n       * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n       */\n      'ring-w-inset': ['ring-inset'],\n      /**\n       * Ring Color\n       * @see https://tailwindcss.com/docs/box-shadow#setting-the-ring-color\n       */\n      'ring-color': [{\n        ring: scaleColor()\n      }],\n      /**\n       * Ring Offset Width\n       * @see https://v3.tailwindcss.com/docs/ring-offset-width\n       * @deprecated since Tailwind CSS v4.0.0\n       * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n       */\n      'ring-offset-w': [{\n        'ring-offset': [isNumber, isArbitraryLength]\n      }],\n      /**\n       * Ring Offset Color\n       * @see https://v3.tailwindcss.com/docs/ring-offset-color\n       * @deprecated since Tailwind CSS v4.0.0\n       * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n       */\n      'ring-offset-color': [{\n        'ring-offset': scaleColor()\n      }],\n      /**\n       * Inset Ring Width\n       * @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-ring\n       */\n      'inset-ring-w': [{\n        'inset-ring': scaleBorderWidth()\n      }],\n      /**\n       * Inset Ring Color\n       * @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-ring-color\n       */\n      'inset-ring-color': [{\n        'inset-ring': scaleColor()\n      }],\n      /**\n       * Text Shadow\n       * @see https://tailwindcss.com/docs/text-shadow\n       */\n      'text-shadow': [{\n        'text-shadow': ['none', themeTextShadow, isArbitraryVariableShadow, isArbitraryShadow]\n      }],\n      /**\n       * Text Shadow Color\n       * @see https://tailwindcss.com/docs/text-shadow#setting-the-shadow-color\n       */\n      'text-shadow-color': [{\n        'text-shadow': scaleColor()\n      }],\n      /**\n       * Opacity\n       * @see https://tailwindcss.com/docs/opacity\n       */\n      opacity: [{\n        opacity: [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Mix Blend Mode\n       * @see https://tailwindcss.com/docs/mix-blend-mode\n       */\n      'mix-blend': [{\n        'mix-blend': [...scaleBlendMode(), 'plus-darker', 'plus-lighter']\n      }],\n      /**\n       * Background Blend Mode\n       * @see https://tailwindcss.com/docs/background-blend-mode\n       */\n      'bg-blend': [{\n        'bg-blend': scaleBlendMode()\n      }],\n      /**\n       * Mask Clip\n       * @see https://tailwindcss.com/docs/mask-clip\n       */\n      'mask-clip': [{\n        'mask-clip': ['border', 'padding', 'content', 'fill', 'stroke', 'view']\n      }, 'mask-no-clip'],\n      /**\n       * Mask Composite\n       * @see https://tailwindcss.com/docs/mask-composite\n       */\n      'mask-composite': [{\n        mask: ['add', 'subtract', 'intersect', 'exclude']\n      }],\n      /**\n       * Mask Image\n       * @see https://tailwindcss.com/docs/mask-image\n       */\n      'mask-image-linear-pos': [{\n        'mask-linear': [isNumber]\n      }],\n      'mask-image-linear-from-pos': [{\n        'mask-linear-from': scaleMaskImagePosition()\n      }],\n      'mask-image-linear-to-pos': [{\n        'mask-linear-to': scaleMaskImagePosition()\n      }],\n      'mask-image-linear-from-color': [{\n        'mask-linear-from': scaleColor()\n      }],\n      'mask-image-linear-to-color': [{\n        'mask-linear-to': scaleColor()\n      }],\n      'mask-image-t-from-pos': [{\n        'mask-t-from': scaleMaskImagePosition()\n      }],\n      'mask-image-t-to-pos': [{\n        'mask-t-to': scaleMaskImagePosition()\n      }],\n      'mask-image-t-from-color': [{\n        'mask-t-from': scaleColor()\n      }],\n      'mask-image-t-to-color': [{\n        'mask-t-to': scaleColor()\n      }],\n      'mask-image-r-from-pos': [{\n        'mask-r-from': scaleMaskImagePosition()\n      }],\n      'mask-image-r-to-pos': [{\n        'mask-r-to': scaleMaskImagePosition()\n      }],\n      'mask-image-r-from-color': [{\n        'mask-r-from': scaleColor()\n      }],\n      'mask-image-r-to-color': [{\n        'mask-r-to': scaleColor()\n      }],\n      'mask-image-b-from-pos': [{\n        'mask-b-from': scaleMaskImagePosition()\n      }],\n      'mask-image-b-to-pos': [{\n        'mask-b-to': scaleMaskImagePosition()\n      }],\n      'mask-image-b-from-color': [{\n        'mask-b-from': scaleColor()\n      }],\n      'mask-image-b-to-color': [{\n        'mask-b-to': scaleColor()\n      }],\n      'mask-image-l-from-pos': [{\n        'mask-l-from': scaleMaskImagePosition()\n      }],\n      'mask-image-l-to-pos': [{\n        'mask-l-to': scaleMaskImagePosition()\n      }],\n      'mask-image-l-from-color': [{\n        'mask-l-from': scaleColor()\n      }],\n      'mask-image-l-to-color': [{\n        'mask-l-to': scaleColor()\n      }],\n      'mask-image-x-from-pos': [{\n        'mask-x-from': scaleMaskImagePosition()\n      }],\n      'mask-image-x-to-pos': [{\n        'mask-x-to': scaleMaskImagePosition()\n      }],\n      'mask-image-x-from-color': [{\n        'mask-x-from': scaleColor()\n      }],\n      'mask-image-x-to-color': [{\n        'mask-x-to': scaleColor()\n      }],\n      'mask-image-y-from-pos': [{\n        'mask-y-from': scaleMaskImagePosition()\n      }],\n      'mask-image-y-to-pos': [{\n        'mask-y-to': scaleMaskImagePosition()\n      }],\n      'mask-image-y-from-color': [{\n        'mask-y-from': scaleColor()\n      }],\n      'mask-image-y-to-color': [{\n        'mask-y-to': scaleColor()\n      }],\n      'mask-image-radial': [{\n        'mask-radial': [isArbitraryVariable, isArbitraryValue]\n      }],\n      'mask-image-radial-from-pos': [{\n        'mask-radial-from': scaleMaskImagePosition()\n      }],\n      'mask-image-radial-to-pos': [{\n        'mask-radial-to': scaleMaskImagePosition()\n      }],\n      'mask-image-radial-from-color': [{\n        'mask-radial-from': scaleColor()\n      }],\n      'mask-image-radial-to-color': [{\n        'mask-radial-to': scaleColor()\n      }],\n      'mask-image-radial-shape': [{\n        'mask-radial': ['circle', 'ellipse']\n      }],\n      'mask-image-radial-size': [{\n        'mask-radial': [{\n          closest: ['side', 'corner'],\n          farthest: ['side', 'corner']\n        }]\n      }],\n      'mask-image-radial-pos': [{\n        'mask-radial-at': scalePosition()\n      }],\n      'mask-image-conic-pos': [{\n        'mask-conic': [isNumber]\n      }],\n      'mask-image-conic-from-pos': [{\n        'mask-conic-from': scaleMaskImagePosition()\n      }],\n      'mask-image-conic-to-pos': [{\n        'mask-conic-to': scaleMaskImagePosition()\n      }],\n      'mask-image-conic-from-color': [{\n        'mask-conic-from': scaleColor()\n      }],\n      'mask-image-conic-to-color': [{\n        'mask-conic-to': scaleColor()\n      }],\n      /**\n       * Mask Mode\n       * @see https://tailwindcss.com/docs/mask-mode\n       */\n      'mask-mode': [{\n        mask: ['alpha', 'luminance', 'match']\n      }],\n      /**\n       * Mask Origin\n       * @see https://tailwindcss.com/docs/mask-origin\n       */\n      'mask-origin': [{\n        'mask-origin': ['border', 'padding', 'content', 'fill', 'stroke', 'view']\n      }],\n      /**\n       * Mask Position\n       * @see https://tailwindcss.com/docs/mask-position\n       */\n      'mask-position': [{\n        mask: scaleBgPosition()\n      }],\n      /**\n       * Mask Repeat\n       * @see https://tailwindcss.com/docs/mask-repeat\n       */\n      'mask-repeat': [{\n        mask: scaleBgRepeat()\n      }],\n      /**\n       * Mask Size\n       * @see https://tailwindcss.com/docs/mask-size\n       */\n      'mask-size': [{\n        mask: scaleBgSize()\n      }],\n      /**\n       * Mask Type\n       * @see https://tailwindcss.com/docs/mask-type\n       */\n      'mask-type': [{\n        'mask-type': ['alpha', 'luminance']\n      }],\n      /**\n       * Mask Image\n       * @see https://tailwindcss.com/docs/mask-image\n       */\n      'mask-image': [{\n        mask: ['none', isArbitraryVariable, isArbitraryValue]\n      }],\n      // ---------------\n      // --- Filters ---\n      // ---------------\n      /**\n       * Filter\n       * @see https://tailwindcss.com/docs/filter\n       */\n      filter: [{\n        filter: [\n        // Deprecated since Tailwind CSS v3.0.0\n        '', 'none', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Blur\n       * @see https://tailwindcss.com/docs/blur\n       */\n      blur: [{\n        blur: scaleBlur()\n      }],\n      /**\n       * Brightness\n       * @see https://tailwindcss.com/docs/brightness\n       */\n      brightness: [{\n        brightness: [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Contrast\n       * @see https://tailwindcss.com/docs/contrast\n       */\n      contrast: [{\n        contrast: [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Drop Shadow\n       * @see https://tailwindcss.com/docs/drop-shadow\n       */\n      'drop-shadow': [{\n        'drop-shadow': [\n        // Deprecated since Tailwind CSS v4.0.0\n        '', 'none', themeDropShadow, isArbitraryVariableShadow, isArbitraryShadow]\n      }],\n      /**\n       * Drop Shadow Color\n       * @see https://tailwindcss.com/docs/filter-drop-shadow#setting-the-shadow-color\n       */\n      'drop-shadow-color': [{\n        'drop-shadow': scaleColor()\n      }],\n      /**\n       * Grayscale\n       * @see https://tailwindcss.com/docs/grayscale\n       */\n      grayscale: [{\n        grayscale: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Hue Rotate\n       * @see https://tailwindcss.com/docs/hue-rotate\n       */\n      'hue-rotate': [{\n        'hue-rotate': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Invert\n       * @see https://tailwindcss.com/docs/invert\n       */\n      invert: [{\n        invert: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Saturate\n       * @see https://tailwindcss.com/docs/saturate\n       */\n      saturate: [{\n        saturate: [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Sepia\n       * @see https://tailwindcss.com/docs/sepia\n       */\n      sepia: [{\n        sepia: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Filter\n       * @see https://tailwindcss.com/docs/backdrop-filter\n       */\n      'backdrop-filter': [{\n        'backdrop-filter': [\n        // Deprecated since Tailwind CSS v3.0.0\n        '', 'none', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Blur\n       * @see https://tailwindcss.com/docs/backdrop-blur\n       */\n      'backdrop-blur': [{\n        'backdrop-blur': scaleBlur()\n      }],\n      /**\n       * Backdrop Brightness\n       * @see https://tailwindcss.com/docs/backdrop-brightness\n       */\n      'backdrop-brightness': [{\n        'backdrop-brightness': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Contrast\n       * @see https://tailwindcss.com/docs/backdrop-contrast\n       */\n      'backdrop-contrast': [{\n        'backdrop-contrast': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Grayscale\n       * @see https://tailwindcss.com/docs/backdrop-grayscale\n       */\n      'backdrop-grayscale': [{\n        'backdrop-grayscale': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Hue Rotate\n       * @see https://tailwindcss.com/docs/backdrop-hue-rotate\n       */\n      'backdrop-hue-rotate': [{\n        'backdrop-hue-rotate': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Invert\n       * @see https://tailwindcss.com/docs/backdrop-invert\n       */\n      'backdrop-invert': [{\n        'backdrop-invert': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Opacity\n       * @see https://tailwindcss.com/docs/backdrop-opacity\n       */\n      'backdrop-opacity': [{\n        'backdrop-opacity': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Saturate\n       * @see https://tailwindcss.com/docs/backdrop-saturate\n       */\n      'backdrop-saturate': [{\n        'backdrop-saturate': [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Backdrop Sepia\n       * @see https://tailwindcss.com/docs/backdrop-sepia\n       */\n      'backdrop-sepia': [{\n        'backdrop-sepia': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      // --------------\n      // --- Tables ---\n      // --------------\n      /**\n       * Border Collapse\n       * @see https://tailwindcss.com/docs/border-collapse\n       */\n      'border-collapse': [{\n        border: ['collapse', 'separate']\n      }],\n      /**\n       * Border Spacing\n       * @see https://tailwindcss.com/docs/border-spacing\n       */\n      'border-spacing': [{\n        'border-spacing': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Border Spacing X\n       * @see https://tailwindcss.com/docs/border-spacing\n       */\n      'border-spacing-x': [{\n        'border-spacing-x': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Border Spacing Y\n       * @see https://tailwindcss.com/docs/border-spacing\n       */\n      'border-spacing-y': [{\n        'border-spacing-y': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Table Layout\n       * @see https://tailwindcss.com/docs/table-layout\n       */\n      'table-layout': [{\n        table: ['auto', 'fixed']\n      }],\n      /**\n       * Caption Side\n       * @see https://tailwindcss.com/docs/caption-side\n       */\n      caption: [{\n        caption: ['top', 'bottom']\n      }],\n      // ---------------------------------\n      // --- Transitions and Animation ---\n      // ---------------------------------\n      /**\n       * Transition Property\n       * @see https://tailwindcss.com/docs/transition-property\n       */\n      transition: [{\n        transition: ['', 'all', 'colors', 'opacity', 'shadow', 'transform', 'none', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Transition Behavior\n       * @see https://tailwindcss.com/docs/transition-behavior\n       */\n      'transition-behavior': [{\n        transition: ['normal', 'discrete']\n      }],\n      /**\n       * Transition Duration\n       * @see https://tailwindcss.com/docs/transition-duration\n       */\n      duration: [{\n        duration: [isNumber, 'initial', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Transition Timing Function\n       * @see https://tailwindcss.com/docs/transition-timing-function\n       */\n      ease: [{\n        ease: ['linear', 'initial', themeEase, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Transition Delay\n       * @see https://tailwindcss.com/docs/transition-delay\n       */\n      delay: [{\n        delay: [isNumber, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Animation\n       * @see https://tailwindcss.com/docs/animation\n       */\n      animate: [{\n        animate: ['none', themeAnimate, isArbitraryVariable, isArbitraryValue]\n      }],\n      // ------------------\n      // --- Transforms ---\n      // ------------------\n      /**\n       * Backface Visibility\n       * @see https://tailwindcss.com/docs/backface-visibility\n       */\n      backface: [{\n        backface: ['hidden', 'visible']\n      }],\n      /**\n       * Perspective\n       * @see https://tailwindcss.com/docs/perspective\n       */\n      perspective: [{\n        perspective: [themePerspective, isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Perspective Origin\n       * @see https://tailwindcss.com/docs/perspective-origin\n       */\n      'perspective-origin': [{\n        'perspective-origin': scalePositionWithArbitrary()\n      }],\n      /**\n       * Rotate\n       * @see https://tailwindcss.com/docs/rotate\n       */\n      rotate: [{\n        rotate: scaleRotate()\n      }],\n      /**\n       * Rotate X\n       * @see https://tailwindcss.com/docs/rotate\n       */\n      'rotate-x': [{\n        'rotate-x': scaleRotate()\n      }],\n      /**\n       * Rotate Y\n       * @see https://tailwindcss.com/docs/rotate\n       */\n      'rotate-y': [{\n        'rotate-y': scaleRotate()\n      }],\n      /**\n       * Rotate Z\n       * @see https://tailwindcss.com/docs/rotate\n       */\n      'rotate-z': [{\n        'rotate-z': scaleRotate()\n      }],\n      /**\n       * Scale\n       * @see https://tailwindcss.com/docs/scale\n       */\n      scale: [{\n        scale: scaleScale()\n      }],\n      /**\n       * Scale X\n       * @see https://tailwindcss.com/docs/scale\n       */\n      'scale-x': [{\n        'scale-x': scaleScale()\n      }],\n      /**\n       * Scale Y\n       * @see https://tailwindcss.com/docs/scale\n       */\n      'scale-y': [{\n        'scale-y': scaleScale()\n      }],\n      /**\n       * Scale Z\n       * @see https://tailwindcss.com/docs/scale\n       */\n      'scale-z': [{\n        'scale-z': scaleScale()\n      }],\n      /**\n       * Scale 3D\n       * @see https://tailwindcss.com/docs/scale\n       */\n      'scale-3d': ['scale-3d'],\n      /**\n       * Skew\n       * @see https://tailwindcss.com/docs/skew\n       */\n      skew: [{\n        skew: scaleSkew()\n      }],\n      /**\n       * Skew X\n       * @see https://tailwindcss.com/docs/skew\n       */\n      'skew-x': [{\n        'skew-x': scaleSkew()\n      }],\n      /**\n       * Skew Y\n       * @see https://tailwindcss.com/docs/skew\n       */\n      'skew-y': [{\n        'skew-y': scaleSkew()\n      }],\n      /**\n       * Transform\n       * @see https://tailwindcss.com/docs/transform\n       */\n      transform: [{\n        transform: [isArbitraryVariable, isArbitraryValue, '', 'none', 'gpu', 'cpu']\n      }],\n      /**\n       * Transform Origin\n       * @see https://tailwindcss.com/docs/transform-origin\n       */\n      'transform-origin': [{\n        origin: scalePositionWithArbitrary()\n      }],\n      /**\n       * Transform Style\n       * @see https://tailwindcss.com/docs/transform-style\n       */\n      'transform-style': [{\n        transform: ['3d', 'flat']\n      }],\n      /**\n       * Translate\n       * @see https://tailwindcss.com/docs/translate\n       */\n      translate: [{\n        translate: scaleTranslate()\n      }],\n      /**\n       * Translate X\n       * @see https://tailwindcss.com/docs/translate\n       */\n      'translate-x': [{\n        'translate-x': scaleTranslate()\n      }],\n      /**\n       * Translate Y\n       * @see https://tailwindcss.com/docs/translate\n       */\n      'translate-y': [{\n        'translate-y': scaleTranslate()\n      }],\n      /**\n       * Translate Z\n       * @see https://tailwindcss.com/docs/translate\n       */\n      'translate-z': [{\n        'translate-z': scaleTranslate()\n      }],\n      /**\n       * Translate None\n       * @see https://tailwindcss.com/docs/translate\n       */\n      'translate-none': ['translate-none'],\n      // ---------------------\n      // --- Interactivity ---\n      // ---------------------\n      /**\n       * Accent Color\n       * @see https://tailwindcss.com/docs/accent-color\n       */\n      accent: [{\n        accent: scaleColor()\n      }],\n      /**\n       * Appearance\n       * @see https://tailwindcss.com/docs/appearance\n       */\n      appearance: [{\n        appearance: ['none', 'auto']\n      }],\n      /**\n       * Caret Color\n       * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities\n       */\n      'caret-color': [{\n        caret: scaleColor()\n      }],\n      /**\n       * Color Scheme\n       * @see https://tailwindcss.com/docs/color-scheme\n       */\n      'color-scheme': [{\n        scheme: ['normal', 'dark', 'light', 'light-dark', 'only-dark', 'only-light']\n      }],\n      /**\n       * Cursor\n       * @see https://tailwindcss.com/docs/cursor\n       */\n      cursor: [{\n        cursor: ['auto', 'default', 'pointer', 'wait', 'text', 'move', 'help', 'not-allowed', 'none', 'context-menu', 'progress', 'cell', 'crosshair', 'vertical-text', 'alias', 'copy', 'no-drop', 'grab', 'grabbing', 'all-scroll', 'col-resize', 'row-resize', 'n-resize', 'e-resize', 's-resize', 'w-resize', 'ne-resize', 'nw-resize', 'se-resize', 'sw-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'zoom-in', 'zoom-out', isArbitraryVariable, isArbitraryValue]\n      }],\n      /**\n       * Field Sizing\n       * @see https://tailwindcss.com/docs/field-sizing\n       */\n      'field-sizing': [{\n        'field-sizing': ['fixed', 'content']\n      }],\n      /**\n       * Pointer Events\n       * @see https://tailwindcss.com/docs/pointer-events\n       */\n      'pointer-events': [{\n        'pointer-events': ['auto', 'none']\n      }],\n      /**\n       * Resize\n       * @see https://tailwindcss.com/docs/resize\n       */\n      resize: [{\n        resize: ['none', '', 'y', 'x']\n      }],\n      /**\n       * Scroll Behavior\n       * @see https://tailwindcss.com/docs/scroll-behavior\n       */\n      'scroll-behavior': [{\n        scroll: ['auto', 'smooth']\n      }],\n      /**\n       * Scroll Margin\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-m': [{\n        'scroll-m': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin X\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-mx': [{\n        'scroll-mx': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin Y\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-my': [{\n        'scroll-my': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin Start\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-ms': [{\n        'scroll-ms': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin End\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-me': [{\n        'scroll-me': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin Top\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-mt': [{\n        'scroll-mt': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin Right\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-mr': [{\n        'scroll-mr': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin Bottom\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-mb': [{\n        'scroll-mb': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Margin Left\n       * @see https://tailwindcss.com/docs/scroll-margin\n       */\n      'scroll-ml': [{\n        'scroll-ml': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-p': [{\n        'scroll-p': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding X\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-px': [{\n        'scroll-px': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding Y\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-py': [{\n        'scroll-py': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding Start\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-ps': [{\n        'scroll-ps': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding End\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-pe': [{\n        'scroll-pe': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding Top\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-pt': [{\n        'scroll-pt': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding Right\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-pr': [{\n        'scroll-pr': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding Bottom\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-pb': [{\n        'scroll-pb': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Padding Left\n       * @see https://tailwindcss.com/docs/scroll-padding\n       */\n      'scroll-pl': [{\n        'scroll-pl': scaleUnambiguousSpacing()\n      }],\n      /**\n       * Scroll Snap Align\n       * @see https://tailwindcss.com/docs/scroll-snap-align\n       */\n      'snap-align': [{\n        snap: ['start', 'end', 'center', 'align-none']\n      }],\n      /**\n       * Scroll Snap Stop\n       * @see https://tailwindcss.com/docs/scroll-snap-stop\n       */\n      'snap-stop': [{\n        snap: ['normal', 'always']\n      }],\n      /**\n       * Scroll Snap Type\n       * @see https://tailwindcss.com/docs/scroll-snap-type\n       */\n      'snap-type': [{\n        snap: ['none', 'x', 'y', 'both']\n      }],\n      /**\n       * Scroll Snap Type Strictness\n       * @see https://tailwindcss.com/docs/scroll-snap-type\n       */\n      'snap-strictness': [{\n        snap: ['mandatory', 'proximity']\n      }],\n      /**\n       * Touch Action\n       * @see https://tailwindcss.com/docs/touch-action\n       */\n      touch: [{\n        touch: ['auto', 'none', 'manipulation']\n      }],\n      /**\n       * Touch Action X\n       * @see https://tailwindcss.com/docs/touch-action\n       */\n      'touch-x': [{\n        'touch-pan': ['x', 'left', 'right']\n      }],\n      /**\n       * Touch Action Y\n       * @see https://tailwindcss.com/docs/touch-action\n       */\n      'touch-y': [{\n        'touch-pan': ['y', 'up', 'down']\n      }],\n      /**\n       * Touch Action Pinch Zoom\n       * @see https://tailwindcss.com/docs/touch-action\n       */\n      'touch-pz': ['touch-pinch-zoom'],\n      /**\n       * User Select\n       * @see https://tailwindcss.com/docs/user-select\n       */\n      select: [{\n        select: ['none', 'text', 'all', 'auto']\n      }],\n      /**\n       * Will Change\n       * @see https://tailwindcss.com/docs/will-change\n       */\n      'will-change': [{\n        'will-change': ['auto', 'scroll', 'contents', 'transform', isArbitraryVariable, isArbitraryValue]\n      }],\n      // -----------\n      // --- SVG ---\n      // -----------\n      /**\n       * Fill\n       * @see https://tailwindcss.com/docs/fill\n       */\n      fill: [{\n        fill: ['none', ...scaleColor()]\n      }],\n      /**\n       * Stroke Width\n       * @see https://tailwindcss.com/docs/stroke-width\n       */\n      'stroke-w': [{\n        stroke: [isNumber, isArbitraryVariableLength, isArbitraryLength, isArbitraryNumber]\n      }],\n      /**\n       * Stroke\n       * @see https://tailwindcss.com/docs/stroke\n       */\n      stroke: [{\n        stroke: ['none', ...scaleColor()]\n      }],\n      // ---------------------\n      // --- Accessibility ---\n      // ---------------------\n      /**\n       * Forced Color Adjust\n       * @see https://tailwindcss.com/docs/forced-color-adjust\n       */\n      'forced-color-adjust': [{\n        'forced-color-adjust': ['auto', 'none']\n      }]\n    },\n    conflictingClassGroups: {\n      overflow: ['overflow-x', 'overflow-y'],\n      overscroll: ['overscroll-x', 'overscroll-y'],\n      inset: ['inset-x', 'inset-y', 'start', 'end', 'top', 'right', 'bottom', 'left'],\n      'inset-x': ['right', 'left'],\n      'inset-y': ['top', 'bottom'],\n      flex: ['basis', 'grow', 'shrink'],\n      gap: ['gap-x', 'gap-y'],\n      p: ['px', 'py', 'ps', 'pe', 'pt', 'pr', 'pb', 'pl'],\n      px: ['pr', 'pl'],\n      py: ['pt', 'pb'],\n      m: ['mx', 'my', 'ms', 'me', 'mt', 'mr', 'mb', 'ml'],\n      mx: ['mr', 'ml'],\n      my: ['mt', 'mb'],\n      size: ['w', 'h'],\n      'font-size': ['leading'],\n      'fvn-normal': ['fvn-ordinal', 'fvn-slashed-zero', 'fvn-figure', 'fvn-spacing', 'fvn-fraction'],\n      'fvn-ordinal': ['fvn-normal'],\n      'fvn-slashed-zero': ['fvn-normal'],\n      'fvn-figure': ['fvn-normal'],\n      'fvn-spacing': ['fvn-normal'],\n      'fvn-fraction': ['fvn-normal'],\n      'line-clamp': ['display', 'overflow'],\n      rounded: ['rounded-s', 'rounded-e', 'rounded-t', 'rounded-r', 'rounded-b', 'rounded-l', 'rounded-ss', 'rounded-se', 'rounded-ee', 'rounded-es', 'rounded-tl', 'rounded-tr', 'rounded-br', 'rounded-bl'],\n      'rounded-s': ['rounded-ss', 'rounded-es'],\n      'rounded-e': ['rounded-se', 'rounded-ee'],\n      'rounded-t': ['rounded-tl', 'rounded-tr'],\n      'rounded-r': ['rounded-tr', 'rounded-br'],\n      'rounded-b': ['rounded-br', 'rounded-bl'],\n      'rounded-l': ['rounded-tl', 'rounded-bl'],\n      'border-spacing': ['border-spacing-x', 'border-spacing-y'],\n      'border-w': ['border-w-x', 'border-w-y', 'border-w-s', 'border-w-e', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l'],\n      'border-w-x': ['border-w-r', 'border-w-l'],\n      'border-w-y': ['border-w-t', 'border-w-b'],\n      'border-color': ['border-color-x', 'border-color-y', 'border-color-s', 'border-color-e', 'border-color-t', 'border-color-r', 'border-color-b', 'border-color-l'],\n      'border-color-x': ['border-color-r', 'border-color-l'],\n      'border-color-y': ['border-color-t', 'border-color-b'],\n      translate: ['translate-x', 'translate-y', 'translate-none'],\n      'translate-none': ['translate', 'translate-x', 'translate-y', 'translate-z'],\n      'scroll-m': ['scroll-mx', 'scroll-my', 'scroll-ms', 'scroll-me', 'scroll-mt', 'scroll-mr', 'scroll-mb', 'scroll-ml'],\n      'scroll-mx': ['scroll-mr', 'scroll-ml'],\n      'scroll-my': ['scroll-mt', 'scroll-mb'],\n      'scroll-p': ['scroll-px', 'scroll-py', 'scroll-ps', 'scroll-pe', 'scroll-pt', 'scroll-pr', 'scroll-pb', 'scroll-pl'],\n      'scroll-px': ['scroll-pr', 'scroll-pl'],\n      'scroll-py': ['scroll-pt', 'scroll-pb'],\n      touch: ['touch-x', 'touch-y', 'touch-pz'],\n      'touch-x': ['touch'],\n      'touch-y': ['touch'],\n      'touch-pz': ['touch']\n    },\n    conflictingClassGroupModifiers: {\n      'font-size': ['leading']\n    },\n    orderSensitiveModifiers: ['*', '**', 'after', 'backdrop', 'before', 'details-content', 'file', 'first-letter', 'first-line', 'marker', 'placeholder', 'selection']\n  };\n};\n\n/**\n * @param baseConfig Config where other config will be merged into. This object will be mutated.\n * @param configExtension Partial config to merge into the `baseConfig`.\n */\nconst mergeConfigs = (baseConfig, {\n  cacheSize,\n  prefix,\n  experimentalParseClassName,\n  extend = {},\n  override = {}\n}) => {\n  overrideProperty(baseConfig, 'cacheSize', cacheSize);\n  overrideProperty(baseConfig, 'prefix', prefix);\n  overrideProperty(baseConfig, 'experimentalParseClassName', experimentalParseClassName);\n  overrideConfigProperties(baseConfig.theme, override.theme);\n  overrideConfigProperties(baseConfig.classGroups, override.classGroups);\n  overrideConfigProperties(baseConfig.conflictingClassGroups, override.conflictingClassGroups);\n  overrideConfigProperties(baseConfig.conflictingClassGroupModifiers, override.conflictingClassGroupModifiers);\n  overrideProperty(baseConfig, 'orderSensitiveModifiers', override.orderSensitiveModifiers);\n  mergeConfigProperties(baseConfig.theme, extend.theme);\n  mergeConfigProperties(baseConfig.classGroups, extend.classGroups);\n  mergeConfigProperties(baseConfig.conflictingClassGroups, extend.conflictingClassGroups);\n  mergeConfigProperties(baseConfig.conflictingClassGroupModifiers, extend.conflictingClassGroupModifiers);\n  mergeArrayProperties(baseConfig, extend, 'orderSensitiveModifiers');\n  return baseConfig;\n};\nconst overrideProperty = (baseObject, overrideKey, overrideValue) => {\n  if (overrideValue !== undefined) {\n    baseObject[overrideKey] = overrideValue;\n  }\n};\nconst overrideConfigProperties = (baseObject, overrideObject) => {\n  if (overrideObject) {\n    for (const key in overrideObject) {\n      overrideProperty(baseObject, key, overrideObject[key]);\n    }\n  }\n};\nconst mergeConfigProperties = (baseObject, mergeObject) => {\n  if (mergeObject) {\n    for (const key in mergeObject) {\n      mergeArrayProperties(baseObject, mergeObject, key);\n    }\n  }\n};\nconst mergeArrayProperties = (baseObject, mergeObject, key) => {\n  const mergeValue = mergeObject[key];\n  if (mergeValue !== undefined) {\n    baseObject[key] = baseObject[key] ? baseObject[key].concat(mergeValue) : mergeValue;\n  }\n};\nconst extendTailwindMerge = (configExtension, ...createConfig) => typeof configExtension === 'function' ? createTailwindMerge(getDefaultConfig, configExtension, ...createConfig) : createTailwindMerge(() => mergeConfigs(getDefaultConfig(), configExtension), ...createConfig);\nconst twMerge = /*#__PURE__*/createTailwindMerge(getDefaultConfig);\nexport { createTailwindMerge, extendTailwindMerge, fromTheme, getDefaultConfig, mergeConfigs, twJoin, twMerge, validators };\n//# sourceMappingURL=bundle-mjs.mjs.map\n","import React from 'react';\nimport { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport type { ButtonGroupProps } from './ButtonGroup.types';\n\nfunction cn(...inputs: ClassValue[]): string {\n  return twMerge(clsx(inputs));\n}\n\n/**\n * ButtonGroup - Grupo de botones toggle conectados\n *\n * Componente de selección tipo radio donde los botones aparecen\n * visualmente conectados. Solo un valor puede estar seleccionado a la vez.\n * Varianite para entorno de Playground.\n *\n * Soporta tres modos por opción:\n * - **Solo texto**: `{ value, label }`\n * - **Icono + texto**: `{ value, label, icon }`\n * - **Solo icono**: `{ value, icon, ariaLabel }` (botón cuadrado)\n *\n * **Figma:** Button Group Item\n * Node ID: 7879-38523\n *\n * @example\n * ```tsx\n * // Solo texto\n * <ButtonGroup\n *   options={[\n *     { value: 'con', label: 'Con' },\n *     { value: 'sin', label: 'Sin' },\n *   ]}\n *   value={selected}\n *   onChange={setSelected}\n * />\n *\n * // Icono + texto\n * <ButtonGroup\n *   options={[\n *     { value: 'playground', label: 'Playground', icon: <StarIcon /> },\n *     { value: 'identified', label: 'Identificado' },\n *   ]}\n *   value={selected}\n *   onChange={setSelected}\n * />\n *\n * // Solo icono\n * <ButtonGroup\n *   options={[\n *     { value: 'list', icon: <ListIcon />, ariaLabel: 'Vista lista' },\n *     { value: 'grid', icon: <GridIcon />, ariaLabel: 'Vista cuadrícula' },\n *   ]}\n *   value={selected}\n *   onChange={setSelected}\n * />\n * ```\n *\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=7879-38523\n */\nexport function ButtonGroup({\n  options,\n  value,\n  onChange,\n  disabled = false,\n  className,\n  'aria-label': ariaLabel,\n}: ButtonGroupProps) {\n  return (\n    <div\n      className={cn('inline-flex', className)}\n      role=\"group\"\n      aria-label={ariaLabel}\n    >\n      {options.map((option, index) => {\n        const isFirst = index === 0;\n        const isLast = index === options.length - 1;\n        const isSelected = value === option.value;\n        const isDisabled = disabled || option.disabled;\n        const isIconOnly = option.icon && !option.label;\n        const iconPos = option.iconPosition || 'left';\n\n        const iconElement = option.icon ? (\n          <span className={cn(\n            \"inline-flex items-center justify-center w-4 h-4 transition-colors duration-150\",\n            !isSelected && \"text-zinc-400 dark:text-zinc-400 group-hover:text-primary\"\n          )}>\n            {option.icon}\n          </span>\n        ) : null;\n\n        const labelElement = option.label ? (\n          <span className=\"text-sm\">{option.label}</span>\n        ) : null;\n\n        return (\n          <button\n            key={option.value}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={isSelected}\n            aria-label={option.ariaLabel || option.label}\n            disabled={isDisabled}\n            onClick={() => !isDisabled && onChange(option.value)}\n            className={cn(\n              'group',\n              'flex items-center justify-center',\n              'text-sm leading-5',\n              'border',\n              'transition-all duration-150',\n              'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-400 focus-visible:ring-offset-1',\n              isIconOnly ? 'p-1.5' : 'px-3.5 py-1.5 gap-1.5',\n              isFirst && 'rounded-l',\n              isLast && 'rounded-r',\n              isSelected && [\n                'font-medium',\n                'bg-primary-100 border-primary-500 text-primary',              \n                'dark:bg-primary-950 dark:border-primary-300 dark:text-primary-300',\n              ],\n              !isSelected && [\n                'font-normal',\n                'bg-white border-zinc-300 text-zinc-900',           \n                'hover:bg-primary-100 hover:border-primary-500 hover:text-primary',\n                'dark:bg-zinc-900 dark:border-zinc-600 dark:text-zinc-100 dark:hover:bg-primary-950 dark:hover:border-primary-300 dark:hover:text-primary-300',\n              ],\n              isDisabled && 'opacity-50 cursor-not-allowed',\n            )}\n          >\n            {iconPos === 'left' && iconElement}\n            {labelElement}\n            {iconPos === 'right' && iconElement}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\nexport default ButtonGroup;\n","import { type ClassValue, clsx } from 'clsx'\nimport { twMerge } from 'tailwind-merge'\n\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(clsx(inputs))\n}\n","import * as React from \"react\"\nimport { cn } from \"../../lib/utils\"\nimport type { InputProps } from \"./Input.types\"\nimport { cva } from \"class-variance-authority\"\n\nexport const labelVariants = cva(\n  \"font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70\",\n  {\n    variants: {\n      size: {\n        xs: \"text-xs\",\n        sm: \"text-sm\",\n        base: \"text-base\",\n        l: \"text-lg\",\n        xl: \"text-xl\",\n      },\n    },\n    defaultVariants: {\n      size: \"base\",\n    },\n  }\n)\n\nconst inputVariants = cva(\n  \"flex w-full rounded-md border border-input bg-transparent transition-colors file:border-0 file:bg-transparent file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-within:ring-1 focus-within:ring-primary-400 focus-within:border-primary-400 disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-zinc-100 dark:disabled:bg-zinc-800/80 disabled:text-zinc-500 dark:disabled:text-zinc-400\",\n  {\n    variants: {\n      inputSize: {\n        xs: \"h-7 px-2 py-1 text-xs file:text-xs\",\n        sm: \"h-8 px-2 py-1 text-sm file:text-sm\",\n        base: \"h-9 px-3 py-1.5 text-base file:text-base\",\n        l: \"h-10 px-3 py-2 text-lg file:text-lg\",\n        xl: \"h-11 px-4 py-2 text-xl file:text-xl\",\n      },\n    },\n    defaultVariants: {\n      inputSize: \"base\",\n    },\n  }\n)\n\nconst iconSizeMap = {\n  xs: \"w-3 h-3\",\n  sm: \"w-3.5 h-3.5\",\n  base: \"w-4 h-4\",\n  l: \"w-5 h-5\",\n  xl: \"w-6 h-6\",\n};\n\nconst Input = React.forwardRef<HTMLInputElement, InputProps>(\n  ({ className, type, label, description, helperText, errorMessage, id, inputSize = 'base', actionText, ...props }, ref) => {\n    const [generatedId] = React.useState(() => Math.random().toString(36).substring(2, 9));\n    const inputId = id || `input-${generatedId}`;\n\n    return (\n      <div className=\"grid w-full items-center gap-2\">\n        {(label || actionText || description) && (\n          <div className=\"flex flex-col gap-2 w-full\">\n            {(label || actionText) && (\n              <div className=\"flex items-center justify-between w-full\">\n                {label && (\n                  <label htmlFor={inputId} className={cn(labelVariants({ size: inputSize }))}>\n                    {label}\n                    {props.required && <span className=\"text-destructive ml-1\">*</span>}\n                  </label>\n                )}\n                {actionText && (\n                  <a href=\"#\" className=\"text-xs font-medium text-primary dark:text-primary-300 cursor-pointer hover:underline\">\n                    {actionText}\n                  </a>\n                )}\n              </div>\n            )}\n            {description && (\n              <p className={cn(inputSize === 'xs' ? \"text-xs\" : \"text-sm\", props.error ? \"text-destructive\" : \"text-muted-foreground\")}>\n                {description}\n              </p>\n            )}\n          </div>\n        )}\n        <div className=\"relative w-full\">\n          {props.startIcon && (\n            <div className={cn(\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none flex items-center justify-center\", props.error ? \"text-destructive\" : \"text-muted-foreground\", iconSizeMap[inputSize])}>\n              {React.cloneElement(props.startIcon as React.ReactElement<any>, {\n                className: cn((props.startIcon as React.ReactElement<any>).props.className, iconSizeMap[inputSize])\n              })}\n            </div>\n          )}\n          <input\n            id={inputId}\n            type={type}\n            className={cn(\n              inputVariants({ inputSize, className }),\n              props.startIcon && \"pl-10\",\n              props.endIcon && \"pr-10\",\n              props.error && \"border-destructive ring-1 ring-destructive focus-within:ring-destructive focus-within:border-destructive text-destructive placeholder:text-destructive/60\",\n              props.readOnly && \"bg-zinc-100 dark:bg-zinc-800/80 text-zinc-500 dark:text-zinc-400 focus-visible:ring-0 focus-visible:border-input focus-visible:ring-offset-0 cursor-default\",\n              type === \"date\" || type === \"time\" || type === \"datetime-local\" || type === \"month\" || type === \"week\" ? \"block\" : \"\"\n            )}\n            ref={ref}\n            {...props}\n          />\n          {props.endIcon && (\n            <div className={cn(\"absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none flex items-center justify-center\", props.error ? \"text-destructive\" : \"text-muted-foreground\", iconSizeMap[inputSize])}>\n              {React.cloneElement(props.endIcon as React.ReactElement<any>, {\n                className: cn((props.endIcon as React.ReactElement<any>).props.className, iconSizeMap[inputSize])\n              })}\n            </div>\n          )}\n        </div>\n        {(helperText || errorMessage) && (\n          <p className={cn(inputSize === 'xs' ? \"text-xs\" : \"text-sm\", props.error ? \"text-destructive\" : \"text-muted-foreground\")}>\n            {props.error && errorMessage ? errorMessage : helperText}\n          </p>\n        )}\n      </div>\n    )\n  }\n)\nInput.displayName = \"Input\"\n\nexport { Input }\n","import { forwardRef, useState } from 'react';\nimport type { TextareaProps } from './Textarea.types';\nimport { labelVariants } from '../Input/Input';\nimport { cn } from '../../lib/utils';\n\nexport const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(\n  (\n    {\n      label,\n      description,\n      helperText,\n      error = false,\n      errorMessage,\n      actionText,\n      fullWidth = false,\n      textareaSize = 'base',\n      resize = 'vertical',\n      className = '',\n      disabled = false,\n      id,\n      rows = 4,\n      ...props\n    },\n    ref\n  ) => {\n    const [generatedId] = useState(() => Math.random().toString(36).substring(2, 9));\n    const textareaId = id || `textarea-${generatedId}`;\n\n    const sizeClasses = {\n      xs: \"px-2 py-1 text-xs\",\n      sm: \"px-2 py-1 text-sm\",\n      base: \"px-3 py-1.5 text-base\",\n      l: \"px-3 py-2 text-lg\",\n      xl: \"px-4 py-2 text-xl\",\n    };\n\n    return (\n      <div className={cn(\"grid w-full items-center gap-2\", className)}>\n        {/* Label y Descripción - Descripción abajo del label */}\n        {(label || actionText || description) && (\n          <div className=\"flex flex-col gap-2 w-full\">\n            {(label || actionText) && (\n              <div className=\"flex items-center justify-between w-full\">\n                {label && (\n                  <label\n                    htmlFor={textareaId}\n                    className={cn(\"text-content-primary dark:text-dark-content-primary\", labelVariants({ size: textareaSize }))}\n                  >\n                    {label}\n                    {props.required && <span className=\"text-destructive ml-1\">*</span>}\n                  </label>\n                )}\n                {actionText && (\n                  <a href=\"#\" className=\"text-xs font-medium text-primary dark:text-primary-300 cursor-pointer hover:underline\">\n                    {actionText}\n                  </a>\n                )}\n              </div>\n            )}\n            {description && (\n              <p className={`${textareaSize === 'xs' ? 'text-xs' : 'text-sm'} ${error ? 'text-destructive' : 'text-muted-foreground'}`}>\n                {description}\n              </p>\n            )}\n          </div>\n        )}\n\n        {/* Textarea Field */}\n        <textarea\n          ref={ref}\n          id={textareaId}\n          disabled={disabled}\n          rows={rows}\n          required={props.required}\n          className={`\n            flex w-full rounded-md border border-input bg-transparent transition-colors\n            placeholder:text-muted-foreground\n            focus-visible:outline-none focus:ring-1 focus:ring-primary-400 focus:border-primary-400 focus-within:ring-1 focus-within:ring-primary-400 focus-within:border-primary-400\n            disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-zinc-100 dark:disabled:bg-zinc-800/80 disabled:text-zinc-500 dark:disabled:text-zinc-400\n\n            ${sizeClasses[textareaSize]}\n\n            ${resize === 'none' ? 'resize-none' : resize === 'vertical' ? 'resize-y' : resize === 'horizontal' ? 'resize-x' : 'resize'}\n\n            ${error ? 'border-destructive ring-1 ring-destructive focus:ring-destructive focus:border-destructive focus-within:ring-destructive focus-within:border-destructive text-destructive placeholder:text-destructive/60' : ''}\n\n            ${props.readOnly ? 'bg-zinc-100 dark:bg-zinc-800/80 text-zinc-500 dark:text-zinc-400 focus-visible:ring-0 focus-visible:border-input focus-visible:ring-offset-0 cursor-default' : ''}\n          `.replace(/\\s+/g, ' ').trim()}\n          {...props}\n        />\n\n        {/* Helper Text o Mensaje de Error */}\n        {(helperText || errorMessage) && (\n          <p className={`${textareaSize === 'xs' ? 'text-xs' : 'text-sm'} ${error ? 'text-destructive' : 'text-muted-foreground'}`}>\n            {error && errorMessage ? errorMessage : helperText}\n          </p>\n        )}\n      </div>\n    );\n  }\n);\n\nTextarea.displayName = 'Textarea';\n","import React, { forwardRef, useId } from 'react';\nimport type { CheckboxProps } from './Checkbox.types';\n\nimport { cn } from \"../../lib/utils\";\n\nexport const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(\n  (\n    {\n      id: providedId,\n      className = '',\n      label,\n      description,\n      fullWidth = false,\n      size = 'md',\n      error = false,\n      invalid = false,\n      labelPosition = 'end',\n      errorMessage,\n      disabled,\n      indeterminate,\n      ...props\n    },\n    ref\n  ) => {\n    const fallbackId = useId();\n    const id = providedId ?? fallbackId;\n\n    // Configurar el ref y el estado indeterminate cuando se monta el input\n    const inputRef = React.useRef<HTMLInputElement>(null);\n    React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);\n\n    React.useEffect(() => {\n      if (inputRef.current) {\n        inputRef.current.indeterminate = indeterminate ?? false;\n      }\n    }, [indeterminate]);\n\n    const isError = error || invalid;\n\n    const sizeClasses = {\n      sm: 'w-4 h-4',\n      md: 'w-5 h-5',\n      lg: 'w-6 h-6',\n    };\n\n    const textSizes = {\n      sm: 'text-sm',\n      md: 'text-base',\n      lg: 'text-lg',\n    };\n\n    const containerClasses = [\n      'flex items-start gap-3',\n      labelPosition === 'start' ? 'flex-row-reverse justify-end w-full' : 'flex-row',\n      fullWidth ? 'w-full' : 'w-auto',\n      disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer',\n      className,\n    ].join(' ');\n\n    // La caja visible es un <span> hermano estilizado con `peer-*` a partir\n    // del estado del <input> (que va oculto pero accesible). Al ser un\n    // elemento normal (no reemplazado) admite hijos y no lo tocan los resets\n    // de `input[type=checkbox]` de las apps consumidoras. El relleno usa `!`\n    // para ganar la cascada frente a esos resets.\n    const boxClasses = [\n      'pointer-events-none relative shrink-0 box-border',\n      'flex items-center justify-center',\n      'rounded border transition-colors duration-200',\n      'bg-white dark:bg-gray-800',\n      sizeClasses[size],\n      isError\n        ? 'border-destructive dark:border-destructive shadow-sm'\n        : 'border-zinc-200 dark:border-zinc-600',\n      // Relleno azul cuando está marcado o indeterminado\n      'peer-checked:bg-primary! peer-checked:border-primary-500! dark:peer-checked:bg-primary-200! dark:peer-checked:border-primary-300!',\n      'peer-indeterminate:bg-primary! peer-indeterminate:border-primary-500! dark:peer-indeterminate:bg-primary-200! dark:peer-indeterminate:border-primary-300!',\n      isError\n        ? 'peer-checked:border-destructive! peer-indeterminate:border-destructive!'\n        : '',\n      // Anillo de foco por teclado (se dispara desde el input via peer)\n      isError\n        ? 'peer-focus-visible:outline-none peer-focus-visible:ring-4 peer-focus-visible:ring-red-400 peer-focus-visible:ring-offset-2 dark:peer-focus-visible:ring-red-500/50 peer-focus-visible:ring-offset-red-100 dark:peer-focus-visible:ring-offset-gray-900'\n        : 'peer-focus-visible:outline-none peer-focus-visible:ring-4 peer-focus-visible:ring-primary-400 peer-focus-visible:ring-offset-2 dark:peer-focus-visible:ring-primary-500/50 peer-focus-visible:ring-offset-primary-100 dark:peer-focus-visible:ring-offset-gray-900',\n    ].join(' ');\n\n    return (\n      <div className={containerClasses}>\n        <div className={[\n          \"flex items-center h-full pt-0.5\",\n          labelPosition === 'start' ? \"ml-auto\" : \"\"\n        ].join(' ')}>\n          <label htmlFor={id} className=\"relative inline-flex cursor-inherit\">\n            <input\n              type=\"checkbox\"\n              id={id}\n              ref={inputRef}\n              className=\"peer sr-only\"\n              disabled={disabled}\n              aria-invalid={isError}\n              aria-describedby={isError && errorMessage ? `${id}-error` : description ? `${id}-description` : undefined}\n              {...props}\n            />\n            {/* Caja visible */}\n            <span className={boxClasses} aria-hidden=\"true\" />\n            {/* Check: visible sólo cuando checked y NO indeterminado.\n                Debe ser hermano del <input> para que `peer-checked` aplique. */}\n            <svg\n              aria-hidden=\"true\"\n              viewBox=\"0 0 16 16\"\n              fill=\"none\"\n              className=\"pointer-events-none absolute inset-0 m-auto w-[75%] h-[75%] opacity-0 text-white dark:text-primary-700 peer-checked:opacity-100 peer-indeterminate:opacity-0\"\n            >\n              <path\n                d=\"M13 4.5 6.5 11.5 3 8\"\n                stroke=\"currentColor\"\n                strokeWidth=\"2\"\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n              />\n            </svg>\n            {/* Guion: visible en estado indeterminado */}\n            <svg\n              aria-hidden=\"true\"\n              viewBox=\"0 0 16 16\"\n              fill=\"none\"\n              className=\"pointer-events-none absolute inset-0 m-auto w-[70%] h-[70%] opacity-0 text-white dark:text-primary-700 peer-indeterminate:opacity-100\"\n            >\n              <path\n                d=\"M3.5 8h9\"\n                stroke=\"currentColor\"\n                strokeWidth=\"2\"\n                strokeLinecap=\"round\"\n              />\n            </svg>\n          </label>\n        </div>\n\n        {(label || description || (isError && errorMessage)) && (\n          <div className=\"flex flex-col gap-1 flex-1\">\n            {label && (\n              <label\n                htmlFor={id}\n                className={cn(\n                  'font-medium text-zinc-900 dark:text-zinc-100 cursor-inherit select-none',\n                  isError && 'text-destructive dark:text-destructive',\n                  textSizes[size]\n                )}\n              >\n                {label}\n              </label>\n            )}\n\n            {description && (\n              <p\n                id={`${id}-description`}\n                className={`text-sm select-none ${isError ? 'text-destructive dark:text-destructive' : 'text-zinc-400'}`}\n              >\n                {description}\n              </p>\n            )}\n\n            {isError && errorMessage && (\n              <p\n                id={`${id}-error`}\n                className=\"text-sm text-destructive dark:text-destructive select-none\"\n              >\n                {errorMessage}\n              </p>\n            )}\n          </div>\n        )}\n      </div>\n    );\n  }\n);\n\nCheckbox.displayName = 'Checkbox';","// src/primitive.tsx\nvar canUseDOM = !!(typeof window !== \"undefined\" && window.document && window.document.createElement);\nfunction composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {\n  return function handleEvent(event) {\n    originalEventHandler?.(event);\n    if (checkForDefaultPrevented === false || !event.defaultPrevented) {\n      return ourEventHandler?.(event);\n    }\n  };\n}\nfunction getOwnerWindow(element) {\n  if (!canUseDOM) {\n    throw new Error(\"Cannot access window outside of the DOM\");\n  }\n  return element?.ownerDocument?.defaultView ?? window;\n}\nfunction getOwnerDocument(element) {\n  if (!canUseDOM) {\n    throw new Error(\"Cannot access document outside of the DOM\");\n  }\n  return element?.ownerDocument ?? document;\n}\nfunction getActiveElement(node, activeDescendant = false) {\n  const { activeElement } = getOwnerDocument(node);\n  if (!activeElement?.nodeName) {\n    return null;\n  }\n  if (isFrame(activeElement) && activeElement.contentDocument) {\n    return getActiveElement(activeElement.contentDocument.body, activeDescendant);\n  }\n  if (activeDescendant) {\n    const id = activeElement.getAttribute(\"aria-activedescendant\");\n    if (id) {\n      const element = getOwnerDocument(activeElement).getElementById(id);\n      if (element) {\n        return element;\n      }\n    }\n  }\n  return activeElement;\n}\nfunction isFrame(element) {\n  return element.tagName === \"IFRAME\";\n}\nexport {\n  canUseDOM,\n  composeEventHandlers,\n  getActiveElement,\n  getOwnerDocument,\n  getOwnerWindow,\n  isFrame\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/compose-refs/src/compose-refs.tsx\nimport * as React from \"react\";\nfunction setRef(ref, value) {\n  if (typeof ref === \"function\") {\n    return ref(value);\n  } else if (ref !== null && ref !== void 0) {\n    ref.current = value;\n  }\n}\nfunction composeRefs(...refs) {\n  return (node) => {\n    let hasCleanup = false;\n    const cleanups = refs.map((ref) => {\n      const cleanup = setRef(ref, node);\n      if (!hasCleanup && typeof cleanup == \"function\") {\n        hasCleanup = true;\n      }\n      return cleanup;\n    });\n    if (hasCleanup) {\n      return () => {\n        for (let i = 0; i < cleanups.length; i++) {\n          const cleanup = cleanups[i];\n          if (typeof cleanup == \"function\") {\n            cleanup();\n          } else {\n            setRef(refs[i], null);\n          }\n        }\n      };\n    }\n  };\n}\nfunction useComposedRefs(...refs) {\n  return React.useCallback(composeRefs(...refs), refs);\n}\nexport {\n  composeRefs,\n  useComposedRefs\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/context/src/create-context.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nfunction createContext2(rootComponentName, defaultContext) {\n  const Context = React.createContext(defaultContext);\n  const Provider = (props) => {\n    const { children, ...context } = props;\n    const value = React.useMemo(() => context, Object.values(context));\n    return /* @__PURE__ */ jsx(Context.Provider, { value, children });\n  };\n  Provider.displayName = rootComponentName + \"Provider\";\n  function useContext2(consumerName) {\n    const context = React.useContext(Context);\n    if (context) return context;\n    if (defaultContext !== void 0) return defaultContext;\n    throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n  }\n  return [Provider, useContext2];\n}\nfunction createContextScope(scopeName, createContextScopeDeps = []) {\n  let defaultContexts = [];\n  function createContext3(rootComponentName, defaultContext) {\n    const BaseContext = React.createContext(defaultContext);\n    const index = defaultContexts.length;\n    defaultContexts = [...defaultContexts, defaultContext];\n    const Provider = (props) => {\n      const { scope, children, ...context } = props;\n      const Context = scope?.[scopeName]?.[index] || BaseContext;\n      const value = React.useMemo(() => context, Object.values(context));\n      return /* @__PURE__ */ jsx(Context.Provider, { value, children });\n    };\n    Provider.displayName = rootComponentName + \"Provider\";\n    function useContext2(consumerName, scope) {\n      const Context = scope?.[scopeName]?.[index] || BaseContext;\n      const context = React.useContext(Context);\n      if (context) return context;\n      if (defaultContext !== void 0) return defaultContext;\n      throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n    }\n    return [Provider, useContext2];\n  }\n  const createScope = () => {\n    const scopeContexts = defaultContexts.map((defaultContext) => {\n      return React.createContext(defaultContext);\n    });\n    return function useScope(scope) {\n      const contexts = scope?.[scopeName] || scopeContexts;\n      return React.useMemo(\n        () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),\n        [scope, contexts]\n      );\n    };\n  };\n  createScope.scopeName = scopeName;\n  return [createContext3, composeContextScopes(createScope, ...createContextScopeDeps)];\n}\nfunction composeContextScopes(...scopes) {\n  const baseScope = scopes[0];\n  if (scopes.length === 1) return baseScope;\n  const createScope = () => {\n    const scopeHooks = scopes.map((createScope2) => ({\n      useScope: createScope2(),\n      scopeName: createScope2.scopeName\n    }));\n    return function useComposedScopes(overrideScopes) {\n      const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => {\n        const scopeProps = useScope(overrideScopes);\n        const currentScope = scopeProps[`__scope${scopeName}`];\n        return { ...nextScopes2, ...currentScope };\n      }, {});\n      return React.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);\n    };\n  };\n  createScope.scopeName = baseScope.scopeName;\n  return createScope;\n}\nexport {\n  createContext2 as createContext,\n  createContextScope\n};\n//# sourceMappingURL=index.mjs.map\n","// src/slot.tsx\nimport * as React from \"react\";\nimport { composeRefs } from \"@radix-ui/react-compose-refs\";\nimport { Fragment as Fragment2, jsx } from \"react/jsx-runtime\";\n// @__NO_SIDE_EFFECTS__\nfunction createSlot(ownerName) {\n  const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);\n  const Slot2 = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    const childrenArray = React.Children.toArray(children);\n    const slottable = childrenArray.find(isSlottable);\n    if (slottable) {\n      const newElement = slottable.props.children;\n      const newChildren = childrenArray.map((child) => {\n        if (child === slottable) {\n          if (React.Children.count(newElement) > 1) return React.Children.only(null);\n          return React.isValidElement(newElement) ? newElement.props.children : null;\n        } else {\n          return child;\n        }\n      });\n      return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: React.isValidElement(newElement) ? React.cloneElement(newElement, void 0, newChildren) : null });\n    }\n    return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });\n  });\n  Slot2.displayName = `${ownerName}.Slot`;\n  return Slot2;\n}\nvar Slot = /* @__PURE__ */ createSlot(\"Slot\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlotClone(ownerName) {\n  const SlotClone = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    if (React.isValidElement(children)) {\n      const childrenRef = getElementRef(children);\n      const props2 = mergeProps(slotProps, children.props);\n      if (children.type !== React.Fragment) {\n        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n      }\n      return React.cloneElement(children, props2);\n    }\n    return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n  });\n  SlotClone.displayName = `${ownerName}.SlotClone`;\n  return SlotClone;\n}\nvar SLOTTABLE_IDENTIFIER = Symbol(\"radix.slottable\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlottable(ownerName) {\n  const Slottable2 = ({ children }) => {\n    return /* @__PURE__ */ jsx(Fragment2, { children });\n  };\n  Slottable2.displayName = `${ownerName}.Slottable`;\n  Slottable2.__radixId = SLOTTABLE_IDENTIFIER;\n  return Slottable2;\n}\nvar Slottable = /* @__PURE__ */ createSlottable(\"Slottable\");\nfunction isSlottable(child) {\n  return React.isValidElement(child) && typeof child.type === \"function\" && \"__radixId\" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;\n}\nfunction mergeProps(slotProps, childProps) {\n  const overrideProps = { ...childProps };\n  for (const propName in childProps) {\n    const slotPropValue = slotProps[propName];\n    const childPropValue = childProps[propName];\n    const isHandler = /^on[A-Z]/.test(propName);\n    if (isHandler) {\n      if (slotPropValue && childPropValue) {\n        overrideProps[propName] = (...args) => {\n          const result = childPropValue(...args);\n          slotPropValue(...args);\n          return result;\n        };\n      } else if (slotPropValue) {\n        overrideProps[propName] = slotPropValue;\n      }\n    } else if (propName === \"style\") {\n      overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n    } else if (propName === \"className\") {\n      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(\" \");\n    }\n  }\n  return { ...slotProps, ...overrideProps };\n}\nfunction getElementRef(element) {\n  let getter = Object.getOwnPropertyDescriptor(element.props, \"ref\")?.get;\n  let mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.ref;\n  }\n  getter = Object.getOwnPropertyDescriptor(element, \"ref\")?.get;\n  mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.props.ref;\n  }\n  return element.props.ref || element.ref;\n}\nexport {\n  Slot as Root,\n  Slot,\n  Slottable,\n  createSlot,\n  createSlottable\n};\n//# sourceMappingURL=index.mjs.map\n","// src/primitive.tsx\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport { createSlot } from \"@radix-ui/react-slot\";\nimport { jsx } from \"react/jsx-runtime\";\nvar NODES = [\n  \"a\",\n  \"button\",\n  \"div\",\n  \"form\",\n  \"h2\",\n  \"h3\",\n  \"img\",\n  \"input\",\n  \"label\",\n  \"li\",\n  \"nav\",\n  \"ol\",\n  \"p\",\n  \"select\",\n  \"span\",\n  \"svg\",\n  \"ul\"\n];\nvar Primitive = NODES.reduce((primitive, node) => {\n  const Slot = createSlot(`Primitive.${node}`);\n  const Node = React.forwardRef((props, forwardedRef) => {\n    const { asChild, ...primitiveProps } = props;\n    const Comp = asChild ? Slot : node;\n    if (typeof window !== \"undefined\") {\n      window[Symbol.for(\"radix-ui\")] = true;\n    }\n    return /* @__PURE__ */ jsx(Comp, { ...primitiveProps, ref: forwardedRef });\n  });\n  Node.displayName = `Primitive.${node}`;\n  return { ...primitive, [node]: Node };\n}, {});\nfunction dispatchDiscreteCustomEvent(target, event) {\n  if (target) ReactDOM.flushSync(() => target.dispatchEvent(event));\n}\nvar Root = Primitive;\nexport {\n  Primitive,\n  Root,\n  dispatchDiscreteCustomEvent\n};\n//# sourceMappingURL=index.mjs.map\n","// src/slot.tsx\nimport * as React from \"react\";\nimport { composeRefs } from \"@radix-ui/react-compose-refs\";\nimport { Fragment as Fragment2, jsx } from \"react/jsx-runtime\";\n// @__NO_SIDE_EFFECTS__\nfunction createSlot(ownerName) {\n  const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);\n  const Slot2 = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    const childrenArray = React.Children.toArray(children);\n    const slottable = childrenArray.find(isSlottable);\n    if (slottable) {\n      const newElement = slottable.props.children;\n      const newChildren = childrenArray.map((child) => {\n        if (child === slottable) {\n          if (React.Children.count(newElement) > 1) return React.Children.only(null);\n          return React.isValidElement(newElement) ? newElement.props.children : null;\n        } else {\n          return child;\n        }\n      });\n      return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: React.isValidElement(newElement) ? React.cloneElement(newElement, void 0, newChildren) : null });\n    }\n    return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });\n  });\n  Slot2.displayName = `${ownerName}.Slot`;\n  return Slot2;\n}\nvar Slot = /* @__PURE__ */ createSlot(\"Slot\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlotClone(ownerName) {\n  const SlotClone = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    if (React.isValidElement(children)) {\n      const childrenRef = getElementRef(children);\n      const props2 = mergeProps(slotProps, children.props);\n      if (children.type !== React.Fragment) {\n        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n      }\n      return React.cloneElement(children, props2);\n    }\n    return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n  });\n  SlotClone.displayName = `${ownerName}.SlotClone`;\n  return SlotClone;\n}\nvar SLOTTABLE_IDENTIFIER = Symbol(\"radix.slottable\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlottable(ownerName) {\n  const Slottable2 = ({ children }) => {\n    return /* @__PURE__ */ jsx(Fragment2, { children });\n  };\n  Slottable2.displayName = `${ownerName}.Slottable`;\n  Slottable2.__radixId = SLOTTABLE_IDENTIFIER;\n  return Slottable2;\n}\nvar Slottable = /* @__PURE__ */ createSlottable(\"Slottable\");\nfunction isSlottable(child) {\n  return React.isValidElement(child) && typeof child.type === \"function\" && \"__radixId\" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;\n}\nfunction mergeProps(slotProps, childProps) {\n  const overrideProps = { ...childProps };\n  for (const propName in childProps) {\n    const slotPropValue = slotProps[propName];\n    const childPropValue = childProps[propName];\n    const isHandler = /^on[A-Z]/.test(propName);\n    if (isHandler) {\n      if (slotPropValue && childPropValue) {\n        overrideProps[propName] = (...args) => {\n          const result = childPropValue(...args);\n          slotPropValue(...args);\n          return result;\n        };\n      } else if (slotPropValue) {\n        overrideProps[propName] = slotPropValue;\n      }\n    } else if (propName === \"style\") {\n      overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n    } else if (propName === \"className\") {\n      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(\" \");\n    }\n  }\n  return { ...slotProps, ...overrideProps };\n}\nfunction getElementRef(element) {\n  let getter = Object.getOwnPropertyDescriptor(element.props, \"ref\")?.get;\n  let mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.ref;\n  }\n  getter = Object.getOwnPropertyDescriptor(element, \"ref\")?.get;\n  mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.props.ref;\n  }\n  return element.props.ref || element.ref;\n}\nexport {\n  Slot as Root,\n  Slot,\n  Slottable,\n  createSlot,\n  createSlottable\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/collection-legacy.tsx\nimport React from \"react\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createSlot } from \"@radix-ui/react-slot\";\nimport { jsx } from \"react/jsx-runtime\";\nfunction createCollection(name) {\n  const PROVIDER_NAME = name + \"CollectionProvider\";\n  const [createCollectionContext, createCollectionScope] = createContextScope(PROVIDER_NAME);\n  const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(\n    PROVIDER_NAME,\n    { collectionRef: { current: null }, itemMap: /* @__PURE__ */ new Map() }\n  );\n  const CollectionProvider = (props) => {\n    const { scope, children } = props;\n    const ref = React.useRef(null);\n    const itemMap = React.useRef(/* @__PURE__ */ new Map()).current;\n    return /* @__PURE__ */ jsx(CollectionProviderImpl, { scope, itemMap, collectionRef: ref, children });\n  };\n  CollectionProvider.displayName = PROVIDER_NAME;\n  const COLLECTION_SLOT_NAME = name + \"CollectionSlot\";\n  const CollectionSlotImpl = createSlot(COLLECTION_SLOT_NAME);\n  const CollectionSlot = React.forwardRef(\n    (props, forwardedRef) => {\n      const { scope, children } = props;\n      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);\n      const composedRefs = useComposedRefs(forwardedRef, context.collectionRef);\n      return /* @__PURE__ */ jsx(CollectionSlotImpl, { ref: composedRefs, children });\n    }\n  );\n  CollectionSlot.displayName = COLLECTION_SLOT_NAME;\n  const ITEM_SLOT_NAME = name + \"CollectionItemSlot\";\n  const ITEM_DATA_ATTR = \"data-radix-collection-item\";\n  const CollectionItemSlotImpl = createSlot(ITEM_SLOT_NAME);\n  const CollectionItemSlot = React.forwardRef(\n    (props, forwardedRef) => {\n      const { scope, children, ...itemData } = props;\n      const ref = React.useRef(null);\n      const composedRefs = useComposedRefs(forwardedRef, ref);\n      const context = useCollectionContext(ITEM_SLOT_NAME, scope);\n      React.useEffect(() => {\n        context.itemMap.set(ref, { ref, ...itemData });\n        return () => void context.itemMap.delete(ref);\n      });\n      return /* @__PURE__ */ jsx(CollectionItemSlotImpl, { ...{ [ITEM_DATA_ATTR]: \"\" }, ref: composedRefs, children });\n    }\n  );\n  CollectionItemSlot.displayName = ITEM_SLOT_NAME;\n  function useCollection(scope) {\n    const context = useCollectionContext(name + \"CollectionConsumer\", scope);\n    const getItems = React.useCallback(() => {\n      const collectionNode = context.collectionRef.current;\n      if (!collectionNode) return [];\n      const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));\n      const items = Array.from(context.itemMap.values());\n      const orderedItems = items.sort(\n        (a, b) => orderedNodes.indexOf(a.ref.current) - orderedNodes.indexOf(b.ref.current)\n      );\n      return orderedItems;\n    }, [context.collectionRef, context.itemMap]);\n    return getItems;\n  }\n  return [\n    { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },\n    useCollection,\n    createCollectionScope\n  ];\n}\n\n// src/collection.tsx\nimport React2 from \"react\";\nimport { createContextScope as createContextScope2 } from \"@radix-ui/react-context\";\nimport { useComposedRefs as useComposedRefs2 } from \"@radix-ui/react-compose-refs\";\nimport { createSlot as createSlot2 } from \"@radix-ui/react-slot\";\n\n// src/ordered-dictionary.ts\nvar __instanciated = /* @__PURE__ */ new WeakMap();\nvar OrderedDict = class _OrderedDict extends Map {\n  #keys;\n  constructor(entries) {\n    super(entries);\n    this.#keys = [...super.keys()];\n    __instanciated.set(this, true);\n  }\n  set(key, value) {\n    if (__instanciated.get(this)) {\n      if (this.has(key)) {\n        this.#keys[this.#keys.indexOf(key)] = key;\n      } else {\n        this.#keys.push(key);\n      }\n    }\n    super.set(key, value);\n    return this;\n  }\n  insert(index, key, value) {\n    const has = this.has(key);\n    const length = this.#keys.length;\n    const relativeIndex = toSafeInteger(index);\n    let actualIndex = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;\n    const safeIndex = actualIndex < 0 || actualIndex >= length ? -1 : actualIndex;\n    if (safeIndex === this.size || has && safeIndex === this.size - 1 || safeIndex === -1) {\n      this.set(key, value);\n      return this;\n    }\n    const size = this.size + (has ? 0 : 1);\n    if (relativeIndex < 0) {\n      actualIndex++;\n    }\n    const keys = [...this.#keys];\n    let nextValue;\n    let shouldSkip = false;\n    for (let i = actualIndex; i < size; i++) {\n      if (actualIndex === i) {\n        let nextKey = keys[i];\n        if (keys[i] === key) {\n          nextKey = keys[i + 1];\n        }\n        if (has) {\n          this.delete(key);\n        }\n        nextValue = this.get(nextKey);\n        this.set(key, value);\n      } else {\n        if (!shouldSkip && keys[i - 1] === key) {\n          shouldSkip = true;\n        }\n        const currentKey = keys[shouldSkip ? i : i - 1];\n        const currentValue = nextValue;\n        nextValue = this.get(currentKey);\n        this.delete(currentKey);\n        this.set(currentKey, currentValue);\n      }\n    }\n    return this;\n  }\n  with(index, key, value) {\n    const copy = new _OrderedDict(this);\n    copy.insert(index, key, value);\n    return copy;\n  }\n  before(key) {\n    const index = this.#keys.indexOf(key) - 1;\n    if (index < 0) {\n      return void 0;\n    }\n    return this.entryAt(index);\n  }\n  /**\n   * Sets a new key-value pair at the position before the given key.\n   */\n  setBefore(key, newKey, value) {\n    const index = this.#keys.indexOf(key);\n    if (index === -1) {\n      return this;\n    }\n    return this.insert(index, newKey, value);\n  }\n  after(key) {\n    let index = this.#keys.indexOf(key);\n    index = index === -1 || index === this.size - 1 ? -1 : index + 1;\n    if (index === -1) {\n      return void 0;\n    }\n    return this.entryAt(index);\n  }\n  /**\n   * Sets a new key-value pair at the position after the given key.\n   */\n  setAfter(key, newKey, value) {\n    const index = this.#keys.indexOf(key);\n    if (index === -1) {\n      return this;\n    }\n    return this.insert(index + 1, newKey, value);\n  }\n  first() {\n    return this.entryAt(0);\n  }\n  last() {\n    return this.entryAt(-1);\n  }\n  clear() {\n    this.#keys = [];\n    return super.clear();\n  }\n  delete(key) {\n    const deleted = super.delete(key);\n    if (deleted) {\n      this.#keys.splice(this.#keys.indexOf(key), 1);\n    }\n    return deleted;\n  }\n  deleteAt(index) {\n    const key = this.keyAt(index);\n    if (key !== void 0) {\n      return this.delete(key);\n    }\n    return false;\n  }\n  at(index) {\n    const key = at(this.#keys, index);\n    if (key !== void 0) {\n      return this.get(key);\n    }\n  }\n  entryAt(index) {\n    const key = at(this.#keys, index);\n    if (key !== void 0) {\n      return [key, this.get(key)];\n    }\n  }\n  indexOf(key) {\n    return this.#keys.indexOf(key);\n  }\n  keyAt(index) {\n    return at(this.#keys, index);\n  }\n  from(key, offset) {\n    const index = this.indexOf(key);\n    if (index === -1) {\n      return void 0;\n    }\n    let dest = index + offset;\n    if (dest < 0) dest = 0;\n    if (dest >= this.size) dest = this.size - 1;\n    return this.at(dest);\n  }\n  keyFrom(key, offset) {\n    const index = this.indexOf(key);\n    if (index === -1) {\n      return void 0;\n    }\n    let dest = index + offset;\n    if (dest < 0) dest = 0;\n    if (dest >= this.size) dest = this.size - 1;\n    return this.keyAt(dest);\n  }\n  find(predicate, thisArg) {\n    let index = 0;\n    for (const entry of this) {\n      if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n        return entry;\n      }\n      index++;\n    }\n    return void 0;\n  }\n  findIndex(predicate, thisArg) {\n    let index = 0;\n    for (const entry of this) {\n      if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n        return index;\n      }\n      index++;\n    }\n    return -1;\n  }\n  filter(predicate, thisArg) {\n    const entries = [];\n    let index = 0;\n    for (const entry of this) {\n      if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n        entries.push(entry);\n      }\n      index++;\n    }\n    return new _OrderedDict(entries);\n  }\n  map(callbackfn, thisArg) {\n    const entries = [];\n    let index = 0;\n    for (const entry of this) {\n      entries.push([entry[0], Reflect.apply(callbackfn, thisArg, [entry, index, this])]);\n      index++;\n    }\n    return new _OrderedDict(entries);\n  }\n  reduce(...args) {\n    const [callbackfn, initialValue] = args;\n    let index = 0;\n    let accumulator = initialValue ?? this.at(0);\n    for (const entry of this) {\n      if (index === 0 && args.length === 1) {\n        accumulator = entry;\n      } else {\n        accumulator = Reflect.apply(callbackfn, this, [accumulator, entry, index, this]);\n      }\n      index++;\n    }\n    return accumulator;\n  }\n  reduceRight(...args) {\n    const [callbackfn, initialValue] = args;\n    let accumulator = initialValue ?? this.at(-1);\n    for (let index = this.size - 1; index >= 0; index--) {\n      const entry = this.at(index);\n      if (index === this.size - 1 && args.length === 1) {\n        accumulator = entry;\n      } else {\n        accumulator = Reflect.apply(callbackfn, this, [accumulator, entry, index, this]);\n      }\n    }\n    return accumulator;\n  }\n  toSorted(compareFn) {\n    const entries = [...this.entries()].sort(compareFn);\n    return new _OrderedDict(entries);\n  }\n  toReversed() {\n    const reversed = new _OrderedDict();\n    for (let index = this.size - 1; index >= 0; index--) {\n      const key = this.keyAt(index);\n      const element = this.get(key);\n      reversed.set(key, element);\n    }\n    return reversed;\n  }\n  toSpliced(...args) {\n    const entries = [...this.entries()];\n    entries.splice(...args);\n    return new _OrderedDict(entries);\n  }\n  slice(start, end) {\n    const result = new _OrderedDict();\n    let stop = this.size - 1;\n    if (start === void 0) {\n      return result;\n    }\n    if (start < 0) {\n      start = start + this.size;\n    }\n    if (end !== void 0 && end > 0) {\n      stop = end - 1;\n    }\n    for (let index = start; index <= stop; index++) {\n      const key = this.keyAt(index);\n      const element = this.get(key);\n      result.set(key, element);\n    }\n    return result;\n  }\n  every(predicate, thisArg) {\n    let index = 0;\n    for (const entry of this) {\n      if (!Reflect.apply(predicate, thisArg, [entry, index, this])) {\n        return false;\n      }\n      index++;\n    }\n    return true;\n  }\n  some(predicate, thisArg) {\n    let index = 0;\n    for (const entry of this) {\n      if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n        return true;\n      }\n      index++;\n    }\n    return false;\n  }\n};\nfunction at(array, index) {\n  if (\"at\" in Array.prototype) {\n    return Array.prototype.at.call(array, index);\n  }\n  const actualIndex = toSafeIndex(array, index);\n  return actualIndex === -1 ? void 0 : array[actualIndex];\n}\nfunction toSafeIndex(array, index) {\n  const length = array.length;\n  const relativeIndex = toSafeInteger(index);\n  const actualIndex = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;\n  return actualIndex < 0 || actualIndex >= length ? -1 : actualIndex;\n}\nfunction toSafeInteger(number) {\n  return number !== number || number === 0 ? 0 : Math.trunc(number);\n}\n\n// src/collection.tsx\nimport { jsx as jsx2 } from \"react/jsx-runtime\";\nfunction createCollection2(name) {\n  const PROVIDER_NAME = name + \"CollectionProvider\";\n  const [createCollectionContext, createCollectionScope] = createContextScope2(PROVIDER_NAME);\n  const [CollectionContextProvider, useCollectionContext] = createCollectionContext(\n    PROVIDER_NAME,\n    {\n      collectionElement: null,\n      collectionRef: { current: null },\n      collectionRefObject: { current: null },\n      itemMap: new OrderedDict(),\n      setItemMap: () => void 0\n    }\n  );\n  const CollectionProvider = ({ state, ...props }) => {\n    return state ? /* @__PURE__ */ jsx2(CollectionProviderImpl, { ...props, state }) : /* @__PURE__ */ jsx2(CollectionInit, { ...props });\n  };\n  CollectionProvider.displayName = PROVIDER_NAME;\n  const CollectionInit = (props) => {\n    const state = useInitCollection();\n    return /* @__PURE__ */ jsx2(CollectionProviderImpl, { ...props, state });\n  };\n  CollectionInit.displayName = PROVIDER_NAME + \"Init\";\n  const CollectionProviderImpl = (props) => {\n    const { scope, children, state } = props;\n    const ref = React2.useRef(null);\n    const [collectionElement, setCollectionElement] = React2.useState(\n      null\n    );\n    const composeRefs = useComposedRefs2(ref, setCollectionElement);\n    const [itemMap, setItemMap] = state;\n    React2.useEffect(() => {\n      if (!collectionElement) return;\n      const observer = getChildListObserver(() => {\n      });\n      observer.observe(collectionElement, {\n        childList: true,\n        subtree: true\n      });\n      return () => {\n        observer.disconnect();\n      };\n    }, [collectionElement]);\n    return /* @__PURE__ */ jsx2(\n      CollectionContextProvider,\n      {\n        scope,\n        itemMap,\n        setItemMap,\n        collectionRef: composeRefs,\n        collectionRefObject: ref,\n        collectionElement,\n        children\n      }\n    );\n  };\n  CollectionProviderImpl.displayName = PROVIDER_NAME + \"Impl\";\n  const COLLECTION_SLOT_NAME = name + \"CollectionSlot\";\n  const CollectionSlotImpl = createSlot2(COLLECTION_SLOT_NAME);\n  const CollectionSlot = React2.forwardRef(\n    (props, forwardedRef) => {\n      const { scope, children } = props;\n      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);\n      const composedRefs = useComposedRefs2(forwardedRef, context.collectionRef);\n      return /* @__PURE__ */ jsx2(CollectionSlotImpl, { ref: composedRefs, children });\n    }\n  );\n  CollectionSlot.displayName = COLLECTION_SLOT_NAME;\n  const ITEM_SLOT_NAME = name + \"CollectionItemSlot\";\n  const ITEM_DATA_ATTR = \"data-radix-collection-item\";\n  const CollectionItemSlotImpl = createSlot2(ITEM_SLOT_NAME);\n  const CollectionItemSlot = React2.forwardRef(\n    (props, forwardedRef) => {\n      const { scope, children, ...itemData } = props;\n      const ref = React2.useRef(null);\n      const [element, setElement] = React2.useState(null);\n      const composedRefs = useComposedRefs2(forwardedRef, ref, setElement);\n      const context = useCollectionContext(ITEM_SLOT_NAME, scope);\n      const { setItemMap } = context;\n      const itemDataRef = React2.useRef(itemData);\n      if (!shallowEqual(itemDataRef.current, itemData)) {\n        itemDataRef.current = itemData;\n      }\n      const memoizedItemData = itemDataRef.current;\n      React2.useEffect(() => {\n        const itemData2 = memoizedItemData;\n        setItemMap((map) => {\n          if (!element) {\n            return map;\n          }\n          if (!map.has(element)) {\n            map.set(element, { ...itemData2, element });\n            return map.toSorted(sortByDocumentPosition);\n          }\n          return map.set(element, { ...itemData2, element }).toSorted(sortByDocumentPosition);\n        });\n        return () => {\n          setItemMap((map) => {\n            if (!element || !map.has(element)) {\n              return map;\n            }\n            map.delete(element);\n            return new OrderedDict(map);\n          });\n        };\n      }, [element, memoizedItemData, setItemMap]);\n      return /* @__PURE__ */ jsx2(CollectionItemSlotImpl, { ...{ [ITEM_DATA_ATTR]: \"\" }, ref: composedRefs, children });\n    }\n  );\n  CollectionItemSlot.displayName = ITEM_SLOT_NAME;\n  function useInitCollection() {\n    return React2.useState(new OrderedDict());\n  }\n  function useCollection(scope) {\n    const { itemMap } = useCollectionContext(name + \"CollectionConsumer\", scope);\n    return itemMap;\n  }\n  const functions = {\n    createCollectionScope,\n    useCollection,\n    useInitCollection\n  };\n  return [\n    { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },\n    functions\n  ];\n}\nfunction shallowEqual(a, b) {\n  if (a === b) return true;\n  if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n  if (a == null || b == null) return false;\n  const keysA = Object.keys(a);\n  const keysB = Object.keys(b);\n  if (keysA.length !== keysB.length) return false;\n  for (const key of keysA) {\n    if (!Object.prototype.hasOwnProperty.call(b, key)) return false;\n    if (a[key] !== b[key]) return false;\n  }\n  return true;\n}\nfunction isElementPreceding(a, b) {\n  return !!(b.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_PRECEDING);\n}\nfunction sortByDocumentPosition(a, b) {\n  return !a[1].element || !b[1].element ? 0 : isElementPreceding(a[1].element, b[1].element) ? -1 : 1;\n}\nfunction getChildListObserver(callback) {\n  const observer = new MutationObserver((mutationsList) => {\n    for (const mutation of mutationsList) {\n      if (mutation.type === \"childList\") {\n        callback();\n        return;\n      }\n    }\n  });\n  return observer;\n}\nexport {\n  createCollection,\n  createCollection2 as unstable_createCollection\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/use-layout-effect/src/use-layout-effect.tsx\nimport * as React from \"react\";\nvar useLayoutEffect2 = globalThis?.document ? React.useLayoutEffect : () => {\n};\nexport {\n  useLayoutEffect2 as useLayoutEffect\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/id/src/id.tsx\nimport * as React from \"react\";\nimport { useLayoutEffect } from \"@radix-ui/react-use-layout-effect\";\nvar useReactId = React[\" useId \".trim().toString()] || (() => void 0);\nvar count = 0;\nfunction useId(deterministicId) {\n  const [id, setId] = React.useState(useReactId());\n  useLayoutEffect(() => {\n    if (!deterministicId) setId((reactId) => reactId ?? String(count++));\n  }, [deterministicId]);\n  return deterministicId || (id ? `radix-${id}` : \"\");\n}\nexport {\n  useId\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/use-callback-ref/src/use-callback-ref.tsx\nimport * as React from \"react\";\nfunction useCallbackRef(callback) {\n  const callbackRef = React.useRef(callback);\n  React.useEffect(() => {\n    callbackRef.current = callback;\n  });\n  return React.useMemo(() => (...args) => callbackRef.current?.(...args), []);\n}\nexport {\n  useCallbackRef\n};\n//# sourceMappingURL=index.mjs.map\n","// src/use-controllable-state.tsx\nimport * as React from \"react\";\nimport { useLayoutEffect } from \"@radix-ui/react-use-layout-effect\";\nvar useInsertionEffect = React[\" useInsertionEffect \".trim().toString()] || useLayoutEffect;\nfunction useControllableState({\n  prop,\n  defaultProp,\n  onChange = () => {\n  },\n  caller\n}) {\n  const [uncontrolledProp, setUncontrolledProp, onChangeRef] = useUncontrolledState({\n    defaultProp,\n    onChange\n  });\n  const isControlled = prop !== void 0;\n  const value = isControlled ? prop : uncontrolledProp;\n  if (true) {\n    const isControlledRef = React.useRef(prop !== void 0);\n    React.useEffect(() => {\n      const wasControlled = isControlledRef.current;\n      if (wasControlled !== isControlled) {\n        const from = wasControlled ? \"controlled\" : \"uncontrolled\";\n        const to = isControlled ? \"controlled\" : \"uncontrolled\";\n        console.warn(\n          `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`\n        );\n      }\n      isControlledRef.current = isControlled;\n    }, [isControlled, caller]);\n  }\n  const setValue = React.useCallback(\n    (nextValue) => {\n      if (isControlled) {\n        const value2 = isFunction(nextValue) ? nextValue(prop) : nextValue;\n        if (value2 !== prop) {\n          onChangeRef.current?.(value2);\n        }\n      } else {\n        setUncontrolledProp(nextValue);\n      }\n    },\n    [isControlled, prop, setUncontrolledProp, onChangeRef]\n  );\n  return [value, setValue];\n}\nfunction useUncontrolledState({\n  defaultProp,\n  onChange\n}) {\n  const [value, setValue] = React.useState(defaultProp);\n  const prevValueRef = React.useRef(value);\n  const onChangeRef = React.useRef(onChange);\n  useInsertionEffect(() => {\n    onChangeRef.current = onChange;\n  }, [onChange]);\n  React.useEffect(() => {\n    if (prevValueRef.current !== value) {\n      onChangeRef.current?.(value);\n      prevValueRef.current = value;\n    }\n  }, [value, prevValueRef]);\n  return [value, setValue, onChangeRef];\n}\nfunction isFunction(value) {\n  return typeof value === \"function\";\n}\n\n// src/use-controllable-state-reducer.tsx\nimport * as React2 from \"react\";\nimport { useEffectEvent } from \"@radix-ui/react-use-effect-event\";\nvar SYNC_STATE = Symbol(\"RADIX:SYNC_STATE\");\nfunction useControllableStateReducer(reducer, userArgs, initialArg, init) {\n  const { prop: controlledState, defaultProp, onChange: onChangeProp, caller } = userArgs;\n  const isControlled = controlledState !== void 0;\n  const onChange = useEffectEvent(onChangeProp);\n  if (true) {\n    const isControlledRef = React2.useRef(controlledState !== void 0);\n    React2.useEffect(() => {\n      const wasControlled = isControlledRef.current;\n      if (wasControlled !== isControlled) {\n        const from = wasControlled ? \"controlled\" : \"uncontrolled\";\n        const to = isControlled ? \"controlled\" : \"uncontrolled\";\n        console.warn(\n          `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`\n        );\n      }\n      isControlledRef.current = isControlled;\n    }, [isControlled, caller]);\n  }\n  const args = [{ ...initialArg, state: defaultProp }];\n  if (init) {\n    args.push(init);\n  }\n  const [internalState, dispatch] = React2.useReducer(\n    (state2, action) => {\n      if (action.type === SYNC_STATE) {\n        return { ...state2, state: action.state };\n      }\n      const next = reducer(state2, action);\n      if (isControlled && !Object.is(next.state, state2.state)) {\n        onChange(next.state);\n      }\n      return next;\n    },\n    ...args\n  );\n  const uncontrolledState = internalState.state;\n  const prevValueRef = React2.useRef(uncontrolledState);\n  React2.useEffect(() => {\n    if (prevValueRef.current !== uncontrolledState) {\n      prevValueRef.current = uncontrolledState;\n      if (!isControlled) {\n        onChange(uncontrolledState);\n      }\n    }\n  }, [onChange, uncontrolledState, prevValueRef, isControlled]);\n  const state = React2.useMemo(() => {\n    const isControlled2 = controlledState !== void 0;\n    if (isControlled2) {\n      return { ...internalState, state: controlledState };\n    }\n    return internalState;\n  }, [internalState, controlledState]);\n  React2.useEffect(() => {\n    if (isControlled && !Object.is(controlledState, internalState.state)) {\n      dispatch({ type: SYNC_STATE, state: controlledState });\n    }\n  }, [controlledState, internalState.state, isControlled]);\n  return [state, dispatch];\n}\nexport {\n  useControllableState,\n  useControllableStateReducer\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/direction/src/direction.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nvar DirectionContext = React.createContext(void 0);\nvar DirectionProvider = (props) => {\n  const { dir, children } = props;\n  return /* @__PURE__ */ jsx(DirectionContext.Provider, { value: dir, children });\n};\nfunction useDirection(localDir) {\n  const globalDir = React.useContext(DirectionContext);\n  return localDir || globalDir || \"ltr\";\n}\nvar Provider = DirectionProvider;\nexport {\n  DirectionProvider,\n  Provider,\n  useDirection\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/roving-focus-group.tsx\nimport * as React from \"react\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { createCollection } from \"@radix-ui/react-collection\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { useId } from \"@radix-ui/react-id\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useControllableState } from \"@radix-ui/react-use-controllable-state\";\nimport { useDirection } from \"@radix-ui/react-direction\";\nimport { jsx } from \"react/jsx-runtime\";\nvar ENTRY_FOCUS = \"rovingFocusGroup.onEntryFocus\";\nvar EVENT_OPTIONS = { bubbles: false, cancelable: true };\nvar GROUP_NAME = \"RovingFocusGroup\";\nvar [Collection, useCollection, createCollectionScope] = createCollection(GROUP_NAME);\nvar [createRovingFocusGroupContext, createRovingFocusGroupScope] = createContextScope(\n  GROUP_NAME,\n  [createCollectionScope]\n);\nvar [RovingFocusProvider, useRovingFocusContext] = createRovingFocusGroupContext(GROUP_NAME);\nvar RovingFocusGroup = React.forwardRef(\n  (props, forwardedRef) => {\n    return /* @__PURE__ */ jsx(Collection.Provider, { scope: props.__scopeRovingFocusGroup, children: /* @__PURE__ */ jsx(Collection.Slot, { scope: props.__scopeRovingFocusGroup, children: /* @__PURE__ */ jsx(RovingFocusGroupImpl, { ...props, ref: forwardedRef }) }) });\n  }\n);\nRovingFocusGroup.displayName = GROUP_NAME;\nvar RovingFocusGroupImpl = React.forwardRef((props, forwardedRef) => {\n  const {\n    __scopeRovingFocusGroup,\n    orientation,\n    loop = false,\n    dir,\n    currentTabStopId: currentTabStopIdProp,\n    defaultCurrentTabStopId,\n    onCurrentTabStopIdChange,\n    onEntryFocus,\n    preventScrollOnEntryFocus = false,\n    ...groupProps\n  } = props;\n  const ref = React.useRef(null);\n  const composedRefs = useComposedRefs(forwardedRef, ref);\n  const direction = useDirection(dir);\n  const [currentTabStopId, setCurrentTabStopId] = useControllableState({\n    prop: currentTabStopIdProp,\n    defaultProp: defaultCurrentTabStopId ?? null,\n    onChange: onCurrentTabStopIdChange,\n    caller: GROUP_NAME\n  });\n  const [isTabbingBackOut, setIsTabbingBackOut] = React.useState(false);\n  const handleEntryFocus = useCallbackRef(onEntryFocus);\n  const getItems = useCollection(__scopeRovingFocusGroup);\n  const isClickFocusRef = React.useRef(false);\n  const [focusableItemsCount, setFocusableItemsCount] = React.useState(0);\n  React.useEffect(() => {\n    const node = ref.current;\n    if (node) {\n      node.addEventListener(ENTRY_FOCUS, handleEntryFocus);\n      return () => node.removeEventListener(ENTRY_FOCUS, handleEntryFocus);\n    }\n  }, [handleEntryFocus]);\n  return /* @__PURE__ */ jsx(\n    RovingFocusProvider,\n    {\n      scope: __scopeRovingFocusGroup,\n      orientation,\n      dir: direction,\n      loop,\n      currentTabStopId,\n      onItemFocus: React.useCallback(\n        (tabStopId) => setCurrentTabStopId(tabStopId),\n        [setCurrentTabStopId]\n      ),\n      onItemShiftTab: React.useCallback(() => setIsTabbingBackOut(true), []),\n      onFocusableItemAdd: React.useCallback(\n        () => setFocusableItemsCount((prevCount) => prevCount + 1),\n        []\n      ),\n      onFocusableItemRemove: React.useCallback(\n        () => setFocusableItemsCount((prevCount) => prevCount - 1),\n        []\n      ),\n      children: /* @__PURE__ */ jsx(\n        Primitive.div,\n        {\n          tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0,\n          \"data-orientation\": orientation,\n          ...groupProps,\n          ref: composedRefs,\n          style: { outline: \"none\", ...props.style },\n          onMouseDown: composeEventHandlers(props.onMouseDown, () => {\n            isClickFocusRef.current = true;\n          }),\n          onFocus: composeEventHandlers(props.onFocus, (event) => {\n            const isKeyboardFocus = !isClickFocusRef.current;\n            if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) {\n              const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS);\n              event.currentTarget.dispatchEvent(entryFocusEvent);\n              if (!entryFocusEvent.defaultPrevented) {\n                const items = getItems().filter((item) => item.focusable);\n                const activeItem = items.find((item) => item.active);\n                const currentItem = items.find((item) => item.id === currentTabStopId);\n                const candidateItems = [activeItem, currentItem, ...items].filter(\n                  Boolean\n                );\n                const candidateNodes = candidateItems.map((item) => item.ref.current);\n                focusFirst(candidateNodes, preventScrollOnEntryFocus);\n              }\n            }\n            isClickFocusRef.current = false;\n          }),\n          onBlur: composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false))\n        }\n      )\n    }\n  );\n});\nvar ITEM_NAME = \"RovingFocusGroupItem\";\nvar RovingFocusGroupItem = React.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      __scopeRovingFocusGroup,\n      focusable = true,\n      active = false,\n      tabStopId,\n      children,\n      ...itemProps\n    } = props;\n    const autoId = useId();\n    const id = tabStopId || autoId;\n    const context = useRovingFocusContext(ITEM_NAME, __scopeRovingFocusGroup);\n    const isCurrentTabStop = context.currentTabStopId === id;\n    const getItems = useCollection(__scopeRovingFocusGroup);\n    const { onFocusableItemAdd, onFocusableItemRemove, currentTabStopId } = context;\n    React.useEffect(() => {\n      if (focusable) {\n        onFocusableItemAdd();\n        return () => onFocusableItemRemove();\n      }\n    }, [focusable, onFocusableItemAdd, onFocusableItemRemove]);\n    return /* @__PURE__ */ jsx(\n      Collection.ItemSlot,\n      {\n        scope: __scopeRovingFocusGroup,\n        id,\n        focusable,\n        active,\n        children: /* @__PURE__ */ jsx(\n          Primitive.span,\n          {\n            tabIndex: isCurrentTabStop ? 0 : -1,\n            \"data-orientation\": context.orientation,\n            ...itemProps,\n            ref: forwardedRef,\n            onMouseDown: composeEventHandlers(props.onMouseDown, (event) => {\n              if (!focusable) event.preventDefault();\n              else context.onItemFocus(id);\n            }),\n            onFocus: composeEventHandlers(props.onFocus, () => context.onItemFocus(id)),\n            onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {\n              if (event.key === \"Tab\" && event.shiftKey) {\n                context.onItemShiftTab();\n                return;\n              }\n              if (event.target !== event.currentTarget) return;\n              const focusIntent = getFocusIntent(event, context.orientation, context.dir);\n              if (focusIntent !== void 0) {\n                if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;\n                event.preventDefault();\n                const items = getItems().filter((item) => item.focusable);\n                let candidateNodes = items.map((item) => item.ref.current);\n                if (focusIntent === \"last\") candidateNodes.reverse();\n                else if (focusIntent === \"prev\" || focusIntent === \"next\") {\n                  if (focusIntent === \"prev\") candidateNodes.reverse();\n                  const currentIndex = candidateNodes.indexOf(event.currentTarget);\n                  candidateNodes = context.loop ? wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1);\n                }\n                setTimeout(() => focusFirst(candidateNodes));\n              }\n            }),\n            children: typeof children === \"function\" ? children({ isCurrentTabStop, hasTabStop: currentTabStopId != null }) : children\n          }\n        )\n      }\n    );\n  }\n);\nRovingFocusGroupItem.displayName = ITEM_NAME;\nvar MAP_KEY_TO_FOCUS_INTENT = {\n  ArrowLeft: \"prev\",\n  ArrowUp: \"prev\",\n  ArrowRight: \"next\",\n  ArrowDown: \"next\",\n  PageUp: \"first\",\n  Home: \"first\",\n  PageDown: \"last\",\n  End: \"last\"\n};\nfunction getDirectionAwareKey(key, dir) {\n  if (dir !== \"rtl\") return key;\n  return key === \"ArrowLeft\" ? \"ArrowRight\" : key === \"ArrowRight\" ? \"ArrowLeft\" : key;\n}\nfunction getFocusIntent(event, orientation, dir) {\n  const key = getDirectionAwareKey(event.key, dir);\n  if (orientation === \"vertical\" && [\"ArrowLeft\", \"ArrowRight\"].includes(key)) return void 0;\n  if (orientation === \"horizontal\" && [\"ArrowUp\", \"ArrowDown\"].includes(key)) return void 0;\n  return MAP_KEY_TO_FOCUS_INTENT[key];\n}\nfunction focusFirst(candidates, preventScroll = false) {\n  const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;\n  for (const candidate of candidates) {\n    if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;\n    candidate.focus({ preventScroll });\n    if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;\n  }\n}\nfunction wrapArray(array, startIndex) {\n  return array.map((_, index) => array[(startIndex + index) % array.length]);\n}\nvar Root = RovingFocusGroup;\nvar Item = RovingFocusGroupItem;\nexport {\n  Item,\n  Root,\n  RovingFocusGroup,\n  RovingFocusGroupItem,\n  createRovingFocusGroupScope\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/use-size/src/use-size.tsx\nimport * as React from \"react\";\nimport { useLayoutEffect } from \"@radix-ui/react-use-layout-effect\";\nfunction useSize(element) {\n  const [size, setSize] = React.useState(void 0);\n  useLayoutEffect(() => {\n    if (element) {\n      setSize({ width: element.offsetWidth, height: element.offsetHeight });\n      const resizeObserver = new ResizeObserver((entries) => {\n        if (!Array.isArray(entries)) {\n          return;\n        }\n        if (!entries.length) {\n          return;\n        }\n        const entry = entries[0];\n        let width;\n        let height;\n        if (\"borderBoxSize\" in entry) {\n          const borderSizeEntry = entry[\"borderBoxSize\"];\n          const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;\n          width = borderSize[\"inlineSize\"];\n          height = borderSize[\"blockSize\"];\n        } else {\n          width = element.offsetWidth;\n          height = element.offsetHeight;\n        }\n        setSize({ width, height });\n      });\n      resizeObserver.observe(element, { box: \"border-box\" });\n      return () => resizeObserver.unobserve(element);\n    } else {\n      setSize(void 0);\n    }\n  }, [element]);\n  return size;\n}\nexport {\n  useSize\n};\n//# sourceMappingURL=index.mjs.map\n","// packages/react/use-previous/src/use-previous.tsx\nimport * as React from \"react\";\nfunction usePrevious(value) {\n  const ref = React.useRef({ value, previous: value });\n  return React.useMemo(() => {\n    if (ref.current.value !== value) {\n      ref.current.previous = ref.current.value;\n      ref.current.value = value;\n    }\n    return ref.current.previous;\n  }, [value]);\n}\nexport {\n  usePrevious\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/presence.tsx\nimport * as React2 from \"react\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { useLayoutEffect } from \"@radix-ui/react-use-layout-effect\";\n\n// src/use-state-machine.tsx\nimport * as React from \"react\";\nfunction useStateMachine(initialState, machine) {\n  return React.useReducer((state, event) => {\n    const nextState = machine[state][event];\n    return nextState ?? state;\n  }, initialState);\n}\n\n// src/presence.tsx\nvar Presence = (props) => {\n  const { present, children } = props;\n  const presence = usePresence(present);\n  const child = typeof children === \"function\" ? children({ present: presence.isPresent }) : React2.Children.only(children);\n  const ref = useComposedRefs(presence.ref, getElementRef(child));\n  const forceMount = typeof children === \"function\";\n  return forceMount || presence.isPresent ? React2.cloneElement(child, { ref }) : null;\n};\nPresence.displayName = \"Presence\";\nfunction usePresence(present) {\n  const [node, setNode] = React2.useState();\n  const stylesRef = React2.useRef(null);\n  const prevPresentRef = React2.useRef(present);\n  const prevAnimationNameRef = React2.useRef(\"none\");\n  const initialState = present ? \"mounted\" : \"unmounted\";\n  const [state, send] = useStateMachine(initialState, {\n    mounted: {\n      UNMOUNT: \"unmounted\",\n      ANIMATION_OUT: \"unmountSuspended\"\n    },\n    unmountSuspended: {\n      MOUNT: \"mounted\",\n      ANIMATION_END: \"unmounted\"\n    },\n    unmounted: {\n      MOUNT: \"mounted\"\n    }\n  });\n  React2.useEffect(() => {\n    const currentAnimationName = getAnimationName(stylesRef.current);\n    prevAnimationNameRef.current = state === \"mounted\" ? currentAnimationName : \"none\";\n  }, [state]);\n  useLayoutEffect(() => {\n    const styles = stylesRef.current;\n    const wasPresent = prevPresentRef.current;\n    const hasPresentChanged = wasPresent !== present;\n    if (hasPresentChanged) {\n      const prevAnimationName = prevAnimationNameRef.current;\n      const currentAnimationName = getAnimationName(styles);\n      if (present) {\n        send(\"MOUNT\");\n      } else if (currentAnimationName === \"none\" || styles?.display === \"none\") {\n        send(\"UNMOUNT\");\n      } else {\n        const isAnimating = prevAnimationName !== currentAnimationName;\n        if (wasPresent && isAnimating) {\n          send(\"ANIMATION_OUT\");\n        } else {\n          send(\"UNMOUNT\");\n        }\n      }\n      prevPresentRef.current = present;\n    }\n  }, [present, send]);\n  useLayoutEffect(() => {\n    if (node) {\n      let timeoutId;\n      const ownerWindow = node.ownerDocument.defaultView ?? window;\n      const handleAnimationEnd = (event) => {\n        const currentAnimationName = getAnimationName(stylesRef.current);\n        const isCurrentAnimation = currentAnimationName.includes(CSS.escape(event.animationName));\n        if (event.target === node && isCurrentAnimation) {\n          send(\"ANIMATION_END\");\n          if (!prevPresentRef.current) {\n            const currentFillMode = node.style.animationFillMode;\n            node.style.animationFillMode = \"forwards\";\n            timeoutId = ownerWindow.setTimeout(() => {\n              if (node.style.animationFillMode === \"forwards\") {\n                node.style.animationFillMode = currentFillMode;\n              }\n            });\n          }\n        }\n      };\n      const handleAnimationStart = (event) => {\n        if (event.target === node) {\n          prevAnimationNameRef.current = getAnimationName(stylesRef.current);\n        }\n      };\n      node.addEventListener(\"animationstart\", handleAnimationStart);\n      node.addEventListener(\"animationcancel\", handleAnimationEnd);\n      node.addEventListener(\"animationend\", handleAnimationEnd);\n      return () => {\n        ownerWindow.clearTimeout(timeoutId);\n        node.removeEventListener(\"animationstart\", handleAnimationStart);\n        node.removeEventListener(\"animationcancel\", handleAnimationEnd);\n        node.removeEventListener(\"animationend\", handleAnimationEnd);\n      };\n    } else {\n      send(\"ANIMATION_END\");\n    }\n  }, [node, send]);\n  return {\n    isPresent: [\"mounted\", \"unmountSuspended\"].includes(state),\n    ref: React2.useCallback((node2) => {\n      stylesRef.current = node2 ? getComputedStyle(node2) : null;\n      setNode(node2);\n    }, [])\n  };\n}\nfunction getAnimationName(styles) {\n  return styles?.animationName || \"none\";\n}\nfunction getElementRef(element) {\n  let getter = Object.getOwnPropertyDescriptor(element.props, \"ref\")?.get;\n  let mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.ref;\n  }\n  getter = Object.getOwnPropertyDescriptor(element, \"ref\")?.get;\n  mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.props.ref;\n  }\n  return element.props.ref || element.ref;\n}\nvar Root = Presence;\nexport {\n  Presence,\n  Root\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/radio-group.tsx\nimport * as React2 from \"react\";\nimport { composeEventHandlers as composeEventHandlers2 } from \"@radix-ui/primitive\";\nimport { useComposedRefs as useComposedRefs2 } from \"@radix-ui/react-compose-refs\";\nimport { createContextScope as createContextScope2 } from \"@radix-ui/react-context\";\nimport { Primitive as Primitive2 } from \"@radix-ui/react-primitive\";\nimport * as RovingFocusGroup from \"@radix-ui/react-roving-focus\";\nimport { createRovingFocusGroupScope } from \"@radix-ui/react-roving-focus\";\nimport { useControllableState } from \"@radix-ui/react-use-controllable-state\";\nimport { useDirection } from \"@radix-ui/react-direction\";\n\n// src/radio.tsx\nimport * as React from \"react\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { useSize } from \"@radix-ui/react-use-size\";\nimport { usePrevious } from \"@radix-ui/react-use-previous\";\nimport { Presence } from \"@radix-ui/react-presence\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { jsx, jsxs } from \"react/jsx-runtime\";\nvar RADIO_NAME = \"Radio\";\nvar [createRadioContext, createRadioScope] = createContextScope(RADIO_NAME);\nvar [RadioProvider, useRadioContext] = createRadioContext(RADIO_NAME);\nvar Radio = React.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      __scopeRadio,\n      name,\n      checked = false,\n      required,\n      disabled,\n      value = \"on\",\n      onCheck,\n      form,\n      ...radioProps\n    } = props;\n    const [button, setButton] = React.useState(null);\n    const composedRefs = useComposedRefs(forwardedRef, (node) => setButton(node));\n    const hasConsumerStoppedPropagationRef = React.useRef(false);\n    const isFormControl = button ? form || !!button.closest(\"form\") : true;\n    return /* @__PURE__ */ jsxs(RadioProvider, { scope: __scopeRadio, checked, disabled, children: [\n      /* @__PURE__ */ jsx(\n        Primitive.button,\n        {\n          type: \"button\",\n          role: \"radio\",\n          \"aria-checked\": checked,\n          \"data-state\": getState(checked),\n          \"data-disabled\": disabled ? \"\" : void 0,\n          disabled,\n          value,\n          ...radioProps,\n          ref: composedRefs,\n          onClick: composeEventHandlers(props.onClick, (event) => {\n            if (!checked) onCheck?.();\n            if (isFormControl) {\n              hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();\n              if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();\n            }\n          })\n        }\n      ),\n      isFormControl && /* @__PURE__ */ jsx(\n        RadioBubbleInput,\n        {\n          control: button,\n          bubbles: !hasConsumerStoppedPropagationRef.current,\n          name,\n          value,\n          checked,\n          required,\n          disabled,\n          form,\n          style: { transform: \"translateX(-100%)\" }\n        }\n      )\n    ] });\n  }\n);\nRadio.displayName = RADIO_NAME;\nvar INDICATOR_NAME = \"RadioIndicator\";\nvar RadioIndicator = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeRadio, forceMount, ...indicatorProps } = props;\n    const context = useRadioContext(INDICATOR_NAME, __scopeRadio);\n    return /* @__PURE__ */ jsx(Presence, { present: forceMount || context.checked, children: /* @__PURE__ */ jsx(\n      Primitive.span,\n      {\n        \"data-state\": getState(context.checked),\n        \"data-disabled\": context.disabled ? \"\" : void 0,\n        ...indicatorProps,\n        ref: forwardedRef\n      }\n    ) });\n  }\n);\nRadioIndicator.displayName = INDICATOR_NAME;\nvar BUBBLE_INPUT_NAME = \"RadioBubbleInput\";\nvar RadioBubbleInput = React.forwardRef(\n  ({\n    __scopeRadio,\n    control,\n    checked,\n    bubbles = true,\n    ...props\n  }, forwardedRef) => {\n    const ref = React.useRef(null);\n    const composedRefs = useComposedRefs(ref, forwardedRef);\n    const prevChecked = usePrevious(checked);\n    const controlSize = useSize(control);\n    React.useEffect(() => {\n      const input = ref.current;\n      if (!input) return;\n      const inputProto = window.HTMLInputElement.prototype;\n      const descriptor = Object.getOwnPropertyDescriptor(\n        inputProto,\n        \"checked\"\n      );\n      const setChecked = descriptor.set;\n      if (prevChecked !== checked && setChecked) {\n        const event = new Event(\"click\", { bubbles });\n        setChecked.call(input, checked);\n        input.dispatchEvent(event);\n      }\n    }, [prevChecked, checked, bubbles]);\n    return /* @__PURE__ */ jsx(\n      Primitive.input,\n      {\n        type: \"radio\",\n        \"aria-hidden\": true,\n        defaultChecked: checked,\n        ...props,\n        tabIndex: -1,\n        ref: composedRefs,\n        style: {\n          ...props.style,\n          ...controlSize,\n          position: \"absolute\",\n          pointerEvents: \"none\",\n          opacity: 0,\n          margin: 0\n        }\n      }\n    );\n  }\n);\nRadioBubbleInput.displayName = BUBBLE_INPUT_NAME;\nfunction getState(checked) {\n  return checked ? \"checked\" : \"unchecked\";\n}\n\n// src/radio-group.tsx\nimport { jsx as jsx2 } from \"react/jsx-runtime\";\nvar ARROW_KEYS = [\"ArrowUp\", \"ArrowDown\", \"ArrowLeft\", \"ArrowRight\"];\nvar RADIO_GROUP_NAME = \"RadioGroup\";\nvar [createRadioGroupContext, createRadioGroupScope] = createContextScope2(RADIO_GROUP_NAME, [\n  createRovingFocusGroupScope,\n  createRadioScope\n]);\nvar useRovingFocusGroupScope = createRovingFocusGroupScope();\nvar useRadioScope = createRadioScope();\nvar [RadioGroupProvider, useRadioGroupContext] = createRadioGroupContext(RADIO_GROUP_NAME);\nvar RadioGroup = React2.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      __scopeRadioGroup,\n      name,\n      defaultValue,\n      value: valueProp,\n      required = false,\n      disabled = false,\n      orientation,\n      dir,\n      loop = true,\n      onValueChange,\n      ...groupProps\n    } = props;\n    const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeRadioGroup);\n    const direction = useDirection(dir);\n    const [value, setValue] = useControllableState({\n      prop: valueProp,\n      defaultProp: defaultValue ?? null,\n      onChange: onValueChange,\n      caller: RADIO_GROUP_NAME\n    });\n    return /* @__PURE__ */ jsx2(\n      RadioGroupProvider,\n      {\n        scope: __scopeRadioGroup,\n        name,\n        required,\n        disabled,\n        value,\n        onValueChange: setValue,\n        children: /* @__PURE__ */ jsx2(\n          RovingFocusGroup.Root,\n          {\n            asChild: true,\n            ...rovingFocusGroupScope,\n            orientation,\n            dir: direction,\n            loop,\n            children: /* @__PURE__ */ jsx2(\n              Primitive2.div,\n              {\n                role: \"radiogroup\",\n                \"aria-required\": required,\n                \"aria-orientation\": orientation,\n                \"data-disabled\": disabled ? \"\" : void 0,\n                dir: direction,\n                ...groupProps,\n                ref: forwardedRef\n              }\n            )\n          }\n        )\n      }\n    );\n  }\n);\nRadioGroup.displayName = RADIO_GROUP_NAME;\nvar ITEM_NAME = \"RadioGroupItem\";\nvar RadioGroupItem = React2.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeRadioGroup, disabled, ...itemProps } = props;\n    const context = useRadioGroupContext(ITEM_NAME, __scopeRadioGroup);\n    const isDisabled = context.disabled || disabled;\n    const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeRadioGroup);\n    const radioScope = useRadioScope(__scopeRadioGroup);\n    const ref = React2.useRef(null);\n    const composedRefs = useComposedRefs2(forwardedRef, ref);\n    const checked = context.value === itemProps.value;\n    const isArrowKeyPressedRef = React2.useRef(false);\n    React2.useEffect(() => {\n      const handleKeyDown = (event) => {\n        if (ARROW_KEYS.includes(event.key)) {\n          isArrowKeyPressedRef.current = true;\n        }\n      };\n      const handleKeyUp = () => isArrowKeyPressedRef.current = false;\n      document.addEventListener(\"keydown\", handleKeyDown);\n      document.addEventListener(\"keyup\", handleKeyUp);\n      return () => {\n        document.removeEventListener(\"keydown\", handleKeyDown);\n        document.removeEventListener(\"keyup\", handleKeyUp);\n      };\n    }, []);\n    return /* @__PURE__ */ jsx2(\n      RovingFocusGroup.Item,\n      {\n        asChild: true,\n        ...rovingFocusGroupScope,\n        focusable: !isDisabled,\n        active: checked,\n        children: /* @__PURE__ */ jsx2(\n          Radio,\n          {\n            disabled: isDisabled,\n            required: context.required,\n            checked,\n            ...radioScope,\n            ...itemProps,\n            name: context.name,\n            ref: composedRefs,\n            onCheck: () => context.onValueChange(itemProps.value),\n            onKeyDown: composeEventHandlers2((event) => {\n              if (event.key === \"Enter\") event.preventDefault();\n            }),\n            onFocus: composeEventHandlers2(itemProps.onFocus, () => {\n              if (isArrowKeyPressedRef.current) ref.current?.click();\n            })\n          }\n        )\n      }\n    );\n  }\n);\nRadioGroupItem.displayName = ITEM_NAME;\nvar INDICATOR_NAME2 = \"RadioGroupIndicator\";\nvar RadioGroupIndicator = React2.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeRadioGroup, ...indicatorProps } = props;\n    const radioScope = useRadioScope(__scopeRadioGroup);\n    return /* @__PURE__ */ jsx2(RadioIndicator, { ...radioScope, ...indicatorProps, ref: forwardedRef });\n  }\n);\nRadioGroupIndicator.displayName = INDICATOR_NAME2;\nvar Root2 = RadioGroup;\nvar Item2 = RadioGroupItem;\nvar Indicator = RadioGroupIndicator;\nexport {\n  Indicator,\n  Item2 as Item,\n  RadioGroup,\n  RadioGroupIndicator,\n  RadioGroupItem,\n  Root2 as Root,\n  createRadioGroupScope\n};\n//# sourceMappingURL=index.mjs.map\n","import * as React from \"react\"\nimport * as RadioGroupPrimitive from \"@radix-ui/react-radio-group\"\nimport { Circle } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\nimport type { RadioGroupItemProps } from \"./Radio.types\"\n\nconst RadioGroup = React.forwardRef<\n  React.ElementRef<typeof RadioGroupPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>\n>(({ className, ...props }, ref) => {\n  return (\n    <RadioGroupPrimitive.Root\n      className={cn(\"grid gap-2\", className)}\n      {...props}\n      ref={ref}\n    />\n  )\n})\nRadioGroup.displayName = RadioGroupPrimitive.Root.displayName\n\nconst RadioGroupItem = React.forwardRef<\n  React.ElementRef<typeof RadioGroupPrimitive.Item>,\n  RadioGroupItemProps\n>(({ className, size = 'md', labelPosition = 'end', invalid = false, label, description, id: providedId, ...props }, ref) => {\n  const fallbackId = React.useId();\n  const id = providedId ?? fallbackId;\n\n  const sizeClasses = {\n    sm: \"h-4 w-4\",\n    md: \"h-5 w-5\",\n    lg: \"h-6 w-6\",\n  };\n\n  const iconSizes = {\n    sm: \"h-2 w-2\",\n    md: \"h-2 w-2\",\n    lg: \"h-3 w-3\",\n  };\n\n  const labelSizes = {\n    sm: \"text-sm\",\n    md: \"text-base\",\n    lg: \"text-lg\",\n  };\n\n  const radioItem = (\n    <RadioGroupPrimitive.Item\n      ref={ref}\n      id={id}\n      className={cn(\n        \"aspect-square rounded-full border ring-offset-background\", \n        \"focus:outline-hidden focus-visible:ring-4 focus-visible:ring-offset-2\",\n        \"shrink-0 transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-50\",\n        invalid\n          ? \"border-destructive data-[state=checked]:bg-primary data-[state=checked]:dark:bg-primary-300 data-[state=checked]:border-destructive text-destructive focus-visible:ring-red-400 focus-visible:ring-offset-red-100 dark:focus-visible:ring-red-500/50 dark:focus-visible:ring-offset-gray-900\"\n          : \"border-zinc-200 data-[state=checked]:bg-primary data-[state=checked]:dark:bg-primary-200 data-[state=checked]:border-primary-500 data-[state=checked]:dark:border-primary-300 text-primary focus-visible:ring-primary-400 focus-visible:ring-offset-primary-100 dark:focus-visible:ring-primary-500/50 dark:focus-visible:ring-offset-gray-900\",\n        sizeClasses[size]\n      )}\n      {...props}\n    >\n      <RadioGroupPrimitive.Indicator className=\"flex items-center justify-center h-full w-full\">\n        <Circle className={cn(\"fill-white text-white dark:fill-primary dark:text-primary relative max-w-full max-h-full\", iconSizes[size])} />\n      </RadioGroupPrimitive.Indicator>\n    </RadioGroupPrimitive.Item>\n  );\n\n  if (!label && !description) {\n    return radioItem;\n  }\n\n  return (\n    <div className={cn(\n      \"flex items-start gap-3\",\n      labelPosition === 'start' ? \"flex-row-reverse justify-end w-full\" : \"flex-row\",\n      className\n    )}>\n      <div className={cn(\"flex pt-0.5\", labelPosition === 'start' ? \"ml-auto\" : \"\")}>\n        {radioItem}\n      </div>\n      <div className=\"flex flex-col gap-1 flex-1\">\n        {label && (\n          <label\n            htmlFor={id}\n            className={cn(\n              \"font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70 leading-none cursor-pointer\",\n              invalid && \"text-destructive\",\n              labelSizes[size]\n            )}\n          >\n            {label}\n          </label>\n        )}\n        {description && (\n          <p className={cn(\"text-sm peer-disabled:opacity-70\", invalid ? \"text-destructive\" : \"text-muted-foreground\")}>\n            {description}\n          </p>\n        )}\n      </div>\n    </div>\n  );\n})\nRadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName\n\n// Mantenemos la exportacion Radio por si se importaba asi externamente\nexport { RadioGroup, RadioGroupItem, RadioGroupItem as Radio }\n","\"use client\";\n\n// src/switch.tsx\nimport * as React from \"react\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { useControllableState } from \"@radix-ui/react-use-controllable-state\";\nimport { usePrevious } from \"@radix-ui/react-use-previous\";\nimport { useSize } from \"@radix-ui/react-use-size\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { jsx, jsxs } from \"react/jsx-runtime\";\nvar SWITCH_NAME = \"Switch\";\nvar [createSwitchContext, createSwitchScope] = createContextScope(SWITCH_NAME);\nvar [SwitchProvider, useSwitchContext] = createSwitchContext(SWITCH_NAME);\nvar Switch = React.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      __scopeSwitch,\n      name,\n      checked: checkedProp,\n      defaultChecked,\n      required,\n      disabled,\n      value = \"on\",\n      onCheckedChange,\n      form,\n      ...switchProps\n    } = props;\n    const [button, setButton] = React.useState(null);\n    const composedRefs = useComposedRefs(forwardedRef, (node) => setButton(node));\n    const hasConsumerStoppedPropagationRef = React.useRef(false);\n    const isFormControl = button ? form || !!button.closest(\"form\") : true;\n    const [checked, setChecked] = useControllableState({\n      prop: checkedProp,\n      defaultProp: defaultChecked ?? false,\n      onChange: onCheckedChange,\n      caller: SWITCH_NAME\n    });\n    return /* @__PURE__ */ jsxs(SwitchProvider, { scope: __scopeSwitch, checked, disabled, children: [\n      /* @__PURE__ */ jsx(\n        Primitive.button,\n        {\n          type: \"button\",\n          role: \"switch\",\n          \"aria-checked\": checked,\n          \"aria-required\": required,\n          \"data-state\": getState(checked),\n          \"data-disabled\": disabled ? \"\" : void 0,\n          disabled,\n          value,\n          ...switchProps,\n          ref: composedRefs,\n          onClick: composeEventHandlers(props.onClick, (event) => {\n            setChecked((prevChecked) => !prevChecked);\n            if (isFormControl) {\n              hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();\n              if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();\n            }\n          })\n        }\n      ),\n      isFormControl && /* @__PURE__ */ jsx(\n        SwitchBubbleInput,\n        {\n          control: button,\n          bubbles: !hasConsumerStoppedPropagationRef.current,\n          name,\n          value,\n          checked,\n          required,\n          disabled,\n          form,\n          style: { transform: \"translateX(-100%)\" }\n        }\n      )\n    ] });\n  }\n);\nSwitch.displayName = SWITCH_NAME;\nvar THUMB_NAME = \"SwitchThumb\";\nvar SwitchThumb = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeSwitch, ...thumbProps } = props;\n    const context = useSwitchContext(THUMB_NAME, __scopeSwitch);\n    return /* @__PURE__ */ jsx(\n      Primitive.span,\n      {\n        \"data-state\": getState(context.checked),\n        \"data-disabled\": context.disabled ? \"\" : void 0,\n        ...thumbProps,\n        ref: forwardedRef\n      }\n    );\n  }\n);\nSwitchThumb.displayName = THUMB_NAME;\nvar BUBBLE_INPUT_NAME = \"SwitchBubbleInput\";\nvar SwitchBubbleInput = React.forwardRef(\n  ({\n    __scopeSwitch,\n    control,\n    checked,\n    bubbles = true,\n    ...props\n  }, forwardedRef) => {\n    const ref = React.useRef(null);\n    const composedRefs = useComposedRefs(ref, forwardedRef);\n    const prevChecked = usePrevious(checked);\n    const controlSize = useSize(control);\n    React.useEffect(() => {\n      const input = ref.current;\n      if (!input) return;\n      const inputProto = window.HTMLInputElement.prototype;\n      const descriptor = Object.getOwnPropertyDescriptor(\n        inputProto,\n        \"checked\"\n      );\n      const setChecked = descriptor.set;\n      if (prevChecked !== checked && setChecked) {\n        const event = new Event(\"click\", { bubbles });\n        setChecked.call(input, checked);\n        input.dispatchEvent(event);\n      }\n    }, [prevChecked, checked, bubbles]);\n    return /* @__PURE__ */ jsx(\n      \"input\",\n      {\n        type: \"checkbox\",\n        \"aria-hidden\": true,\n        defaultChecked: checked,\n        ...props,\n        tabIndex: -1,\n        ref: composedRefs,\n        style: {\n          ...props.style,\n          ...controlSize,\n          position: \"absolute\",\n          pointerEvents: \"none\",\n          opacity: 0,\n          margin: 0\n        }\n      }\n    );\n  }\n);\nSwitchBubbleInput.displayName = BUBBLE_INPUT_NAME;\nfunction getState(checked) {\n  return checked ? \"checked\" : \"unchecked\";\n}\nvar Root = Switch;\nvar Thumb = SwitchThumb;\nexport {\n  Root,\n  Switch,\n  SwitchThumb,\n  Thumb,\n  createSwitchScope\n};\n//# sourceMappingURL=index.mjs.map\n","import * as React from \"react\"\nimport * as SwitchPrimitives from \"@radix-ui/react-switch\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"../../lib/utils\"\nimport type { SwitchProps } from \"./Switch.types\"\n\nconst switchVariants = cva(\n  \"peer inline-flex shrink-0 cursor-pointer items-center rounded-full border transition-colors focus-visible:outline-hidden focus-visible:ring-4 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:dark:bg-primary-200 data-[state=checked]:border-primary-500 data-[state=unchecked]:bg-zinc-100 data-[state=unchecked]:border-zinc-200 min-w-max\",\n  {\n    variants: {\n      size: {\n        sm: \"h-4 w-7\",\n        md: \"h-5 w-9\",\n        lg: \"h-6 w-11\",\n      },\n    },\n    defaultVariants: {\n      size: \"md\",\n    },\n  }\n)\n\nconst thumbVariants = cva(\n  \"pointer-events-none block rounded-full border bg-white shadow-lg ring-0 transition-transform data-[state=checked]:border-primary-500 data-[state=checked]:dark:border-primary-300 data-[state=unchecked]:border-zinc-200 data-[state=unchecked]:translate-x-0\",\n  {\n    variants: {\n      size: {\n        sm: \"h-3 w-3 data-[state=checked]:translate-x-3\",\n        md: \"h-4 w-4 data-[state=checked]:translate-x-4\",\n        lg: \"h-5 w-5 data-[state=checked]:translate-x-5\",\n      },\n    },\n    defaultVariants: {\n      size: \"md\",\n    },\n  }\n)\n\nconst labelVariants = cva(\n  \"font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70\",\n  {\n    variants: {\n      size: {\n        sm: \"text-sm\",\n        md: \"text-base\",\n        lg: \"text-lg\",\n      },\n      isInvalid: {\n        true: \"text-destructive\",\n      }\n    },\n    defaultVariants: {\n      size: \"md\",\n    },\n  }\n)\n\nconst Switch = React.forwardRef<\n  React.ElementRef<typeof SwitchPrimitives.Root>,\n  SwitchProps\n>(({ className, size = \"md\", label, description, labelPosition = \"end\", isInvalid, id, ...props }, ref) => {\n  const switchId = id || React.useId();\n\n  const switchElement = (\n    <SwitchPrimitives.Root\n      id={switchId}\n      className={cn(\n        switchVariants({ size }),\n        isInvalid\n          ? \"data-[state=unchecked]:border-destructive data-[state=unchecked]:bg-zinc-200 focus-visible:ring-red-400 focus-visible:ring-offset-red-100 dark:focus-visible:ring-red-500/50 dark:focus-visible:ring-offset-gray-900\"\n          : \"focus-visible:ring-primary-400 focus-visible:ring-offset-primary-100 dark:focus-visible:ring-primary-500/50 dark:focus-visible:ring-offset-gray-900\",\n        className\n      )}\n      {...props}\n      ref={ref}\n    >\n      <SwitchPrimitives.Thumb\n        className={cn(thumbVariants({ size }))}\n      />\n    </SwitchPrimitives.Root>\n  );\n\n  if (!label && !description) {\n    return switchElement;\n  }\n\n  const labelContainer = (\n    <div className=\"grid gap-1.5 leading-none\">\n      {label && (\n        <label\n          htmlFor={switchId}\n          className={cn(labelVariants({ size, isInvalid }))}\n        >\n          {label}\n        </label>\n      )}\n      {description && (\n        <p className={cn(\"text-sm text-muted-foreground\", isInvalid && \"text-destructive/80\")}>\n          {description}\n        </p>\n      )}\n    </div>\n  );\n\n  const isReversed = labelPosition === \"start\";\n\n  return (\n    <div className={cn(\n      \"flex space-x-2\",\n      description ? \"items-start\" : \"items-center\",\n      className\n    )}>\n      {isReversed ? (\n        <>\n          <div className=\"flex flex-1\">{labelContainer}</div>\n          <div className={cn(description && \"pt-0.5\", \"flex shrink-0\")}>{switchElement}</div>\n        </>\n      ) : (\n        <>\n          <div className={cn(description && \"pt-0.5\", \"flex shrink-0\")}>{switchElement}</div>\n          {labelContainer}\n        </>\n      )}\n    </div>\n  )\n})\nSwitch.displayName = SwitchPrimitives.Root.displayName\n\nexport { Switch }\n","import React, { useState } from 'react';\nimport type { AvatarProps } from './Avatar.types';\n\nexport const Avatar: React.FC<AvatarProps> = ({\n  src,\n  alt = 'Avatar',\n  name,\n  icon,\n  size = 'md',\n  shape = 'circle',\n  status,\n  statusRingWidth = 'ring-2',\n  statusRingColor = 'ring-white dark:ring-zinc-900',\n  className = '',\n}) => {\n  const [imageError, setImageError] = useState(false);\n\n  const getInitials = (name: string) => {\n    const parts = name.trim().split(/\\s+/);\n    if (parts.length === 0) return '';\n    if (parts.length === 1) return parts[0].charAt(0).toUpperCase();\n    return `${parts[0].charAt(0)}${parts[parts.length - 1].charAt(0)}`.toUpperCase();\n  };\n\n  const sizeClasses = {\n    xs: 'w-6 h-6 text-xs',\n    sm: 'w-8 h-8 text-sm',\n    md: 'w-10 h-10 text-base',\n    lg: 'w-12 h-12 text-lg',\n    xl: 'w-14 h-14 text-xl',\n  };\n\n  const shapeClasses = {\n    circle: 'rounded-full',\n    square: 'rounded-md',\n  };\n\n  const statusColors = {\n    online: 'bg-lime-400 ',\n    offline: 'bg-zinc-400',\n    busy: 'bg-red-400',\n    away: 'bg-yellow-400',\n  };\n\n  const statusSizes = {\n    xs: 'w-1.5 h-1.5 ring-1',\n    sm: 'w-2 h-2 ring-1',\n    md: 'w-2.5 h-2.5 ring-2',\n    lg: 'w-3 h-3 ring-2',\n    xl: 'w-3.5 h-3.5 ring-2',\n  };\n\n  // Adjust position depending on shape\n  const statusPositionClasses = shape === 'circle'\n    ? 'bottom-0 right-0'\n    : '-bottom-1 -right-1';\n\n  // Translate ring width correctly if a custom one is provided, otherwise keep default sizes\n  const statusDotClasses = [\n    'absolute',\n    'rounded-full',\n    statusPositionClasses,\n    statusColors[status as keyof typeof statusColors],\n    statusSizes[size].replace(/ring-\\d/, statusRingWidth),\n    statusRingColor,\n  ].join(' ');\n\n  const containerClasses = [\n    'relative inline-flex items-center justify-center overflow-visible bg-gray-100 dark:bg-gray-700',\n    sizeClasses[size],\n    shapeClasses[shape],\n    className\n  ].join(' ');\n\n  const contentClasses = [\n    'w-full h-full object-cover object-center flex items-center justify-center',\n    shapeClasses[shape]\n  ].join(' ');\n\n  return (\n    <div className={containerClasses}>\n      {src && !imageError ? (\n        <img\n          src={src}\n          alt={alt}\n          className={contentClasses}\n          onError={() => setImageError(true)}\n        />\n      ) : name ? (\n        <span className=\"font-medium text-gray-600 dark:text-gray-300 select-none\">\n          {getInitials(name)}\n        </span>\n      ) : icon ? (\n        <div className=\"flex items-center justify-center text-gray-500 dark:text-gray-400 w-1/2 h-1/2\">\n          {icon}\n        </div>\n      ) : (\n        <svg\n          className=\"w-[60%] h-[60%] text-gray-400 dark:text-gray-500\"\n          fill=\"currentColor\"\n          viewBox=\"0 0 20 20\"\n          xmlns=\"http://www.w3.org/2000/svg\"\n        >\n          <path\n            fillRule=\"evenodd\"\n            d=\"M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z\"\n            clipRule=\"evenodd\"\n          />\n        </svg>\n      )}\n\n      {status && (\n        <span className={statusDotClasses} />\n      )}\n    </div>\n  );\n};","import { forwardRef } from 'react';\nimport type { DividerProps } from './Divider.types';\n\n/**\n * Divider del sistema de diseño Siesa\n *\n * Línea horizontal de 1px para separar contenido visual o semánticamente.\n * Implementa dos variantes con soporte completo de dark mode.\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Componente semántico usando elemento <hr>\n *\n * @see docs/colors.md - Sistema de colores (border-primary, border-secondary)\n * @see docs/spacing.md - Sistema de espaciado (altura de 1px)\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4096-8445 - Especificaciones Figma\n *\n * @example\n * ```tsx\n * // Default divider (más visible)\n * <Divider />\n * <Divider type=\"default\" />\n *\n * // Soft divider (más sutil)\n * <Divider type=\"soft\" />\n *\n * // Con clases personalizadas\n * <Divider className=\"my-6\" />\n * ```\n */\nexport const Divider = forwardRef<HTMLHRElement, DividerProps>(\n  (\n    {\n      type = 'default',\n      className = '',\n      ...props\n    },\n    ref\n  ) => {\n    // ===== CLASES DE TIPO =====\n    // Orden de modificadores: {dark}:{utility}\n    const typeClasses = {\n      // Default: Línea más visible para separaciones claras\n      // Light: border-primary (#e4e4e7)\n      // Dark: dark-border-primary (#71717a)\n      default: 'bg-border-primary dark:bg-dark-border-primary',\n\n      // Soft: Línea más sutil para separaciones suaves\n      // Light: border-secondary (#f4f4f5 - muy claro)\n      // Dark: gray-700 (#374151 - gris medio-oscuro, más sutil que dark-border-primary)\n      soft: 'bg-border-secondary dark:bg-gray-700',\n    };\n\n    // ===== CLASES BASE =====\n    const baseClasses = 'w-full h-px border-0';\n\n    // ===== COMBINAR CLASES =====\n    const finalClasses = [\n      baseClasses,\n      typeClasses[type],\n      className,\n    ]\n      .join(' ')\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    return (\n      <hr\n        ref={ref}\n        className={finalClasses}\n        {...props}\n      />\n    );\n  }\n);\n\nDivider.displayName = 'Divider';\n","import { forwardRef } from 'react';\nimport type { DescriptionListProps } from './DescriptionList.types';\n\n/**\n * DescriptionList del sistema de diseño Siesa\n *\n * Componente para mostrar información estructurada en formato clave-valor (term/details).\n * Layout de dos columnas con separador inferior entre items.\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Layout flexible y responsive\n * - Tipografía del sistema (Paragraph/Small - 14px)\n *\n * @see docs/colors.md - Sistema de colores (content-primary, content-secondary)\n * @see docs/typography.md - Sistema tipográfico (Paragraph/Small)\n * @see docs/spacing.md - Sistema de espaciado (padding, gaps)\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4103-8449 - Especificaciones Figma\n *\n * @example\n * ```tsx\n * // Item básico\n * <DescriptionList\n *   term=\"Customer\"\n *   details=\"Jhonatan Diaz\"\n * />\n *\n * // Lista completa\n * <div>\n *   <DescriptionList term=\"Event\" details=\"Bear Hug: Live in Concert\" />\n *   <DescriptionList term=\"Amount\" details=\"$120,000 COP\" />\n *   <DescriptionList term=\"Fee\" details=\"$20,000 COP\" />\n * </div>\n * ```\n */\nexport const DescriptionList = forwardRef<HTMLDivElement, DescriptionListProps>(\n  (\n    {\n      term,\n      details,\n      className = '',\n      ...props\n    },\n    ref\n  ) => {\n    // ===== CLASES BASE =====\n    const baseClasses = `\n      flex\n      flex-wrap\n      gap-1\n      items-start\n      py-2.5\n      border-b\n      border-border-secondary\n      dark:border-gray-700\n    `;\n\n    // ===== CLASES DE COLUMNA =====\n    // Cada columna ocupa el 50% del espacio disponible (flex-1)\n    // con un ancho mínimo de 180px para mantener legibilidad\n    const columnClasses = 'flex-1 min-w-[180px]';\n\n    // ===== COMBINAR CLASES =====\n    const finalClasses = [baseClasses, className]\n      .join(' ')\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    return (\n      <div ref={ref} className={finalClasses} {...props}>\n        {/* Term Column (izquierda) */}\n        {/* Light: content-secondary (#a1a1aa) */}\n        {/* Dark: gray-400 (#9ca3af - gris medio claro para mantener contraste) */}\n        <div className={columnClasses}>\n          <p className=\"text-sm leading-5 text-content-secondary dark:text-gray-400 font-normal\">\n            {term}\n          </p>\n        </div>\n\n        {/* Details Column (derecha) */}\n        {/* Light: content-primary (#18181b) */}\n        {/* Dark: dark-content-primary (#ffffff) */}\n        <div className={columnClasses}>\n          <p className=\"text-sm leading-5 text-content-primary dark:text-dark-content-primary font-normal\">\n            {details}\n          </p>\n        </div>\n      </div>\n    );\n  }\n);\n\nDescriptionList.displayName = 'DescriptionList';\n","import * as React from \"react\";\nfunction ArchiveBoxIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m20.25 7.5-.625 10.632a2.25 2.25 0 0 1-2.247 2.118H6.622a2.25 2.25 0 0 1-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArchiveBoxIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowDownTrayIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowDownTrayIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowLeftStartOnRectangleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M8.25 9V5.25A2.25 2.25 0 0 1 10.5 3h6a2.25 2.25 0 0 1 2.25 2.25v13.5A2.25 2.25 0 0 1 16.5 21h-6a2.25 2.25 0 0 1-2.25-2.25V15m-3 0-3-3m0 0 3-3m-3 3H15\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowLeftStartOnRectangleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowLeftIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowLeftIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowPathIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowPathIcon);\nexport default ForwardRef;","import * as React from \"react\";\n/** @deprecated */\nfunction ArrowRightOnRectangleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-6a2.25 2.25 0 0 0-2.25 2.25v13.5A2.25 2.25 0 0 0 7.5 21h6a2.25 2.25 0 0 0 2.25-2.25V15m3 0 3-3m0 0-3-3m3 3H9\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowRightOnRectangleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowUpTrayIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowUpTrayIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowUturnLeftIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M9 15 3 9m0 0 6-6M3 9h12a6 6 0 0 1 0 12h-3\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowUturnLeftIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowsPointingInIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M9 9V4.5M9 9H4.5M9 9 3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5 5.25 5.25\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowsPointingInIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ArrowsPointingOutIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ArrowsPointingOutIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction Bars3Icon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(Bars3Icon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction BellIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(BellIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction BuildingOffice2Icon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M2.25 21h19.5m-18-18v18m10.5-18v18m6-13.5V21M6.75 6.75h.75m-.75 3h.75m-.75 3h.75m3-6h.75m-.75 3h.75m-.75 3h.75M6.75 21v-3.375c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21M3 3h12m-.75 4.5H21m-3.75 3.75h.008v.008h-.008v-.008Zm0 3h.008v.008h-.008v-.008Zm0 3h.008v.008h-.008v-.008Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(BuildingOffice2Icon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction BuildingOfficeIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3.75 21h16.5M4.5 3h15M5.25 3v18m13.5-18v18M9 6.75h1.5m-1.5 3h1.5m-1.5 3h1.5m3-6H15m-1.5 3H15m-1.5 3H15M9 21v-3.375c0-.621.504-1.125 1.125-1.125h3.75c.621 0 1.125.504 1.125 1.125V21\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(BuildingOfficeIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction CalendarIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 0 1 2.25-2.25h13.5A2.25 2.25 0 0 1 21 7.5v11.25m-18 0A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75m-18 0v-7.5A2.25 2.25 0 0 1 5.25 9h13.5A2.25 2.25 0 0 1 21 11.25v7.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CalendarIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction CheckCircleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CheckCircleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction CheckIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m4.5 12.75 6 6 9-13.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CheckIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ChevronDownIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m19.5 8.25-7.5 7.5-7.5-7.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ChevronDownIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ChevronLeftIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15.75 19.5 8.25 12l7.5-7.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ChevronLeftIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ChevronRightIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m8.25 4.5 7.5 7.5-7.5 7.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ChevronRightIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ClockIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ClockIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction CloudArrowUpIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CloudArrowUpIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ComputerDesktopIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M9 17.25v1.007a3 3 0 0 1-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0 1 15 18.257V17.25m6-12V15a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 15V5.25m18 0A2.25 2.25 0 0 0 18.75 3H5.25A2.25 2.25 0 0 0 3 5.25m18 0V12a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 12V5.25\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ComputerDesktopIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction CreditCardIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M2.25 8.25h19.5M2.25 9h19.5m-16.5 5.25h6m-6 2.25h3m-3.75 3h15a2.25 2.25 0 0 0 2.25-2.25V6.75A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25v10.5A2.25 2.25 0 0 0 4.5 19.5Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CreditCardIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction CubeIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m21 7.5-9-5.25L3 7.5m18 0-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-9v9\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CubeIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction DocumentArrowDownIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m.75 12 3 3m0 0 3-3m-3 3v-6m-1.5-9H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(DocumentArrowDownIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction DocumentDuplicateIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(DocumentDuplicateIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction DocumentTextIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(DocumentTextIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction DocumentIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(DocumentIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction EllipsisVerticalIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 6.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 12.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 18.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(EllipsisVerticalIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ExclamationCircleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ExclamationCircleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ExclamationTriangleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ExclamationTriangleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction EyeIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z\"\n  }), /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(EyeIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction FilmIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 0 1-1.125-1.125M3.375 19.5h1.5C5.496 19.5 6 18.996 6 18.375m-3.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-1.5A1.125 1.125 0 0 1 18 18.375M20.625 4.5H3.375m17.25 0c.621 0 1.125.504 1.125 1.125M20.625 4.5h-1.5C18.504 4.5 18 5.004 18 5.625m3.75 0v1.5c0 .621-.504 1.125-1.125 1.125M3.375 4.5c-.621 0-1.125.504-1.125 1.125M3.375 4.5h1.5C5.496 4.5 6 5.004 6 5.625m-3.75 0v1.5c0 .621.504 1.125 1.125 1.125m0 0h1.5m-1.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m1.5-3.75C5.496 8.25 6 7.746 6 7.125v-1.5M4.875 8.25C5.496 8.25 6 8.754 6 9.375v1.5m0-5.25v5.25m0-5.25C6 5.004 6.504 4.5 7.125 4.5h9.75c.621 0 1.125.504 1.125 1.125m1.125 2.625h1.5m-1.5 0A1.125 1.125 0 0 1 18 7.125v-1.5m1.125 2.625c-.621 0-1.125.504-1.125 1.125v1.5m2.625-2.625c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125M18 5.625v5.25M7.125 12h9.75m-9.75 0A1.125 1.125 0 0 1 6 10.875M7.125 12C6.504 12 6 12.504 6 13.125m0-2.25C6 11.496 5.496 12 4.875 12M18 10.875c0 .621-.504 1.125-1.125 1.125M18 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m-12 5.25v-5.25m0 5.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125m-12 0v-1.5c0-.621-.504-1.125-1.125-1.125M18 18.375v-5.25m0 5.25v-1.5c0-.621.504-1.125 1.125-1.125M18 13.125v1.5c0 .621.504 1.125 1.125 1.125M18 13.125c0-.621.504-1.125 1.125-1.125M6 13.125v1.5c0 .621-.504 1.125-1.125 1.125M6 13.125C6 12.504 5.496 12 4.875 12m-1.5 0h1.5m-1.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M19.125 12h1.5m0 0c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h1.5m14.25 0h1.5\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(FilmIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction FunnelIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 3c2.755 0 5.455.232 8.083.678.533.09.917.556.917 1.096v1.044a2.25 2.25 0 0 1-.659 1.591l-5.432 5.432a2.25 2.25 0 0 0-.659 1.591v2.927a2.25 2.25 0 0 1-1.244 2.013L9.75 21v-6.568a2.25 2.25 0 0 0-.659-1.591L3.659 7.409A2.25 2.25 0 0 1 3 5.818V4.774c0-.54.384-1.006.917-1.096A48.32 48.32 0 0 1 12 3Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(FunnelIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction GlobeAltIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(GlobeAltIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction InformationCircleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(InformationCircleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction LinkIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(LinkIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ListBulletIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0ZM3.75 12h.007v.008H3.75V12Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm-.375 5.25h.007v.008H3.75v-.008Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ListBulletIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction LockClosedIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(LockClosedIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction LockOpenIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M13.5 10.5V6.75a4.5 4.5 0 1 1 9 0v3.75M3.75 21.75h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H3.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(LockOpenIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction MagnifyingGlassIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(MagnifyingGlassIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction MinusCircleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15 12H9m12 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(MinusCircleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction MoonIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(MoonIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction MusicalNoteIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m9 9 10.5-3m0 6.553v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 1 1-.99-3.467l2.31-.66a2.25 2.25 0 0 0 1.632-2.163Zm0 0V2.25L9 5.25v10.303m0 0v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 0 1-.99-3.467l2.31-.66A2.25 2.25 0 0 0 9 15.553Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(MusicalNoteIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction NoSymbolIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M18.364 18.364A9 9 0 0 0 5.636 5.636m12.728 12.728A9 9 0 0 1 5.636 5.636m12.728 12.728L5.636 5.636\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(NoSymbolIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction PencilSquareIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(PencilSquareIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction PencilIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L6.832 19.82a4.5 4.5 0 0 1-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 0 1 1.13-1.897L16.863 4.487Zm0 0L19.5 7.125\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(PencilIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction PhotoIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(PhotoIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction PlusIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M12 4.5v15m7.5-7.5h-15\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(PlusIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction PrinterIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0 1 10.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0 .229 2.523a1.125 1.125 0 0 1-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.318 0h1.091A2.25 2.25 0 0 0 21 15.75V9.456c0-1.081-.768-2.015-1.837-2.175a48.055 48.055 0 0 0-1.913-.247M6.34 18H5.25A2.25 2.25 0 0 1 3 15.75V9.456c0-1.081.768-2.015 1.837-2.175a48.041 48.041 0 0 1 1.913-.247m10.5 0a48.536 48.536 0 0 0-10.5 0m10.5 0V3.375c0-.621-.504-1.125-1.125-1.125h-8.25c-.621 0-1.125.504-1.125 1.125v3.659M18 10.5h.008v.008H18V10.5Zm-3 0h.008v.008H15V10.5Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(PrinterIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ShoppingBagIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007ZM8.625 10.5a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm7.5 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ShoppingBagIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ShoppingCartIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ShoppingCartIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction Squares2X2Icon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(Squares2X2Icon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction TrashIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(TrashIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction UserIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(UserIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction XCircleIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(XCircleIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction XMarkIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    fill: \"none\",\n    viewBox: \"0 0 24 24\",\n    strokeWidth: 1.5,\n    stroke: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    d: \"M6 18 18 6M6 6l12 12\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(XMarkIcon);\nexport default ForwardRef;","import { forwardRef } from 'react';\nimport type { AlertDialogProps } from './AlertDialog.types';\nimport { Button } from '../Button/Button';\nimport { Dialog, Transition } from '@headlessui/react';\nimport { Fragment } from 'react';\nimport {\n  ExclamationTriangleIcon,\n  ExclamationCircleIcon,\n  CheckIcon,\n  InformationCircleIcon\n} from '@heroicons/react/24/outline';\n\n/**\n * AlertDialog - Componente de alerta/diálogo del sistema de diseño Siesa\n *\n * Componente modal para confirmaciones con soporte para:\n * - Título y descripción\n * - Contenido personalizado (children)\n * - Botones de acción personalizados o por defecto\n * - Dark mode\n * - Transiciones y accesibilidad (basado en Headless UI Dialog)\n *\n * 🚨 NOTA IMPORTANTE:\n * El prop `inline={true}` es ESTRICTAMENTE PARA DOCUMENTACIÓN EN STORYBOOK.\n * Nunca utilice `inline` en aplicaciones de producción ya que destruye el bloqueo de foco (focus lock)\n * y la gestión de portales, causando problemas severos de accesibilidad.\n *\n * @example\n * ```tsx\n * <AlertDialog\n *   isOpen={isOpen}\n *   title=\"Are you sure you want to refund this payment?\"\n *   description=\"The refund will be reflected in 2 to 3 business days.\"\n *   onCancel={() => setIsOpen(false)}\n *   onConfirm={() => console.log('Confirmed')}\n *   confirmText=\"Refund\"\n * />\n * ```\n */\nexport const AlertDialog = forwardRef<HTMLDivElement, AlertDialogProps>(\n  (\n    {\n      title,\n      description,\n      isOpen = true, // Defaulting to true for backward compatibility\n      inline = false, // Renderiza sin React Portal para previsualizaciones (Storybook)\n      icon,\n      align = 'left',\n      fullWidthButtons = false,\n      fullWidthButtonsDirection = 'vertical',\n      hideCancel = false,\n      showCloseButton = false,\n      actions,\n      onCancel,\n      onConfirm,\n      cancelText = 'Cancelar',\n      confirmText = 'Confirmar',\n      isProcess = false,\n      preventCloseOnOverlayClick = false,\n      size = 'max-w-lg', // Por defecto Tailwind hace max-w-lg = 32rem (512px)\n      type = 'default',\n      className = '',\n      ...props\n    },\n    ref\n  ) => {\n    // Generar clases para el contenedor de botones\n    let buttonsContainerClasses = 'flex flex-wrap items-center justify-end gap-3 mt-2';\n    if (fullWidthButtons) {\n        if (fullWidthButtonsDirection === 'horizontal') {\n            buttonsContainerClasses = 'flex flex-row items-center gap-3 mt-2 w-full [&>button]:flex-1';\n        } else {\n            buttonsContainerClasses = 'flex flex-col-reverse gap-3 mt-2 w-full';\n        }\n    }\n\n    // Si se proveen actions personalizadas, usarlas. Si no, usar botones por defecto\n    const actionButtons = actions || (\n      <>\n        {!hideCancel && onCancel && (\n          <Button type=\"plain\" size=\"base\" onClick={onCancel} disabled={isProcess} fullWidth={fullWidthButtons && fullWidthButtonsDirection === 'vertical'}>\n            {cancelText}\n          </Button>\n        )}\n        {onConfirm && (\n          <Button type=\"default\" size=\"base\" onClick={onConfirm} disabled={isProcess} fullWidth={fullWidthButtons && fullWidthButtonsDirection === 'vertical'}>\n            <span className=\"flex items-center justify-center gap-2 whitespace-nowrap\">\n              {confirmText}\n              {isProcess && (\n                <svg\n                  className=\"animate-spin h-4 w-4 text-white shrink-0\"\n                  xmlns=\"http://www.w3.org/2000/svg\"\n                  fill=\"none\"\n                  viewBox=\"0 0 24 24\"\n                >\n                  <circle\n                    className=\"opacity-25\"\n                    cx=\"12\"\n                    cy=\"12\"\n                    r=\"10\"\n                    stroke=\"currentColor\"\n                    strokeWidth=\"4\"\n                  ></circle>\n                  <path\n                    className=\"opacity-75\"\n                    fill=\"currentColor\"\n                    d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n                  ></path>\n                </svg>\n              )}\n            </span>\n          </Button>\n        )}\n      </>\n    );\n\n    const handleClose = () => {\n        if (!preventCloseOnOverlayClick && onCancel && !isProcess) {\n            onCancel();\n        }\n    };\n\n    // Variaciones basadas en el alineamiento\n    const isCentered = align === 'center';\n\n    const getIconByType = () => {\n      if (icon) return icon;\n\n      const containerClasses = `flex shrink-0 items-center justify-center rounded-full h-12 w-12`;\n      const iconClasses = `h-6 w-6`;\n\n      switch (type) {\n        case 'warning':\n          return (\n            <div className={`${containerClasses} bg-yellow-100 dark:bg-yellow-950`}>\n                <ExclamationTriangleIcon className={`${iconClasses} text-yellow-700 dark:text-yellow-300`} aria-hidden=\"true\" />\n            </div>\n          );\n        case 'danger':\n          return (\n            <div className={`${containerClasses} bg-red-100 dark:bg-red-950`}>\n              <ExclamationCircleIcon className={`${iconClasses} text-red-700 dark:text-red-300`} aria-hidden=\"true\" />\n            </div>\n          );\n        case 'success':\n          return (\n            <div className={`${containerClasses} bg-green-100 dark:bg-green-950`}>\n              <CheckIcon className={`${iconClasses} text-lime-700 dark:text-lime-300`} aria-hidden=\"true\" />\n            </div>\n          );\n        case 'info':\n          return (\n            <div className={`${containerClasses} bg-cyan-100 dark:bg-cyan-950`}>\n               <InformationCircleIcon className={`${iconClasses} text-cyan-700 dark:text-cyan-300`} aria-hidden=\"true\" />\n            </div>\n          );\n        default:\n          return null;\n      }\n    };\n\n    // Clases del contenedor principal\n    const containerClasses = `\n      w-full\n      ${size}\n      bg-white dark:bg-zinc-900\n      border border-zinc-200 dark:border-zinc-600\n      rounded-xl\n      transform flex-col overflow-hidden text-left align-middle shadow-xl transition-all\n      ${className}\n    `.trim().replace(/\\s+/g, ' ');\n\n    const PanelContent = (\n      <div className=\"p-6 flex flex-col gap-4 relative\">\n        {/* Close Button X (Optional) */}\n        {showCloseButton && (\n          <button\n            type=\"button\"\n            className=\"absolute top-4 right-4 rounded-md text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 dark:hover:text-gray-300\"\n            onClick={handleClose}\n            disabled={isProcess}\n          >\n            <span className=\"sr-only\">Cerrar</span>\n            <svg className=\"h-5 w-5\" fill=\"none\" viewBox=\"0 0 24 24\" strokeWidth=\"1.5\" stroke=\"currentColor\" aria-hidden=\"true\">\n              <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M6 18L18 6M6 6l12 12\" />\n            </svg>\n          </button>\n        )}\n\n        <div className={`flex ${isCentered ? 'flex-col items-center text-center' : 'items-start'} gap-4`}>\n          {/* Icon (Optional/Generated) */}\n          {(icon || type !== 'default') && (\n            <div className={`flex-shrink-0 ${isCentered ? 'mx-auto' : 'mt-0.5'}`}>\n              {getIconByType()}\n            </div>\n          )}\n\n          {/* Main Content Area */}\n          <div className=\"flex flex-col gap-4 flex-1 w-full\">\n            {/* Text Section / Title & Default Description */}\n            <div className=\"flex flex-col gap-3\">\n              {/* Title */}\n              {inline ? (\n                <p className={`text-sm leading-5 font-bold ${!isCentered && showCloseButton ? 'pr-6' : ''}`}>\n                  {title}\n                </p>\n              ) : (\n                <Dialog.Title as=\"p\" className={`text-sm leading-5 font-bold ${!isCentered && showCloseButton ? 'pr-6' : ''}`}>\n                  {title}\n                </Dialog.Title>\n              )}\n\n              {/* Description (Opcional) */}\n              {description && (\n                <div className={`text-sm leading-5 font-normal text-content-tertiary dark:text-dark-content-tertiary ${isCentered ? 'text-center' : ''}`}>\n                  {description}\n                </div>\n              )}\n            </div>\n          </div>\n        </div>\n\n        {/* Actions */}\n        <div className={buttonsContainerClasses}>\n          {actionButtons}\n        </div>\n      </div>\n    );\n\n    // Si está en modo 'inline' (Storybook Preview), devuelve un contenedor simple y manejable\n    // que se ajustará a su elemento padre perfectamente.\n    if (inline) {\n      if (!isOpen) return null;\n      return (\n        <div className={`absolute inset-0 z-50 flex items-center justify-center p-4 sm:p-0 transition-opacity duration-300 pointer-events-auto`}>\n          <div\n            className=\"absolute inset-0 bg-black/60 backdrop-blur-[2px] transition-opacity cursor-pointer\"\n            onClick={handleClose}\n          />\n          <div ref={ref as any} className={`${containerClasses} relative z-10 w-full flex justify-center`} {...props}>\n            {PanelContent}\n          </div>\n        </div>\n      );\n    }\n\n    return (\n      <Transition appear show={isOpen} as={Fragment}>\n        <Dialog as=\"div\" open={isOpen} className=\"relative z-50 text-left\" onClose={handleClose}>\n          <Transition.Child\n            as={Fragment}\n            enter=\"ease-out duration-300\"\n            enterFrom=\"opacity-0\"\n            enterTo=\"opacity-100\"\n            leave=\"ease-in duration-200\"\n            leaveFrom=\"opacity-100\"\n            leaveTo=\"opacity-0\"\n          >\n            <div className=\"fixed inset-0 bg-black/60 backdrop-blur-[2px] transition-opacity\" />\n          </Transition.Child>\n\n          <div className=\"fixed inset-0 z-10 overflow-y-auto\">\n            <div className=\"flex min-h-full items-center justify-center p-4 text-center sm:p-0\">\n              <Transition.Child\n                as={Fragment}\n                enter=\"ease-out duration-300\"\n                enterFrom=\"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95\"\n                enterTo=\"opacity-100 translate-y-0 sm:scale-100\"\n                leave=\"ease-in duration-200\"\n                leaveFrom=\"opacity-100 translate-y-0 sm:scale-100\"\n                leaveTo=\"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95\"\n              >\n                <Dialog.Panel\n                  ref={ref as any}\n                  className={containerClasses}\n                  {...props}\n                >\n                  {PanelContent}\n                </Dialog.Panel>\n              </Transition.Child>\n            </div>\n          </div>\n        </Dialog>\n      </Transition>\n    );\n  }\n);\n\nAlertDialog.displayName = 'AlertDialog';\n","import { forwardRef } from 'react';\nimport type { AlertProps } from './Alert.types';\nimport { Button } from '../Button/Button';\n\n/**\n * Alert - Componente de alerta/diálogo del sistema de diseño Siesa\n *\n * Componente modal para confirmaciones con soporte para:\n * - Título y descripción\n * - Contenido personalizado (children)\n * - Botones de acción personalizados o por defecto\n * - Dark mode\n *\n * @example\n * ```tsx\n * <Alert\n *   title=\"Are you sure you want to refund this payment?\"\n *   description=\"The refund will be reflected in 2 to 3 business days.\"\n *   onCancel={() => console.log('Cancelled')}\n *   onConfirm={() => console.log('Confirmed')}\n *   confirmText=\"Refund\"\n * />\n * ```\n */\nexport const Alert = forwardRef<HTMLDivElement, AlertProps>(\n  (\n    {\n      title,\n      description,\n      children,\n      actions,\n      onCancel,\n      onConfirm,\n      cancelText = 'Cancel',\n      confirmText = 'Confirm',\n      className = '',\n      ...props\n    },\n    ref\n  ) => {\n    // Si se proveen actions personalizadas, usarlas. Si no, usar botones por defecto\n    const actionButtons = actions || (\n      <>\n        {onCancel && (\n          <Button type=\"plain\" size=\"base\" onClick={onCancel}>\n            {cancelText}\n          </Button>\n        )}\n        {onConfirm && (\n          <Button type=\"default\" size=\"base\" onClick={onConfirm}>\n            {confirmText}\n          </Button>\n        )}\n      </>\n    );\n\n    return (\n      <div\n        ref={ref}\n        className={`\n          w-[512px]\n          bg-white\n          dark:bg-dark-bg-primary\n          border\n          border-border-primary\n          dark:border-dark-border-primary\n          rounded-xl\n          ${className}\n        `.trim().replace(/\\s+/g, ' ')}\n        {...props}\n      >\n        {/* Content Container */}\n        <div className=\"p-6 flex flex-col gap-4\">\n          {/* Text Section */}\n          <div className=\"flex flex-col gap-3\">\n            {/* Title */}\n            <p className=\"text-sm leading-5 font-bold text-content-primary dark:text-dark-content-primary\">\n              {title}\n            </p>\n\n            {/* Description (optional) */}\n            {description && (\n              <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n                {description}\n              </p>\n            )}\n          </div>\n\n          {/* Body Content (optional) */}\n          {children && (\n            <div className=\"flex flex-col gap-3\">\n              {children}\n            </div>\n          )}\n\n          {/* Actions */}\n          <div className=\"flex flex-wrap gap-3 items-center justify-end\">\n            {actionButtons}\n          </div>\n        </div>\n      </div>\n    );\n  }\n);\n\nAlert.displayName = 'Alert';\n","import { forwardRef, cloneElement } from 'react';\nimport type { BadgeProps, BadgeColor } from './Badge.types';\n\nconst badgeColors: Record<BadgeColor, { bg: string; text: string; hover: string; notificationBg: string; notificationText: string }> = {\n  zinc: {\n    bg: 'bg-zinc-100 dark:bg-zinc-950',\n    text: 'text-zinc-700 dark:text-zinc-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-zinc-700 dark:bg-zinc-400',\n    notificationText: 'text-zinc-100 dark:text-zinc-950'\n  },\n  red: {\n    bg: 'bg-red-100 dark:bg-red-950',\n    text: 'text-red-700 dark:text-red-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-red-700 dark:bg-red-400',\n    notificationText: 'text-red-100 dark:text-red-950'\n  },\n  orange: {\n    bg: 'bg-orange-100 dark:bg-orange-950',\n    text: 'text-orange-700 dark:text-orange-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-orange-700 dark:bg-orange-400',\n    notificationText: 'text-orange-100 dark:text-orange-950'\n  },\n  amber: {\n    bg: 'bg-amber-100 dark:bg-amber-950',\n    text: 'text-amber-700 dark:text-amber-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-amber-700 dark:bg-amber-400',\n    notificationText: 'text-amber-100 dark:text-amber-950'\n  },\n  yellow: {\n    bg: 'bg-yellow-100 dark:bg-yellow-950',\n    text: 'text-yellow-700 dark:text-yellow-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-yellow-700 dark:bg-yellow-400',\n    notificationText: 'text-yellow-100 dark:text-yellow-950'\n  },\n  lime: {\n    bg: 'bg-lime-100 dark:bg-lime-950',\n    text: 'text-lime-700 dark:text-lime-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-lime-700 dark:bg-lime-400',\n    notificationText: 'text-lime-100 dark:text-lime-950'\n  },\n  green: {\n    bg: 'bg-green-100 dark:bg-green-950',\n    text: 'text-green-700 dark:text-green-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-green-700 dark:bg-green-400',\n    notificationText: 'text-green-100 dark:text-green-950'\n  },\n  emerald: {\n    bg: 'bg-emerald-100 dark:bg-emerald-950',\n    text: 'text-emerald-700 dark:text-emerald-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-emerald-700 dark:bg-emerald-400',\n    notificationText: 'text-emerald-100 dark:text-emerald-950'\n  },\n  teal: {\n    bg: 'bg-teal-100 dark:bg-teal-950',\n    text: 'text-teal-700 dark:text-teal-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-teal-700 dark:bg-teal-400',\n    notificationText: 'text-teal-100 dark:text-teal-950'\n  },\n  cyan: {\n    bg: 'bg-cyan-100 dark:bg-cyan-950',\n    text: 'text-cyan-700 dark:text-cyan-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-cyan-700 dark:bg-cyan-400',\n    notificationText: 'text-cyan-100 dark:text-cyan-950'\n  },\n  sky: {\n    bg: 'bg-sky-100 dark:bg-sky-950',\n    text: 'text-sky-700 dark:text-sky-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-sky-700 dark:bg-sky-400',\n    notificationText: 'text-sky-100 dark:text-sky-950'\n  },\n  blue: {\n    bg: 'bg-blue-100 dark:bg-blue-950',\n    text: 'text-blue-700 dark:text-blue-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-blue-700 dark:bg-blue-400',\n    notificationText: 'text-blue-100 dark:text-blue-950'\n  },\n  indigo: {\n    bg: 'bg-indigo-100 dark:bg-indigo-950',\n    text: 'text-indigo-700 dark:text-indigo-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-indigo-700 dark:bg-indigo-400',\n    notificationText: 'text-indigo-100 dark:text-indigo-950'\n  },\n  violet: {\n    bg: 'bg-violet-100 dark:bg-violet-950',\n    text: 'text-violet-700 dark:text-violet-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-violet-700 dark:bg-violet-400',\n    notificationText: 'text-violet-100 dark:text-violet-950'\n  },\n  purple: {\n    bg: 'bg-purple-100 dark:bg-purple-950',\n    text: 'text-purple-700 dark:text-purple-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-purple-700 dark:bg-purple-400',\n    notificationText: 'text-purple-100 dark:text-purple-950'\n  },\n  fuchsia: {\n    bg: 'bg-fuchsia-100 dark:bg-fuchsia-950',\n    text: 'text-fuchsia-700 dark:text-fuchsia-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-fuchsia-700 dark:bg-fuchsia-400',\n    notificationText: 'text-fuchsia-100 dark:text-fuchsia-950'\n  },\n  pink: {\n    bg: 'bg-pink-100 dark:bg-pink-950',\n    text: 'text-pink-700 dark:text-pink-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-pink-700 dark:bg-pink-400',\n    notificationText: 'text-pink-100 dark:text-pink-950'\n  },\n  rose: {\n    bg: 'bg-rose-100 dark:bg-rose-950',\n    text: 'text-rose-700 dark:text-rose-400',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-rose-700 dark:bg-rose-400',\n    notificationText: 'text-rose-100 dark:text-rose-950'\n  },\n  primary: {\n    bg: 'bg-primary-100 dark:bg-primary-950',\n    text: 'text-primary dark:text-primary-300',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-primary dark:bg-primary-200',\n    notificationText: 'text-primary-50 dark:text-primary'\n  },\n  secondary: {\n    bg: 'bg-secondary-50 dark:bg-secondary',\n    text: 'text-secondary dark:text-secondary-300',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-secondary dark:bg-secondary-300',\n    notificationText: 'text-secondary-50 dark:text-secondary'\n  },\n  tertiary: {\n    bg: 'bg-tertiary-200 dark:bg-tertiary',\n    text: 'text-tertiary dark:text-tertiary-300',\n    hover: 'hover:brightness-98 dark:hover:brightness-95',\n    notificationBg: 'bg-tertiary dark:bg-tertiary-300',\n    notificationText: 'text-tertiary-200 dark:text-tertiary'\n  },\n};\n\n/**\n * Badge del sistema de diseño Siesa\n *\n * Componente para mostrar etiquetas con múltiples variantes de color.\n * Los badges mantienen sus colores vibrantes en light y dark mode para\n * garantizar visibilidad y consistencia visual.\n *\n * Características implementadas:\n * - 21 variantes de color (zinc, red, orange, amber, yellow, lime, green, emerald, teal, cyan, sky, blue, indigo, violet, purple, fuchsia, pink, rose, primary, secondary, tertiary)\n * - Icono opcional a la izquierda (12x12px)\n * - Contador/notification badge opcional\n * - Estados hover con transiciones suaves\n * - Los colores se mantienen vibrantes en dark mode (según diseño Figma)\n * - Tipografía: Label Tiny (12px Bold)\n *\n * Mejores prácticas implementadas:\n * - Tokens de color de Tailwind estándar para badges\n * - Font-family explícita (Inter via font-sans)\n * - Transiciones suaves (duration-200)\n * - Estructura clara y mantenible\n *\n * @see docs/typography.md - Sistema tipográfico (Label Tiny)\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4130-9382\n *\n * @example\n * ```tsx\n * // Badge simple\n * <Badge color=\"blue\" label=\"Label\" />\n *\n * // Badge con icono\n * <Badge color=\"green\" label=\"Success\" leftIcon={<CheckIcon />} />\n *\n * // Badge con contador\n * <Badge color=\"red\" label=\"Errors\" count={5} />\n *\n * // Badge completo\n * <Badge color=\"primary\" label=\"Messages\" leftIcon={<MailIcon />} count={12} />\n * ```\n */\nexport const Badge = forwardRef<HTMLDivElement, BadgeProps>(\n  (\n    {\n      color = 'zinc',\n      leftIcon,\n      label,\n      count,\n      className = '',\n      ...props\n    },\n    ref\n  ) => {\n    const colors = badgeColors[color] || badgeColors.zinc;\n\n    // Renderizar icono con tamaño correcto (12x12)\n    const renderIcon = (icon: React.ReactElement) => {\n      const existingClassName = (icon.props as any).className || '';\n      return (\n        <span>\n          {cloneElement(icon as React.ReactElement<any>, {\n            className: `w-full h-full object-contain ${existingClassName}`.replace(/(w|h|size)-[wd-]+/g, '').trim(),\n          })}\n        </span>\n      );\n    };\n\n    // ===== COMBINAR CLASES =====\n    const isInteractive = 'onClick' in props;\n\n    const finalClasses = [\n      'inline-flex',\n      'items-center',\n      'justify-center',\n      'gap-1',\n      'px-1.5',\n      'py-1',\n      'rounded-md',\n      colors.bg,\n      isInteractive ? colors.hover : '',\n      isInteractive ? 'cursor-pointer' : '',\n      'transition-colors',\n      'duration-200',\n      className,\n    ]\n      .filter(Boolean)\n      .join(' ')\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    return (\n      <div\n        ref={ref}\n        className={finalClasses}\n        {...props}\n      >\n        {/* Icono izquierdo */}\n        {leftIcon && (\n          <div className={`w-3 h-3 ${colors.text}`}>\n            {renderIcon(leftIcon)}\n          </div>\n        )}\n\n        {/* Label del badge */}\n        <span className={`text-xs font-medium ${colors.text}`}>\n          {label}\n        </span>\n\n        {/* Contador opcional */}\n        {count !== undefined && (\n          <span\n            className={`text-xs font-medium px-1 rounded-sm ${colors.notificationBg} ${colors.notificationText}`}\n            aria-label={`${count} notificaciones`}\n          >\n            {count > 99 ? '99+' : count}\n          </span>\n        )}\n      </div>\n    );\n  }\n);\n\nBadge.displayName = 'Badge';\n","import { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(clsx(inputs));\n}\n","import { cn } from './cn';\nimport type {\n  CardProps,\n  CardHeaderProps,\n  CardTitleProps,\n  CardDescriptionProps,\n  CardActionProps,\n  CardContentProps,\n  CardFooterProps,\n} from './Card.types';\n\n/**\n * Componente Card del sistema de diseño Siesa\n *\n * Contenedor versátil tipo tarjeta compuesto por 7 sub-componentes:\n * `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardAction`,\n * `CardContent` y `CardFooter`.\n *\n * **Estructura típica:**\n * ```\n * Card\n *   ├── CardHeader\n *   │     ├── CardTitle\n *   │     ├── CardDescription\n *   │     └── CardAction (opcional)\n *   ├── CardContent\n *   └── CardFooter (opcional)\n * ```\n *\n * **Tokens de color Siesa utilizados:**\n * - Fondo: `bg-bg-primary` / `dark:bg-dark-bg-secondary`\n * - Texto: `text-content-primary` / `dark:text-dark-content-primary`\n * - Texto secundario: `text-content-secondary` / `dark:text-dark-content-secondary`\n * - Borde: `border-border-primary` / `dark:border-dark-border-primary`\n *\n * **Dark Mode:**\n * Soporte completo mediante las clases `dark:` del sistema de diseño Siesa.\n * Activar añadiendo la clase `dark` al elemento `<html>`.\n *\n * @example\n * ```tsx\n * // Tarjeta básica\n * <Card>\n *   <CardHeader>\n *     <CardTitle>Título de la tarjeta</CardTitle>\n *     <CardDescription>Descripción opcional del contenido</CardDescription>\n *   </CardHeader>\n *   <CardContent>\n *     <p>Contenido principal de la tarjeta.</p>\n *   </CardContent>\n *   <CardFooter>\n *     <Button type=\"default\" size=\"base\">Guardar</Button>\n *   </CardFooter>\n * </Card>\n *\n * // Tarjeta con acción en el header\n * <Card>\n *   <CardHeader>\n *     <CardTitle>Resumen</CardTitle>\n *     <CardAction>\n *       <Button type=\"plain\" size=\"sm\" iconOnly leftIcon={<EditIcon />} ariaLabel=\"Editar\" />\n *     </CardAction>\n *   </CardHeader>\n *   <CardContent>Contenido</CardContent>\n * </Card>\n * ```\n */\nexport function Card({ className, ...props }: CardProps) {\n  return (\n    <div\n      data-slot=\"card\"\n      className={cn(\n        'flex flex-col gap-6 rounded-xl border border-zinc-200 bg-white py-6 shadow-sm',\n        'dark:border-zinc-600 dark:bg-zinc-900',\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\n/**\n * Cabecera de la tarjeta con grid layout.\n *\n * Cuando contiene un `CardAction`, el grid cambia automáticamente a 2 columnas\n * para posicionar la acción en la esquina superior derecha.\n * Soporta container queries (`@container/card-header`).\n */\nexport function CardHeader({ className, ...props }: CardHeaderProps) {\n  return (\n    <div\n      data-slot=\"card-header\"\n      className={cn(\n        '@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6',\n        'has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\n/**\n * Título principal de la tarjeta.\n *\n * Usa tipografía semibold con `leading-none` para alineación precisa.\n */\nexport function CardTitle({ className, ...props }: CardTitleProps) {\n  return (\n    <div\n      data-slot=\"card-title\"\n      className={cn('leading-none font-bold', className)}\n      {...props}\n    />\n  );\n}\n\n/**\n * Descripción secundaria de la tarjeta.\n *\n * Renderizada con color de texto secundario del sistema de diseño Siesa.\n */\nexport function CardDescription({ className, ...props }: CardDescriptionProps) {\n  return (\n    <div\n      data-slot=\"card-description\"\n      className={cn(\n        'text-sm text-zinc-500 dark:text-zinc-400',\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\n/**\n * Acción posicionada en la esquina superior derecha del `CardHeader`.\n *\n * Debe ser hijo directo de `CardHeader` para que el posicionamiento grid funcione.\n * Se ubica en la primera fila junto al título.\n */\nexport function CardAction({ className, ...props }: CardActionProps) {\n  return (\n    <div\n      data-slot=\"card-action\"\n      className={cn(\n        'col-start-2 row-start-1 self-start justify-self-end',\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\n/**\n * Área de contenido principal de la tarjeta.\n *\n * Aplica padding horizontal estándar de 24px (px-6) consistente con el header.\n */\nexport function CardContent({ className, ...props }: CardContentProps) {\n  return (\n    <div\n      data-slot=\"card-content\"\n      className={cn('px-6', className)}\n      {...props}\n    />\n  );\n}\n\n/**\n * Pie de la tarjeta con layout flex horizontal.\n *\n * Cuando tiene borde superior (`border-t`), aplica padding vertical automático (pt-6).\n * Ideal para agrupar acciones o información de estado.\n */\nexport function CardFooter({ className, ...props }: CardFooterProps) {\n  return (\n    <div\n      data-slot=\"card-footer\"\n      className={cn('flex items-center px-6 [.border-t]:pt-6', className)}\n      {...props}\n    />\n  );\n}\n","import * as React from \"react\"\nimport type { InputNumberProps } from \"./InputNumber.types\"\nimport { Input, labelVariants } from \"../Input/Input\"\nimport { cn } from \"../../lib/utils\"\n\nconst MinusIcon = ({ className }: { className?: string }) => (\n  <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n    <path d=\"M5 12h14\" />\n  </svg>\n);\n\nconst PlusIcon = ({ className }: { className?: string }) => (\n  <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n    <path d=\"M5 12h14\" />\n    <path d=\"M12 5v14\" />\n  </svg>\n);\n\nconst inputSizeClassMap = {\n  xs: \"h-7 text-xs\",\n  sm: \"h-8 text-sm\",\n  base: \"h-9 text-base\",\n  l: \"h-10 text-lg\",\n  xl: \"h-11 text-xl\",\n};\n\nconst iconSizeClassMap = {\n  xs: \"w-3 h-3 text-inherit\",\n  sm: \"w-3.5 h-3.5 text-inherit\",\n  base: \"w-4 h-4 text-inherit\",\n  l: \"w-4.5 h-4.5 text-inherit\",\n  xl: \"w-5 h-5 text-inherit\",\n};\n\nconst InputNumber = React.forwardRef<HTMLInputElement, InputNumberProps>(\n  ({ className, onChange, min, max, step = 1, disabled, readOnly, value, defaultValue, error, label, description, helperText, errorMessage, actionText, id, required, showControls = false, inputSize = 'base', ...props }, ref) => {\n\n    const inputRef = React.useRef<HTMLInputElement>(null);\n\n    const setRefs = React.useCallback(\n      (node: HTMLInputElement) => {\n        inputRef.current = node;\n        if (typeof ref === 'function') {\n          ref(node);\n        } else if (ref) {\n          (ref as React.MutableRefObject<HTMLInputElement | null>).current = node;\n        }\n      },\n      [ref]\n    );\n\n    const isControlled = value !== undefined;\n    const [internalValue, setInternalValue] = React.useState<number | string | readonly string[]>(\n      isControlled && value !== undefined ? value : (defaultValue !== undefined ? defaultValue : '')\n    );\n\n    React.useEffect(() => {\n      if (isControlled && value !== undefined) {\n        setInternalValue(value);\n      }\n    }, [value, isControlled]);\n\n    const triggerChange = (newVal: number) => {\n      if (!isControlled) {\n        setInternalValue(newVal);\n      }\n\n      if (inputRef.current) {\n        const nativeInputValueSetter = Object.getOwnPropertyDescriptor(\n          window.HTMLInputElement.prototype,\n          'value'\n        )?.set;\n        nativeInputValueSetter?.call(inputRef.current, newVal.toString());\n\n        const event = new Event('input', { bubbles: true });\n        inputRef.current.dispatchEvent(event);\n      }\n    };\n\n    const handleIncrement = (e: React.MouseEvent) => {\n      e.preventDefault();\n      if (disabled || readOnly) return;\n\n      const currentVal = Number(internalValue !== '' ? internalValue : 0);\n      const nextVal = currentVal + Number(step);\n\n      if (max !== undefined && nextVal > Number(max)) return;\n\n      triggerChange(nextVal);\n    };\n\n    const handleDecrement = (e: React.MouseEvent) => {\n      e.preventDefault();\n      if (disabled || readOnly) return;\n\n      const currentVal = Number(internalValue !== '' ? internalValue : 0);\n      const nextVal = currentVal - Number(step);\n\n      if (min !== undefined && nextVal < Number(min)) return;\n\n      triggerChange(nextVal);\n    };\n\n    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n      if (!isControlled) {\n        setInternalValue(e.target.value);\n      }\n      onChange?.(e);\n    };\n\n    const [generatedId] = React.useState(() => Math.random().toString(36).substring(2, 9));\n    const inputId = id || `input-number-${generatedId}`;\n\n    if (!showControls) {\n      return (\n        <Input\n          type=\"number\"\n          ref={setRefs}\n          min={min}\n          max={max}\n          step={step}\n          disabled={disabled}\n          readOnly={readOnly}\n          value={value}\n          defaultValue={defaultValue}\n          onChange={handleChange}\n          className={className}\n          error={error}\n          label={label}\n          description={description}\n          actionText={actionText}\n          id={id}\n          required={required}\n          inputSize={inputSize}\n          {...props}\n        />\n      );\n    }\n\n    return (\n      <div className={cn(\"grid w-full items-center gap-2\", className)}>\n        {(label || actionText || description) && (\n          <div className=\"flex flex-col gap-2 w-full\">\n            {(label || actionText) && (\n              <div className=\"flex items-center justify-between w-full\">\n                {label && (\n                  <label htmlFor={inputId} className={cn(\"text-content-primary dark:text-dark-content-primary\", labelVariants({ size: inputSize }))}>\n                    {label}\n                    {required && <span className=\"text-destructive ml-1\">*</span>}\n                  </label>\n                )}\n                {actionText && (\n                  <a href=\"#\" className=\"text-xs font-medium text-primary dark:text-primary-300 cursor-pointer hover:underline\">\n                    {actionText}\n                  </a>\n                )}\n              </div>\n            )}\n            {description && (\n              <p className={cn(inputSize === 'xs' ? \"text-xs\" : \"text-sm\", error ? \"text-destructive\" : \"text-muted-foreground\")}>\n                {description}\n              </p>\n            )}\n          </div>\n        )}\n\n        <div\n          className={cn(\n            \"flex items-center justify-between p-0.5 w-full sm:w-auto bg-white border rounded-md dark:bg-transparent transition-colors overflow-hidden\",\n            inputSizeClassMap[inputSize],\n            error ? \"border-destructive ring-1 ring-destructive\" : \"border-input dark:border-gray-700 focus-within:ring-1 focus-within:ring-primary-400 focus-within:border-primary-400\",\n            disabled && \"opacity-50 cursor-not-allowed bg-zinc-100 dark:bg-zinc-800/80\",\n            readOnly && \"bg-zinc-100 dark:bg-zinc-800/80 cursor-default\"\n          )}\n        >\n          <button\n            type=\"button\"\n            tabIndex={-1}\n            onClick={handleDecrement}\n            disabled={disabled || readOnly || (min !== undefined && Number(internalValue || 0) <= Number(min))}\n            className=\"flex items-center justify-center h-full aspect-square shrink-0 rounded-sm text-foreground hover:bg-zinc-100 dark:hover:bg-zinc-800 active:bg-zinc-200 dark:active:bg-zinc-700 active:scale-95 disabled:opacity-50 disabled:pointer-events-none focus:outline-none transition-colors\"\n            aria-label=\"Disminuir\"\n          >\n            <MinusIcon className={iconSizeClassMap[inputSize]} />\n          </button>\n\n          <input\n            {...props}\n            id={inputId}\n            ref={setRefs}\n            type=\"number\"\n            min={min}\n            max={max}\n            step={step}\n            disabled={disabled}\n            readOnly={readOnly}\n            value={isControlled ? value : internalValue}\n            onChange={handleChange}\n            className={cn(\n              \"p-0 w-full min-w-[3rem] h-full text-center bg-transparent border-0 outline-none focus:outline-none focus:ring-0 text-zinc-800 dark:text-white\",\n              \"[&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none\",\n              disabled && \"cursor-not-allowed\",\n              readOnly && \"text-zinc-500 dark:text-zinc-400 focus:ring-0 cursor-default\"\n            )}\n            style={{ MozAppearance: 'textfield' }}\n          />\n\n          <button\n            type=\"button\"\n            tabIndex={-1}\n            onClick={handleIncrement}\n            disabled={disabled || readOnly || (max !== undefined && Number(internalValue || 0) >= Number(max))}\n            className=\"flex items-center justify-center h-full aspect-square shrink-0 rounded-sm text-foreground hover:bg-zinc-100 dark:hover:bg-zinc-800 active:bg-zinc-200 dark:active:bg-zinc-700 active:scale-95 disabled:opacity-50 disabled:pointer-events-none focus:outline-none transition-colors\"\n            aria-label=\"Aumentar\"\n          >\n            <PlusIcon className={iconSizeClassMap[inputSize]} />\n          </button>\n        </div>\n\n        {(helperText || errorMessage) && (\n          <p className={cn(inputSize === 'xs' ? \"text-xs\" : \"text-sm\", error ? \"text-destructive\" : \"text-muted-foreground\")}>\n            {error && errorMessage ? errorMessage : helperText}\n          </p>\n        )}\n      </div>\n    );\n  }\n)\nInputNumber.displayName = \"InputNumber\"\n\nexport { InputNumber }\n","import React from 'react';\nimport type { NavigationRailItemProps } from './NavigationRailItem.types';\n\n/**\n * NavigationRailItem - Componente independiente para items de NavigationRail\n *\n * Item individual de navegación vertical (rail) para aplicaciones. Proporciona\n * un punto de acceso a destinos mediante un icono, label opcional y badges.\n *\n * **Características principales:**\n * - Ancho fijo de 56px según Figma\n * - Estados completos: normal, hover, selected, focus, disabled\n * - Badges de notificación con contador opcional\n * - Tipografía Label XXSmall (10px Bold) según sistema de diseño\n * - Dark mode completo con estrategia 'class'\n * - Focus rings adaptativos para accesibilidad\n * - Soporte para iconos 16x16px\n *\n * **Especificaciones de Figma (node 4294-22931):**\n * - Ancho: 56px (w-14)\n * - Icon container: 32px altura, px-4 py-1, rounded-full\n * - Label: 10px Bold, leading 12px (Label XXSmall)\n * - Gap: 4px (gap-1)\n * - Badge: 13x13px, posición absolute\n *\n * **Estados visuales (según Figma):**\n * - **Enabled**: Icon transparent, label text-content-primary\n * - **Hover**: Icon container bg-primary-100 (#dbeefe), icon text-primary-600\n * - **Selected**: Icon container bg-primary-100 con overlay, icon text-primary-600\n * - **Focus**: Focus ring 2px (#60b6fa) con offset 2px (#dbeefe), sombras combinadas\n * - **Disabled**: Opacity 55%, no interactivo\n *\n * **Dark Mode:**\n * - Background: dark-bg-primary\n * - Hover icon container: dark-bg-primary/20\n * - Selected icon container: dark-primary-600/30\n * - Icon colors: dark-content-primary, dark-white on selected\n * - Focus ring: dark-border-custom\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Tokens de color consistentes con documentación\n * - Accesibilidad ARIA completa\n * - Focus visible para keyboard navigation\n * - Badge positioning absoluto para no afectar layout\n *\n * @see docs/colors.md - Sistema de colores (primary-custom, dark-*, content-*)\n * @see docs/typography.md - Tipografía (Label XXSmall)\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras y focus rings\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4294-22931\n *\n * @example\n * ```tsx\n * // Item básico\n * <NavigationRailItem\n *   id=\"home\"\n *   icon={<HomeIcon />}\n *   label=\"Inicio\"\n *   selected={true}\n *   onClick={() => navigate('/')}\n * />\n *\n * // Con badge de notificación\n * <NavigationRailItem\n *   id=\"notifications\"\n *   icon={<BellIcon />}\n *   label=\"Notificaciones\"\n *   badgeCount={5}\n *   onClick={() => navigate('/notifications')}\n * />\n *\n * // Item deshabilitado\n * <NavigationRailItem\n *   id=\"premium\"\n *   icon={<StarIcon />}\n *   label=\"Premium\"\n *   disabled={true}\n * />\n *\n * // Solo icono (sin label)\n * <NavigationRailItem\n *   id=\"home\"\n *   icon={<HomeIcon />}\n *   label=\"Inicio\"\n *   showLabelText={false}\n * />\n * ```\n */\nexport const NavigationRailItem: React.FC<NavigationRailItemProps> = ({\n  icon,\n  label,\n  selected = false,\n  disabled = false,\n  badge = false,\n  badgeCount,\n  onClick,\n  onMouseEnter,\n  onMouseLeave,\n  ariaLabel,\n  id,\n  showLabelText = true,\n  showIcon = true,\n  className = '',\n}) => {\n  // ===== CLASES DEL ICON CONTAINER =====\n  // Según Figma node 4294-22931, el icon container tiene comportamiento diferente\n  // según el estado:\n  // - Enabled: bg-transparent, hover:bg-primary-100\n  // - Hover: bg-primary-100\n  // - Selected: bg-primary-100 con overlay (rgba(0,0,0,0.024))\n  // - Focus: bg-primary-100 con focus ring y sombras\n  // - Disabled: opacidad 55%\n  const iconContainerClasses = [\n    // Base layout\n    'flex',\n    'flex-col',\n    'items-center',\n    'justify-center',\n    'px-4', // 16px horizontal según Figma\n    'py-1', // 4px vertical según Figma\n    'rounded-full',\n    'overflow-hidden',\n    'shrink-0',\n\n    // Estados - Background\n    selected\n      ? // Selected: bg-primary-100 con overlay\n        'bg-primary-100 dark:bg-primary-600/30'\n      : // Default/Hover: transparent → hover:bg-primary-100\n        'bg-transparent hover:bg-primary-100 dark:hover:bg-primary-600/20',\n\n    // Transiciones\n    'transition-colors',\n    'duration-150',\n  ].join(' ');\n\n  // ===== CLASES DEL ICONO =====\n  // Tamaño fijo 16x16px según Figma\n  // Colores según estado:\n  // - Default: text-content-primary\n  // - Hover: text-primary-600\n  // - Selected: text-primary-600\n  // - Disabled: text-content-tertiary\n  // Dark mode: invierte colores\n  const iconClasses = [\n    'w-4', // 16px\n    'h-4', // 16px\n    'shrink-0',\n\n    // Colores según estado\n    selected\n      ? // Selected: primary-600 (azul oscuro)\n        'text-primary-600 dark:text-white'\n      : disabled\n        ? // Disabled: content-tertiary\n          'text-content-tertiary dark:text-content-tertiary'\n        : // Default/Hover: content-primary → hover:primary-600\n          'text-content-primary hover:text-primary-600 dark:text-dark-content-primary dark:hover:text-white',\n\n    'transition-colors',\n    'duration-150',\n  ].join(' ');\n\n  // ===== CLASES DEL LABEL =====\n  // Tipografía: Label XXSmall (10px Bold, leading 12px) según Figma\n  // Color: text-content-primary, dark:text-dark-content-primary\n  const labelClasses = [\n    // Tipografía: Label XXSmall (10px Bold)\n    'text-xs', // 12px en lugar de text-[10px]\n    'leading-3', // 12px\n    'font-bold',\n    'text-center',\n    'w-full',\n    'min-w-full',\n\n    // Colores\n    'text-content-primary',\n    'dark:text-dark-content-primary',\n\n    // Para multiline labels, agregar truncate o text-nowrap si es necesario\n    'wrap-break-word',\n  ].join(' ');\n\n  // ===== CLASES DEL CONTENEDOR PRINCIPAL =====\n  // Según Figma: ancho 56px, flex-col, gap-1, items-center\n  const containerClasses = [\n    'relative',\n    'flex',\n    'flex-col',\n    'items-center',\n    'gap-1', // 4px según Figma\n    'px-0.5', // 2px horizontal según Figma\n    'py-0',\n    'w-14', // 56px según Figma\n    'shrink-0',\n\n    // Interactividad\n    disabled\n      ? 'cursor-not-allowed opacity-55 pointer-events-none'\n      : 'cursor-pointer',\n\n    // Focus visible (accesibilidad)\n    'focus:outline-hidden',\n    'focus-visible:ring-2',\n    'focus-visible:ring-primary-400', // 4px ring\n    'focus-visible:ring-offset-2',\n    'focus-visible:ring-offset-primary-100', // offset #dbeefe según Figma\n    'dark:focus-visible:ring-dark-border-custom',\n    'dark:focus-visible:ring-offset-dark-bg-primary',\n\n    // Focus sombras adicionales según Figma:\n    'focus-visible:shadow-lg',\n    'dark:focus-visible:shadow-2xl',\n\n    'rounded-lg',\n\n    // Clases personalizadas\n    className,\n  ].join(' ');\n\n  // ===== RENDERIZAR BADGE =====\n  const renderBadge = () => {\n    if (!badge && badgeCount === undefined) return null;\n\n    // Badge con número\n    if (badgeCount !== undefined) {\n      return (\n        <span\n          className=\"\n            absolute\n            -top-0.5\n            left-8\n            flex\n            items-center\n            justify-center\n            min-w-3\n            h-3\n            px-1\n            rounded-full\n            text-xs\n            font-bold\n            leading-none\n            bg-red-700\n            text-white\n            dark:bg-red-700\n            dark:text-white\n            pointer-events-none\n            select-none\n          \"\n          aria-label={`${badgeCount} notificaciones`}\n          data-badge\n        >\n          {badgeCount > 99 ? '99+' : badgeCount}\n        </span>\n      );\n    }\n\n    // Badge dot simple\n    return (\n      <span\n        className=\"\n          absolute\n          -top-0.5\n          left-8\n          w-3\n          h-3\n          rounded-full\n          bg-red-700\n          dark:bg-red-700\n          pointer-events-none\n          select-none\n        \"\n        aria-label=\"Notificación\"\n        data-badge\n      />\n    );\n  };\n\n  return (\n    <button\n      type=\"button\"\n      className={containerClasses}\n      disabled={disabled}\n      onClick={onClick}\n      onMouseEnter={onMouseEnter}\n      onMouseLeave={onMouseLeave}\n      aria-label={ariaLabel || label}\n      aria-current={selected ? 'page' : undefined}\n      aria-disabled={disabled}\n      data-item-id={id}\n      data-testid={`navigation-rail-item-${id}`}\n    >\n      {/* Icon Container */}\n      {showIcon && (\n        <div className={iconContainerClasses}>\n          <span className={iconClasses}>\n            {icon}\n          </span>\n        </div>\n      )}\n\n      {/* Label */}\n      {showLabelText && (\n        <p className={labelClasses}>\n          {label}\n        </p>\n      )}\n\n      {/* Badge */}\n      {renderBadge()}\n    </button>\n  );\n};\n\nNavigationRailItem.displayName = 'NavigationRailItem';\n","/**\n * Iconos para el componente Dropdown\n * Usando heroicons-micro según especificaciones de Figma\n */\n\nexport const ChevronDownIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const CogIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M6.455 1.45A.5.5 0 0 1 6.952 1h2.096a.5.5 0 0 1 .497.45l.186 1.858a4.996 4.996 0 0 1 1.466.848l1.703-.769a.5.5 0 0 1 .639.206l1.047 1.814a.5.5 0 0 1-.14.656l-1.517 1.09a5.026 5.026 0 0 1 0 1.694l1.516 1.09a.5.5 0 0 1 .141.656l-1.047 1.814a.5.5 0 0 1-.639.206l-1.703-.768c-.433.36-.928.649-1.466.847l-.186 1.858a.5.5 0 0 1-.497.45H6.952a.5.5 0 0 1-.497-.45l-.186-1.858a4.993 4.993 0 0 1-1.466-.848l-1.703.769a.5.5 0 0 1-.639-.206l-1.047-1.814a.5.5 0 0 1 .14-.656l1.517-1.09a5.033 5.033 0 0 1 0-1.694l-1.516-1.09a.5.5 0 0 1-.141-.656L2.461 3.39a.5.5 0 0 1 .639-.206l1.703.768c.433-.36.928-.649 1.466-.847l.186-1.858ZM8 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const UserIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path d=\"M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM12.735 14c.618 0 1.093-.561.872-1.139a6.002 6.002 0 0 0-11.215 0c-.22.578.254 1.139.872 1.139h9.47Z\" />\n  </svg>\n);\n\nexport const BellIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M12 5a4 4 0 0 0-8 0v2.379a1.5 1.5 0 0 1-.44 1.06L2.294 9.707a1 1 0 0 0-.293.707V11a1 1 0 0 0 1 1h2a3 3 0 1 0 6 0h2a1 1 0 0 0 1-1v-.586a1 1 0 0 0-.293-.707L12.44 8.44A1.5 1.5 0 0 1 12 7.38V5Zm-5.5 7a1.5 1.5 0 0 0 3 0h-3Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const CreditCardIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n\nexport const MoonIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M9.598 1.591a.749.749 0 0 1 .785-.175 7.001 7.001 0 1 1-8.967 8.967.75.75 0 0 1 .961-.96 5.5 5.5 0 0 0 7.046-7.046.75.75 0 0 1 .175-.786Zm1.616 1.945a7 7 0 0 1-7.678 7.678 5.499 5.499 0 1 0 7.678-7.678Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const DocumentTextIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4 2a1.5 1.5 0 0 0-1.5 1.5v9A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5V6.621a1.5 1.5 0 0 0-.44-1.06L9.94 2.439A1.5 1.5 0 0 0 8.878 2H4Zm4 9.5a.75.75 0 0 1-.75-.75V9.5a.75.75 0 0 1 1.5 0v1.25a.75.75 0 0 1-.75.75Zm-2.5-4.5A.75.75 0 0 0 5 7v.25a.75.75 0 0 0 1.5 0V7Zm4 0a.75.75 0 0 0-.5.75v.25a.75.75 0 0 0 1.5 0V7.5a.75.75 0 0 0-.5-.75Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const ArrowRightStartOnRectangleIcon = () => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4 2a1.5 1.5 0 0 0-1.5 1.5v9A1.5 1.5 0 0 0 4 14h3a.5.5 0 0 0 0-1H4a.5.5 0 0 1-.5-.5v-9A.5.5 0 0 1 4 3h3a.5.5 0 0 0 0-1H4Zm7.53 4.22a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.75.75 0 1 1-1.06-1.06l.72-.72H8.5a.75.75 0 0 1 0-1.5h3.75l-.72-.72a.75.75 0 0 1 0-1.06Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n","import React, { useState, useRef, useEffect, useCallback } from 'react';\nimport { createPortal } from 'react-dom';\nimport type {\n  DropdownProps,\n  DropdownItemProps,\n  DropdownHeadingProps,\n  DropdownDividerProps,\n} from './Dropdown.types';\nimport { ChevronDownIcon } from './icons';\n\n/**\n * Componente Dropdown del sistema de diseño Siesa\n *\n * Implementación actualizada con React Portal para evitar problemas de overflow (clipping)\n * en contenedores con scroll (como tablas).\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n */\nexport const Dropdown: React.FC<DropdownProps> = ({\n  variant = 'default',\n  children,\n  items,\n  open: controlledOpen,\n  onOpenChange,\n  disabled = false,\n  className = '',\n  menuClassName = '',\n  ariaLabel,\n  placeholder = 'Options',\n  renderTrigger,\n}) => {\n  const [internalOpen, setInternalOpen] = useState(false);\n  const [menuCoords, setMenuCoords] = useState<{ top: number; left: number; align: 'left' | 'right' } | null>(null);\n  const dropdownRef = useRef<HTMLDivElement>(null);\n  const menuRef = useRef<HTMLDivElement>(null);\n\n  // Determinar si es controlado o no controlado\n  const isControlled = controlledOpen !== undefined;\n  const isOpen = isControlled ? controlledOpen : internalOpen;\n\n  // Calcular la posición óptima del menú\n  const calculateMenuPosition = useCallback(() => {\n    if (!dropdownRef.current) return;\n\n    const triggerRect = dropdownRef.current.getBoundingClientRect();\n    const viewportWidth = window.innerWidth;\n    const viewportHeight = window.innerHeight;\n    \n    // Estimación básica\n    const menuMinWidth = 182; \n    \n    // Default: Abajo a la izquierda\n    let top = triggerRect.bottom + 4;\n    let left = triggerRect.left;\n    let align: 'left' | 'right' = 'left';\n\n    // Ajuste horizontal: Si se sale por la derecha, alinear a la derecha del trigger\n    if (left + menuMinWidth > viewportWidth) {\n      left = triggerRect.right;\n      align = 'right';\n    }\n\n    // Ajuste vertical básico: Si se sale por abajo, intentar arriba\n    // (Nota: Para hacerlo perfecto necesitaríamos la altura real del menú, \n    //  aquí hacemos una estimación o dejamos que el navegador maneje el scroll si es fixed)\n    const estimatedHeight = Math.min(items.length * 40 + 20, 300);\n    if (top + estimatedHeight > viewportHeight && triggerRect.top > estimatedHeight) {\n       top = triggerRect.top - 4;\n       // Si abrimos hacia arriba, el CSS transform tendrá que manejar el `bottom-0` simulado\n       // O simplemente seteamos `top` restando altura.\n       // Para simplificar con Portal y no medir altura pre-render, usaremos abajo por defecto\n       // y si el usuario hace scroll, el menú se cierra (comportamiento estándar).\n    }\n\n    setMenuCoords({ top, left, align });\n  }, [items.length]);\n\n  // Actualizar posición al abrir\n  useEffect(() => {\n    if (isOpen) {\n      calculateMenuPosition();\n      // Recalcular al hacer scroll o resize\n      window.addEventListener('scroll', calculateMenuPosition, true);\n      window.addEventListener('resize', calculateMenuPosition);\n    }\n    return () => {\n      window.removeEventListener('scroll', calculateMenuPosition, true);\n      window.removeEventListener('resize', calculateMenuPosition);\n    };\n  }, [isOpen, calculateMenuPosition]);\n\n  // Función para cambiar el estado\n  const handleToggle = () => {\n    if (disabled) return;\n\n    const newOpen = !isOpen;\n    \n    if (!isControlled) {\n      setInternalOpen(newOpen);\n    }\n    onOpenChange?.(newOpen);\n  };\n\n  // Cerrar al hacer click fuera\n  useEffect(() => {\n    const handleClickOutside = (event: MouseEvent) => {\n      const target = event.target as HTMLElement;\n\n      // 1. Verificar si el click fue en el trigger de este dropdown\n      if (dropdownRef.current && dropdownRef.current.contains(target)) {\n        return;\n      }\n      // 2. Verificar si el click fue dentro del menú de este dropdown\n      if (menuRef.current && menuRef.current.contains(target)) {\n        return;\n      }\n\n      // 3. Lógica de anidamiento: Si el click fue dentro de CUALQUIER otro menú de Siesa,\n      // no cerramos el actual. Esto permite que selectores de idioma o submenús\n      // mantengan abierto el menú padre.\n      if (target.closest('[data-siesa-dropdown-menu=\"true\"]')) {\n        return;\n      }\n      \n      if (isOpen) {\n        if (!isControlled) setInternalOpen(false);\n        onOpenChange?.(false);\n      }\n    };\n\n    if (isOpen) {\n      document.addEventListener('mousedown', handleClickOutside);\n      return () => document.removeEventListener('mousedown', handleClickOutside);\n    }\n  }, [isOpen, isControlled, onOpenChange]);\n\n  // Handler para item click\n  const handleItemClick = (item: DropdownItemProps) => {\n    if (item.disabled || item.isDivider || item.isHeading) return;\n    if (item.onClick) item.onClick({} as React.MouseEvent<HTMLButtonElement>);\n    \n    if (!isControlled) setInternalOpen(false);\n    onOpenChange?.(false);\n  };\n\n  // Renderizar el menú en un Portal\n  const renderMenu = () => {\n    if (!isOpen || !menuCoords) return null;\n\n    const style: React.CSSProperties = {\n      position: 'fixed',\n      top: menuCoords.top,\n      left: menuCoords.left,\n      transform: menuCoords.align === 'right' ? 'translateX(-100%)' : 'none',\n      zIndex: 9999, // Asegurar que esté encima de todo (modales, etc.)\n      maxHeight: '300px', // Scroll si es muy alto\n      overflowY: 'auto',\n    };\n\n    // Clases del menú\n    const menuClasses = [\n      'min-w-[182px]',\n      'rounded-lg',\n      'p-1',\n      'border',\n      'bg-background-secondary',\n      'border-border-primary',\n      'dark:bg-dark-bg-primary',\n      'dark:border-dark-border-primary',\n      'shadow-lg',\n      menuClassName,\n    ]\n      .filter(Boolean)\n      .join(' ')\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    return createPortal(\n      <div \n        ref={menuRef} \n        style={style} \n        className={menuClasses}\n        data-siesa-dropdown-menu=\"true\"\n      >\n        {items.map((item, index) => {\n          if (item.isDivider) {\n            return <DropdownDivider key={index} className={item.className} />;\n          }\n          if (item.isHeading) {\n            return (\n              <DropdownHeading key={index} className={item.className}>\n                {item.children}\n              </DropdownHeading>\n            );\n          }\n          if (item.customContent) {\n            return (\n              <div key={index} className=\"w-full\">\n                {item.customContent}\n              </div>\n            );\n          }\n          return (\n            <DropdownItem\n              key={index}\n              {...item}\n              onClick={() => handleItemClick(item)}\n            />\n          );\n        })}\n      </div>,\n      document.body\n    );\n  };\n\n  // Clases del Trigger\n  const triggerClasses = [\n    'inline-flex', 'items-center', 'justify-center', 'rounded-lg', 'font-bold', 'text-sm', 'whitespace-nowrap',\n    'transition-all', 'duration-150',\n    variant === 'icon-only' ? 'w-9 h-9' : 'gap-2 px-3 py-2',\n    'bg-white', 'text-content-secondary', 'border', 'border-border-primary', 'hover:bg-background-secondary',\n    'dark:bg-dark-bg-primary', 'dark:text-dark-content-primary', 'dark:border-dark-border-primary', 'dark:hover:bg-dark-bg-secondary',\n    'focus:outline-hidden', 'focus:ring-2', 'focus:ring-primary-400', 'focus:ring-offset-2',\n    'dark:focus:ring-dark-border-custom', 'dark:focus:ring-offset-dark-bg-primary',\n    disabled && 'opacity-50', disabled && 'cursor-not-allowed', disabled && 'pointer-events-none',\n    className,\n  ].filter(Boolean).join(' ').trim();\n\n  // Determinar si el contenedor raíz debe ser full width\n  const isFullWidth = className.includes('w-full');\n\n  return (\n    <>\n      <div \n        ref={dropdownRef} \n        className={`relative ${isFullWidth ? 'w-full flex' : 'inline-flex'}`}\n      >\n        {renderTrigger ? (\n          <div \n            onClick={handleToggle} \n            role=\"button\" \n            tabIndex={disabled ? -1 : 0}\n            className={`${isFullWidth ? 'w-full' : 'inline-flex'} items-center justify-center`}\n          >\n            {renderTrigger(isOpen)}\n          </div>\n        ) : (\n          <button\n            type=\"button\"\n            className={triggerClasses}\n            onClick={handleToggle}\n            disabled={disabled}\n            aria-label={ariaLabel || (variant === 'icon-only' ? 'Abrir menú' : undefined)}\n            aria-haspopup=\"true\"\n            aria-expanded={isOpen}\n          >\n            {variant === 'default' && <span>{children || placeholder}</span>}\n            <ChevronDownIcon />\n          </button>\n        )}\n      </div>\n      {renderMenu()}\n    </>\n  );\n};\n\n// ... Resto de componentes (DropdownItem, etc.) se mantienen igual ...\n// Los copiaré para mantener el archivo completo\n\nexport const DropdownItem: React.FC<DropdownItemProps> = ({\n  children,\n  icon,\n  description,\n  shortcut,\n  disabled = false,\n  selected = false,\n  onClick,\n  className = '',\n}) => {\n  const itemClasses = [\n    'flex', 'items-center', 'gap-3', 'px-4', 'py-2', 'rounded-lg', 'text-sm', 'font-normal', 'w-full', 'text-left',\n    'text-content-primary', !disabled && 'hover:bg-bg-primary', selected && 'bg-bg-primary',\n    'dark:text-dark-content-primary', !disabled && 'dark:hover:bg-dark-bg-secondary', selected && 'dark:bg-dark-bg-secondary',\n    disabled && 'opacity-50', disabled && 'cursor-not-allowed', !disabled && 'cursor-pointer',\n    className,\n  ].filter(Boolean).join(' ').trim();\n\n  return (\n    <button type=\"button\" className={itemClasses} onClick={onClick} disabled={disabled}>\n      {icon && (\n        <span className=\"inline-flex items-center justify-center w-4 h-4 text-content-secondary dark:text-dark-content-secondary\">\n          {icon}\n        </span>\n      )}\n      <div className=\"flex-1 min-w-0\">\n        <div className=\"text-content-primary dark:text-dark-content-primary\">{children}</div>\n        {description && (\n          <div className=\"text-xs text-content-secondary dark:text-dark-content-secondary mt-0.5\">{description}</div>\n        )}\n      </div>\n      {shortcut && (\n        <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary ml-auto whitespace-nowrap\">\n          {shortcut}\n        </span>\n      )}\n    </button>\n  );\n};\n\nexport const DropdownHeading: React.FC<DropdownHeadingProps> = ({ children, className = '' }) => {\n  const headingClasses = [\n    'px-4', 'py-1', 'text-xs', 'font-normal', 'text-content-tertiary', 'dark:text-dark-content-tertiary', className,\n  ].filter(Boolean).join(' ').trim();\n  return <div className={headingClasses}>{children}</div>;\n};\n\nexport const DropdownDivider: React.FC<DropdownDividerProps> = ({ className = '' }) => {\n  const dividerClasses = ['px-4', 'py-1', className].filter(Boolean).join(' ').trim();\n  return (\n    <div className={dividerClasses}>\n      <div className=\"h-px bg-border-primary dark:bg-dark-border-primary\" />\n    </div>\n  );\n};","import React from 'react';\n\n/**\n * Icono ChevronDown para el toggle del colapsable\n * Diseño basado en heroicons-micro/chevron-down\n * Tamaño: 16x16px\n *\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=6135-34374\n */\nexport const ChevronDownIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M4 6L8 10L12 6\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n/**\n * Icono de usuario placeholder para ejemplos en stories\n * Tamaño: 16x16px\n */\nexport const UserIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M8 8C9.10457 8 10 7.10457 10 6C10 4.89543 9.10457 4 8 4C6.89543 4 6 4.89543 6 6C6 7.10457 6.89543 8 8 8Z\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n    <path\n      d=\"M4.5 13C4.5 11.3431 6.13401 10 8 10C9.86599 10 11.5 11.3431 11.5 13\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type {\n  DropdownItemCollapsibleProps,\n  DropdownItemCollapsibleChildProps,\n} from './DropdownItemCollapsible.types';\nimport { ChevronDownIcon } from './icons';\nimport { Badge } from '../Badge/Badge';\n\n/**\n * Componente DropdownItemCollapsible del sistema de diseño Siesa\n *\n * Item colapsable para uso dentro de Dropdowns que permite agrupar\n * items relacionados en secciones expandibles.\n *\n * **Características:**\n * - Soporte completo para expandir/colapsar\n * - Iconos personalizables en header y children\n * - Items anidados indentados automáticamente\n * - Dark mode completo con inversión de colores\n * - Estados: default, hover, active, disabled\n * - Focus rings adaptativos\n * - Animación suave de rotación del chevron\n *\n * **Estados visuales:**\n * - `collapsed`: Muestra solo el header con chevron apuntando down\n * - `expanded`: Muestra header y lista de items anidados\n * - `disabled`: Opacidad 50%, sin interacción\n * - `hover`: Fondo de hover sutil, color primario del icono\n * - `active`: Item anidado seleccionado con fondo custom-primary\n *\n * **Espaciado según Figma:**\n * - Header padding: px-4 py-2 (16px horizontal, 8px vertical)\n * - Item anidado padding: pl-6 pr-4 py-2 (24px left, 16px right, 8px vertical)\n * - Gap entre elementos: gap-3 (12px)\n * - Gap interno (icon + text): gap-3 (12px)\n * - Indent entre niveles: 8px adicional por nivel\n * - Divisor: borde top de 1px con spacing-0.5 (2px) arriba\n * - Sección heading: pt-3 pb-1 px-0 (12px top, 4px bottom, sin horizontal)\n *\n * **Tipografía:**\n * - Header: Paragraph/Small (14px, Regular, line-height 20px) - text-content-primary\n * - Items anidados: Paragraph/Small (14px, Regular, line-height 20px) - text-content-primary\n * - Heading: Paragraph/Tiny (12px, Regular, line-height 16px) - text-content-tertiary\n *\n * **Colores (Light Mode):**\n * - Header text: content-primary (#18181b)\n * - Header icon: content-secondary (#a1a1aa)\n * - Header hover: bg-background-custom-primary (#dbeefe)\n * - Header text hover: content-custom-primary (#0e79fd)\n * - Item text: content-primary (#18181b)\n * - Item hover: bg-transparent (sin fondo)\n * - Divider: border-border-primary (#e4e4e7)\n * - Heading text: content-tertiary (#71717a)\n *\n * **Colores (Dark Mode):**\n * - Header text: content-primary/dark (#fafafa)\n * - Header icon: content-secondary/dark (#a1a1aa)\n * - Header hover: bg-background-custom-primary/dark (#0e5ab0)\n * - Header text hover: content-custom-primary/dark (#bfe2fe)\n * - Item text: content-primary/dark (#fafafa)\n * - Divider: border-border-primary/dark (#3f3f46)\n * - Heading text: content-tertiary/dark (#a1a1aa)\n *\n * **Border radius:**\n * - Todos los items: rounded-lg (8px)\n *\n * **Sombras:**\n * - Ninguna (usado dentro de dropdowns)\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=6135-34374\n *\n * @example\n * ```tsx\n * // Item colapsable simple\n * <DropdownItemCollapsible\n *   label=\"Users\"\n *   icon={<UserIcon />}\n *   children={[\n *     { label: \"Active Users\", icon: <CheckIcon /> },\n *     { label: \"Inactive Users\", icon: <CloseIcon /> },\n *   ]}\n * />\n *\n * // Con encabezado de sección\n * <DropdownItemCollapsible\n *   label=\"Customers\"\n *   icon={<BuildingIcon />}\n *   showHeading={true}\n *   headingLabel=\"SECTION 1\"\n *   children={[...]}\n * />\n *\n * // Item no colapsable (actúa como botón normal)\n * <DropdownItemCollapsible\n *   label=\"Single Item\"\n *   icon={<StarIcon />}\n *   isCollapsible={false}\n *   onClick={() => console.log('clicked')}\n * />\n * ```\n */\nexport const DropdownItemCollapsible: React.FC<DropdownItemCollapsibleProps> = ({\n  label,\n  icon,\n  children = [],\n  defaultOpen = false,\n  disabled = false,\n  onOpenChange,\n  onClick,\n  isCollapsible = children.length > 0,\n  showHeading = false,\n  headingLabel,\n  showDivider = true,\n  selected = false,\n  badge = false,\n  badgeCount,\n  badgeColor = 'red',\n  stickyHeader = false,\n  className = '',\n}) => {\n  const [isOpen, setIsOpen] = useState(defaultOpen);\n\n  React.useEffect(() => {\n    setIsOpen(defaultOpen);\n  }, [defaultOpen]);\n\n  const handleToggle = () => {\n    if (disabled || !isCollapsible) return;\n\n    const newOpen = !isOpen;\n    setIsOpen(newOpen);\n    onOpenChange?.(newOpen);\n  };\n\n  const handleHeaderClick = (e: React.MouseEvent<HTMLButtonElement>) => {\n    if (disabled) return;\n\n    if (isCollapsible) {\n      handleToggle();\n    } else {\n      onClick?.(e);\n    }\n  };\n\n  const handleChildClick = (child: DropdownItemCollapsibleChildProps) => (\n    e: React.MouseEvent<HTMLDivElement>,\n  ) => {\n    if (child.disabled) return;\n    child.onClick?.(e);\n  };\n\n  return (\n    <div className={`flex flex-col gap-0.5 w-full ${className}`}>\n      {/* Sticky Header Wrapper */}\n      <div\n        className={[\n          'flex flex-col gap-0.5 w-full transition-all duration-200 rounded-lg',\n          stickyHeader && 'sticky top-0 z-10 bg-gray-50 dark:bg-dark-bg-primary shadow-xs mb-0.5',\n        ]\n          .filter(Boolean)\n          .join(' ')}\n      >\n        {/* Section Heading */}\n        {showHeading && headingLabel && (\n          <div className=\"flex flex-col gap-0 items-start pb-1 pt-3 px-0 w-full\">\n            <p className=\"font-['Inter:Regular',sans-serif] font-normal leading-4 not-italic text-xs text-content-tertiary dark:text-content-tertiary w-full\">\n              {headingLabel}\n            </p>\n          </div>\n        )}\n\n        {/* Header Button */}\n        <button\n          onClick={handleHeaderClick}\n          disabled={disabled}\n          className={[\n            // Base\n            'flex items-center gap-3 px-4 py-2 w-full',\n            'rounded-lg cursor-pointer',\n            'transition-all duration-150',\n\n            // Colores y estados (Light Mode)\n            selected && !disabled && 'bg-primary-100 text-primary-600',\n            !selected && !disabled && 'text-content-primary',\n            !disabled && 'hover:bg-primary-100',\n            !disabled && 'hover:text-primary-600',\n\n            // Dark Mode\n            selected && !disabled && 'dark:bg-dark-bg-custom dark:text-dark-content-custom',\n            !selected && !disabled && 'dark:text-content-primary',\n            !disabled && 'dark:hover:bg-dark-bg-custom',\n            !disabled && 'dark:hover:text-dark-content-custom',\n\n            // Focus ring\n            !disabled && 'focus:outline-hidden',\n            !disabled && 'focus:ring-2',\n            !disabled && 'focus:ring-offset-2',\n            !disabled && 'focus:ring-primary-400',\n            !disabled && 'focus:ring-offset-bg-primary',\n            !disabled && 'dark:focus:ring-offset-dark-bg-primary',\n\n            // Disabled\n            disabled && 'opacity-50',\n            disabled && 'cursor-not-allowed',\n          ]\n            .filter(Boolean)\n            .join(' ')}\n          aria-expanded={isOpen && isCollapsible}\n          aria-disabled={disabled}\n        >\n          {/* Icon Wrapper */}\n          {icon && (\n            <div className=\"flex items-center justify-center w-4 h-4 shrink-0 text-content-secondary dark:text-content-secondary\">\n              {icon}\n            </div>\n          )}\n\n          {/* Content Wrapper */}\n          <div className=\"flex flex-1 flex-col items-start justify-center gap-0.5\">\n            <p className=\"font-['Inter:Regular',sans-serif] font-normal leading-5 not-italic text-sm text-left\">\n              {label}\n            </p>\n          </div>\n\n          {/* Badge */}\n          {(badge || badgeCount) && (\n            <div className=\"flex items-center justify-center shrink-0\">\n              {badgeCount ? (\n                <div className=\"flex items-center justify-center px-1.5 py-0.5 rounded-full bg-red-500 dark:bg-red-600 text-white text-xs font-bold min-w-6 h-6\">\n                  {badgeCount > 99 ? '99+' : badgeCount}\n                </div>\n              ) : (\n                <div className=\"w-2 h-2 rounded-full bg-red-500 dark:bg-red-600 shrink-0\" />\n              )}\n            </div>\n          )}\n\n          {/* Chevron (solo visible si es colapsable) */}\n          {isCollapsible && (\n            <div\n              className={[\n                'flex items-center justify-center w-4 h-4 shrink-0',\n                'text-content-secondary dark:text-content-secondary',\n                'transition-transform duration-200',\n                isOpen ? 'rotate-180' : 'rotate-0',\n              ].join(' ')}\n            >\n              <ChevronDownIcon className=\"w-4 h-4\" />\n            </div>\n          )}\n        </button>\n\n        {/* Divider */}\n        {showDivider && <div className=\"w-full h-px bg-border-primary dark:bg-dark-border-primary\" />}\n      </div>\n\n      {/* Children Container (expanded) */}\n      {isOpen && isCollapsible && children.length > 0 && (\n        <div className=\"flex flex-col gap-0.5 w-full py-2 px-0\">\n          {children.map((child, index) => (\n            <div\n              key={index}\n              onClick={handleChildClick(child)}\n              className={[\n                // Base\n                'flex gap-3 items-center pl-6 pr-4 py-2 w-full',\n                'rounded-lg cursor-pointer',\n                'transition-all duration-150',\n\n                // Colores y estados (Light Mode)\n                !child.disabled && 'text-content-primary',\n                !child.disabled && 'hover:bg-primary-100',\n                !child.disabled && 'hover:text-primary-600',\n\n                // Dark Mode\n                !child.disabled && 'dark:text-content-primary',\n                !child.disabled && 'dark:hover:bg-dark-bg-custom',\n                !child.disabled && 'dark:hover:text-dark-content-custom',\n\n                // Focus ring\n                !child.disabled && 'focus:outline-hidden',\n                !child.disabled && 'focus:ring-2',\n                !child.disabled && 'focus:ring-offset-2',\n                !child.disabled && 'focus:ring-primary-400',\n                !child.disabled && 'focus:ring-offset-bg-primary',\n                !child.disabled && 'dark:focus:ring-offset-dark-bg-primary',\n\n                // Disabled\n                child.disabled && 'opacity-50',\n                child.disabled && 'cursor-not-allowed',\n\n                // Custom classes\n                child.className,\n              ]\n                .filter(Boolean)\n                .join(' ')}\n            >\n              {/* Child Icon Wrapper */}\n              {child.icon && (\n                <div className=\"flex items-center justify-center w-4 h-4 shrink-0 text-content-secondary dark:text-content-secondary\">\n                  {child.icon}\n                </div>\n              )}\n\n              {/* Child Content Wrapper */}\n              <div className=\"flex flex-1 flex-col items-start justify-center gap-0.5\">\n                <p className=\"font-['Inter:Regular',sans-serif] font-normal leading-5 not-italic text-sm text-left\">\n                  {child.label}\n                </p>\n              </div>\n            </div>\n          ))}\n        </div>\n      )}\n    </div>\n  );\n};\n\nexport default DropdownItemCollapsible;","/**\n * Iconos para el componente DropdownItemHeading\n * Usando heroicons-micro según especificaciones de Figma\n * \n * Los iconos se pueden pasar como strings al componente:\n * - 'cog-6-tooth': Icono de engranaje\n * - 'check': Icono de check\n * - 'x': Icono de cerrar\n * - 'chevron-down': Icono de chevron hacia abajo\n * \n * @see DropdownItemHeading.tsx para ver cómo se usan\n */\n\nimport React from 'react';\n\ninterface IconProps {\n  className?: string;\n}\n\n/**\n * Icono Cog (heroicons-micro/cog-6-tooth)\n * Usado como icono por defecto en DropdownItemHeading\n * Tamaño: 16x16px\n */\nexport const CogIcon = ({ className = 'w-4 h-4' }: IconProps) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className={className}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M6.455 1.45A.5.5 0 0 1 6.952 1h2.096a.5.5 0 0 1 .497.45l.186 1.858a4.996 4.996 0 0 1 1.466.848l1.703-.769a.5.5 0 0 1 .639.206l1.047 1.814a.5.5 0 0 1-.14.656l-1.517 1.09a5.026 5.026 0 0 1 0 1.694l1.516 1.09a.5.5 0 0 1 .141.656l-1.047 1.814a.5.5 0 0 1-.639.206l-1.703-.768c-.433.36-.928.649-1.466.847l-.186 1.858a.5.5 0 0 1-.497.45H6.952a.5.5 0 0 1-.497-.45l-.186-1.858a4.993 4.993 0 0 1-1.466-.848l-1.703.769a.5.5 0 0 1-.639-.206l-1.047-1.814a.5.5 0 0 1 .14-.656l1.517-1.09a5.033 5.033 0 0 1 0-1.694l-1.516-1.09a.5.5 0 0 1-.141-.656L2.461 3.39a.5.5 0 0 1 .639-.206l1.703.768c.433-.36.928-.649 1.466-.847l.186-1.858ZM8 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono Check (heroicons-micro/check)\n */\nexport const CheckIcon = ({ className = 'w-4 h-4' }: IconProps) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className={className}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 1 1-1.06-1.06L12.69 4.22a.75.75 0 0 1 1.06 0Z\"\n      clipRule=\"evenodd\"\n    />\n    <path\n      fillRule=\"evenodd\"\n      d=\"M2.22 9.28a.75.75 0 0 0 0 1.06l2.5 2.5a.75.75 0 1 0 1.06-1.06l-2.5-2.5a.75.75 0 0 0-1.06 0Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono X (heroicons-micro/x-mark)\n */\nexport const XIcon = ({ className = 'w-4 h-4' }: IconProps) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className={className}\n  >\n    <path d=\"M5.28 4.22a.75.75 0 0 0-1.06 1.06L6.94 8l-2.72 2.72a.75.75 0 1 0 1.06 1.06L8 9.06l2.72 2.72a.75.75 0 1 0 1.06-1.06L9.06 8l2.72-2.72a.75.75 0 0 0-1.06-1.06L8 6.94 5.28 4.22Z\" />\n  </svg>\n);\n\n/**\n * Icono ChevronDown (heroicons-micro/chevron-down)\n */\nexport const ChevronDownIcon = ({ className = 'w-4 h-4' }: IconProps) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className={className}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Mapeo de nombres de iconos a componentes\n * Permite usar strings para referenciar iconos\n */\nexport const iconMap: Record<string, React.FC<IconProps>> = {\n  'cog-6-tooth': CogIcon,\n  'check': CheckIcon,\n  'x': XIcon,\n  'chevron-down': ChevronDownIcon,\n};\n\n/**\n * Obtener un icono por su nombre\n * @param iconName - Nombre del icono (ej: 'cog-6-tooth', 'check', 'x', 'chevron-down')\n * @param className - Clases CSS adicionales\n * @returns Componente del icono o null si no existe\n */\nexport const getIcon = (\n  iconName: string | null | undefined,\n  className?: string\n): React.ReactNode => {\n  if (!iconName) return null;\n\n  const IconComponent = iconMap[iconName];\n  if (!IconComponent) {\n    console.warn(`Icon \"${iconName}\" not found in iconMap`);\n    return null;\n  }\n\n  return <IconComponent className={className} />;\n};\n","import React from 'react';\nimport type { DropdownItemHeadingProps } from './DropdownItemHeading.types';\nimport { getIcon } from './icons';\n\n/**\n * Componente DropdownItemHeading del sistema de diseño Siesa\n *\n * Implementación pixel-perfect basada en Figma (node 6135:32539)\n * para encabezados en menús dropdown con icono, label, descripción y acción.\n *\n * **Estructura:**\n * - Icon Wrapper: Opcional, icono de 16x16px\n * - Content Wrapper: Label + Description (flexible)\n * - Action Wrapper: Opcional, texto de acción en la derecha\n *\n * **Dimensiones:**\n * - Altura flexible (contenido vertical)\n * - Width mínimo: 224px\n * - Padding: 8px vertical, 16px horizontal\n * - Border radius: 8px (rounded-lg)\n *\n * **Tipografía:**\n * - Label: Label/Small (14px Bold) - content-primary\n * - Description: Paragraph/Tiny (12px Regular) - content-secondary\n * - Action: Paragraph/XXSmall (10px Regular) - content-secondary\n *\n * **Dark Mode:**\n * - Label: #18181b (light) → #bfe2fe (dark)\n * - Description: #a1a1aa (light) → #93d1fd (dark)\n * - Icon: #0e79fd (light) → #bfe2fe (dark)\n * - Action: #a1a1aa (light) → #93d1fd (dark)\n *\n * **Estados:**\n * - Default: Sin hover/focus\n * - Hover: Overlay sutil (managed by parent Dropdown)\n * - Disabled: Opacity 50% (managed by parent Dropdown)\n *\n * **Especificaciones de Figma:**\n * - Gap entre elementos: 12px\n * - Gap entre label y description: 2px\n * - Rounded: 8px (rounded-lg)\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Label/Small, Paragraph/Tiny)\n * @see docs/spacing.md - Sistema de espaciado\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=6135-32539 - Diseño Figma\n *\n * @example\n * ```tsx\n * // Con icono, label, descripción y acción\n * <DropdownItemHeading\n *   label=\"Settings\"\n *   description=\"Configure your preferences\"\n *   showDescription={true}\n *   icon={<SettingsIcon />}\n *   showIcon={true}\n *   actionLabel=\"Clear\"\n *   showAction={true}\n *   onActionClick={handleClear}\n * />\n *\n * // Solo label y descripción (sin icono ni acción)\n * <DropdownItemHeading\n *   label=\"My Account\"\n *   description=\"user@example.com\"\n *   showDescription={true}\n * />\n *\n * // Solo label\n * <DropdownItemHeading\n *   label=\"Quick Actions\"\n *   showDescription={false}\n * />\n * ```\n */\nexport const DropdownItemHeading: React.FC<DropdownItemHeadingProps> = ({\n  label = 'Label',\n  description,\n  showDescription = true,\n  iconName = 'cog-6-tooth',\n  showIcon = true,\n  actionLabel,\n  showAction = false,\n  onActionClick,\n  className = '',\n  ...rest\n}) => {\n\n  return (\n    <div\n      className={`\n        flex\n        gap-3\n        items-center\n        px-4\n        py-2\n        rounded-lg\n        w-56\n        ${className}\n      `}\n      data-testid=\"dropdown-item-heading\"\n      {...rest}\n    >\n      {/* ===== ICON WRAPPER ===== */}\n      {showIcon && iconName && (\n        <div\n          className=\"\n            flex\n            items-center\n            justify-center\n            shrink-0\n            w-4\n            h-4\n          \"\n          data-testid=\"icon-wrapper\"\n        >\n          <div className=\"text-primary-600 dark:text-dark-content-inverse\">\n            {getIcon(iconName, 'w-4 h-4')}\n          </div>\n        </div>\n      )}\n\n      {/* ===== CONTENT WRAPPER ===== */}\n      <div\n        className=\"\n          flex\n          flex-1\n          flex-col\n          gap-0.5\n          items-start\n          justify-center\n          min-w-0\n        \"\n        data-testid=\"content-wrapper\"\n      >\n        {/* Label */}\n        <p\n          className=\"\n            font-bold\n            text-sm\n            leading-5\n            text-content-primary\n            dark:text-dark-content-inverse\n            whitespace-nowrap\n            overflow-hidden\n            text-ellipsis\n          \"\n          data-testid=\"label\"\n        >\n          {label}\n        </p>\n\n        {/* Description */}\n        {showDescription && description && (\n          <p\n            className=\"\n              font-normal\n              text-xs\n              leading-4\n              text-content-secondary\n              dark:text-dark-border-inverse\n              w-full\n              whitespace-pre-wrap\n              overflow-hidden\n              text-ellipsis\n            \"\n            data-testid=\"description\"\n          >\n            {description}\n          </p>\n        )}\n      </div>\n\n      {/* ===== ACTION WRAPPER ===== */}\n      {showAction && actionLabel && (\n        <div\n          className=\"\n            flex\n            items-center\n            justify-center\n            shrink-0\n            cursor-pointer\n            hover:opacity-80\n            transition-opacity\n            duration-150\n          \"\n          data-testid=\"action-wrapper\"\n          onClick={onActionClick}\n          role=\"button\"\n          tabIndex={0}\n          onKeyDown={(e) => {\n            if (e.key === 'Enter' || e.key === ' ') {\n              onActionClick?.(e as any);\n            }\n          }}\n        >\n          <p\n            className=\"\n              font-normal\n              text-xs\n              leading-3\n              text-content-secondary\n              dark:text-dark-border-inverse\n              whitespace-nowrap\n            \"\n            data-testid=\"action-label\"\n          >\n            {actionLabel}\n          </p>\n        </div>\n      )}\n    </div>\n  );\n};\n\nDropdownItemHeading.displayName = 'DropdownItemHeading';\n","import React from 'react';\nimport type { NotificationProps } from './Notification.types';\n\n/**\n * Componente Notification del sistema de diseño Siesa\n *\n * Badge de notificación para indicar alertas, mensajes o notificaciones pendientes.\n * Puede mostrar un punto simple o un contador numérico con límite automático a 99+.\n *\n * **Especificaciones de Figma:**\n * - Badge con número: 27px × 13px (aprox), Label/XXSmall (10px Bold, line-height 12px)\n * - Badge simple (dot): 13px × 13px\n * - Color: `content-extensions-red` (#b91c1c) por defecto\n * - Border radius: Pill (rounded-full)\n * - Padding: 4px horizontal\n *\n * **Variantes:**\n * - Sin count: Muestra punto circular (dot)\n * - Con count: Muestra badge con número (máximo 99+)\n *\n * **Uso típico:**\n * - Como overlay en iconos o botones\n * - En elementos de menú o navegación\n * - Standalone para indicar estado\n *\n * @see docs/colors.md - Sistema de colores (token content-extensions-red)\n * @see docs/typography.md - Sistema tipográfico (Label/XXSmall)\n * @see src/components/Button/Button.tsx - Referencia de badges en botones\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4310-22651\n *\n * @example\n * ```tsx\n * // Badge simple (punto)\n * <Notification />\n *\n * // Badge con número\n * <Notification count={5} />\n *\n * // Badge con muchos (muestra 99+)\n * <Notification count={150} />\n *\n * // Con color personalizado\n * <Notification count={3} color=\"green\" />\n *\n * // Como overlay en botón\n * <button className=\"relative\">\n *   <BellIcon />\n *   <Notification count={5} className=\"absolute -top-1 -right-1\" />\n * </button>\n * ```\n */\nexport const Notification: React.FC<NotificationProps> = ({\n  count,\n  color = 'red',\n  className = '',\n  ariaLabel,\n}) => {\n  // ===== MAPA DE COLORES =====\n  // Sistema de colores consistente con Button y Badge\n  const colorClasses: Record<string, { bg: string; text: string }> = {\n    zinc: { bg: 'bg-zinc-600', text: 'text-white' },\n    red: { bg: 'bg-content-extensions-red', text: 'text-white' },\n    orange: { bg: 'bg-orange-700', text: 'text-white' },\n    amber: { bg: 'bg-amber-700', text: 'text-white' },\n    yellow: { bg: 'bg-yellow-700', text: 'text-white' },\n    lime: { bg: 'bg-lime-700', text: 'text-white' },\n    green: { bg: 'bg-green-700', text: 'text-white' },\n    emerald: { bg: 'bg-emerald-700', text: 'text-white' },\n    teal: { bg: 'bg-teal-700', text: 'text-white' },\n    cyan: { bg: 'bg-cyan-700', text: 'text-white' },\n    sky: { bg: 'bg-sky-700', text: 'text-white' },\n    blue: { bg: 'bg-blue-700', text: 'text-white' },\n    indigo: { bg: 'bg-indigo-700', text: 'text-white' },\n    violet: { bg: 'bg-violet-700', text: 'text-white' },\n    purple: { bg: 'bg-purple-700', text: 'text-white' },\n    fuchsia: { bg: 'bg-fuchsia-700', text: 'text-white' },\n    pink: { bg: 'bg-pink-700', text: 'text-white' },\n    rose: { bg: 'bg-rose-700', text: 'text-white' },\n    primary: { bg: 'bg-primary-600', text: 'text-white' },\n    secondary: { bg: 'bg-zinc-600', text: 'text-white' },\n    tertiary: { bg: 'bg-zinc-600', text: 'text-white' },\n  };\n\n  const colors = colorClasses[color] || colorClasses.red;\n\n  // ===== ARIA LABEL DINÁMICO =====\n  const dynamicAriaLabel = ariaLabel ||\n    (count !== undefined && count > 0\n      ? `${count} notificaci${count === 1 ? 'ón' : 'ones'}`\n      : 'Notificación pendiente');\n\n  // ===== BADGE CON NÚMERO =====\n  if (count !== undefined && count > 0) {\n    const displayCount = count > 99 ? '99+' : count.toString();\n\n    return (\n      <span\n        className={`\n          inline-flex\n          items-center\n          justify-center\n          min-w-[16px]\n          h-4\n          px-1\n          rounded-full\n          text-[10px]\n          font-bold\n          leading-none\n          ${colors.bg}\n          ${colors.text}\n          pointer-events-none\n          dark:${colors.bg}\n          dark:${colors.text}\n          ${className}\n        `\n          .trim()\n          .replace(/\\s+/g, ' ')}\n        role=\"status\"\n        aria-label={dynamicAriaLabel}\n      >\n        {displayCount}\n      </span>\n    );\n  }\n\n  // ===== BADGE SIMPLE (DOT) =====\n  return (\n    <span\n      className={`\n        inline-block\n        w-2\n        h-2\n        rounded-full\n        ${colors.bg}\n        pointer-events-none\n        dark:${colors.bg}\n        ${className}\n      `\n        .trim()\n        .replace(/\\s+/g, ' ')}\n      role=\"status\"\n      aria-label={dynamicAriaLabel}\n    />\n  );\n};\n","import React from 'react';\n\n/**\n * Icono de flecha izquierda (ChevronLeft)\n * Usado en el botón \"Back\"\n * Heroicons Micro (16x16px)\n */\nexport const ArrowLeftIcon: React.FC<{ className?: string }> = ({ className = '' }) => {\n  return (\n    <svg\n      className={className}\n      xmlns=\"http://www.w3.org/2000/svg\"\n      viewBox=\"0 0 16 16\"\n      fill=\"currentColor\"\n      aria-hidden=\"true\"\n    >\n      <path\n        fillRule=\"evenodd\"\n        d=\"M9.78 4.22a.75.75 0 0 1 0 1.06L7.06 8l2.72 2.72a.75.75 0 1 1-1.06 1.06L5.47 8.53a.75.75 0 0 1 0-1.06l3.25-3.25a.75.75 0 0 1 1.06 0Z\"\n        clipRule=\"evenodd\"\n      />\n    </svg>\n  );\n};\n\n/**\n * Icono de flecha derecha (ChevronRight)\n * Usado en el botón \"Next\"\n * Heroicons Micro (16x16px)\n */\nexport const ArrowRightIcon: React.FC<{ className?: string }> = ({ className = '' }) => {\n  return (\n    <svg\n      className={className}\n      xmlns=\"http://www.w3.org/2000/svg\"\n      viewBox=\"0 0 16 16\"\n      fill=\"currentColor\"\n      aria-hidden=\"true\"\n    >\n      <path\n        fillRule=\"evenodd\"\n        d=\"M6.22 4.22a.75.75 0 0 1 1.06 0l3.25 3.25a.75.75 0 0 1 0 1.06l-3.25 3.25a.75.75 0 0 1-1.06-1.06L8.94 8 6.22 5.28a.75.75 0 0 1 0-1.06Z\"\n        clipRule=\"evenodd\"\n      />\n    </svg>\n  );\n};\n","import React, { useMemo } from 'react';\nimport type { PaginationProps, PageButtonProps } from './Pagination.types';\nimport { ArrowLeftIcon, ArrowRightIcon } from './icons';\n\n/**\n * Componente Pagination del sistema de diseño Siesa\n * Basado en especificaciones de Figma con Tailwind CSS\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n * - Algoritmo de paginación inteligente\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Label Small)\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * <Pagination\n *   currentPage={1}\n *   totalPages={66}\n *   onPageChange={(page) => console.log(page)}\n * />\n * ```\n */\nexport const Pagination: React.FC<PaginationProps> = ({\n  currentPage = 1,\n  totalPages,\n  onPageChange,\n  backText = 'Atrás',\n  nextText = 'Siguiente',\n  siblingCount = 1,\n  showBackButton = true,\n  showNextButton = true,\n  className = '',\n  ariaLabel = 'Paginación',\n}) => {\n  /**\n   * Genera el array de páginas a mostrar\n   * Algoritmo: [1] ... [currentPage-1] [currentPage] [currentPage+1] ... [totalPages]\n   */\n  const paginationRange = useMemo(() => {\n    const totalNumbers = siblingCount * 2 + 3; // Página actual + siblings + primera + última\n    const totalBlocks = totalNumbers + 2; // + 2 separadores \"...\"\n\n    // Si el total de páginas es menor que el total de bloques, mostrar todas\n    if (totalPages <= totalBlocks) {\n      return Array.from({ length: totalPages }, (_, i) => i + 1);\n    }\n\n    const leftSiblingIndex = Math.max(currentPage - siblingCount, 1);\n    const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPages);\n\n    const shouldShowLeftDots = leftSiblingIndex > 2;\n    const shouldShowRightDots = rightSiblingIndex < totalPages - 1;\n\n    const firstPageIndex = 1;\n    const lastPageIndex = totalPages;\n\n    // No mostrar dots a la izquierda\n    if (!shouldShowLeftDots && shouldShowRightDots) {\n      const leftItemCount = 3 + 2 * siblingCount;\n      const leftRange = Array.from({ length: leftItemCount }, (_, i) => i + 1);\n      return [...leftRange, '...', totalPages];\n    }\n\n    // No mostrar dots a la derecha\n    if (shouldShowLeftDots && !shouldShowRightDots) {\n      const rightItemCount = 3 + 2 * siblingCount;\n      const rightRange = Array.from(\n        { length: rightItemCount },\n        (_, i) => totalPages - rightItemCount + i + 1\n      );\n      return [firstPageIndex, '...', ...rightRange];\n    }\n\n    // Mostrar ambos dots\n    if (shouldShowLeftDots && shouldShowRightDots) {\n      const middleRange = Array.from(\n        { length: rightSiblingIndex - leftSiblingIndex + 1 },\n        (_, i) => leftSiblingIndex + i\n      );\n      return [firstPageIndex, '...', ...middleRange, '...', lastPageIndex];\n    }\n\n    return [];\n  }, [currentPage, totalPages, siblingCount]);\n\n  /**\n   * Handler para cambio de página\n   */\n  const handlePageChange = (page: number) => {\n    if (page >= 1 && page <= totalPages && page !== currentPage) {\n      onPageChange?.(page);\n    }\n  };\n\n  /**\n   * Componente interno: Botón de página\n   */\n  const PageButton: React.FC<PageButtonProps> = ({\n    page,\n    isActive = false,\n    disabled = false,\n    onClick,\n    ariaLabel: buttonAriaLabel,\n  }) => {\n    const isDots = page === '...';\n\n    // ===== CLASES BASE =====\n    const baseClasses = `\n      inline-flex\n      items-center\n      justify-center\n      gap-3\n      px-3\n      py-2\n      rounded-md\n      font-bold\n      text-sm\n      whitespace-nowrap\n      transition-all\n      duration-150\n    `;\n\n    // ===== CLASES DE ESTADO =====\n    const stateClasses = isDots\n      ? `\n          text-primary-600\n          dark:text-primary-600\n          cursor-default\n          pointer-events-none\n        `\n      : isActive\n      ? `\n          bg-primary-100\n          text-primary-600\n          dark:bg-primary-100\n          dark:text-primary-600\n        `\n      : `\n          text-primary-600\n          hover:bg-primary-100\n          active:scale-95\n          dark:text-primary-600\n          dark:hover:bg-primary-100\n          dark:active:scale-95\n        `;\n\n    // ===== CLASES DE DISABLED =====\n    const disabledClasses = disabled\n      ? `\n          opacity-50\n          cursor-not-allowed\n          pointer-events-none\n        `\n      : '';\n\n    // ===== COMBINAR CLASES =====\n    const buttonClasses = [baseClasses, stateClasses, disabledClasses]\n      .join(' ')\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    return (\n      <button\n        type=\"button\"\n        className={buttonClasses}\n        onClick={onClick}\n        disabled={disabled || isDots}\n        aria-label={buttonAriaLabel}\n        aria-current={isActive ? 'page' : undefined}\n      >\n        {page}\n      </button>\n    );\n  };\n\n  // ===== CLASES DEL CONTAINER =====\n  const containerClasses = `\n    inline-flex\n    items-center\n    justify-between\n    gap-0\n    ${className}\n  `\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <nav className={containerClasses} aria-label={ariaLabel} role=\"navigation\">\n      {/* ===== BOTÓN BACK ===== */}\n      {showBackButton && (\n        <button\n          type=\"button\"\n          className={`\n            inline-flex\n            items-center\n            justify-center\n            gap-3\n            px-3\n            py-2\n            rounded-md\n            font-bold\n            text-sm\n            text-primary-600\n            hover:bg-primary-100\n            active:scale-95\n            dark:text-primary-600\n            dark:hover:bg-primary-100\n            dark:active:scale-95\n            transition-all\n            duration-150\n            ${currentPage === 1 ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}\n          `\n            .replace(/\\s+/g, ' ')\n            .trim()}\n          onClick={() => handlePageChange(currentPage - 1)}\n          disabled={currentPage === 1}\n          aria-label={`${backText} page`}\n        >\n          <ArrowLeftIcon className=\"w-4 h-4\" />\n          {backText}\n        </button>\n      )}\n\n      {/* ===== NÚMEROS DE PÁGINA ===== */}\n      <div className=\"inline-flex items-center\">\n        {paginationRange.map((page, index) => (\n          <PageButton\n            key={`${page}-${index}`}\n            page={page}\n            isActive={page === currentPage}\n            onClick={() => typeof page === 'number' && handlePageChange(page)}\n            ariaLabel={\n              typeof page === 'number' ? `Go to page ${page}` : `Page ${page}`\n            }\n          />\n        ))}\n      </div>\n\n      {/* ===== BOTÓN NEXT ===== */}\n      {showNextButton && (\n        <button\n          type=\"button\"\n          className={`\n            inline-flex\n            items-center\n            justify-center\n            gap-3\n            px-3\n            py-2\n            rounded-md\n            font-bold\n            text-sm\n            text-primary-600\n            hover:bg-primary-100\n            active:scale-95\n            dark:text-primary-600\n            dark:hover:bg-primary-100\n            dark:active:scale-95\n            transition-all\n            duration-150\n            ${\n              currentPage === totalPages\n                ? 'opacity-50 cursor-not-allowed pointer-events-none'\n                : ''\n            }\n          `\n            .replace(/\\s+/g, ' ')\n            .trim()}\n          onClick={() => handlePageChange(currentPage + 1)}\n          disabled={currentPage === totalPages}\n          aria-label={`${nextText} page`}\n        >\n          {nextText}\n          <ArrowRightIcon className=\"w-4 h-4\" />\n        </button>\n      )}\n    </nav>\n  );\n};\n","import * as React from \"react\";\nfunction CheckIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z\",\n    clipRule: \"evenodd\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(CheckIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ChevronLeftIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z\",\n    clipRule: \"evenodd\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ChevronLeftIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ChevronRightIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z\",\n    clipRule: \"evenodd\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ChevronRightIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction ChevronUpDownIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M10.53 3.47a.75.75 0 0 0-1.06 0L6.22 6.72a.75.75 0 0 0 1.06 1.06L10 5.06l2.72 2.72a.75.75 0 1 0 1.06-1.06l-3.25-3.25Zm-4.31 9.81 3.25 3.25a.75.75 0 0 0 1.06 0l3.25-3.25a.75.75 0 1 0-1.06-1.06L10 14.94l-2.72-2.72a.75.75 0 0 0-1.06 1.06Z\",\n    clipRule: \"evenodd\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(ChevronUpDownIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction MagnifyingGlassIcon({\n  title,\n  titleId,\n  ...props\n}, svgRef) {\n  return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n    xmlns: \"http://www.w3.org/2000/svg\",\n    viewBox: \"0 0 20 20\",\n    fill: \"currentColor\",\n    \"aria-hidden\": \"true\",\n    \"data-slot\": \"icon\",\n    ref: svgRef,\n    \"aria-labelledby\": titleId\n  }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n    id: titleId\n  }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n    fillRule: \"evenodd\",\n    d: \"M9 3.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11ZM2 9a7 7 0 1 1 12.452 4.391l3.328 3.329a.75.75 0 1 1-1.06 1.06l-3.329-3.328A7 7 0 0 1 2 9Z\",\n    clipRule: \"evenodd\"\n  }));\n}\nconst ForwardRef = /*#__PURE__*/ React.forwardRef(MagnifyingGlassIcon);\nexport default ForwardRef;","function hasWindow() {\n  return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n  if (isNode(node)) {\n    return (node.nodeName || '').toLowerCase();\n  }\n  // Mocked nodes in testing environments may not be instances of Node. By\n  // returning `#document` an infinite loop won't occur.\n  // https://github.com/floating-ui/floating-ui/issues/2317\n  return '#document';\n}\nfunction getWindow(node) {\n  var _node$ownerDocument;\n  return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n  var _ref;\n  return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n  if (!hasWindow()) {\n    return false;\n  }\n  return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n  if (!hasWindow()) {\n    return false;\n  }\n  return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n  if (!hasWindow()) {\n    return false;\n  }\n  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n  if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n    return false;\n  }\n  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nconst invalidOverflowDisplayValues = /*#__PURE__*/new Set(['inline', 'contents']);\nfunction isOverflowElement(element) {\n  const {\n    overflow,\n    overflowX,\n    overflowY,\n    display\n  } = getComputedStyle(element);\n  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);\n}\nconst tableElements = /*#__PURE__*/new Set(['table', 'td', 'th']);\nfunction isTableElement(element) {\n  return tableElements.has(getNodeName(element));\n}\nconst topLayerSelectors = [':popover-open', ':modal'];\nfunction isTopLayer(element) {\n  return topLayerSelectors.some(selector => {\n    try {\n      return element.matches(selector);\n    } catch (_e) {\n      return false;\n    }\n  });\n}\nconst transformProperties = ['transform', 'translate', 'scale', 'rotate', 'perspective'];\nconst willChangeValues = ['transform', 'translate', 'scale', 'rotate', 'perspective', 'filter'];\nconst containValues = ['paint', 'layout', 'strict', 'content'];\nfunction isContainingBlock(elementOrCss) {\n  const webkit = isWebKit();\n  const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n  // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n  // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n  return transformProperties.some(value => css[value] ? css[value] !== 'none' : false) || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || willChangeValues.some(value => (css.willChange || '').includes(value)) || containValues.some(value => (css.contain || '').includes(value));\n}\nfunction getContainingBlock(element) {\n  let currentNode = getParentNode(element);\n  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n    if (isContainingBlock(currentNode)) {\n      return currentNode;\n    } else if (isTopLayer(currentNode)) {\n      return null;\n    }\n    currentNode = getParentNode(currentNode);\n  }\n  return null;\n}\nfunction isWebKit() {\n  if (typeof CSS === 'undefined' || !CSS.supports) return false;\n  return CSS.supports('-webkit-backdrop-filter', 'none');\n}\nconst lastTraversableNodeNames = /*#__PURE__*/new Set(['html', 'body', '#document']);\nfunction isLastTraversableNode(node) {\n  return lastTraversableNodeNames.has(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n  return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n  if (isElement(element)) {\n    return {\n      scrollLeft: element.scrollLeft,\n      scrollTop: element.scrollTop\n    };\n  }\n  return {\n    scrollLeft: element.scrollX,\n    scrollTop: element.scrollY\n  };\n}\nfunction getParentNode(node) {\n  if (getNodeName(node) === 'html') {\n    return node;\n  }\n  const result =\n  // Step into the shadow DOM of the parent of a slotted node.\n  node.assignedSlot ||\n  // DOM Element detected.\n  node.parentNode ||\n  // ShadowRoot detected.\n  isShadowRoot(node) && node.host ||\n  // Fallback.\n  getDocumentElement(node);\n  return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n  const parentNode = getParentNode(node);\n  if (isLastTraversableNode(parentNode)) {\n    return node.ownerDocument ? node.ownerDocument.body : node.body;\n  }\n  if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n    return parentNode;\n  }\n  return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n  var _node$ownerDocument2;\n  if (list === void 0) {\n    list = [];\n  }\n  if (traverseIframes === void 0) {\n    traverseIframes = true;\n  }\n  const scrollableAncestor = getNearestOverflowAncestor(node);\n  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n  const win = getWindow(scrollableAncestor);\n  if (isBody) {\n    const frameElement = getFrameElement(win);\n    return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n  }\n  return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n}\nfunction getFrameElement(win) {\n  return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","/**\n * Custom positioning reference element.\n * @see https://floating-ui.com/docs/virtual-elements\n */\n\nconst sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n  x: v,\n  y: v\n});\nconst oppositeSideMap = {\n  left: 'right',\n  right: 'left',\n  bottom: 'top',\n  top: 'bottom'\n};\nconst oppositeAlignmentMap = {\n  start: 'end',\n  end: 'start'\n};\nfunction clamp(start, value, end) {\n  return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n  return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n  return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n  return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n  return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n  return axis === 'y' ? 'height' : 'width';\n}\nconst yAxisSides = /*#__PURE__*/new Set(['top', 'bottom']);\nfunction getSideAxis(placement) {\n  return yAxisSides.has(getSide(placement)) ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n  return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n  if (rtl === void 0) {\n    rtl = false;\n  }\n  const alignment = getAlignment(placement);\n  const alignmentAxis = getAlignmentAxis(placement);\n  const length = getAxisLength(alignmentAxis);\n  let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n  if (rects.reference[length] > rects.floating[length]) {\n    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n  }\n  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n  const oppositePlacement = getOppositePlacement(placement);\n  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n  return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);\n}\nconst lrPlacement = ['left', 'right'];\nconst rlPlacement = ['right', 'left'];\nconst tbPlacement = ['top', 'bottom'];\nconst btPlacement = ['bottom', 'top'];\nfunction getSideList(side, isStart, rtl) {\n  switch (side) {\n    case 'top':\n    case 'bottom':\n      if (rtl) return isStart ? rlPlacement : lrPlacement;\n      return isStart ? lrPlacement : rlPlacement;\n    case 'left':\n    case 'right':\n      return isStart ? tbPlacement : btPlacement;\n    default:\n      return [];\n  }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n  const alignment = getAlignment(placement);\n  let list = getSideList(getSide(placement), direction === 'start', rtl);\n  if (alignment) {\n    list = list.map(side => side + \"-\" + alignment);\n    if (flipAlignment) {\n      list = list.concat(list.map(getOppositeAlignmentPlacement));\n    }\n  }\n  return list;\n}\nfunction getOppositePlacement(placement) {\n  return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);\n}\nfunction expandPaddingObject(padding) {\n  return {\n    top: 0,\n    right: 0,\n    bottom: 0,\n    left: 0,\n    ...padding\n  };\n}\nfunction getPaddingObject(padding) {\n  return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n    top: padding,\n    right: padding,\n    bottom: padding,\n    left: padding\n  };\n}\nfunction rectToClientRect(rect) {\n  const {\n    x,\n    y,\n    width,\n    height\n  } = rect;\n  return {\n    width,\n    height,\n    top: y,\n    left: x,\n    right: x + width,\n    bottom: y + height,\n    x,\n    y\n  };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { isShadowRoot, isHTMLElement } from '@floating-ui/utils/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport { floor } from '@floating-ui/utils';\nimport { tabbable } from 'tabbable';\n\n// Avoid Chrome DevTools blue warning.\nfunction getPlatform() {\n  const uaData = navigator.userAgentData;\n  if (uaData != null && uaData.platform) {\n    return uaData.platform;\n  }\n  return navigator.platform;\n}\nfunction getUserAgent() {\n  const uaData = navigator.userAgentData;\n  if (uaData && Array.isArray(uaData.brands)) {\n    return uaData.brands.map(_ref => {\n      let {\n        brand,\n        version\n      } = _ref;\n      return brand + \"/\" + version;\n    }).join(' ');\n  }\n  return navigator.userAgent;\n}\nfunction isSafari() {\n  // Chrome DevTools does not complain about navigator.vendor\n  return /apple/i.test(navigator.vendor);\n}\nfunction isAndroid() {\n  const re = /android/i;\n  return re.test(getPlatform()) || re.test(getUserAgent());\n}\nfunction isMac() {\n  return getPlatform().toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;\n}\nfunction isJSDOM() {\n  return getUserAgent().includes('jsdom/');\n}\n\nconst FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';\nconst TYPEABLE_SELECTOR = \"input:not([type='hidden']):not([disabled]),\" + \"[contenteditable]:not([contenteditable='false']),textarea:not([disabled])\";\nconst ARROW_LEFT = 'ArrowLeft';\nconst ARROW_RIGHT = 'ArrowRight';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nfunction activeElement(doc) {\n  let activeElement = doc.activeElement;\n  while (((_activeElement = activeElement) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {\n    var _activeElement;\n    activeElement = activeElement.shadowRoot.activeElement;\n  }\n  return activeElement;\n}\nfunction contains(parent, child) {\n  if (!parent || !child) {\n    return false;\n  }\n  const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();\n\n  // First, attempt with faster native method\n  if (parent.contains(child)) {\n    return true;\n  }\n\n  // then fallback to custom implementation with Shadow DOM support\n  if (rootNode && isShadowRoot(rootNode)) {\n    let next = child;\n    while (next) {\n      if (parent === next) {\n        return true;\n      }\n      // @ts-ignore\n      next = next.parentNode || next.host;\n    }\n  }\n\n  // Give up, the result is false\n  return false;\n}\nfunction getTarget(event) {\n  if ('composedPath' in event) {\n    return event.composedPath()[0];\n  }\n\n  // TS thinks `event` is of type never as it assumes all browsers support\n  // `composedPath()`, but browsers without shadow DOM don't.\n  return event.target;\n}\nfunction isEventTargetWithin(event, node) {\n  if (node == null) {\n    return false;\n  }\n  if ('composedPath' in event) {\n    return event.composedPath().includes(node);\n  }\n\n  // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't\n  const e = event;\n  return e.target != null && node.contains(e.target);\n}\nfunction isRootElement(element) {\n  return element.matches('html,body');\n}\nfunction getDocument(node) {\n  return (node == null ? void 0 : node.ownerDocument) || document;\n}\nfunction isTypeableElement(element) {\n  return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);\n}\nfunction isTypeableCombobox(element) {\n  if (!element) return false;\n  return element.getAttribute('role') === 'combobox' && isTypeableElement(element);\n}\nfunction matchesFocusVisible(element) {\n  // We don't want to block focus from working with `visibleOnly`\n  // (JSDOM doesn't match `:focus-visible` when the element has `:focus`)\n  if (!element || isJSDOM()) return true;\n  try {\n    return element.matches(':focus-visible');\n  } catch (_e) {\n    return true;\n  }\n}\nfunction getFloatingFocusElement(floatingElement) {\n  if (!floatingElement) {\n    return null;\n  }\n  // Try to find the element that has `{...getFloatingProps()}` spread on it.\n  // This indicates the floating element is acting as a positioning wrapper, and\n  // so focus should be managed on the child element with the event handlers and\n  // aria props.\n  return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(\"[\" + FOCUSABLE_ATTRIBUTE + \"]\") || floatingElement;\n}\n\nfunction getNodeChildren(nodes, id, onlyOpenChildren) {\n  if (onlyOpenChildren === void 0) {\n    onlyOpenChildren = true;\n  }\n  const directChildren = nodes.filter(node => {\n    var _node$context;\n    return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));\n  });\n  return directChildren.flatMap(child => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\nfunction getDeepestNode(nodes, id) {\n  let deepestNodeId;\n  let maxDepth = -1;\n  function findDeepest(nodeId, depth) {\n    if (depth > maxDepth) {\n      deepestNodeId = nodeId;\n      maxDepth = depth;\n    }\n    const children = getNodeChildren(nodes, nodeId);\n    children.forEach(child => {\n      findDeepest(child.id, depth + 1);\n    });\n  }\n  findDeepest(id, 0);\n  return nodes.find(node => node.id === deepestNodeId);\n}\nfunction getNodeAncestors(nodes, id) {\n  var _nodes$find;\n  let allAncestors = [];\n  let currentParentId = (_nodes$find = nodes.find(node => node.id === id)) == null ? void 0 : _nodes$find.parentId;\n  while (currentParentId) {\n    const currentNode = nodes.find(node => node.id === currentParentId);\n    currentParentId = currentNode == null ? void 0 : currentNode.parentId;\n    if (currentNode) {\n      allAncestors = allAncestors.concat(currentNode);\n    }\n  }\n  return allAncestors;\n}\n\nfunction stopEvent(event) {\n  event.preventDefault();\n  event.stopPropagation();\n}\nfunction isReactEvent(event) {\n  return 'nativeEvent' in event;\n}\n\n// License: https://github.com/adobe/react-spectrum/blob/b35d5c02fe900badccd0cf1a8f23bb593419f238/packages/@react-aria/utils/src/isVirtualEvent.ts\nfunction isVirtualClick(event) {\n  // FIXME: Firefox is now emitting a deprecation warning for `mozInputSource`.\n  // Try to find a workaround for this. `react-aria` source still has the check.\n  if (event.mozInputSource === 0 && event.isTrusted) {\n    return true;\n  }\n  if (isAndroid() && event.pointerType) {\n    return event.type === 'click' && event.buttons === 1;\n  }\n  return event.detail === 0 && !event.pointerType;\n}\nfunction isVirtualPointerEvent(event) {\n  if (isJSDOM()) return false;\n  return !isAndroid() && event.width === 0 && event.height === 0 || isAndroid() && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||\n  // iOS VoiceOver returns 0.333• for width/height.\n  event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';\n}\nfunction isMouseLikePointerType(pointerType, strict) {\n  // On some Linux machines with Chromium, mouse inputs return a `pointerType`\n  // of \"pen\": https://github.com/floating-ui/floating-ui/issues/2015\n  const values = ['mouse', 'pen'];\n  if (!strict) {\n    values.push('', undefined);\n  }\n  return values.includes(pointerType);\n}\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\nconst SafeReact = {\n  ...React\n};\n\nfunction useLatestRef(value) {\n  const ref = React.useRef(value);\n  index(() => {\n    ref.current = value;\n  });\n  return ref;\n}\nconst useInsertionEffect = SafeReact.useInsertionEffect;\nconst useSafeInsertionEffect = useInsertionEffect || (fn => fn());\nfunction useEffectEvent(callback) {\n  const ref = React.useRef(() => {\n    if (process.env.NODE_ENV !== \"production\") {\n      throw new Error('Cannot call an event handler while rendering.');\n    }\n  });\n  useSafeInsertionEffect(() => {\n    ref.current = callback;\n  });\n  return React.useCallback(function () {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n    return ref.current == null ? void 0 : ref.current(...args);\n  }, []);\n}\n\nfunction isDifferentGridRow(index, cols, prevRow) {\n  return Math.floor(index / cols) !== prevRow;\n}\nfunction isIndexOutOfListBounds(listRef, index) {\n  return index < 0 || index >= listRef.current.length;\n}\nfunction getMinListIndex(listRef, disabledIndices) {\n  return findNonDisabledListIndex(listRef, {\n    disabledIndices\n  });\n}\nfunction getMaxListIndex(listRef, disabledIndices) {\n  return findNonDisabledListIndex(listRef, {\n    decrement: true,\n    startingIndex: listRef.current.length,\n    disabledIndices\n  });\n}\nfunction findNonDisabledListIndex(listRef, _temp) {\n  let {\n    startingIndex = -1,\n    decrement = false,\n    disabledIndices,\n    amount = 1\n  } = _temp === void 0 ? {} : _temp;\n  let index = startingIndex;\n  do {\n    index += decrement ? -amount : amount;\n  } while (index >= 0 && index <= listRef.current.length - 1 && isListIndexDisabled(listRef, index, disabledIndices));\n  return index;\n}\nfunction getGridNavigatedIndex(listRef, _ref) {\n  let {\n    event,\n    orientation,\n    loop,\n    rtl,\n    cols,\n    disabledIndices,\n    minIndex,\n    maxIndex,\n    prevIndex,\n    stopEvent: stop = false\n  } = _ref;\n  let nextIndex = prevIndex;\n  if (event.key === ARROW_UP) {\n    stop && stopEvent(event);\n    if (prevIndex === -1) {\n      nextIndex = maxIndex;\n    } else {\n      nextIndex = findNonDisabledListIndex(listRef, {\n        startingIndex: nextIndex,\n        amount: cols,\n        decrement: true,\n        disabledIndices\n      });\n      if (loop && (prevIndex - cols < minIndex || nextIndex < 0)) {\n        const col = prevIndex % cols;\n        const maxCol = maxIndex % cols;\n        const offset = maxIndex - (maxCol - col);\n        if (maxCol === col) {\n          nextIndex = maxIndex;\n        } else {\n          nextIndex = maxCol > col ? offset : offset - cols;\n        }\n      }\n    }\n    if (isIndexOutOfListBounds(listRef, nextIndex)) {\n      nextIndex = prevIndex;\n    }\n  }\n  if (event.key === ARROW_DOWN) {\n    stop && stopEvent(event);\n    if (prevIndex === -1) {\n      nextIndex = minIndex;\n    } else {\n      nextIndex = findNonDisabledListIndex(listRef, {\n        startingIndex: prevIndex,\n        amount: cols,\n        disabledIndices\n      });\n      if (loop && prevIndex + cols > maxIndex) {\n        nextIndex = findNonDisabledListIndex(listRef, {\n          startingIndex: prevIndex % cols - cols,\n          amount: cols,\n          disabledIndices\n        });\n      }\n    }\n    if (isIndexOutOfListBounds(listRef, nextIndex)) {\n      nextIndex = prevIndex;\n    }\n  }\n\n  // Remains on the same row/column.\n  if (orientation === 'both') {\n    const prevRow = floor(prevIndex / cols);\n    if (event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT)) {\n      stop && stopEvent(event);\n      if (prevIndex % cols !== cols - 1) {\n        nextIndex = findNonDisabledListIndex(listRef, {\n          startingIndex: prevIndex,\n          disabledIndices\n        });\n        if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {\n          nextIndex = findNonDisabledListIndex(listRef, {\n            startingIndex: prevIndex - prevIndex % cols - 1,\n            disabledIndices\n          });\n        }\n      } else if (loop) {\n        nextIndex = findNonDisabledListIndex(listRef, {\n          startingIndex: prevIndex - prevIndex % cols - 1,\n          disabledIndices\n        });\n      }\n      if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n        nextIndex = prevIndex;\n      }\n    }\n    if (event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT)) {\n      stop && stopEvent(event);\n      if (prevIndex % cols !== 0) {\n        nextIndex = findNonDisabledListIndex(listRef, {\n          startingIndex: prevIndex,\n          decrement: true,\n          disabledIndices\n        });\n        if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {\n          nextIndex = findNonDisabledListIndex(listRef, {\n            startingIndex: prevIndex + (cols - prevIndex % cols),\n            decrement: true,\n            disabledIndices\n          });\n        }\n      } else if (loop) {\n        nextIndex = findNonDisabledListIndex(listRef, {\n          startingIndex: prevIndex + (cols - prevIndex % cols),\n          decrement: true,\n          disabledIndices\n        });\n      }\n      if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n        nextIndex = prevIndex;\n      }\n    }\n    const lastRow = floor(maxIndex / cols) === prevRow;\n    if (isIndexOutOfListBounds(listRef, nextIndex)) {\n      if (loop && lastRow) {\n        nextIndex = event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT) ? maxIndex : findNonDisabledListIndex(listRef, {\n          startingIndex: prevIndex - prevIndex % cols - 1,\n          disabledIndices\n        });\n      } else {\n        nextIndex = prevIndex;\n      }\n    }\n  }\n  return nextIndex;\n}\n\n/** For each cell index, gets the item index that occupies that cell */\nfunction createGridCellMap(sizes, cols, dense) {\n  const cellMap = [];\n  let startIndex = 0;\n  sizes.forEach((_ref2, index) => {\n    let {\n      width,\n      height\n    } = _ref2;\n    if (width > cols) {\n      if (process.env.NODE_ENV !== \"production\") {\n        throw new Error(\"[Floating UI]: Invalid grid - item width at index \" + index + \" is greater than grid columns\");\n      }\n    }\n    let itemPlaced = false;\n    if (dense) {\n      startIndex = 0;\n    }\n    while (!itemPlaced) {\n      const targetCells = [];\n      for (let i = 0; i < width; i++) {\n        for (let j = 0; j < height; j++) {\n          targetCells.push(startIndex + i + j * cols);\n        }\n      }\n      if (startIndex % cols + width <= cols && targetCells.every(cell => cellMap[cell] == null)) {\n        targetCells.forEach(cell => {\n          cellMap[cell] = index;\n        });\n        itemPlaced = true;\n      } else {\n        startIndex++;\n      }\n    }\n  });\n\n  // convert into a non-sparse array\n  return [...cellMap];\n}\n\n/** Gets cell index of an item's corner or -1 when index is -1. */\nfunction getGridCellIndexOfCorner(index, sizes, cellMap, cols, corner) {\n  if (index === -1) return -1;\n  const firstCellIndex = cellMap.indexOf(index);\n  const sizeItem = sizes[index];\n  switch (corner) {\n    case 'tl':\n      return firstCellIndex;\n    case 'tr':\n      if (!sizeItem) {\n        return firstCellIndex;\n      }\n      return firstCellIndex + sizeItem.width - 1;\n    case 'bl':\n      if (!sizeItem) {\n        return firstCellIndex;\n      }\n      return firstCellIndex + (sizeItem.height - 1) * cols;\n    case 'br':\n      return cellMap.lastIndexOf(index);\n  }\n}\n\n/** Gets all cell indices that correspond to the specified indices */\nfunction getGridCellIndices(indices, cellMap) {\n  return cellMap.flatMap((index, cellIndex) => indices.includes(index) ? [cellIndex] : []);\n}\nfunction isListIndexDisabled(listRef, index, disabledIndices) {\n  if (typeof disabledIndices === 'function') {\n    return disabledIndices(index);\n  } else if (disabledIndices) {\n    return disabledIndices.includes(index);\n  }\n  const element = listRef.current[index];\n  return element == null || element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true';\n}\n\nconst getTabbableOptions = () => ({\n  getShadowRoot: true,\n  displayCheck:\n  // JSDOM does not support the `tabbable` library. To solve this we can\n  // check if `ResizeObserver` is a real function (not polyfilled), which\n  // determines if the current environment is JSDOM-like.\n  typeof ResizeObserver === 'function' && ResizeObserver.toString().includes('[native code]') ? 'full' : 'none'\n});\nfunction getTabbableIn(container, dir) {\n  const list = tabbable(container, getTabbableOptions());\n  const len = list.length;\n  if (len === 0) return;\n  const active = activeElement(getDocument(container));\n  const index = list.indexOf(active);\n  const nextIndex = index === -1 ? dir === 1 ? 0 : len - 1 : index + dir;\n  return list[nextIndex];\n}\nfunction getNextTabbable(referenceElement) {\n  return getTabbableIn(getDocument(referenceElement).body, 1) || referenceElement;\n}\nfunction getPreviousTabbable(referenceElement) {\n  return getTabbableIn(getDocument(referenceElement).body, -1) || referenceElement;\n}\nfunction isOutsideEvent(event, container) {\n  const containerElement = container || event.currentTarget;\n  const relatedTarget = event.relatedTarget;\n  return !relatedTarget || !contains(containerElement, relatedTarget);\n}\nfunction disableFocusInside(container) {\n  const tabbableElements = tabbable(container, getTabbableOptions());\n  tabbableElements.forEach(element => {\n    element.dataset.tabindex = element.getAttribute('tabindex') || '';\n    element.setAttribute('tabindex', '-1');\n  });\n}\nfunction enableFocusInside(container) {\n  const elements = container.querySelectorAll('[data-tabindex]');\n  elements.forEach(element => {\n    const tabindex = element.dataset.tabindex;\n    delete element.dataset.tabindex;\n    if (tabindex) {\n      element.setAttribute('tabindex', tabindex);\n    } else {\n      element.removeAttribute('tabindex');\n    }\n  });\n}\n\nexport { activeElement, contains, createGridCellMap, disableFocusInside, enableFocusInside, findNonDisabledListIndex, getDeepestNode, getDocument, getFloatingFocusElement, getGridCellIndexOfCorner, getGridCellIndices, getGridNavigatedIndex, getMaxListIndex, getMinListIndex, getNextTabbable, getNodeAncestors, getNodeChildren, getPlatform, getPreviousTabbable, getTabbableOptions, getTarget, getUserAgent, isAndroid, isDifferentGridRow, isEventTargetWithin, isIndexOutOfListBounds, isJSDOM, isListIndexDisabled, isMac, isMouseLikePointerType, isOutsideEvent, isReactEvent, isRootElement, isSafari, isTypeableCombobox, isTypeableElement, isVirtualClick, isVirtualPointerEvent, matchesFocusVisible, stopEvent, useEffectEvent, useLatestRef, index as useModernLayoutEffect };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n  let {\n    reference,\n    floating\n  } = _ref;\n  const sideAxis = getSideAxis(placement);\n  const alignmentAxis = getAlignmentAxis(placement);\n  const alignLength = getAxisLength(alignmentAxis);\n  const side = getSide(placement);\n  const isVertical = sideAxis === 'y';\n  const commonX = reference.x + reference.width / 2 - floating.width / 2;\n  const commonY = reference.y + reference.height / 2 - floating.height / 2;\n  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n  let coords;\n  switch (side) {\n    case 'top':\n      coords = {\n        x: commonX,\n        y: reference.y - floating.height\n      };\n      break;\n    case 'bottom':\n      coords = {\n        x: commonX,\n        y: reference.y + reference.height\n      };\n      break;\n    case 'right':\n      coords = {\n        x: reference.x + reference.width,\n        y: commonY\n      };\n      break;\n    case 'left':\n      coords = {\n        x: reference.x - floating.width,\n        y: commonY\n      };\n      break;\n    default:\n      coords = {\n        x: reference.x,\n        y: reference.y\n      };\n  }\n  switch (getAlignment(placement)) {\n    case 'start':\n      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n      break;\n    case 'end':\n      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n      break;\n  }\n  return coords;\n}\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n  const {\n    placement = 'bottom',\n    strategy = 'absolute',\n    middleware = [],\n    platform\n  } = config;\n  const validMiddleware = middleware.filter(Boolean);\n  const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n  let rects = await platform.getElementRects({\n    reference,\n    floating,\n    strategy\n  });\n  let {\n    x,\n    y\n  } = computeCoordsFromPlacement(rects, placement, rtl);\n  let statefulPlacement = placement;\n  let middlewareData = {};\n  let resetCount = 0;\n  for (let i = 0; i < validMiddleware.length; i++) {\n    const {\n      name,\n      fn\n    } = validMiddleware[i];\n    const {\n      x: nextX,\n      y: nextY,\n      data,\n      reset\n    } = await fn({\n      x,\n      y,\n      initialPlacement: placement,\n      placement: statefulPlacement,\n      strategy,\n      middlewareData,\n      rects,\n      platform,\n      elements: {\n        reference,\n        floating\n      }\n    });\n    x = nextX != null ? nextX : x;\n    y = nextY != null ? nextY : y;\n    middlewareData = {\n      ...middlewareData,\n      [name]: {\n        ...middlewareData[name],\n        ...data\n      }\n    };\n    if (reset && resetCount <= 50) {\n      resetCount++;\n      if (typeof reset === 'object') {\n        if (reset.placement) {\n          statefulPlacement = reset.placement;\n        }\n        if (reset.rects) {\n          rects = reset.rects === true ? await platform.getElementRects({\n            reference,\n            floating,\n            strategy\n          }) : reset.rects;\n        }\n        ({\n          x,\n          y\n        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n      }\n      i = -1;\n    }\n  }\n  return {\n    x,\n    y,\n    placement: statefulPlacement,\n    strategy,\n    middlewareData\n  };\n};\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n  var _await$platform$isEle;\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    x,\n    y,\n    platform,\n    rects,\n    elements,\n    strategy\n  } = state;\n  const {\n    boundary = 'clippingAncestors',\n    rootBoundary = 'viewport',\n    elementContext = 'floating',\n    altBoundary = false,\n    padding = 0\n  } = evaluate(options, state);\n  const paddingObject = getPaddingObject(padding);\n  const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n  const element = elements[altBoundary ? altContext : elementContext];\n  const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n    element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n    boundary,\n    rootBoundary,\n    strategy\n  }));\n  const rect = elementContext === 'floating' ? {\n    x,\n    y,\n    width: rects.floating.width,\n    height: rects.floating.height\n  } : rects.reference;\n  const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n  const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n    x: 1,\n    y: 1\n  } : {\n    x: 1,\n    y: 1\n  };\n  const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n    elements,\n    rect,\n    offsetParent,\n    strategy\n  }) : rect);\n  return {\n    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n  };\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n  name: 'arrow',\n  options,\n  async fn(state) {\n    const {\n      x,\n      y,\n      placement,\n      rects,\n      platform,\n      elements,\n      middlewareData\n    } = state;\n    // Since `element` is required, we don't Partial<> the type.\n    const {\n      element,\n      padding = 0\n    } = evaluate(options, state) || {};\n    if (element == null) {\n      return {};\n    }\n    const paddingObject = getPaddingObject(padding);\n    const coords = {\n      x,\n      y\n    };\n    const axis = getAlignmentAxis(placement);\n    const length = getAxisLength(axis);\n    const arrowDimensions = await platform.getDimensions(element);\n    const isYAxis = axis === 'y';\n    const minProp = isYAxis ? 'top' : 'left';\n    const maxProp = isYAxis ? 'bottom' : 'right';\n    const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n    const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n    const startDiff = coords[axis] - rects.reference[axis];\n    const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n    let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n    // DOM platform can return `window` as the `offsetParent`.\n    if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n      clientSize = elements.floating[clientProp] || rects.floating[length];\n    }\n    const centerToReference = endDiff / 2 - startDiff / 2;\n\n    // If the padding is large enough that it causes the arrow to no longer be\n    // centered, modify the padding so that it is centered.\n    const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n    const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n    const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n    // Make sure the arrow doesn't overflow the floating element if the center\n    // point is outside the floating element's bounds.\n    const min$1 = minPadding;\n    const max = clientSize - arrowDimensions[length] - maxPadding;\n    const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n    const offset = clamp(min$1, center, max);\n\n    // If the reference is small enough that the arrow's padding causes it to\n    // to point to nothing for an aligned placement, adjust the offset of the\n    // floating element itself. To ensure `shift()` continues to take action,\n    // a single reset is performed when this is true.\n    const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n    const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n    return {\n      [axis]: coords[axis] + alignmentOffset,\n      data: {\n        [axis]: offset,\n        centerOffset: center - offset - alignmentOffset,\n        ...(shouldAddOffset && {\n          alignmentOffset\n        })\n      },\n      reset: shouldAddOffset\n    };\n  }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n  const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n  return allowedPlacementsSortedByAlignment.filter(placement => {\n    if (alignment) {\n      return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n    }\n    return true;\n  });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'autoPlacement',\n    options,\n    async fn(state) {\n      var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n      const {\n        rects,\n        middlewareData,\n        placement,\n        platform,\n        elements\n      } = state;\n      const {\n        crossAxis = false,\n        alignment,\n        allowedPlacements = placements,\n        autoAlignment = true,\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n      const overflow = await detectOverflow(state, detectOverflowOptions);\n      const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n      const currentPlacement = placements$1[currentIndex];\n      if (currentPlacement == null) {\n        return {};\n      }\n      const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n      // Make `computeCoords` start from the right place.\n      if (placement !== currentPlacement) {\n        return {\n          reset: {\n            placement: placements$1[0]\n          }\n        };\n      }\n      const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n      const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n        placement: currentPlacement,\n        overflows: currentOverflows\n      }];\n      const nextPlacement = placements$1[currentIndex + 1];\n\n      // There are more placements to check.\n      if (nextPlacement) {\n        return {\n          data: {\n            index: currentIndex + 1,\n            overflows: allOverflows\n          },\n          reset: {\n            placement: nextPlacement\n          }\n        };\n      }\n      const placementsSortedByMostSpace = allOverflows.map(d => {\n        const alignment = getAlignment(d.placement);\n        return [d.placement, alignment && crossAxis ?\n        // Check along the mainAxis and main crossAxis side.\n        d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n        // Check only the mainAxis.\n        d.overflows[0], d.overflows];\n      }).sort((a, b) => a[1] - b[1]);\n      const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n      // Aligned placements should not check their opposite crossAxis\n      // side.\n      getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n      const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n      if (resetPlacement !== placement) {\n        return {\n          data: {\n            index: currentIndex + 1,\n            overflows: allOverflows\n          },\n          reset: {\n            placement: resetPlacement\n          }\n        };\n      }\n      return {};\n    }\n  };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'flip',\n    options,\n    async fn(state) {\n      var _middlewareData$arrow, _middlewareData$flip;\n      const {\n        placement,\n        middlewareData,\n        rects,\n        initialPlacement,\n        platform,\n        elements\n      } = state;\n      const {\n        mainAxis: checkMainAxis = true,\n        crossAxis: checkCrossAxis = true,\n        fallbackPlacements: specifiedFallbackPlacements,\n        fallbackStrategy = 'bestFit',\n        fallbackAxisSideDirection = 'none',\n        flipAlignment = true,\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n\n      // If a reset by the arrow was caused due to an alignment offset being\n      // added, we should skip any logic now since `flip()` has already done its\n      // work.\n      // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n        return {};\n      }\n      const side = getSide(placement);\n      const initialSideAxis = getSideAxis(initialPlacement);\n      const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n      const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n      const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';\n      if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {\n        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n      }\n      const placements = [initialPlacement, ...fallbackPlacements];\n      const overflow = await detectOverflow(state, detectOverflowOptions);\n      const overflows = [];\n      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n      if (checkMainAxis) {\n        overflows.push(overflow[side]);\n      }\n      if (checkCrossAxis) {\n        const sides = getAlignmentSides(placement, rects, rtl);\n        overflows.push(overflow[sides[0]], overflow[sides[1]]);\n      }\n      overflowsData = [...overflowsData, {\n        placement,\n        overflows\n      }];\n\n      // One or more sides is overflowing.\n      if (!overflows.every(side => side <= 0)) {\n        var _middlewareData$flip2, _overflowsData$filter;\n        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n        const nextPlacement = placements[nextIndex];\n        if (nextPlacement) {\n          const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;\n          if (!ignoreCrossAxisOverflow ||\n          // We leave the current main axis only if every placement on that axis\n          // overflows the main axis.\n          overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {\n            // Try next placement and re-run the lifecycle.\n            return {\n              data: {\n                index: nextIndex,\n                overflows: overflowsData\n              },\n              reset: {\n                placement: nextPlacement\n              }\n            };\n          }\n        }\n\n        // First, find the candidates that fit on the mainAxis side of overflow,\n        // then find the placement that fits the best on the main crossAxis side.\n        let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;\n\n        // Otherwise fallback.\n        if (!resetPlacement) {\n          switch (fallbackStrategy) {\n            case 'bestFit':\n              {\n                var _overflowsData$filter2;\n                const placement = (_overflowsData$filter2 = overflowsData.filter(d => {\n                  if (hasFallbackAxisSideDirection) {\n                    const currentSideAxis = getSideAxis(d.placement);\n                    return currentSideAxis === initialSideAxis ||\n                    // Create a bias to the `y` side axis due to horizontal\n                    // reading directions favoring greater width.\n                    currentSideAxis === 'y';\n                  }\n                  return true;\n                }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];\n                if (placement) {\n                  resetPlacement = placement;\n                }\n                break;\n              }\n            case 'initialPlacement':\n              resetPlacement = initialPlacement;\n              break;\n          }\n        }\n        if (placement !== resetPlacement) {\n          return {\n            reset: {\n              placement: resetPlacement\n            }\n          };\n        }\n      }\n      return {};\n    }\n  };\n};\n\nfunction getSideOffsets(overflow, rect) {\n  return {\n    top: overflow.top - rect.height,\n    right: overflow.right - rect.width,\n    bottom: overflow.bottom - rect.height,\n    left: overflow.left - rect.width\n  };\n}\nfunction isAnySideFullyClipped(overflow) {\n  return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'hide',\n    options,\n    async fn(state) {\n      const {\n        rects\n      } = state;\n      const {\n        strategy = 'referenceHidden',\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      switch (strategy) {\n        case 'referenceHidden':\n          {\n            const overflow = await detectOverflow(state, {\n              ...detectOverflowOptions,\n              elementContext: 'reference'\n            });\n            const offsets = getSideOffsets(overflow, rects.reference);\n            return {\n              data: {\n                referenceHiddenOffsets: offsets,\n                referenceHidden: isAnySideFullyClipped(offsets)\n              }\n            };\n          }\n        case 'escaped':\n          {\n            const overflow = await detectOverflow(state, {\n              ...detectOverflowOptions,\n              altBoundary: true\n            });\n            const offsets = getSideOffsets(overflow, rects.floating);\n            return {\n              data: {\n                escapedOffsets: offsets,\n                escaped: isAnySideFullyClipped(offsets)\n              }\n            };\n          }\n        default:\n          {\n            return {};\n          }\n      }\n    }\n  };\n};\n\nfunction getBoundingRect(rects) {\n  const minX = min(...rects.map(rect => rect.left));\n  const minY = min(...rects.map(rect => rect.top));\n  const maxX = max(...rects.map(rect => rect.right));\n  const maxY = max(...rects.map(rect => rect.bottom));\n  return {\n    x: minX,\n    y: minY,\n    width: maxX - minX,\n    height: maxY - minY\n  };\n}\nfunction getRectsByLine(rects) {\n  const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n  const groups = [];\n  let prevRect = null;\n  for (let i = 0; i < sortedRects.length; i++) {\n    const rect = sortedRects[i];\n    if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n      groups.push([rect]);\n    } else {\n      groups[groups.length - 1].push(rect);\n    }\n    prevRect = rect;\n  }\n  return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'inline',\n    options,\n    async fn(state) {\n      const {\n        placement,\n        elements,\n        rects,\n        platform,\n        strategy\n      } = state;\n      // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n      // ClientRect's bounds, despite the event listener being triggered. A\n      // padding of 2 seems to handle this issue.\n      const {\n        padding = 2,\n        x,\n        y\n      } = evaluate(options, state);\n      const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n      const clientRects = getRectsByLine(nativeClientRects);\n      const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n      const paddingObject = getPaddingObject(padding);\n      function getBoundingClientRect() {\n        // There are two rects and they are disjoined.\n        if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n          // Find the first rect in which the point is fully inside.\n          return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n        }\n\n        // There are 2 or more connected rects.\n        if (clientRects.length >= 2) {\n          if (getSideAxis(placement) === 'y') {\n            const firstRect = clientRects[0];\n            const lastRect = clientRects[clientRects.length - 1];\n            const isTop = getSide(placement) === 'top';\n            const top = firstRect.top;\n            const bottom = lastRect.bottom;\n            const left = isTop ? firstRect.left : lastRect.left;\n            const right = isTop ? firstRect.right : lastRect.right;\n            const width = right - left;\n            const height = bottom - top;\n            return {\n              top,\n              bottom,\n              left,\n              right,\n              width,\n              height,\n              x: left,\n              y: top\n            };\n          }\n          const isLeftSide = getSide(placement) === 'left';\n          const maxRight = max(...clientRects.map(rect => rect.right));\n          const minLeft = min(...clientRects.map(rect => rect.left));\n          const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n          const top = measureRects[0].top;\n          const bottom = measureRects[measureRects.length - 1].bottom;\n          const left = minLeft;\n          const right = maxRight;\n          const width = right - left;\n          const height = bottom - top;\n          return {\n            top,\n            bottom,\n            left,\n            right,\n            width,\n            height,\n            x: left,\n            y: top\n          };\n        }\n        return fallback;\n      }\n      const resetRects = await platform.getElementRects({\n        reference: {\n          getBoundingClientRect\n        },\n        floating: elements.floating,\n        strategy\n      });\n      if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n        return {\n          reset: {\n            rects: resetRects\n          }\n        };\n      }\n      return {};\n    }\n  };\n};\n\nconst originSides = /*#__PURE__*/new Set(['left', 'top']);\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\n\nasync function convertValueToCoords(state, options) {\n  const {\n    placement,\n    platform,\n    elements\n  } = state;\n  const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n  const side = getSide(placement);\n  const alignment = getAlignment(placement);\n  const isVertical = getSideAxis(placement) === 'y';\n  const mainAxisMulti = originSides.has(side) ? -1 : 1;\n  const crossAxisMulti = rtl && isVertical ? -1 : 1;\n  const rawValue = evaluate(options, state);\n\n  // eslint-disable-next-line prefer-const\n  let {\n    mainAxis,\n    crossAxis,\n    alignmentAxis\n  } = typeof rawValue === 'number' ? {\n    mainAxis: rawValue,\n    crossAxis: 0,\n    alignmentAxis: null\n  } : {\n    mainAxis: rawValue.mainAxis || 0,\n    crossAxis: rawValue.crossAxis || 0,\n    alignmentAxis: rawValue.alignmentAxis\n  };\n  if (alignment && typeof alignmentAxis === 'number') {\n    crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n  }\n  return isVertical ? {\n    x: crossAxis * crossAxisMulti,\n    y: mainAxis * mainAxisMulti\n  } : {\n    x: mainAxis * mainAxisMulti,\n    y: crossAxis * crossAxisMulti\n  };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n  if (options === void 0) {\n    options = 0;\n  }\n  return {\n    name: 'offset',\n    options,\n    async fn(state) {\n      var _middlewareData$offse, _middlewareData$arrow;\n      const {\n        x,\n        y,\n        placement,\n        middlewareData\n      } = state;\n      const diffCoords = await convertValueToCoords(state, options);\n\n      // If the placement is the same and the arrow caused an alignment offset\n      // then we don't need to change the positioning coordinates.\n      if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n        return {};\n      }\n      return {\n        x: x + diffCoords.x,\n        y: y + diffCoords.y,\n        data: {\n          ...diffCoords,\n          placement\n        }\n      };\n    }\n  };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'shift',\n    options,\n    async fn(state) {\n      const {\n        x,\n        y,\n        placement\n      } = state;\n      const {\n        mainAxis: checkMainAxis = true,\n        crossAxis: checkCrossAxis = false,\n        limiter = {\n          fn: _ref => {\n            let {\n              x,\n              y\n            } = _ref;\n            return {\n              x,\n              y\n            };\n          }\n        },\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      const coords = {\n        x,\n        y\n      };\n      const overflow = await detectOverflow(state, detectOverflowOptions);\n      const crossAxis = getSideAxis(getSide(placement));\n      const mainAxis = getOppositeAxis(crossAxis);\n      let mainAxisCoord = coords[mainAxis];\n      let crossAxisCoord = coords[crossAxis];\n      if (checkMainAxis) {\n        const minSide = mainAxis === 'y' ? 'top' : 'left';\n        const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n        const min = mainAxisCoord + overflow[minSide];\n        const max = mainAxisCoord - overflow[maxSide];\n        mainAxisCoord = clamp(min, mainAxisCoord, max);\n      }\n      if (checkCrossAxis) {\n        const minSide = crossAxis === 'y' ? 'top' : 'left';\n        const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n        const min = crossAxisCoord + overflow[minSide];\n        const max = crossAxisCoord - overflow[maxSide];\n        crossAxisCoord = clamp(min, crossAxisCoord, max);\n      }\n      const limitedCoords = limiter.fn({\n        ...state,\n        [mainAxis]: mainAxisCoord,\n        [crossAxis]: crossAxisCoord\n      });\n      return {\n        ...limitedCoords,\n        data: {\n          x: limitedCoords.x - x,\n          y: limitedCoords.y - y,\n          enabled: {\n            [mainAxis]: checkMainAxis,\n            [crossAxis]: checkCrossAxis\n          }\n        }\n      };\n    }\n  };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    options,\n    fn(state) {\n      const {\n        x,\n        y,\n        placement,\n        rects,\n        middlewareData\n      } = state;\n      const {\n        offset = 0,\n        mainAxis: checkMainAxis = true,\n        crossAxis: checkCrossAxis = true\n      } = evaluate(options, state);\n      const coords = {\n        x,\n        y\n      };\n      const crossAxis = getSideAxis(placement);\n      const mainAxis = getOppositeAxis(crossAxis);\n      let mainAxisCoord = coords[mainAxis];\n      let crossAxisCoord = coords[crossAxis];\n      const rawOffset = evaluate(offset, state);\n      const computedOffset = typeof rawOffset === 'number' ? {\n        mainAxis: rawOffset,\n        crossAxis: 0\n      } : {\n        mainAxis: 0,\n        crossAxis: 0,\n        ...rawOffset\n      };\n      if (checkMainAxis) {\n        const len = mainAxis === 'y' ? 'height' : 'width';\n        const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n        const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n        if (mainAxisCoord < limitMin) {\n          mainAxisCoord = limitMin;\n        } else if (mainAxisCoord > limitMax) {\n          mainAxisCoord = limitMax;\n        }\n      }\n      if (checkCrossAxis) {\n        var _middlewareData$offse, _middlewareData$offse2;\n        const len = mainAxis === 'y' ? 'width' : 'height';\n        const isOriginSide = originSides.has(getSide(placement));\n        const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n        const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n        if (crossAxisCoord < limitMin) {\n          crossAxisCoord = limitMin;\n        } else if (crossAxisCoord > limitMax) {\n          crossAxisCoord = limitMax;\n        }\n      }\n      return {\n        [mainAxis]: mainAxisCoord,\n        [crossAxis]: crossAxisCoord\n      };\n    }\n  };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'size',\n    options,\n    async fn(state) {\n      var _state$middlewareData, _state$middlewareData2;\n      const {\n        placement,\n        rects,\n        platform,\n        elements\n      } = state;\n      const {\n        apply = () => {},\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      const overflow = await detectOverflow(state, detectOverflowOptions);\n      const side = getSide(placement);\n      const alignment = getAlignment(placement);\n      const isYAxis = getSideAxis(placement) === 'y';\n      const {\n        width,\n        height\n      } = rects.floating;\n      let heightSide;\n      let widthSide;\n      if (side === 'top' || side === 'bottom') {\n        heightSide = side;\n        widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n      } else {\n        widthSide = side;\n        heightSide = alignment === 'end' ? 'top' : 'bottom';\n      }\n      const maximumClippingHeight = height - overflow.top - overflow.bottom;\n      const maximumClippingWidth = width - overflow.left - overflow.right;\n      const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);\n      const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);\n      const noShift = !state.middlewareData.shift;\n      let availableHeight = overflowAvailableHeight;\n      let availableWidth = overflowAvailableWidth;\n      if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {\n        availableWidth = maximumClippingWidth;\n      }\n      if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {\n        availableHeight = maximumClippingHeight;\n      }\n      if (noShift && !alignment) {\n        const xMin = max(overflow.left, 0);\n        const xMax = max(overflow.right, 0);\n        const yMin = max(overflow.top, 0);\n        const yMax = max(overflow.bottom, 0);\n        if (isYAxis) {\n          availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n        } else {\n          availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n        }\n      }\n      await apply({\n        ...state,\n        availableWidth,\n        availableHeight\n      });\n      const nextDimensions = await platform.getDimensions(elements.floating);\n      if (width !== nextDimensions.width || height !== nextDimensions.height) {\n        return {\n          reset: {\n            rects: true\n          }\n        };\n      }\n      return {};\n    }\n  };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle as getComputedStyle$1, isHTMLElement, isElement, getWindow, isWebKit, getFrameElement, getNodeScroll, getDocumentElement, isTopLayer, getNodeName, isOverflowElement, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n  const css = getComputedStyle$1(element);\n  // In testing environments, the `width` and `height` properties are empty\n  // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n  let width = parseFloat(css.width) || 0;\n  let height = parseFloat(css.height) || 0;\n  const hasOffset = isHTMLElement(element);\n  const offsetWidth = hasOffset ? element.offsetWidth : width;\n  const offsetHeight = hasOffset ? element.offsetHeight : height;\n  const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n  if (shouldFallback) {\n    width = offsetWidth;\n    height = offsetHeight;\n  }\n  return {\n    width,\n    height,\n    $: shouldFallback\n  };\n}\n\nfunction unwrapElement(element) {\n  return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n  const domElement = unwrapElement(element);\n  if (!isHTMLElement(domElement)) {\n    return createCoords(1);\n  }\n  const rect = domElement.getBoundingClientRect();\n  const {\n    width,\n    height,\n    $\n  } = getCssDimensions(domElement);\n  let x = ($ ? round(rect.width) : rect.width) / width;\n  let y = ($ ? round(rect.height) : rect.height) / height;\n\n  // 0, NaN, or Infinity should always fallback to 1.\n\n  if (!x || !Number.isFinite(x)) {\n    x = 1;\n  }\n  if (!y || !Number.isFinite(y)) {\n    y = 1;\n  }\n  return {\n    x,\n    y\n  };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n  const win = getWindow(element);\n  if (!isWebKit() || !win.visualViewport) {\n    return noOffsets;\n  }\n  return {\n    x: win.visualViewport.offsetLeft,\n    y: win.visualViewport.offsetTop\n  };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n  if (isFixed === void 0) {\n    isFixed = false;\n  }\n  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n    return false;\n  }\n  return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n  if (includeScale === void 0) {\n    includeScale = false;\n  }\n  if (isFixedStrategy === void 0) {\n    isFixedStrategy = false;\n  }\n  const clientRect = element.getBoundingClientRect();\n  const domElement = unwrapElement(element);\n  let scale = createCoords(1);\n  if (includeScale) {\n    if (offsetParent) {\n      if (isElement(offsetParent)) {\n        scale = getScale(offsetParent);\n      }\n    } else {\n      scale = getScale(element);\n    }\n  }\n  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n  let x = (clientRect.left + visualOffsets.x) / scale.x;\n  let y = (clientRect.top + visualOffsets.y) / scale.y;\n  let width = clientRect.width / scale.x;\n  let height = clientRect.height / scale.y;\n  if (domElement) {\n    const win = getWindow(domElement);\n    const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n    let currentWin = win;\n    let currentIFrame = getFrameElement(currentWin);\n    while (currentIFrame && offsetParent && offsetWin !== currentWin) {\n      const iframeScale = getScale(currentIFrame);\n      const iframeRect = currentIFrame.getBoundingClientRect();\n      const css = getComputedStyle$1(currentIFrame);\n      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n      x *= iframeScale.x;\n      y *= iframeScale.y;\n      width *= iframeScale.x;\n      height *= iframeScale.y;\n      x += left;\n      y += top;\n      currentWin = getWindow(currentIFrame);\n      currentIFrame = getFrameElement(currentWin);\n    }\n  }\n  return rectToClientRect({\n    width,\n    height,\n    x,\n    y\n  });\n}\n\n// If <html> has a CSS width greater than the viewport, then this will be\n// incorrect for RTL.\nfunction getWindowScrollBarX(element, rect) {\n  const leftScroll = getNodeScroll(element).scrollLeft;\n  if (!rect) {\n    return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;\n  }\n  return rect.left + leftScroll;\n}\n\nfunction getHTMLOffset(documentElement, scroll) {\n  const htmlRect = documentElement.getBoundingClientRect();\n  const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);\n  const y = htmlRect.top + scroll.scrollTop;\n  return {\n    x,\n    y\n  };\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n  let {\n    elements,\n    rect,\n    offsetParent,\n    strategy\n  } = _ref;\n  const isFixed = strategy === 'fixed';\n  const documentElement = getDocumentElement(offsetParent);\n  const topLayer = elements ? isTopLayer(elements.floating) : false;\n  if (offsetParent === documentElement || topLayer && isFixed) {\n    return rect;\n  }\n  let scroll = {\n    scrollLeft: 0,\n    scrollTop: 0\n  };\n  let scale = createCoords(1);\n  const offsets = createCoords(0);\n  const isOffsetParentAnElement = isHTMLElement(offsetParent);\n  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n    if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n      scroll = getNodeScroll(offsetParent);\n    }\n    if (isHTMLElement(offsetParent)) {\n      const offsetRect = getBoundingClientRect(offsetParent);\n      scale = getScale(offsetParent);\n      offsets.x = offsetRect.x + offsetParent.clientLeft;\n      offsets.y = offsetRect.y + offsetParent.clientTop;\n    }\n  }\n  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n  return {\n    width: rect.width * scale.x,\n    height: rect.height * scale.y,\n    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,\n    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y\n  };\n}\n\nfunction getClientRects(element) {\n  return Array.from(element.getClientRects());\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n  const html = getDocumentElement(element);\n  const scroll = getNodeScroll(element);\n  const body = element.ownerDocument.body;\n  const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n  const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n  let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n  const y = -scroll.scrollTop;\n  if (getComputedStyle$1(body).direction === 'rtl') {\n    x += max(html.clientWidth, body.clientWidth) - width;\n  }\n  return {\n    width,\n    height,\n    x,\n    y\n  };\n}\n\n// Safety check: ensure the scrollbar space is reasonable in case this\n// calculation is affected by unusual styles.\n// Most scrollbars leave 15-18px of space.\nconst SCROLLBAR_MAX = 25;\nfunction getViewportRect(element, strategy) {\n  const win = getWindow(element);\n  const html = getDocumentElement(element);\n  const visualViewport = win.visualViewport;\n  let width = html.clientWidth;\n  let height = html.clientHeight;\n  let x = 0;\n  let y = 0;\n  if (visualViewport) {\n    width = visualViewport.width;\n    height = visualViewport.height;\n    const visualViewportBased = isWebKit();\n    if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n      x = visualViewport.offsetLeft;\n      y = visualViewport.offsetTop;\n    }\n  }\n  const windowScrollbarX = getWindowScrollBarX(html);\n  // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the\n  // visual width of the <html> but this is not considered in the size\n  // of `html.clientWidth`.\n  if (windowScrollbarX <= 0) {\n    const doc = html.ownerDocument;\n    const body = doc.body;\n    const bodyStyles = getComputedStyle(body);\n    const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;\n    const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);\n    if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {\n      width -= clippingStableScrollbarWidth;\n    }\n  } else if (windowScrollbarX <= SCROLLBAR_MAX) {\n    // If the <body> scrollbar is on the left, the width needs to be extended\n    // by the scrollbar amount so there isn't extra space on the right.\n    width += windowScrollbarX;\n  }\n  return {\n    width,\n    height,\n    x,\n    y\n  };\n}\n\nconst absoluteOrFixed = /*#__PURE__*/new Set(['absolute', 'fixed']);\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n  const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n  const top = clientRect.top + element.clientTop;\n  const left = clientRect.left + element.clientLeft;\n  const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n  const width = element.clientWidth * scale.x;\n  const height = element.clientHeight * scale.y;\n  const x = left * scale.x;\n  const y = top * scale.y;\n  return {\n    width,\n    height,\n    x,\n    y\n  };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n  let rect;\n  if (clippingAncestor === 'viewport') {\n    rect = getViewportRect(element, strategy);\n  } else if (clippingAncestor === 'document') {\n    rect = getDocumentRect(getDocumentElement(element));\n  } else if (isElement(clippingAncestor)) {\n    rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n  } else {\n    const visualOffsets = getVisualOffsets(element);\n    rect = {\n      x: clippingAncestor.x - visualOffsets.x,\n      y: clippingAncestor.y - visualOffsets.y,\n      width: clippingAncestor.width,\n      height: clippingAncestor.height\n    };\n  }\n  return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n  const parentNode = getParentNode(element);\n  if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n    return false;\n  }\n  return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n  const cachedResult = cache.get(element);\n  if (cachedResult) {\n    return cachedResult;\n  }\n  let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n  let currentContainingBlockComputedStyle = null;\n  const elementIsFixed = getComputedStyle$1(element).position === 'fixed';\n  let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n  // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n  while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n    const computedStyle = getComputedStyle$1(currentNode);\n    const currentNodeIsContaining = isContainingBlock(currentNode);\n    if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n      currentContainingBlockComputedStyle = null;\n    }\n    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n    if (shouldDropCurrentNode) {\n      // Drop non-containing blocks.\n      result = result.filter(ancestor => ancestor !== currentNode);\n    } else {\n      // Record last containing block for next iteration.\n      currentContainingBlockComputedStyle = computedStyle;\n    }\n    currentNode = getParentNode(currentNode);\n  }\n  cache.set(element, result);\n  return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n  let {\n    element,\n    boundary,\n    rootBoundary,\n    strategy\n  } = _ref;\n  const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);\n  const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n  const firstClippingAncestor = clippingAncestors[0];\n  const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {\n    const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);\n    accRect.top = max(rect.top, accRect.top);\n    accRect.right = min(rect.right, accRect.right);\n    accRect.bottom = min(rect.bottom, accRect.bottom);\n    accRect.left = max(rect.left, accRect.left);\n    return accRect;\n  }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));\n  return {\n    width: clippingRect.right - clippingRect.left,\n    height: clippingRect.bottom - clippingRect.top,\n    x: clippingRect.left,\n    y: clippingRect.top\n  };\n}\n\nfunction getDimensions(element) {\n  const {\n    width,\n    height\n  } = getCssDimensions(element);\n  return {\n    width,\n    height\n  };\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n  const isOffsetParentAnElement = isHTMLElement(offsetParent);\n  const documentElement = getDocumentElement(offsetParent);\n  const isFixed = strategy === 'fixed';\n  const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n  let scroll = {\n    scrollLeft: 0,\n    scrollTop: 0\n  };\n  const offsets = createCoords(0);\n\n  // If the <body> scrollbar appears on the left (e.g. RTL systems). Use\n  // Firefox with layout.scrollbar.side = 3 in about:config to test this.\n  function setLeftRTLScrollbarOffset() {\n    offsets.x = getWindowScrollBarX(documentElement);\n  }\n  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n    if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n      scroll = getNodeScroll(offsetParent);\n    }\n    if (isOffsetParentAnElement) {\n      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n      offsets.x = offsetRect.x + offsetParent.clientLeft;\n      offsets.y = offsetRect.y + offsetParent.clientTop;\n    } else if (documentElement) {\n      setLeftRTLScrollbarOffset();\n    }\n  }\n  if (isFixed && !isOffsetParentAnElement && documentElement) {\n    setLeftRTLScrollbarOffset();\n  }\n  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n  const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;\n  const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;\n  return {\n    x,\n    y,\n    width: rect.width,\n    height: rect.height\n  };\n}\n\nfunction isStaticPositioned(element) {\n  return getComputedStyle$1(element).position === 'static';\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n  if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {\n    return null;\n  }\n  if (polyfill) {\n    return polyfill(element);\n  }\n  let rawOffsetParent = element.offsetParent;\n\n  // Firefox returns the <html> element as the offsetParent if it's non-static,\n  // while Chrome and Safari return the <body> element. The <body> element must\n  // be used to perform the correct calculations even if the <html> element is\n  // non-static.\n  if (getDocumentElement(element) === rawOffsetParent) {\n    rawOffsetParent = rawOffsetParent.ownerDocument.body;\n  }\n  return rawOffsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n  const win = getWindow(element);\n  if (isTopLayer(element)) {\n    return win;\n  }\n  if (!isHTMLElement(element)) {\n    let svgOffsetParent = getParentNode(element);\n    while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {\n      if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {\n        return svgOffsetParent;\n      }\n      svgOffsetParent = getParentNode(svgOffsetParent);\n    }\n    return win;\n  }\n  let offsetParent = getTrueOffsetParent(element, polyfill);\n  while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {\n    offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n  }\n  if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {\n    return win;\n  }\n  return offsetParent || getContainingBlock(element) || win;\n}\n\nconst getElementRects = async function (data) {\n  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n  const getDimensionsFn = this.getDimensions;\n  const floatingDimensions = await getDimensionsFn(data.floating);\n  return {\n    reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),\n    floating: {\n      x: 0,\n      y: 0,\n      width: floatingDimensions.width,\n      height: floatingDimensions.height\n    }\n  };\n};\n\nfunction isRTL(element) {\n  return getComputedStyle$1(element).direction === 'rtl';\n}\n\nconst platform = {\n  convertOffsetParentRelativeRectToViewportRelativeRect,\n  getDocumentElement,\n  getClippingRect,\n  getOffsetParent,\n  getElementRects,\n  getClientRects,\n  getDimensions,\n  getScale,\n  isElement,\n  isRTL\n};\n\nfunction rectsAreEqual(a, b) {\n  return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n  let io = null;\n  let timeoutId;\n  const root = getDocumentElement(element);\n  function cleanup() {\n    var _io;\n    clearTimeout(timeoutId);\n    (_io = io) == null || _io.disconnect();\n    io = null;\n  }\n  function refresh(skip, threshold) {\n    if (skip === void 0) {\n      skip = false;\n    }\n    if (threshold === void 0) {\n      threshold = 1;\n    }\n    cleanup();\n    const elementRectForRootMargin = element.getBoundingClientRect();\n    const {\n      left,\n      top,\n      width,\n      height\n    } = elementRectForRootMargin;\n    if (!skip) {\n      onMove();\n    }\n    if (!width || !height) {\n      return;\n    }\n    const insetTop = floor(top);\n    const insetRight = floor(root.clientWidth - (left + width));\n    const insetBottom = floor(root.clientHeight - (top + height));\n    const insetLeft = floor(left);\n    const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n    const options = {\n      rootMargin,\n      threshold: max(0, min(1, threshold)) || 1\n    };\n    let isFirstUpdate = true;\n    function handleObserve(entries) {\n      const ratio = entries[0].intersectionRatio;\n      if (ratio !== threshold) {\n        if (!isFirstUpdate) {\n          return refresh();\n        }\n        if (!ratio) {\n          // If the reference is clipped, the ratio is 0. Throttle the refresh\n          // to prevent an infinite loop of updates.\n          timeoutId = setTimeout(() => {\n            refresh(false, 1e-7);\n          }, 1000);\n        } else {\n          refresh(false, ratio);\n        }\n      }\n      if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {\n        // It's possible that even though the ratio is reported as 1, the\n        // element is not actually fully within the IntersectionObserver's root\n        // area anymore. This can happen under performance constraints. This may\n        // be a bug in the browser's IntersectionObserver implementation. To\n        // work around this, we compare the element's bounding rect now with\n        // what it was at the time we created the IntersectionObserver. If they\n        // are not equal then the element moved, so we refresh.\n        refresh();\n      }\n      isFirstUpdate = false;\n    }\n\n    // Older browsers don't support a `document` as the root and will throw an\n    // error.\n    try {\n      io = new IntersectionObserver(handleObserve, {\n        ...options,\n        // Handle <iframe>s\n        root: root.ownerDocument\n      });\n    } catch (_e) {\n      io = new IntersectionObserver(handleObserve, options);\n    }\n    io.observe(element);\n  }\n  refresh(true);\n  return cleanup;\n}\n\n/**\n * Automatically updates the position of the floating element when necessary.\n * Should only be called when the floating element is mounted on the DOM or\n * visible on the screen.\n * @returns cleanup function that should be invoked when the floating element is\n * removed from the DOM or hidden from the screen.\n * @see https://floating-ui.com/docs/autoUpdate\n */\nfunction autoUpdate(reference, floating, update, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    ancestorScroll = true,\n    ancestorResize = true,\n    elementResize = typeof ResizeObserver === 'function',\n    layoutShift = typeof IntersectionObserver === 'function',\n    animationFrame = false\n  } = options;\n  const referenceEl = unwrapElement(reference);\n  const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];\n  ancestors.forEach(ancestor => {\n    ancestorScroll && ancestor.addEventListener('scroll', update, {\n      passive: true\n    });\n    ancestorResize && ancestor.addEventListener('resize', update);\n  });\n  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;\n  let reobserveFrame = -1;\n  let resizeObserver = null;\n  if (elementResize) {\n    resizeObserver = new ResizeObserver(_ref => {\n      let [firstEntry] = _ref;\n      if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {\n        // Prevent update loops when using the `size` middleware.\n        // https://github.com/floating-ui/floating-ui/issues/1740\n        resizeObserver.unobserve(floating);\n        cancelAnimationFrame(reobserveFrame);\n        reobserveFrame = requestAnimationFrame(() => {\n          var _resizeObserver;\n          (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);\n        });\n      }\n      update();\n    });\n    if (referenceEl && !animationFrame) {\n      resizeObserver.observe(referenceEl);\n    }\n    resizeObserver.observe(floating);\n  }\n  let frameId;\n  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;\n  if (animationFrame) {\n    frameLoop();\n  }\n  function frameLoop() {\n    const nextRefRect = getBoundingClientRect(reference);\n    if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {\n      update();\n    }\n    prevRefRect = nextRefRect;\n    frameId = requestAnimationFrame(frameLoop);\n  }\n  update();\n  return () => {\n    var _resizeObserver2;\n    ancestors.forEach(ancestor => {\n      ancestorScroll && ancestor.removeEventListener('scroll', update);\n      ancestorResize && ancestor.removeEventListener('resize', update);\n    });\n    cleanupIo == null || cleanupIo();\n    (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();\n    resizeObserver = null;\n    if (animationFrame) {\n      cancelAnimationFrame(frameId);\n    }\n  };\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nconst detectOverflow = detectOverflow$1;\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = offset$1;\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = autoPlacement$1;\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = shift$1;\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = flip$1;\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = size$1;\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = hide$1;\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = arrow$1;\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = inline$1;\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = limitShift$1;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n */\nconst computePosition = (reference, floating, options) => {\n  // This caches the expensive `getClippingElementAncestors` function so that\n  // multiple lifecycle resets re-use the same result. It only lives for a\n  // single call. If other functions become expensive, we can add them as well.\n  const cache = new Map();\n  const mergedOptions = {\n    platform,\n    ...options\n  };\n  const platformWithCache = {\n    ...mergedOptions.platform,\n    _c: cache\n  };\n  return computePosition$1(reference, floating, {\n    ...mergedOptions,\n    platform: platformWithCache\n  });\n};\n\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, platform, shift, size };\n","import { computePosition, arrow as arrow$2, autoPlacement as autoPlacement$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1 } from '@floating-ui/dom';\nexport { autoUpdate, computePosition, detectOverflow, getOverflowAncestors, platform } from '@floating-ui/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport * as ReactDOM from 'react-dom';\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// Fork of `fast-deep-equal` that only does the comparisons we need and compares\n// functions\nfunction deepEqual(a, b) {\n  if (a === b) {\n    return true;\n  }\n  if (typeof a !== typeof b) {\n    return false;\n  }\n  if (typeof a === 'function' && a.toString() === b.toString()) {\n    return true;\n  }\n  let length;\n  let i;\n  let keys;\n  if (a && b && typeof a === 'object') {\n    if (Array.isArray(a)) {\n      length = a.length;\n      if (length !== b.length) return false;\n      for (i = length; i-- !== 0;) {\n        if (!deepEqual(a[i], b[i])) {\n          return false;\n        }\n      }\n      return true;\n    }\n    keys = Object.keys(a);\n    length = keys.length;\n    if (length !== Object.keys(b).length) {\n      return false;\n    }\n    for (i = length; i-- !== 0;) {\n      if (!{}.hasOwnProperty.call(b, keys[i])) {\n        return false;\n      }\n    }\n    for (i = length; i-- !== 0;) {\n      const key = keys[i];\n      if (key === '_owner' && a.$$typeof) {\n        continue;\n      }\n      if (!deepEqual(a[key], b[key])) {\n        return false;\n      }\n    }\n    return true;\n  }\n  return a !== a && b !== b;\n}\n\nfunction getDPR(element) {\n  if (typeof window === 'undefined') {\n    return 1;\n  }\n  const win = element.ownerDocument.defaultView || window;\n  return win.devicePixelRatio || 1;\n}\n\nfunction roundByDPR(element, value) {\n  const dpr = getDPR(element);\n  return Math.round(value * dpr) / dpr;\n}\n\nfunction useLatestRef(value) {\n  const ref = React.useRef(value);\n  index(() => {\n    ref.current = value;\n  });\n  return ref;\n}\n\n/**\n * Provides data to position a floating element.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    placement = 'bottom',\n    strategy = 'absolute',\n    middleware = [],\n    platform,\n    elements: {\n      reference: externalReference,\n      floating: externalFloating\n    } = {},\n    transform = true,\n    whileElementsMounted,\n    open\n  } = options;\n  const [data, setData] = React.useState({\n    x: 0,\n    y: 0,\n    strategy,\n    placement,\n    middlewareData: {},\n    isPositioned: false\n  });\n  const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);\n  if (!deepEqual(latestMiddleware, middleware)) {\n    setLatestMiddleware(middleware);\n  }\n  const [_reference, _setReference] = React.useState(null);\n  const [_floating, _setFloating] = React.useState(null);\n  const setReference = React.useCallback(node => {\n    if (node !== referenceRef.current) {\n      referenceRef.current = node;\n      _setReference(node);\n    }\n  }, []);\n  const setFloating = React.useCallback(node => {\n    if (node !== floatingRef.current) {\n      floatingRef.current = node;\n      _setFloating(node);\n    }\n  }, []);\n  const referenceEl = externalReference || _reference;\n  const floatingEl = externalFloating || _floating;\n  const referenceRef = React.useRef(null);\n  const floatingRef = React.useRef(null);\n  const dataRef = React.useRef(data);\n  const hasWhileElementsMounted = whileElementsMounted != null;\n  const whileElementsMountedRef = useLatestRef(whileElementsMounted);\n  const platformRef = useLatestRef(platform);\n  const openRef = useLatestRef(open);\n  const update = React.useCallback(() => {\n    if (!referenceRef.current || !floatingRef.current) {\n      return;\n    }\n    const config = {\n      placement,\n      strategy,\n      middleware: latestMiddleware\n    };\n    if (platformRef.current) {\n      config.platform = platformRef.current;\n    }\n    computePosition(referenceRef.current, floatingRef.current, config).then(data => {\n      const fullData = {\n        ...data,\n        // The floating element's position may be recomputed while it's closed\n        // but still mounted (such as when transitioning out). To ensure\n        // `isPositioned` will be `false` initially on the next open, avoid\n        // setting it to `true` when `open === false` (must be specified).\n        isPositioned: openRef.current !== false\n      };\n      if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {\n        dataRef.current = fullData;\n        ReactDOM.flushSync(() => {\n          setData(fullData);\n        });\n      }\n    });\n  }, [latestMiddleware, placement, strategy, platformRef, openRef]);\n  index(() => {\n    if (open === false && dataRef.current.isPositioned) {\n      dataRef.current.isPositioned = false;\n      setData(data => ({\n        ...data,\n        isPositioned: false\n      }));\n    }\n  }, [open]);\n  const isMountedRef = React.useRef(false);\n  index(() => {\n    isMountedRef.current = true;\n    return () => {\n      isMountedRef.current = false;\n    };\n  }, []);\n  index(() => {\n    if (referenceEl) referenceRef.current = referenceEl;\n    if (floatingEl) floatingRef.current = floatingEl;\n    if (referenceEl && floatingEl) {\n      if (whileElementsMountedRef.current) {\n        return whileElementsMountedRef.current(referenceEl, floatingEl, update);\n      }\n      update();\n    }\n  }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);\n  const refs = React.useMemo(() => ({\n    reference: referenceRef,\n    floating: floatingRef,\n    setReference,\n    setFloating\n  }), [setReference, setFloating]);\n  const elements = React.useMemo(() => ({\n    reference: referenceEl,\n    floating: floatingEl\n  }), [referenceEl, floatingEl]);\n  const floatingStyles = React.useMemo(() => {\n    const initialStyles = {\n      position: strategy,\n      left: 0,\n      top: 0\n    };\n    if (!elements.floating) {\n      return initialStyles;\n    }\n    const x = roundByDPR(elements.floating, data.x);\n    const y = roundByDPR(elements.floating, data.y);\n    if (transform) {\n      return {\n        ...initialStyles,\n        transform: \"translate(\" + x + \"px, \" + y + \"px)\",\n        ...(getDPR(elements.floating) >= 1.5 && {\n          willChange: 'transform'\n        })\n      };\n    }\n    return {\n      position: strategy,\n      left: x,\n      top: y\n    };\n  }, [strategy, transform, elements.floating, data.x, data.y]);\n  return React.useMemo(() => ({\n    ...data,\n    update,\n    refs,\n    elements,\n    floatingStyles\n  }), [data, update, refs, elements, floatingStyles]);\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow$1 = options => {\n  function isRef(value) {\n    return {}.hasOwnProperty.call(value, 'current');\n  }\n  return {\n    name: 'arrow',\n    options,\n    fn(state) {\n      const {\n        element,\n        padding\n      } = typeof options === 'function' ? options(state) : options;\n      if (element && isRef(element)) {\n        if (element.current != null) {\n          return arrow$2({\n            element: element.current,\n            padding\n          }).fn(state);\n        }\n        return {};\n      }\n      if (element) {\n        return arrow$2({\n          element,\n          padding\n        }).fn(state);\n      }\n      return {};\n    }\n  };\n};\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = (options, deps) => ({\n  ...offset$1(options),\n  options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = (options, deps) => ({\n  ...shift$1(options),\n  options: [options, deps]\n});\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = (options, deps) => ({\n  ...limitShift$1(options),\n  options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = (options, deps) => ({\n  ...flip$1(options),\n  options: [options, deps]\n});\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = (options, deps) => ({\n  ...size$1(options),\n  options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = (options, deps) => ({\n  ...autoPlacement$1(options),\n  options: [options, deps]\n});\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = (options, deps) => ({\n  ...hide$1(options),\n  options: [options, deps]\n});\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = (options, deps) => ({\n  ...inline$1(options),\n  options: [options, deps]\n});\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = (options, deps) => ({\n  ...arrow$1(options),\n  options: [options, deps]\n});\n\nexport { arrow, autoPlacement, flip, hide, inline, limitShift, offset, shift, size, useFloating };\n","import * as React from 'react';\nimport { useModernLayoutEffect, useEffectEvent, getMinListIndex, getMaxListIndex, createGridCellMap, isListIndexDisabled, getGridNavigatedIndex, getGridCellIndexOfCorner, getGridCellIndices, findNonDisabledListIndex, isIndexOutOfListBounds, useLatestRef, getDocument as getDocument$1, isMouseLikePointerType, contains as contains$1, isSafari, enableFocusInside, isOutsideEvent, getPreviousTabbable, getNextTabbable, disableFocusInside, isTypeableCombobox, getFloatingFocusElement, getTabbableOptions, getNodeAncestors, activeElement, getNodeChildren as getNodeChildren$1, stopEvent, getTarget as getTarget$1, isVirtualClick, isVirtualPointerEvent, getPlatform, isTypeableElement, isReactEvent, isRootElement, isEventTargetWithin, matchesFocusVisible, isMac, getDeepestNode, getUserAgent } from '@floating-ui/react/utils';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { getComputedStyle, isElement, isShadowRoot, getNodeName, isNode, isHTMLElement, getWindow, isLastTraversableNode, getParentNode, isWebKit } from '@floating-ui/utils/dom';\nimport { tabbable, isTabbable, focusable } from 'tabbable';\nimport * as ReactDOM from 'react-dom';\nimport { getOverflowAncestors, useFloating as useFloating$1, offset, detectOverflow } from '@floating-ui/react-dom';\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, getOverflowAncestors, hide, inline, limitShift, offset, platform, shift, size } from '@floating-ui/react-dom';\nimport { evaluate, max, round, min } from '@floating-ui/utils';\n\n/**\n * Merges an array of refs into a single memoized callback ref or `null`.\n * @see https://floating-ui.com/docs/react-utils#usemergerefs\n */\nfunction useMergeRefs(refs) {\n  const cleanupRef = React.useRef(undefined);\n  const refEffect = React.useCallback(instance => {\n    const cleanups = refs.map(ref => {\n      if (ref == null) {\n        return;\n      }\n      if (typeof ref === 'function') {\n        const refCallback = ref;\n        const refCleanup = refCallback(instance);\n        return typeof refCleanup === 'function' ? refCleanup : () => {\n          refCallback(null);\n        };\n      }\n      ref.current = instance;\n      return () => {\n        ref.current = null;\n      };\n    });\n    return () => {\n      cleanups.forEach(refCleanup => refCleanup == null ? void 0 : refCleanup());\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, refs);\n  return React.useMemo(() => {\n    if (refs.every(ref => ref == null)) {\n      return null;\n    }\n    return value => {\n      if (cleanupRef.current) {\n        cleanupRef.current();\n        cleanupRef.current = undefined;\n      }\n      if (value != null) {\n        cleanupRef.current = refEffect(value);\n      }\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, refs);\n}\n\nfunction sortByDocumentPosition(a, b) {\n  const position = a.compareDocumentPosition(b);\n  if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {\n    return -1;\n  }\n  if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {\n    return 1;\n  }\n  return 0;\n}\nconst FloatingListContext = /*#__PURE__*/React.createContext({\n  register: () => {},\n  unregister: () => {},\n  map: /*#__PURE__*/new Map(),\n  elementsRef: {\n    current: []\n  }\n});\n/**\n * Provides context for a list of items within the floating element.\n * @see https://floating-ui.com/docs/FloatingList\n */\nfunction FloatingList(props) {\n  const {\n    children,\n    elementsRef,\n    labelsRef\n  } = props;\n  const [nodes, setNodes] = React.useState(() => new Set());\n  const register = React.useCallback(node => {\n    setNodes(prevSet => new Set(prevSet).add(node));\n  }, []);\n  const unregister = React.useCallback(node => {\n    setNodes(prevSet => {\n      const set = new Set(prevSet);\n      set.delete(node);\n      return set;\n    });\n  }, []);\n  const map = React.useMemo(() => {\n    const newMap = new Map();\n    const sortedNodes = Array.from(nodes.keys()).sort(sortByDocumentPosition);\n    sortedNodes.forEach((node, index) => {\n      newMap.set(node, index);\n    });\n    return newMap;\n  }, [nodes]);\n  return /*#__PURE__*/jsx(FloatingListContext.Provider, {\n    value: React.useMemo(() => ({\n      register,\n      unregister,\n      map,\n      elementsRef,\n      labelsRef\n    }), [register, unregister, map, elementsRef, labelsRef]),\n    children: children\n  });\n}\n/**\n * Used to register a list item and its index (DOM position) in the\n * `FloatingList`.\n * @see https://floating-ui.com/docs/FloatingList#uselistitem\n */\nfunction useListItem(props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    label\n  } = props;\n  const {\n    register,\n    unregister,\n    map,\n    elementsRef,\n    labelsRef\n  } = React.useContext(FloatingListContext);\n  const [index, setIndex] = React.useState(null);\n  const componentRef = React.useRef(null);\n  const ref = React.useCallback(node => {\n    componentRef.current = node;\n    if (index !== null) {\n      elementsRef.current[index] = node;\n      if (labelsRef) {\n        var _node$textContent;\n        const isLabelDefined = label !== undefined;\n        labelsRef.current[index] = isLabelDefined ? label : (_node$textContent = node == null ? void 0 : node.textContent) != null ? _node$textContent : null;\n      }\n    }\n  }, [index, elementsRef, labelsRef, label]);\n  useModernLayoutEffect(() => {\n    const node = componentRef.current;\n    if (node) {\n      register(node);\n      return () => {\n        unregister(node);\n      };\n    }\n  }, [register, unregister]);\n  useModernLayoutEffect(() => {\n    const index = componentRef.current ? map.get(componentRef.current) : null;\n    if (index != null) {\n      setIndex(index);\n    }\n  }, [map]);\n  return React.useMemo(() => ({\n    ref,\n    index: index == null ? -1 : index\n  }), [index, ref]);\n}\n\nconst FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';\nconst ACTIVE_KEY = 'active';\nconst SELECTED_KEY = 'selected';\nconst ARROW_LEFT = 'ArrowLeft';\nconst ARROW_RIGHT = 'ArrowRight';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nfunction renderJsx(render, computedProps) {\n  if (typeof render === 'function') {\n    return render(computedProps);\n  }\n  if (render) {\n    return /*#__PURE__*/React.cloneElement(render, computedProps);\n  }\n  return /*#__PURE__*/jsx(\"div\", {\n    ...computedProps\n  });\n}\nconst CompositeContext = /*#__PURE__*/React.createContext({\n  activeIndex: 0,\n  onNavigate: () => {}\n});\nconst horizontalKeys = [ARROW_LEFT, ARROW_RIGHT];\nconst verticalKeys = [ARROW_UP, ARROW_DOWN];\nconst allKeys = [...horizontalKeys, ...verticalKeys];\n\n/**\n * Creates a single tab stop whose items are navigated by arrow keys, which\n * provides list navigation outside of floating element contexts.\n *\n * This is useful to enable navigation of a list of items that aren’t part of a\n * floating element. A menubar is an example of a composite, with each reference\n * element being an item.\n * @see https://floating-ui.com/docs/Composite\n */\nconst Composite = /*#__PURE__*/React.forwardRef(function Composite(props, forwardedRef) {\n  const {\n    render,\n    orientation = 'both',\n    loop = true,\n    rtl = false,\n    cols = 1,\n    disabledIndices,\n    activeIndex: externalActiveIndex,\n    onNavigate: externalSetActiveIndex,\n    itemSizes,\n    dense = false,\n    ...domProps\n  } = props;\n  const [internalActiveIndex, internalSetActiveIndex] = React.useState(0);\n  const activeIndex = externalActiveIndex != null ? externalActiveIndex : internalActiveIndex;\n  const onNavigate = useEffectEvent(externalSetActiveIndex != null ? externalSetActiveIndex : internalSetActiveIndex);\n  const elementsRef = React.useRef([]);\n  const renderElementProps = render && typeof render !== 'function' ? render.props : {};\n  const contextValue = React.useMemo(() => ({\n    activeIndex,\n    onNavigate\n  }), [activeIndex, onNavigate]);\n  const isGrid = cols > 1;\n  function handleKeyDown(event) {\n    if (!allKeys.includes(event.key)) return;\n    let nextIndex = activeIndex;\n    const minIndex = getMinListIndex(elementsRef, disabledIndices);\n    const maxIndex = getMaxListIndex(elementsRef, disabledIndices);\n    const horizontalEndKey = rtl ? ARROW_LEFT : ARROW_RIGHT;\n    const horizontalStartKey = rtl ? ARROW_RIGHT : ARROW_LEFT;\n    if (isGrid) {\n      const sizes = itemSizes || Array.from({\n        length: elementsRef.current.length\n      }, () => ({\n        width: 1,\n        height: 1\n      }));\n      // To calculate movements on the grid, we use hypothetical cell indices\n      // as if every item was 1x1, then convert back to real indices.\n      const cellMap = createGridCellMap(sizes, cols, dense);\n      const minGridIndex = cellMap.findIndex(index => index != null && !isListIndexDisabled(elementsRef, index, disabledIndices));\n      // last enabled index\n      const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isListIndexDisabled(elementsRef, index, disabledIndices) ? cellIndex : foundIndex, -1);\n      const maybeNextIndex = cellMap[getGridNavigatedIndex({\n        current: cellMap.map(itemIndex => itemIndex ? elementsRef.current[itemIndex] : null)\n      }, {\n        event,\n        orientation,\n        loop,\n        rtl,\n        cols,\n        // treat undefined (empty grid spaces) as disabled indices so we\n        // don't end up in them\n        disabledIndices: getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || elementsRef.current.map((_, index) => isListIndexDisabled(elementsRef, index, disabledIndices) ? index : undefined)), undefined], cellMap),\n        minIndex: minGridIndex,\n        maxIndex: maxGridIndex,\n        prevIndex: getGridCellIndexOfCorner(activeIndex > maxIndex ? minIndex : activeIndex, sizes, cellMap, cols,\n        // use a corner matching the edge closest to the direction we're\n        // moving in so we don't end up in the same item. Prefer\n        // top/left over bottom/right.\n        event.key === ARROW_DOWN ? 'bl' : event.key === horizontalEndKey ? 'tr' : 'tl')\n      })];\n      if (maybeNextIndex != null) {\n        nextIndex = maybeNextIndex;\n      }\n    }\n    const toEndKeys = {\n      horizontal: [horizontalEndKey],\n      vertical: [ARROW_DOWN],\n      both: [horizontalEndKey, ARROW_DOWN]\n    }[orientation];\n    const toStartKeys = {\n      horizontal: [horizontalStartKey],\n      vertical: [ARROW_UP],\n      both: [horizontalStartKey, ARROW_UP]\n    }[orientation];\n    const preventedKeys = isGrid ? allKeys : {\n      horizontal: horizontalKeys,\n      vertical: verticalKeys,\n      both: allKeys\n    }[orientation];\n    if (nextIndex === activeIndex && [...toEndKeys, ...toStartKeys].includes(event.key)) {\n      if (loop && nextIndex === maxIndex && toEndKeys.includes(event.key)) {\n        nextIndex = minIndex;\n      } else if (loop && nextIndex === minIndex && toStartKeys.includes(event.key)) {\n        nextIndex = maxIndex;\n      } else {\n        nextIndex = findNonDisabledListIndex(elementsRef, {\n          startingIndex: nextIndex,\n          decrement: toStartKeys.includes(event.key),\n          disabledIndices\n        });\n      }\n    }\n    if (nextIndex !== activeIndex && !isIndexOutOfListBounds(elementsRef, nextIndex)) {\n      var _elementsRef$current$;\n      event.stopPropagation();\n      if (preventedKeys.includes(event.key)) {\n        event.preventDefault();\n      }\n      onNavigate(nextIndex);\n      (_elementsRef$current$ = elementsRef.current[nextIndex]) == null || _elementsRef$current$.focus();\n    }\n  }\n  const computedProps = {\n    ...domProps,\n    ...renderElementProps,\n    ref: forwardedRef,\n    'aria-orientation': orientation === 'both' ? undefined : orientation,\n    onKeyDown(e) {\n      domProps.onKeyDown == null || domProps.onKeyDown(e);\n      renderElementProps.onKeyDown == null || renderElementProps.onKeyDown(e);\n      handleKeyDown(e);\n    }\n  };\n  return /*#__PURE__*/jsx(CompositeContext.Provider, {\n    value: contextValue,\n    children: /*#__PURE__*/jsx(FloatingList, {\n      elementsRef: elementsRef,\n      children: renderJsx(render, computedProps)\n    })\n  });\n});\n/**\n * @see https://floating-ui.com/docs/Composite\n */\nconst CompositeItem = /*#__PURE__*/React.forwardRef(function CompositeItem(props, forwardedRef) {\n  const {\n    render,\n    ...domProps\n  } = props;\n  const renderElementProps = render && typeof render !== 'function' ? render.props : {};\n  const {\n    activeIndex,\n    onNavigate\n  } = React.useContext(CompositeContext);\n  const {\n    ref,\n    index\n  } = useListItem();\n  const mergedRef = useMergeRefs([ref, forwardedRef, renderElementProps.ref]);\n  const isActive = activeIndex === index;\n  const computedProps = {\n    ...domProps,\n    ...renderElementProps,\n    ref: mergedRef,\n    tabIndex: isActive ? 0 : -1,\n    'data-active': isActive ? '' : undefined,\n    onFocus(e) {\n      domProps.onFocus == null || domProps.onFocus(e);\n      renderElementProps.onFocus == null || renderElementProps.onFocus(e);\n      onNavigate(index);\n    }\n  };\n  return renderJsx(render, computedProps);\n});\n\n// https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\nconst SafeReact = {\n  ...React\n};\n\nlet serverHandoffComplete = false;\nlet count = 0;\nconst genId = () => // Ensure the id is unique with multiple independent versions of Floating UI\n// on <React 18\n\"floating-ui-\" + Math.random().toString(36).slice(2, 6) + count++;\nfunction useFloatingId() {\n  const [id, setId] = React.useState(() => serverHandoffComplete ? genId() : undefined);\n  useModernLayoutEffect(() => {\n    if (id == null) {\n      setId(genId());\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n  React.useEffect(() => {\n    serverHandoffComplete = true;\n  }, []);\n  return id;\n}\nconst useReactId = SafeReact.useId;\n\n/**\n * Uses React 18's built-in `useId()` when available, or falls back to a\n * slightly less performant (requiring a double render) implementation for\n * earlier React versions.\n * @see https://floating-ui.com/docs/react-utils#useid\n */\nconst useId = useReactId || useFloatingId;\n\nlet devMessageSet;\nif (process.env.NODE_ENV !== \"production\") {\n  devMessageSet = /*#__PURE__*/new Set();\n}\nfunction warn() {\n  var _devMessageSet;\n  for (var _len = arguments.length, messages = new Array(_len), _key = 0; _key < _len; _key++) {\n    messages[_key] = arguments[_key];\n  }\n  const message = \"Floating UI: \" + messages.join(' ');\n  if (!((_devMessageSet = devMessageSet) != null && _devMessageSet.has(message))) {\n    var _devMessageSet2;\n    (_devMessageSet2 = devMessageSet) == null || _devMessageSet2.add(message);\n    console.warn(message);\n  }\n}\nfunction error() {\n  var _devMessageSet3;\n  for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n    messages[_key2] = arguments[_key2];\n  }\n  const message = \"Floating UI: \" + messages.join(' ');\n  if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {\n    var _devMessageSet4;\n    (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);\n    console.error(message);\n  }\n}\n\n/**\n * Renders a pointing arrow triangle.\n * @see https://floating-ui.com/docs/FloatingArrow\n */\nconst FloatingArrow = /*#__PURE__*/React.forwardRef(function FloatingArrow(props, ref) {\n  const {\n    context: {\n      placement,\n      elements: {\n        floating\n      },\n      middlewareData: {\n        arrow,\n        shift\n      }\n    },\n    width = 14,\n    height = 7,\n    tipRadius = 0,\n    strokeWidth = 0,\n    staticOffset,\n    stroke,\n    d,\n    style: {\n      transform,\n      ...restStyle\n    } = {},\n    ...rest\n  } = props;\n  if (process.env.NODE_ENV !== \"production\") {\n    if (!ref) {\n      warn('The `ref` prop is required for `FloatingArrow`.');\n    }\n  }\n  const clipPathId = useId();\n  const [isRTL, setIsRTL] = React.useState(false);\n\n  // https://github.com/floating-ui/floating-ui/issues/2932\n  useModernLayoutEffect(() => {\n    if (!floating) return;\n    const isRTL = getComputedStyle(floating).direction === 'rtl';\n    if (isRTL) {\n      setIsRTL(true);\n    }\n  }, [floating]);\n  if (!floating) {\n    return null;\n  }\n  const [side, alignment] = placement.split('-');\n  const isVerticalSide = side === 'top' || side === 'bottom';\n  let computedStaticOffset = staticOffset;\n  if (isVerticalSide && shift != null && shift.x || !isVerticalSide && shift != null && shift.y) {\n    computedStaticOffset = null;\n  }\n\n  // Strokes must be double the border width, this ensures the stroke's width\n  // works as you'd expect.\n  const computedStrokeWidth = strokeWidth * 2;\n  const halfStrokeWidth = computedStrokeWidth / 2;\n  const svgX = width / 2 * (tipRadius / -8 + 1);\n  const svgY = height / 2 * tipRadius / 4;\n  const isCustomShape = !!d;\n  const yOffsetProp = computedStaticOffset && alignment === 'end' ? 'bottom' : 'top';\n  let xOffsetProp = computedStaticOffset && alignment === 'end' ? 'right' : 'left';\n  if (computedStaticOffset && isRTL) {\n    xOffsetProp = alignment === 'end' ? 'left' : 'right';\n  }\n  const arrowX = (arrow == null ? void 0 : arrow.x) != null ? computedStaticOffset || arrow.x : '';\n  const arrowY = (arrow == null ? void 0 : arrow.y) != null ? computedStaticOffset || arrow.y : '';\n  const dValue = d || 'M0,0' + (\" H\" + width) + (\" L\" + (width - svgX) + \",\" + (height - svgY)) + (\" Q\" + width / 2 + \",\" + height + \" \" + svgX + \",\" + (height - svgY)) + ' Z';\n  const rotation = {\n    top: isCustomShape ? 'rotate(180deg)' : '',\n    left: isCustomShape ? 'rotate(90deg)' : 'rotate(-90deg)',\n    bottom: isCustomShape ? '' : 'rotate(180deg)',\n    right: isCustomShape ? 'rotate(-90deg)' : 'rotate(90deg)'\n  }[side];\n  return /*#__PURE__*/jsxs(\"svg\", {\n    ...rest,\n    \"aria-hidden\": true,\n    ref: ref,\n    width: isCustomShape ? width : width + computedStrokeWidth,\n    height: width,\n    viewBox: \"0 0 \" + width + \" \" + (height > width ? height : width),\n    style: {\n      position: 'absolute',\n      pointerEvents: 'none',\n      [xOffsetProp]: arrowX,\n      [yOffsetProp]: arrowY,\n      [side]: isVerticalSide || isCustomShape ? '100%' : \"calc(100% - \" + computedStrokeWidth / 2 + \"px)\",\n      transform: [rotation, transform].filter(t => !!t).join(' '),\n      ...restStyle\n    },\n    children: [computedStrokeWidth > 0 && /*#__PURE__*/jsx(\"path\", {\n      clipPath: \"url(#\" + clipPathId + \")\",\n      fill: \"none\",\n      stroke: stroke\n      // Account for the stroke on the fill path rendered below.\n      ,\n      strokeWidth: computedStrokeWidth + (d ? 0 : 1),\n      d: dValue\n    }), /*#__PURE__*/jsx(\"path\", {\n      stroke: computedStrokeWidth && !d ? rest.fill : 'none',\n      d: dValue\n    }), /*#__PURE__*/jsx(\"clipPath\", {\n      id: clipPathId,\n      children: /*#__PURE__*/jsx(\"rect\", {\n        x: -halfStrokeWidth,\n        y: halfStrokeWidth * (isCustomShape ? -1 : 1),\n        width: width + computedStrokeWidth,\n        height: width\n      })\n    })]\n  });\n});\n\nfunction createEventEmitter() {\n  const map = new Map();\n  return {\n    emit(event, data) {\n      var _map$get;\n      (_map$get = map.get(event)) == null || _map$get.forEach(listener => listener(data));\n    },\n    on(event, listener) {\n      if (!map.has(event)) {\n        map.set(event, new Set());\n      }\n      map.get(event).add(listener);\n    },\n    off(event, listener) {\n      var _map$get2;\n      (_map$get2 = map.get(event)) == null || _map$get2.delete(listener);\n    }\n  };\n}\n\nconst FloatingNodeContext = /*#__PURE__*/React.createContext(null);\nconst FloatingTreeContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the parent node id for nested floating elements, if available.\n * Returns `null` for top-level floating elements.\n */\nconst useFloatingParentNodeId = () => {\n  var _React$useContext;\n  return ((_React$useContext = React.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;\n};\n\n/**\n * Returns the nearest floating tree context, if available.\n */\nconst useFloatingTree = () => React.useContext(FloatingTreeContext);\n\n/**\n * Registers a node into the `FloatingTree`, returning its id.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction useFloatingNodeId(customParentId) {\n  const id = useId();\n  const tree = useFloatingTree();\n  const reactParentId = useFloatingParentNodeId();\n  const parentId = customParentId || reactParentId;\n  useModernLayoutEffect(() => {\n    if (!id) return;\n    const node = {\n      id,\n      parentId\n    };\n    tree == null || tree.addNode(node);\n    return () => {\n      tree == null || tree.removeNode(node);\n    };\n  }, [tree, id, parentId]);\n  return id;\n}\n/**\n * Provides parent node context for nested floating elements.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction FloatingNode(props) {\n  const {\n    children,\n    id\n  } = props;\n  const parentId = useFloatingParentNodeId();\n  return /*#__PURE__*/jsx(FloatingNodeContext.Provider, {\n    value: React.useMemo(() => ({\n      id,\n      parentId\n    }), [id, parentId]),\n    children: children\n  });\n}\n/**\n * Provides context for nested floating elements when they are not children of\n * each other on the DOM.\n * This is not necessary in all cases, except when there must be explicit communication between parent and child floating elements. It is necessary for:\n * - The `bubbles` option in the `useDismiss()` Hook\n * - Nested virtual list navigation\n * - Nested floating elements that each open on hover\n * - Custom communication between parent and child floating elements\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction FloatingTree(props) {\n  const {\n    children\n  } = props;\n  const nodesRef = React.useRef([]);\n  const addNode = React.useCallback(node => {\n    nodesRef.current = [...nodesRef.current, node];\n  }, []);\n  const removeNode = React.useCallback(node => {\n    nodesRef.current = nodesRef.current.filter(n => n !== node);\n  }, []);\n  const [events] = React.useState(() => createEventEmitter());\n  return /*#__PURE__*/jsx(FloatingTreeContext.Provider, {\n    value: React.useMemo(() => ({\n      nodesRef,\n      addNode,\n      removeNode,\n      events\n    }), [addNode, removeNode, events]),\n    children: children\n  });\n}\n\nfunction createAttribute(name) {\n  return \"data-floating-ui-\" + name;\n}\n\nfunction clearTimeoutIfSet(timeoutRef) {\n  if (timeoutRef.current !== -1) {\n    clearTimeout(timeoutRef.current);\n    timeoutRef.current = -1;\n  }\n}\n\nconst safePolygonIdentifier = /*#__PURE__*/createAttribute('safe-polygon');\nfunction getDelay(value, prop, pointerType) {\n  if (pointerType && !isMouseLikePointerType(pointerType)) {\n    return 0;\n  }\n  if (typeof value === 'number') {\n    return value;\n  }\n  if (typeof value === 'function') {\n    const result = value();\n    if (typeof result === 'number') {\n      return result;\n    }\n    return result == null ? void 0 : result[prop];\n  }\n  return value == null ? void 0 : value[prop];\n}\nfunction getRestMs(value) {\n  if (typeof value === 'function') {\n    return value();\n  }\n  return value;\n}\n/**\n * Opens the floating element while hovering over the reference element, like\n * CSS `:hover`.\n * @see https://floating-ui.com/docs/useHover\n */\nfunction useHover(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    onOpenChange,\n    dataRef,\n    events,\n    elements\n  } = context;\n  const {\n    enabled = true,\n    delay = 0,\n    handleClose = null,\n    mouseOnly = false,\n    restMs = 0,\n    move = true\n  } = props;\n  const tree = useFloatingTree();\n  const parentId = useFloatingParentNodeId();\n  const handleCloseRef = useLatestRef(handleClose);\n  const delayRef = useLatestRef(delay);\n  const openRef = useLatestRef(open);\n  const restMsRef = useLatestRef(restMs);\n  const pointerTypeRef = React.useRef();\n  const timeoutRef = React.useRef(-1);\n  const handlerRef = React.useRef();\n  const restTimeoutRef = React.useRef(-1);\n  const blockMouseMoveRef = React.useRef(true);\n  const performedPointerEventsMutationRef = React.useRef(false);\n  const unbindMouseMoveRef = React.useRef(() => {});\n  const restTimeoutPendingRef = React.useRef(false);\n  const isHoverOpen = useEffectEvent(() => {\n    var _dataRef$current$open;\n    const type = (_dataRef$current$open = dataRef.current.openEvent) == null ? void 0 : _dataRef$current$open.type;\n    return (type == null ? void 0 : type.includes('mouse')) && type !== 'mousedown';\n  });\n\n  // When closing before opening, clear the delay timeouts to cancel it\n  // from showing.\n  React.useEffect(() => {\n    if (!enabled) return;\n    function onOpenChange(_ref) {\n      let {\n        open\n      } = _ref;\n      if (!open) {\n        clearTimeoutIfSet(timeoutRef);\n        clearTimeoutIfSet(restTimeoutRef);\n        blockMouseMoveRef.current = true;\n        restTimeoutPendingRef.current = false;\n      }\n    }\n    events.on('openchange', onOpenChange);\n    return () => {\n      events.off('openchange', onOpenChange);\n    };\n  }, [enabled, events]);\n  React.useEffect(() => {\n    if (!enabled) return;\n    if (!handleCloseRef.current) return;\n    if (!open) return;\n    function onLeave(event) {\n      if (isHoverOpen()) {\n        onOpenChange(false, event, 'hover');\n      }\n    }\n    const html = getDocument$1(elements.floating).documentElement;\n    html.addEventListener('mouseleave', onLeave);\n    return () => {\n      html.removeEventListener('mouseleave', onLeave);\n    };\n  }, [elements.floating, open, onOpenChange, enabled, handleCloseRef, isHoverOpen]);\n  const closeWithDelay = React.useCallback(function (event, runElseBranch, reason) {\n    if (runElseBranch === void 0) {\n      runElseBranch = true;\n    }\n    if (reason === void 0) {\n      reason = 'hover';\n    }\n    const closeDelay = getDelay(delayRef.current, 'close', pointerTypeRef.current);\n    if (closeDelay && !handlerRef.current) {\n      clearTimeoutIfSet(timeoutRef);\n      timeoutRef.current = window.setTimeout(() => onOpenChange(false, event, reason), closeDelay);\n    } else if (runElseBranch) {\n      clearTimeoutIfSet(timeoutRef);\n      onOpenChange(false, event, reason);\n    }\n  }, [delayRef, onOpenChange]);\n  const cleanupMouseMoveHandler = useEffectEvent(() => {\n    unbindMouseMoveRef.current();\n    handlerRef.current = undefined;\n  });\n  const clearPointerEvents = useEffectEvent(() => {\n    if (performedPointerEventsMutationRef.current) {\n      const body = getDocument$1(elements.floating).body;\n      body.style.pointerEvents = '';\n      body.removeAttribute(safePolygonIdentifier);\n      performedPointerEventsMutationRef.current = false;\n    }\n  });\n  const isClickLikeOpenEvent = useEffectEvent(() => {\n    return dataRef.current.openEvent ? ['click', 'mousedown'].includes(dataRef.current.openEvent.type) : false;\n  });\n\n  // Registering the mouse events on the reference directly to bypass React's\n  // delegation system. If the cursor was on a disabled element and then entered\n  // the reference (no gap), `mouseenter` doesn't fire in the delegation system.\n  React.useEffect(() => {\n    if (!enabled) return;\n    function onReferenceMouseEnter(event) {\n      clearTimeoutIfSet(timeoutRef);\n      blockMouseMoveRef.current = false;\n      if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current) || getRestMs(restMsRef.current) > 0 && !getDelay(delayRef.current, 'open')) {\n        return;\n      }\n      const openDelay = getDelay(delayRef.current, 'open', pointerTypeRef.current);\n      if (openDelay) {\n        timeoutRef.current = window.setTimeout(() => {\n          if (!openRef.current) {\n            onOpenChange(true, event, 'hover');\n          }\n        }, openDelay);\n      } else if (!open) {\n        onOpenChange(true, event, 'hover');\n      }\n    }\n    function onReferenceMouseLeave(event) {\n      if (isClickLikeOpenEvent()) {\n        clearPointerEvents();\n        return;\n      }\n      unbindMouseMoveRef.current();\n      const doc = getDocument$1(elements.floating);\n      clearTimeoutIfSet(restTimeoutRef);\n      restTimeoutPendingRef.current = false;\n      if (handleCloseRef.current && dataRef.current.floatingContext) {\n        // Prevent clearing `onScrollMouseLeave` timeout.\n        if (!open) {\n          clearTimeoutIfSet(timeoutRef);\n        }\n        handlerRef.current = handleCloseRef.current({\n          ...dataRef.current.floatingContext,\n          tree,\n          x: event.clientX,\n          y: event.clientY,\n          onClose() {\n            clearPointerEvents();\n            cleanupMouseMoveHandler();\n            if (!isClickLikeOpenEvent()) {\n              closeWithDelay(event, true, 'safe-polygon');\n            }\n          }\n        });\n        const handler = handlerRef.current;\n        doc.addEventListener('mousemove', handler);\n        unbindMouseMoveRef.current = () => {\n          doc.removeEventListener('mousemove', handler);\n        };\n        return;\n      }\n\n      // Allow interactivity without `safePolygon` on touch devices. With a\n      // pointer, a short close delay is an alternative, so it should work\n      // consistently.\n      const shouldClose = pointerTypeRef.current === 'touch' ? !contains$1(elements.floating, event.relatedTarget) : true;\n      if (shouldClose) {\n        closeWithDelay(event);\n      }\n    }\n\n    // Ensure the floating element closes after scrolling even if the pointer\n    // did not move.\n    // https://github.com/floating-ui/floating-ui/discussions/1692\n    function onScrollMouseLeave(event) {\n      if (isClickLikeOpenEvent()) return;\n      if (!dataRef.current.floatingContext) return;\n      handleCloseRef.current == null || handleCloseRef.current({\n        ...dataRef.current.floatingContext,\n        tree,\n        x: event.clientX,\n        y: event.clientY,\n        onClose() {\n          clearPointerEvents();\n          cleanupMouseMoveHandler();\n          if (!isClickLikeOpenEvent()) {\n            closeWithDelay(event);\n          }\n        }\n      })(event);\n    }\n    function onFloatingMouseEnter() {\n      clearTimeoutIfSet(timeoutRef);\n    }\n    function onFloatingMouseLeave(event) {\n      if (!isClickLikeOpenEvent()) {\n        closeWithDelay(event, false);\n      }\n    }\n    if (isElement(elements.domReference)) {\n      const reference = elements.domReference;\n      const floating = elements.floating;\n      if (open) {\n        reference.addEventListener('mouseleave', onScrollMouseLeave);\n      }\n      if (move) {\n        reference.addEventListener('mousemove', onReferenceMouseEnter, {\n          once: true\n        });\n      }\n      reference.addEventListener('mouseenter', onReferenceMouseEnter);\n      reference.addEventListener('mouseleave', onReferenceMouseLeave);\n      if (floating) {\n        floating.addEventListener('mouseleave', onScrollMouseLeave);\n        floating.addEventListener('mouseenter', onFloatingMouseEnter);\n        floating.addEventListener('mouseleave', onFloatingMouseLeave);\n      }\n      return () => {\n        if (open) {\n          reference.removeEventListener('mouseleave', onScrollMouseLeave);\n        }\n        if (move) {\n          reference.removeEventListener('mousemove', onReferenceMouseEnter);\n        }\n        reference.removeEventListener('mouseenter', onReferenceMouseEnter);\n        reference.removeEventListener('mouseleave', onReferenceMouseLeave);\n        if (floating) {\n          floating.removeEventListener('mouseleave', onScrollMouseLeave);\n          floating.removeEventListener('mouseenter', onFloatingMouseEnter);\n          floating.removeEventListener('mouseleave', onFloatingMouseLeave);\n        }\n      };\n    }\n  }, [elements, enabled, context, mouseOnly, move, closeWithDelay, cleanupMouseMoveHandler, clearPointerEvents, onOpenChange, open, openRef, tree, delayRef, handleCloseRef, dataRef, isClickLikeOpenEvent, restMsRef]);\n\n  // Block pointer-events of every element other than the reference and floating\n  // while the floating element is open and has a `handleClose` handler. Also\n  // handles nested floating elements.\n  // https://github.com/floating-ui/floating-ui/issues/1722\n  useModernLayoutEffect(() => {\n    var _handleCloseRef$curre;\n    if (!enabled) return;\n    if (open && (_handleCloseRef$curre = handleCloseRef.current) != null && (_handleCloseRef$curre = _handleCloseRef$curre.__options) != null && _handleCloseRef$curre.blockPointerEvents && isHoverOpen()) {\n      performedPointerEventsMutationRef.current = true;\n      const floatingEl = elements.floating;\n      if (isElement(elements.domReference) && floatingEl) {\n        var _tree$nodesRef$curren;\n        const body = getDocument$1(elements.floating).body;\n        body.setAttribute(safePolygonIdentifier, '');\n        const ref = elements.domReference;\n        const parentFloating = tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null ? void 0 : _tree$nodesRef$curren.elements.floating;\n        if (parentFloating) {\n          parentFloating.style.pointerEvents = '';\n        }\n        body.style.pointerEvents = 'none';\n        ref.style.pointerEvents = 'auto';\n        floatingEl.style.pointerEvents = 'auto';\n        return () => {\n          body.style.pointerEvents = '';\n          ref.style.pointerEvents = '';\n          floatingEl.style.pointerEvents = '';\n        };\n      }\n    }\n  }, [enabled, open, parentId, elements, tree, handleCloseRef, isHoverOpen]);\n  useModernLayoutEffect(() => {\n    if (!open) {\n      pointerTypeRef.current = undefined;\n      restTimeoutPendingRef.current = false;\n      cleanupMouseMoveHandler();\n      clearPointerEvents();\n    }\n  }, [open, cleanupMouseMoveHandler, clearPointerEvents]);\n  React.useEffect(() => {\n    return () => {\n      cleanupMouseMoveHandler();\n      clearTimeoutIfSet(timeoutRef);\n      clearTimeoutIfSet(restTimeoutRef);\n      clearPointerEvents();\n    };\n  }, [enabled, elements.domReference, cleanupMouseMoveHandler, clearPointerEvents]);\n  const reference = React.useMemo(() => {\n    function setPointerRef(event) {\n      pointerTypeRef.current = event.pointerType;\n    }\n    return {\n      onPointerDown: setPointerRef,\n      onPointerEnter: setPointerRef,\n      onMouseMove(event) {\n        const {\n          nativeEvent\n        } = event;\n        function handleMouseMove() {\n          if (!blockMouseMoveRef.current && !openRef.current) {\n            onOpenChange(true, nativeEvent, 'hover');\n          }\n        }\n        if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current)) {\n          return;\n        }\n        if (open || getRestMs(restMsRef.current) === 0) {\n          return;\n        }\n\n        // Ignore insignificant movements to account for tremors.\n        if (restTimeoutPendingRef.current && event.movementX ** 2 + event.movementY ** 2 < 2) {\n          return;\n        }\n        clearTimeoutIfSet(restTimeoutRef);\n        if (pointerTypeRef.current === 'touch') {\n          handleMouseMove();\n        } else {\n          restTimeoutPendingRef.current = true;\n          restTimeoutRef.current = window.setTimeout(handleMouseMove, getRestMs(restMsRef.current));\n        }\n      }\n    };\n  }, [mouseOnly, onOpenChange, open, openRef, restMsRef]);\n  return React.useMemo(() => enabled ? {\n    reference\n  } : {}, [enabled, reference]);\n}\n\nconst NOOP = () => {};\nconst FloatingDelayGroupContext = /*#__PURE__*/React.createContext({\n  delay: 0,\n  initialDelay: 0,\n  timeoutMs: 0,\n  currentId: null,\n  setCurrentId: NOOP,\n  setState: NOOP,\n  isInstantPhase: false\n});\n\n/**\n * @deprecated\n * Use the return value of `useDelayGroup()` instead.\n */\nconst useDelayGroupContext = () => React.useContext(FloatingDelayGroupContext);\n/**\n * Provides context for a group of floating elements that should share a\n * `delay`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction FloatingDelayGroup(props) {\n  const {\n    children,\n    delay,\n    timeoutMs = 0\n  } = props;\n  const [state, setState] = React.useReducer((prev, next) => ({\n    ...prev,\n    ...next\n  }), {\n    delay,\n    timeoutMs,\n    initialDelay: delay,\n    currentId: null,\n    isInstantPhase: false\n  });\n  const initialCurrentIdRef = React.useRef(null);\n  const setCurrentId = React.useCallback(currentId => {\n    setState({\n      currentId\n    });\n  }, []);\n  useModernLayoutEffect(() => {\n    if (state.currentId) {\n      if (initialCurrentIdRef.current === null) {\n        initialCurrentIdRef.current = state.currentId;\n      } else if (!state.isInstantPhase) {\n        setState({\n          isInstantPhase: true\n        });\n      }\n    } else {\n      if (state.isInstantPhase) {\n        setState({\n          isInstantPhase: false\n        });\n      }\n      initialCurrentIdRef.current = null;\n    }\n  }, [state.currentId, state.isInstantPhase]);\n  return /*#__PURE__*/jsx(FloatingDelayGroupContext.Provider, {\n    value: React.useMemo(() => ({\n      ...state,\n      setState,\n      setCurrentId\n    }), [state, setCurrentId]),\n    children: children\n  });\n}\n/**\n * Enables grouping when called inside a component that's a child of a\n * `FloatingDelayGroup`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction useDelayGroup(context, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    open,\n    onOpenChange,\n    floatingId\n  } = context;\n  const {\n    id: optionId,\n    enabled = true\n  } = options;\n  const id = optionId != null ? optionId : floatingId;\n  const groupContext = useDelayGroupContext();\n  const {\n    currentId,\n    setCurrentId,\n    initialDelay,\n    setState,\n    timeoutMs\n  } = groupContext;\n  useModernLayoutEffect(() => {\n    if (!enabled) return;\n    if (!currentId) return;\n    setState({\n      delay: {\n        open: 1,\n        close: getDelay(initialDelay, 'close')\n      }\n    });\n    if (currentId !== id) {\n      onOpenChange(false);\n    }\n  }, [enabled, id, onOpenChange, setState, currentId, initialDelay]);\n  useModernLayoutEffect(() => {\n    function unset() {\n      onOpenChange(false);\n      setState({\n        delay: initialDelay,\n        currentId: null\n      });\n    }\n    if (!enabled) return;\n    if (!currentId) return;\n    if (!open && currentId === id) {\n      if (timeoutMs) {\n        const timeout = window.setTimeout(unset, timeoutMs);\n        return () => {\n          clearTimeout(timeout);\n        };\n      }\n      unset();\n    }\n  }, [enabled, open, setState, currentId, id, onOpenChange, initialDelay, timeoutMs]);\n  useModernLayoutEffect(() => {\n    if (!enabled) return;\n    if (setCurrentId === NOOP || !open) return;\n    setCurrentId(id);\n  }, [enabled, open, setCurrentId, id]);\n  return groupContext;\n}\n\nconst NextFloatingDelayGroupContext = /*#__PURE__*/React.createContext({\n  hasProvider: false,\n  timeoutMs: 0,\n  delayRef: {\n    current: 0\n  },\n  initialDelayRef: {\n    current: 0\n  },\n  timeoutIdRef: {\n    current: -1\n  },\n  currentIdRef: {\n    current: null\n  },\n  currentContextRef: {\n    current: null\n  }\n});\n/**\n * Experimental next version of `FloatingDelayGroup` to become the default\n * in the future. This component is not yet stable.\n * Provides context for a group of floating elements that should share a\n * `delay`. Unlike `FloatingDelayGroup`, `useNextDelayGroup` with this\n * component does not cause a re-render of unrelated consumers of the\n * context when the delay changes.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction NextFloatingDelayGroup(props) {\n  const {\n    children,\n    delay,\n    timeoutMs = 0\n  } = props;\n  const delayRef = React.useRef(delay);\n  const initialDelayRef = React.useRef(delay);\n  const currentIdRef = React.useRef(null);\n  const currentContextRef = React.useRef(null);\n  const timeoutIdRef = React.useRef(-1);\n  return /*#__PURE__*/jsx(NextFloatingDelayGroupContext.Provider, {\n    value: React.useMemo(() => ({\n      hasProvider: true,\n      delayRef,\n      initialDelayRef,\n      currentIdRef,\n      timeoutMs,\n      currentContextRef,\n      timeoutIdRef\n    }), [timeoutMs]),\n    children: children\n  });\n}\n/**\n * Enables grouping when called inside a component that's a child of a\n * `NextFloatingDelayGroup`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction useNextDelayGroup(context, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    open,\n    onOpenChange,\n    floatingId\n  } = context;\n  const {\n    enabled = true\n  } = options;\n  const groupContext = React.useContext(NextFloatingDelayGroupContext);\n  const {\n    currentIdRef,\n    delayRef,\n    timeoutMs,\n    initialDelayRef,\n    currentContextRef,\n    hasProvider,\n    timeoutIdRef\n  } = groupContext;\n  const [isInstantPhase, setIsInstantPhase] = React.useState(false);\n  useModernLayoutEffect(() => {\n    function unset() {\n      var _currentContextRef$cu;\n      setIsInstantPhase(false);\n      (_currentContextRef$cu = currentContextRef.current) == null || _currentContextRef$cu.setIsInstantPhase(false);\n      currentIdRef.current = null;\n      currentContextRef.current = null;\n      delayRef.current = initialDelayRef.current;\n    }\n    if (!enabled) return;\n    if (!currentIdRef.current) return;\n    if (!open && currentIdRef.current === floatingId) {\n      setIsInstantPhase(false);\n      if (timeoutMs) {\n        timeoutIdRef.current = window.setTimeout(unset, timeoutMs);\n        return () => {\n          clearTimeout(timeoutIdRef.current);\n        };\n      }\n      unset();\n    }\n  }, [enabled, open, floatingId, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeoutIdRef]);\n  useModernLayoutEffect(() => {\n    if (!enabled) return;\n    if (!open) return;\n    const prevContext = currentContextRef.current;\n    const prevId = currentIdRef.current;\n    currentContextRef.current = {\n      onOpenChange,\n      setIsInstantPhase\n    };\n    currentIdRef.current = floatingId;\n    delayRef.current = {\n      open: 0,\n      close: getDelay(initialDelayRef.current, 'close')\n    };\n    if (prevId !== null && prevId !== floatingId) {\n      clearTimeoutIfSet(timeoutIdRef);\n      setIsInstantPhase(true);\n      prevContext == null || prevContext.setIsInstantPhase(true);\n      prevContext == null || prevContext.onOpenChange(false);\n    } else {\n      setIsInstantPhase(false);\n      prevContext == null || prevContext.setIsInstantPhase(false);\n    }\n  }, [enabled, open, floatingId, onOpenChange, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeoutIdRef]);\n  useModernLayoutEffect(() => {\n    return () => {\n      currentContextRef.current = null;\n    };\n  }, [currentContextRef]);\n  return React.useMemo(() => ({\n    hasProvider,\n    delayRef,\n    isInstantPhase\n  }), [hasProvider, delayRef, isInstantPhase]);\n}\n\nlet rafId = 0;\nfunction enqueueFocus(el, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    preventScroll = false,\n    cancelPrevious = true,\n    sync = false\n  } = options;\n  cancelPrevious && cancelAnimationFrame(rafId);\n  const exec = () => el == null ? void 0 : el.focus({\n    preventScroll\n  });\n  if (sync) {\n    exec();\n  } else {\n    rafId = requestAnimationFrame(exec);\n  }\n}\n\nfunction contains(parent, child) {\n  if (!parent || !child) {\n    return false;\n  }\n  const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();\n\n  // First, attempt with faster native method\n  if (parent.contains(child)) {\n    return true;\n  }\n\n  // then fallback to custom implementation with Shadow DOM support\n  if (rootNode && isShadowRoot(rootNode)) {\n    let next = child;\n    while (next) {\n      if (parent === next) {\n        return true;\n      }\n      // @ts-ignore\n      next = next.parentNode || next.host;\n    }\n  }\n\n  // Give up, the result is false\n  return false;\n}\nfunction getTarget(event) {\n  if ('composedPath' in event) {\n    return event.composedPath()[0];\n  }\n\n  // TS thinks `event` is of type never as it assumes all browsers support\n  // `composedPath()`, but browsers without shadow DOM don't.\n  return event.target;\n}\nfunction getDocument(node) {\n  return (node == null ? void 0 : node.ownerDocument) || document;\n}\n\n// Modified to add conditional `aria-hidden` support:\n// https://github.com/theKashey/aria-hidden/blob/9220c8f4a4fd35f63bee5510a9f41a37264382d4/src/index.ts\nconst counters = {\n  inert: /*#__PURE__*/new WeakMap(),\n  'aria-hidden': /*#__PURE__*/new WeakMap(),\n  none: /*#__PURE__*/new WeakMap()\n};\nfunction getCounterMap(control) {\n  if (control === 'inert') return counters.inert;\n  if (control === 'aria-hidden') return counters['aria-hidden'];\n  return counters.none;\n}\nlet uncontrolledElementsSet = /*#__PURE__*/new WeakSet();\nlet markerMap = {};\nlet lockCount$1 = 0;\nconst supportsInert = () => typeof HTMLElement !== 'undefined' && 'inert' in HTMLElement.prototype;\nconst unwrapHost = node => node && (node.host || unwrapHost(node.parentNode));\nconst correctElements = (parent, targets) => targets.map(target => {\n  if (parent.contains(target)) {\n    return target;\n  }\n  const correctedTarget = unwrapHost(target);\n  if (parent.contains(correctedTarget)) {\n    return correctedTarget;\n  }\n  return null;\n}).filter(x => x != null);\nfunction applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert) {\n  const markerName = 'data-floating-ui-inert';\n  const controlAttribute = inert ? 'inert' : ariaHidden ? 'aria-hidden' : null;\n  const avoidElements = correctElements(body, uncorrectedAvoidElements);\n  const elementsToKeep = new Set();\n  const elementsToStop = new Set(avoidElements);\n  const hiddenElements = [];\n  if (!markerMap[markerName]) {\n    markerMap[markerName] = new WeakMap();\n  }\n  const markerCounter = markerMap[markerName];\n  avoidElements.forEach(keep);\n  deep(body);\n  elementsToKeep.clear();\n  function keep(el) {\n    if (!el || elementsToKeep.has(el)) {\n      return;\n    }\n    elementsToKeep.add(el);\n    el.parentNode && keep(el.parentNode);\n  }\n  function deep(parent) {\n    if (!parent || elementsToStop.has(parent)) {\n      return;\n    }\n    [].forEach.call(parent.children, node => {\n      if (getNodeName(node) === 'script') return;\n      if (elementsToKeep.has(node)) {\n        deep(node);\n      } else {\n        const attr = controlAttribute ? node.getAttribute(controlAttribute) : null;\n        const alreadyHidden = attr !== null && attr !== 'false';\n        const counterMap = getCounterMap(controlAttribute);\n        const counterValue = (counterMap.get(node) || 0) + 1;\n        const markerValue = (markerCounter.get(node) || 0) + 1;\n        counterMap.set(node, counterValue);\n        markerCounter.set(node, markerValue);\n        hiddenElements.push(node);\n        if (counterValue === 1 && alreadyHidden) {\n          uncontrolledElementsSet.add(node);\n        }\n        if (markerValue === 1) {\n          node.setAttribute(markerName, '');\n        }\n        if (!alreadyHidden && controlAttribute) {\n          node.setAttribute(controlAttribute, controlAttribute === 'inert' ? '' : 'true');\n        }\n      }\n    });\n  }\n  lockCount$1++;\n  return () => {\n    hiddenElements.forEach(element => {\n      const counterMap = getCounterMap(controlAttribute);\n      const currentCounterValue = counterMap.get(element) || 0;\n      const counterValue = currentCounterValue - 1;\n      const markerValue = (markerCounter.get(element) || 0) - 1;\n      counterMap.set(element, counterValue);\n      markerCounter.set(element, markerValue);\n      if (!counterValue) {\n        if (!uncontrolledElementsSet.has(element) && controlAttribute) {\n          element.removeAttribute(controlAttribute);\n        }\n        uncontrolledElementsSet.delete(element);\n      }\n      if (!markerValue) {\n        element.removeAttribute(markerName);\n      }\n    });\n    lockCount$1--;\n    if (!lockCount$1) {\n      counters.inert = new WeakMap();\n      counters['aria-hidden'] = new WeakMap();\n      counters.none = new WeakMap();\n      uncontrolledElementsSet = new WeakSet();\n      markerMap = {};\n    }\n  };\n}\nfunction markOthers(avoidElements, ariaHidden, inert) {\n  if (ariaHidden === void 0) {\n    ariaHidden = false;\n  }\n  if (inert === void 0) {\n    inert = false;\n  }\n  const body = getDocument(avoidElements[0]).body;\n  return applyAttributeToOthers(avoidElements.concat(Array.from(body.querySelectorAll('[aria-live],[role=\"status\"],output'))), body, ariaHidden, inert);\n}\n\nconst HIDDEN_STYLES = {\n  border: 0,\n  clip: 'rect(0 0 0 0)',\n  height: '1px',\n  margin: '-1px',\n  overflow: 'hidden',\n  padding: 0,\n  position: 'fixed',\n  whiteSpace: 'nowrap',\n  width: '1px',\n  top: 0,\n  left: 0\n};\nconst FocusGuard = /*#__PURE__*/React.forwardRef(function FocusGuard(props, ref) {\n  const [role, setRole] = React.useState();\n  useModernLayoutEffect(() => {\n    if (isSafari()) {\n      // Unlike other screen readers such as NVDA and JAWS, the virtual cursor\n      // on VoiceOver does trigger the onFocus event, so we can use the focus\n      // trap element. On Safari, only buttons trigger the onFocus event.\n      // NB: \"group\" role in the Sandbox no longer appears to work, must be a\n      // button role.\n      setRole('button');\n    }\n  }, []);\n  const restProps = {\n    ref,\n    tabIndex: 0,\n    // Role is only for VoiceOver\n    role,\n    'aria-hidden': role ? undefined : true,\n    [createAttribute('focus-guard')]: '',\n    style: HIDDEN_STYLES\n  };\n  return /*#__PURE__*/jsx(\"span\", {\n    ...props,\n    ...restProps\n  });\n});\n\nconst PortalContext = /*#__PURE__*/React.createContext(null);\nconst attr = /*#__PURE__*/createAttribute('portal');\n/**\n * @see https://floating-ui.com/docs/FloatingPortal#usefloatingportalnode\n */\nfunction useFloatingPortalNode(props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    id,\n    root\n  } = props;\n  const uniqueId = useId();\n  const portalContext = usePortalContext();\n  const [portalNode, setPortalNode] = React.useState(null);\n  const portalNodeRef = React.useRef(null);\n  useModernLayoutEffect(() => {\n    return () => {\n      portalNode == null || portalNode.remove();\n      // Allow the subsequent layout effects to create a new node on updates.\n      // The portal node will still be cleaned up on unmount.\n      // https://github.com/floating-ui/floating-ui/issues/2454\n      queueMicrotask(() => {\n        portalNodeRef.current = null;\n      });\n    };\n  }, [portalNode]);\n  useModernLayoutEffect(() => {\n    // Wait for the uniqueId to be generated before creating the portal node in\n    // React <18 (using `useFloatingId` instead of the native `useId`).\n    // https://github.com/floating-ui/floating-ui/issues/2778\n    if (!uniqueId) return;\n    if (portalNodeRef.current) return;\n    const existingIdRoot = id ? document.getElementById(id) : null;\n    if (!existingIdRoot) return;\n    const subRoot = document.createElement('div');\n    subRoot.id = uniqueId;\n    subRoot.setAttribute(attr, '');\n    existingIdRoot.appendChild(subRoot);\n    portalNodeRef.current = subRoot;\n    setPortalNode(subRoot);\n  }, [id, uniqueId]);\n  useModernLayoutEffect(() => {\n    // Wait for the root to exist before creating the portal node. The root must\n    // be stored in state, not a ref, for this to work reactively.\n    if (root === null) return;\n    if (!uniqueId) return;\n    if (portalNodeRef.current) return;\n    let container = root || (portalContext == null ? void 0 : portalContext.portalNode);\n    if (container && !isNode(container)) container = container.current;\n    container = container || document.body;\n    let idWrapper = null;\n    if (id) {\n      idWrapper = document.createElement('div');\n      idWrapper.id = id;\n      container.appendChild(idWrapper);\n    }\n    const subRoot = document.createElement('div');\n    subRoot.id = uniqueId;\n    subRoot.setAttribute(attr, '');\n    container = idWrapper || container;\n    container.appendChild(subRoot);\n    portalNodeRef.current = subRoot;\n    setPortalNode(subRoot);\n  }, [id, root, uniqueId, portalContext]);\n  return portalNode;\n}\n/**\n * Portals the floating element into a given container element — by default,\n * outside of the app root and into the body.\n * This is necessary to ensure the floating element can appear outside any\n * potential parent containers that cause clipping (such as `overflow: hidden`),\n * while retaining its location in the React tree.\n * @see https://floating-ui.com/docs/FloatingPortal\n */\nfunction FloatingPortal(props) {\n  const {\n    children,\n    id,\n    root,\n    preserveTabOrder = true\n  } = props;\n  const portalNode = useFloatingPortalNode({\n    id,\n    root\n  });\n  const [focusManagerState, setFocusManagerState] = React.useState(null);\n  const beforeOutsideRef = React.useRef(null);\n  const afterOutsideRef = React.useRef(null);\n  const beforeInsideRef = React.useRef(null);\n  const afterInsideRef = React.useRef(null);\n  const modal = focusManagerState == null ? void 0 : focusManagerState.modal;\n  const open = focusManagerState == null ? void 0 : focusManagerState.open;\n  const shouldRenderGuards =\n  // The FocusManager and therefore floating element are currently open/\n  // rendered.\n  !!focusManagerState &&\n  // Guards are only for non-modal focus management.\n  !focusManagerState.modal &&\n  // Don't render if unmount is transitioning.\n  focusManagerState.open && preserveTabOrder && !!(root || portalNode);\n\n  // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/TabbablePortal.tsx\n  React.useEffect(() => {\n    if (!portalNode || !preserveTabOrder || modal) {\n      return;\n    }\n\n    // Make sure elements inside the portal element are tabbable only when the\n    // portal has already been focused, either by tabbing into a focus trap\n    // element outside or using the mouse.\n    function onFocus(event) {\n      if (portalNode && isOutsideEvent(event)) {\n        const focusing = event.type === 'focusin';\n        const manageFocus = focusing ? enableFocusInside : disableFocusInside;\n        manageFocus(portalNode);\n      }\n    }\n    // Listen to the event on the capture phase so they run before the focus\n    // trap elements onFocus prop is called.\n    portalNode.addEventListener('focusin', onFocus, true);\n    portalNode.addEventListener('focusout', onFocus, true);\n    return () => {\n      portalNode.removeEventListener('focusin', onFocus, true);\n      portalNode.removeEventListener('focusout', onFocus, true);\n    };\n  }, [portalNode, preserveTabOrder, modal]);\n  React.useEffect(() => {\n    if (!portalNode) return;\n    if (open) return;\n    enableFocusInside(portalNode);\n  }, [open, portalNode]);\n  return /*#__PURE__*/jsxs(PortalContext.Provider, {\n    value: React.useMemo(() => ({\n      preserveTabOrder,\n      beforeOutsideRef,\n      afterOutsideRef,\n      beforeInsideRef,\n      afterInsideRef,\n      portalNode,\n      setFocusManagerState\n    }), [preserveTabOrder, portalNode]),\n    children: [shouldRenderGuards && portalNode && /*#__PURE__*/jsx(FocusGuard, {\n      \"data-type\": \"outside\",\n      ref: beforeOutsideRef,\n      onFocus: event => {\n        if (isOutsideEvent(event, portalNode)) {\n          var _beforeInsideRef$curr;\n          (_beforeInsideRef$curr = beforeInsideRef.current) == null || _beforeInsideRef$curr.focus();\n        } else {\n          const domReference = focusManagerState ? focusManagerState.domReference : null;\n          const prevTabbable = getPreviousTabbable(domReference);\n          prevTabbable == null || prevTabbable.focus();\n        }\n      }\n    }), shouldRenderGuards && portalNode && /*#__PURE__*/jsx(\"span\", {\n      \"aria-owns\": portalNode.id,\n      style: HIDDEN_STYLES\n    }), portalNode && /*#__PURE__*/ReactDOM.createPortal(children, portalNode), shouldRenderGuards && portalNode && /*#__PURE__*/jsx(FocusGuard, {\n      \"data-type\": \"outside\",\n      ref: afterOutsideRef,\n      onFocus: event => {\n        if (isOutsideEvent(event, portalNode)) {\n          var _afterInsideRef$curre;\n          (_afterInsideRef$curre = afterInsideRef.current) == null || _afterInsideRef$curre.focus();\n        } else {\n          const domReference = focusManagerState ? focusManagerState.domReference : null;\n          const nextTabbable = getNextTabbable(domReference);\n          nextTabbable == null || nextTabbable.focus();\n          (focusManagerState == null ? void 0 : focusManagerState.closeOnFocusOut) && (focusManagerState == null ? void 0 : focusManagerState.onOpenChange(false, event.nativeEvent, 'focus-out'));\n        }\n      }\n    })]\n  });\n}\nconst usePortalContext = () => React.useContext(PortalContext);\n\nfunction useLiteMergeRefs(refs) {\n  return React.useMemo(() => {\n    return value => {\n      refs.forEach(ref => {\n        if (ref) {\n          ref.current = value;\n        }\n      });\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, refs);\n}\n\nconst LIST_LIMIT = 20;\nlet previouslyFocusedElements = [];\nfunction clearDisconnectedPreviouslyFocusedElements() {\n  previouslyFocusedElements = previouslyFocusedElements.filter(el => el.isConnected);\n}\nfunction addPreviouslyFocusedElement(element) {\n  clearDisconnectedPreviouslyFocusedElements();\n  if (element && getNodeName(element) !== 'body') {\n    previouslyFocusedElements.push(element);\n    if (previouslyFocusedElements.length > LIST_LIMIT) {\n      previouslyFocusedElements = previouslyFocusedElements.slice(-20);\n    }\n  }\n}\nfunction getPreviouslyFocusedElement() {\n  clearDisconnectedPreviouslyFocusedElements();\n  return previouslyFocusedElements[previouslyFocusedElements.length - 1];\n}\nfunction getFirstTabbableElement(container) {\n  const tabbableOptions = getTabbableOptions();\n  if (isTabbable(container, tabbableOptions)) {\n    return container;\n  }\n  return tabbable(container, tabbableOptions)[0] || container;\n}\nfunction handleTabIndex(floatingFocusElement, orderRef) {\n  var _floatingFocusElement;\n  if (!orderRef.current.includes('floating') && !((_floatingFocusElement = floatingFocusElement.getAttribute('role')) != null && _floatingFocusElement.includes('dialog'))) {\n    return;\n  }\n  const options = getTabbableOptions();\n  const focusableElements = focusable(floatingFocusElement, options);\n  const tabbableContent = focusableElements.filter(element => {\n    const dataTabIndex = element.getAttribute('data-tabindex') || '';\n    return isTabbable(element, options) || element.hasAttribute('data-tabindex') && !dataTabIndex.startsWith('-');\n  });\n  const tabIndex = floatingFocusElement.getAttribute('tabindex');\n  if (orderRef.current.includes('floating') || tabbableContent.length === 0) {\n    if (tabIndex !== '0') {\n      floatingFocusElement.setAttribute('tabindex', '0');\n    }\n  } else if (tabIndex !== '-1' || floatingFocusElement.hasAttribute('data-tabindex') && floatingFocusElement.getAttribute('data-tabindex') !== '-1') {\n    floatingFocusElement.setAttribute('tabindex', '-1');\n    floatingFocusElement.setAttribute('data-tabindex', '-1');\n  }\n}\nconst VisuallyHiddenDismiss = /*#__PURE__*/React.forwardRef(function VisuallyHiddenDismiss(props, ref) {\n  return /*#__PURE__*/jsx(\"button\", {\n    ...props,\n    type: \"button\",\n    ref: ref,\n    tabIndex: -1,\n    style: HIDDEN_STYLES\n  });\n});\n/**\n * Provides focus management for the floating element.\n * @see https://floating-ui.com/docs/FloatingFocusManager\n */\nfunction FloatingFocusManager(props) {\n  const {\n    context,\n    children,\n    disabled = false,\n    order = ['content'],\n    guards: _guards = true,\n    initialFocus = 0,\n    returnFocus = true,\n    restoreFocus = false,\n    modal = true,\n    visuallyHiddenDismiss = false,\n    closeOnFocusOut = true,\n    outsideElementsInert = false,\n    getInsideElements: _getInsideElements = () => []\n  } = props;\n  const {\n    open,\n    onOpenChange,\n    events,\n    dataRef,\n    elements: {\n      domReference,\n      floating\n    }\n  } = context;\n  const getNodeId = useEffectEvent(() => {\n    var _dataRef$current$floa;\n    return (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;\n  });\n  const getInsideElements = useEffectEvent(_getInsideElements);\n  const ignoreInitialFocus = typeof initialFocus === 'number' && initialFocus < 0;\n  // If the reference is a combobox and is typeable (e.g. input/textarea),\n  // there are different focus semantics. The guards should not be rendered, but\n  // aria-hidden should be applied to all nodes still. Further, the visually\n  // hidden dismiss button should only appear at the end of the list, not the\n  // start.\n  const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;\n\n  // Force the guards to be rendered if the `inert` attribute is not supported.\n  const inertSupported = supportsInert();\n  const guards = inertSupported ? _guards : true;\n  const useInert = !guards || inertSupported && outsideElementsInert;\n  const orderRef = useLatestRef(order);\n  const initialFocusRef = useLatestRef(initialFocus);\n  const returnFocusRef = useLatestRef(returnFocus);\n  const tree = useFloatingTree();\n  const portalContext = usePortalContext();\n  const startDismissButtonRef = React.useRef(null);\n  const endDismissButtonRef = React.useRef(null);\n  const preventReturnFocusRef = React.useRef(false);\n  const isPointerDownRef = React.useRef(false);\n  const tabbableIndexRef = React.useRef(-1);\n  const blurTimeoutRef = React.useRef(-1);\n  const isInsidePortal = portalContext != null;\n  const floatingFocusElement = getFloatingFocusElement(floating);\n  const getTabbableContent = useEffectEvent(function (container) {\n    if (container === void 0) {\n      container = floatingFocusElement;\n    }\n    return container ? tabbable(container, getTabbableOptions()) : [];\n  });\n  const getTabbableElements = useEffectEvent(container => {\n    const content = getTabbableContent(container);\n    return orderRef.current.map(type => {\n      if (domReference && type === 'reference') {\n        return domReference;\n      }\n      if (floatingFocusElement && type === 'floating') {\n        return floatingFocusElement;\n      }\n      return content;\n    }).filter(Boolean).flat();\n  });\n  React.useEffect(() => {\n    if (disabled) return;\n    if (!modal) return;\n    function onKeyDown(event) {\n      if (event.key === 'Tab') {\n        // The focus guards have nothing to focus, so we need to stop the event.\n        if (contains$1(floatingFocusElement, activeElement(getDocument$1(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {\n          stopEvent(event);\n        }\n        const els = getTabbableElements();\n        const target = getTarget$1(event);\n        if (orderRef.current[0] === 'reference' && target === domReference) {\n          stopEvent(event);\n          if (event.shiftKey) {\n            enqueueFocus(els[els.length - 1]);\n          } else {\n            enqueueFocus(els[1]);\n          }\n        }\n        if (orderRef.current[1] === 'floating' && target === floatingFocusElement && event.shiftKey) {\n          stopEvent(event);\n          enqueueFocus(els[0]);\n        }\n      }\n    }\n    const doc = getDocument$1(floatingFocusElement);\n    doc.addEventListener('keydown', onKeyDown);\n    return () => {\n      doc.removeEventListener('keydown', onKeyDown);\n    };\n  }, [disabled, domReference, floatingFocusElement, modal, orderRef, isUntrappedTypeableCombobox, getTabbableContent, getTabbableElements]);\n  React.useEffect(() => {\n    if (disabled) return;\n    if (!floating) return;\n    function handleFocusIn(event) {\n      const target = getTarget$1(event);\n      const tabbableContent = getTabbableContent();\n      const tabbableIndex = tabbableContent.indexOf(target);\n      if (tabbableIndex !== -1) {\n        tabbableIndexRef.current = tabbableIndex;\n      }\n    }\n    floating.addEventListener('focusin', handleFocusIn);\n    return () => {\n      floating.removeEventListener('focusin', handleFocusIn);\n    };\n  }, [disabled, floating, getTabbableContent]);\n  React.useEffect(() => {\n    if (disabled) return;\n    if (!closeOnFocusOut) return;\n\n    // In Safari, buttons lose focus when pressing them.\n    function handlePointerDown() {\n      isPointerDownRef.current = true;\n      setTimeout(() => {\n        isPointerDownRef.current = false;\n      });\n    }\n    function handleFocusOutside(event) {\n      const relatedTarget = event.relatedTarget;\n      const currentTarget = event.currentTarget;\n      const target = getTarget$1(event);\n      queueMicrotask(() => {\n        const nodeId = getNodeId();\n        const movedToUnrelatedNode = !(contains$1(domReference, relatedTarget) || contains$1(floating, relatedTarget) || contains$1(relatedTarget, floating) || contains$1(portalContext == null ? void 0 : portalContext.portalNode, relatedTarget) || relatedTarget != null && relatedTarget.hasAttribute(createAttribute('focus-guard')) || tree && (getNodeChildren$1(tree.nodesRef.current, nodeId).find(node => {\n          var _node$context, _node$context2;\n          return contains$1((_node$context = node.context) == null ? void 0 : _node$context.elements.floating, relatedTarget) || contains$1((_node$context2 = node.context) == null ? void 0 : _node$context2.elements.domReference, relatedTarget);\n        }) || getNodeAncestors(tree.nodesRef.current, nodeId).find(node => {\n          var _node$context3, _node$context4, _node$context5;\n          return [(_node$context3 = node.context) == null ? void 0 : _node$context3.elements.floating, getFloatingFocusElement((_node$context4 = node.context) == null ? void 0 : _node$context4.elements.floating)].includes(relatedTarget) || ((_node$context5 = node.context) == null ? void 0 : _node$context5.elements.domReference) === relatedTarget;\n        })));\n        if (currentTarget === domReference && floatingFocusElement) {\n          handleTabIndex(floatingFocusElement, orderRef);\n        }\n\n        // Restore focus to the previous tabbable element index to prevent\n        // focus from being lost outside the floating tree.\n        if (restoreFocus && currentTarget !== domReference && !(target != null && target.isConnected) && activeElement(getDocument$1(floatingFocusElement)) === getDocument$1(floatingFocusElement).body) {\n          // Let `FloatingPortal` effect knows that focus is still inside the\n          // floating tree.\n          if (isHTMLElement(floatingFocusElement)) {\n            floatingFocusElement.focus();\n          }\n          const prevTabbableIndex = tabbableIndexRef.current;\n          const tabbableContent = getTabbableContent();\n          const nodeToFocus = tabbableContent[prevTabbableIndex] || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;\n          if (isHTMLElement(nodeToFocus)) {\n            nodeToFocus.focus();\n          }\n        }\n\n        // https://github.com/floating-ui/floating-ui/issues/3060\n        if (dataRef.current.insideReactTree) {\n          dataRef.current.insideReactTree = false;\n          return;\n        }\n\n        // Focus did not move inside the floating tree, and there are no tabbable\n        // portal guards to handle closing.\n        if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current &&\n        // Fix React 18 Strict Mode returnFocus due to double rendering.\n        relatedTarget !== getPreviouslyFocusedElement()) {\n          preventReturnFocusRef.current = true;\n          onOpenChange(false, event, 'focus-out');\n        }\n      });\n    }\n    const shouldHandleBlurCapture = Boolean(!tree && portalContext);\n    function markInsideReactTree() {\n      clearTimeoutIfSet(blurTimeoutRef);\n      dataRef.current.insideReactTree = true;\n      blurTimeoutRef.current = window.setTimeout(() => {\n        dataRef.current.insideReactTree = false;\n      });\n    }\n    if (floating && isHTMLElement(domReference)) {\n      domReference.addEventListener('focusout', handleFocusOutside);\n      domReference.addEventListener('pointerdown', handlePointerDown);\n      floating.addEventListener('focusout', handleFocusOutside);\n      if (shouldHandleBlurCapture) {\n        floating.addEventListener('focusout', markInsideReactTree, true);\n      }\n      return () => {\n        domReference.removeEventListener('focusout', handleFocusOutside);\n        domReference.removeEventListener('pointerdown', handlePointerDown);\n        floating.removeEventListener('focusout', handleFocusOutside);\n        if (shouldHandleBlurCapture) {\n          floating.removeEventListener('focusout', markInsideReactTree, true);\n        }\n      };\n    }\n  }, [disabled, domReference, floating, floatingFocusElement, modal, tree, portalContext, onOpenChange, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox, getNodeId, orderRef, dataRef]);\n  const beforeGuardRef = React.useRef(null);\n  const afterGuardRef = React.useRef(null);\n  const mergedBeforeGuardRef = useLiteMergeRefs([beforeGuardRef, portalContext == null ? void 0 : portalContext.beforeInsideRef]);\n  const mergedAfterGuardRef = useLiteMergeRefs([afterGuardRef, portalContext == null ? void 0 : portalContext.afterInsideRef]);\n  React.useEffect(() => {\n    var _portalContext$portal, _ancestors$find;\n    if (disabled) return;\n    if (!floating) return;\n\n    // Don't hide portals nested within the parent portal.\n    const portalNodes = Array.from((portalContext == null || (_portalContext$portal = portalContext.portalNode) == null ? void 0 : _portalContext$portal.querySelectorAll(\"[\" + createAttribute('portal') + \"]\")) || []);\n    const ancestors = tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : [];\n    const rootAncestorComboboxDomReference = (_ancestors$find = ancestors.find(node => {\n      var _node$context6;\n      return isTypeableCombobox(((_node$context6 = node.context) == null ? void 0 : _node$context6.elements.domReference) || null);\n    })) == null || (_ancestors$find = _ancestors$find.context) == null ? void 0 : _ancestors$find.elements.domReference;\n    const insideElements = [floating, rootAncestorComboboxDomReference, ...portalNodes, ...getInsideElements(), startDismissButtonRef.current, endDismissButtonRef.current, beforeGuardRef.current, afterGuardRef.current, portalContext == null ? void 0 : portalContext.beforeOutsideRef.current, portalContext == null ? void 0 : portalContext.afterOutsideRef.current, orderRef.current.includes('reference') || isUntrappedTypeableCombobox ? domReference : null].filter(x => x != null);\n    const cleanup = modal || isUntrappedTypeableCombobox ? markOthers(insideElements, !useInert, useInert) : markOthers(insideElements);\n    return () => {\n      cleanup();\n    };\n  }, [disabled, domReference, floating, modal, orderRef, portalContext, isUntrappedTypeableCombobox, guards, useInert, tree, getNodeId, getInsideElements]);\n  useModernLayoutEffect(() => {\n    if (disabled || !isHTMLElement(floatingFocusElement)) return;\n    const doc = getDocument$1(floatingFocusElement);\n    const previouslyFocusedElement = activeElement(doc);\n\n    // Wait for any layout effect state setters to execute to set `tabIndex`.\n    queueMicrotask(() => {\n      const focusableElements = getTabbableElements(floatingFocusElement);\n      const initialFocusValue = initialFocusRef.current;\n      const elToFocus = (typeof initialFocusValue === 'number' ? focusableElements[initialFocusValue] : initialFocusValue.current) || floatingFocusElement;\n      const focusAlreadyInsideFloatingEl = contains$1(floatingFocusElement, previouslyFocusedElement);\n      if (!ignoreInitialFocus && !focusAlreadyInsideFloatingEl && open) {\n        enqueueFocus(elToFocus, {\n          preventScroll: elToFocus === floatingFocusElement\n        });\n      }\n    });\n  }, [disabled, open, floatingFocusElement, ignoreInitialFocus, getTabbableElements, initialFocusRef]);\n  useModernLayoutEffect(() => {\n    if (disabled || !floatingFocusElement) return;\n    const doc = getDocument$1(floatingFocusElement);\n    const previouslyFocusedElement = activeElement(doc);\n    addPreviouslyFocusedElement(previouslyFocusedElement);\n\n    // Dismissing via outside press should always ignore `returnFocus` to\n    // prevent unwanted scrolling.\n    function onOpenChange(_ref) {\n      let {\n        reason,\n        event,\n        nested\n      } = _ref;\n      if (['hover', 'safe-polygon'].includes(reason) && event.type === 'mouseleave') {\n        preventReturnFocusRef.current = true;\n      }\n      if (reason !== 'outside-press') return;\n      if (nested) {\n        preventReturnFocusRef.current = false;\n      } else if (isVirtualClick(event) || isVirtualPointerEvent(event)) {\n        preventReturnFocusRef.current = false;\n      } else {\n        let isPreventScrollSupported = false;\n        document.createElement('div').focus({\n          get preventScroll() {\n            isPreventScrollSupported = true;\n            return false;\n          }\n        });\n        if (isPreventScrollSupported) {\n          preventReturnFocusRef.current = false;\n        } else {\n          preventReturnFocusRef.current = true;\n        }\n      }\n    }\n    events.on('openchange', onOpenChange);\n    const fallbackEl = doc.createElement('span');\n    fallbackEl.setAttribute('tabindex', '-1');\n    fallbackEl.setAttribute('aria-hidden', 'true');\n    Object.assign(fallbackEl.style, HIDDEN_STYLES);\n    if (isInsidePortal && domReference) {\n      domReference.insertAdjacentElement('afterend', fallbackEl);\n    }\n    function getReturnElement() {\n      if (typeof returnFocusRef.current === 'boolean') {\n        const el = domReference || getPreviouslyFocusedElement();\n        return el && el.isConnected ? el : fallbackEl;\n      }\n      return returnFocusRef.current.current || fallbackEl;\n    }\n    return () => {\n      events.off('openchange', onOpenChange);\n      const activeEl = activeElement(doc);\n      const isFocusInsideFloatingTree = contains$1(floating, activeEl) || tree && getNodeChildren$1(tree.nodesRef.current, getNodeId(), false).some(node => {\n        var _node$context7;\n        return contains$1((_node$context7 = node.context) == null ? void 0 : _node$context7.elements.floating, activeEl);\n      });\n      const returnElement = getReturnElement();\n      queueMicrotask(() => {\n        // This is `returnElement`, if it's tabbable, or its first tabbable child.\n        const tabbableReturnElement = getFirstTabbableElement(returnElement);\n        if (\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        returnFocusRef.current && !preventReturnFocusRef.current && isHTMLElement(tabbableReturnElement) && (\n        // If the focus moved somewhere else after mount, avoid returning focus\n        // since it likely entered a different element which should be\n        // respected: https://github.com/floating-ui/floating-ui/issues/2607\n        tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {\n          tabbableReturnElement.focus({\n            preventScroll: true\n          });\n        }\n        fallbackEl.remove();\n      });\n    };\n  }, [disabled, floating, floatingFocusElement, returnFocusRef, dataRef, events, tree, isInsidePortal, domReference, getNodeId]);\n  React.useEffect(() => {\n    // The `returnFocus` cleanup behavior is inside a microtask; ensure we\n    // wait for it to complete before resetting the flag.\n    queueMicrotask(() => {\n      preventReturnFocusRef.current = false;\n    });\n    return () => {\n      queueMicrotask(clearDisconnectedPreviouslyFocusedElements);\n    };\n  }, [disabled]);\n\n  // Synchronize the `context` & `modal` value to the FloatingPortal context.\n  // It will decide whether or not it needs to render its own guards.\n  useModernLayoutEffect(() => {\n    if (disabled) return;\n    if (!portalContext) return;\n    portalContext.setFocusManagerState({\n      modal,\n      closeOnFocusOut,\n      open,\n      onOpenChange,\n      domReference\n    });\n    return () => {\n      portalContext.setFocusManagerState(null);\n    };\n  }, [disabled, portalContext, modal, open, onOpenChange, closeOnFocusOut, domReference]);\n  useModernLayoutEffect(() => {\n    if (disabled) return;\n    if (!floatingFocusElement) return;\n    handleTabIndex(floatingFocusElement, orderRef);\n  }, [disabled, floatingFocusElement, orderRef]);\n  function renderDismissButton(location) {\n    if (disabled || !visuallyHiddenDismiss || !modal) {\n      return null;\n    }\n    return /*#__PURE__*/jsx(VisuallyHiddenDismiss, {\n      ref: location === 'start' ? startDismissButtonRef : endDismissButtonRef,\n      onClick: event => onOpenChange(false, event.nativeEvent),\n      children: typeof visuallyHiddenDismiss === 'string' ? visuallyHiddenDismiss : 'Dismiss'\n    });\n  }\n  const shouldRenderGuards = !disabled && guards && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);\n  return /*#__PURE__*/jsxs(Fragment, {\n    children: [shouldRenderGuards && /*#__PURE__*/jsx(FocusGuard, {\n      \"data-type\": \"inside\",\n      ref: mergedBeforeGuardRef,\n      onFocus: event => {\n        if (modal) {\n          const els = getTabbableElements();\n          enqueueFocus(order[0] === 'reference' ? els[0] : els[els.length - 1]);\n        } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {\n          preventReturnFocusRef.current = false;\n          if (isOutsideEvent(event, portalContext.portalNode)) {\n            const nextTabbable = getNextTabbable(domReference);\n            nextTabbable == null || nextTabbable.focus();\n          } else {\n            var _portalContext$before;\n            (_portalContext$before = portalContext.beforeOutsideRef.current) == null || _portalContext$before.focus();\n          }\n        }\n      }\n    }), !isUntrappedTypeableCombobox && renderDismissButton('start'), children, renderDismissButton('end'), shouldRenderGuards && /*#__PURE__*/jsx(FocusGuard, {\n      \"data-type\": \"inside\",\n      ref: mergedAfterGuardRef,\n      onFocus: event => {\n        if (modal) {\n          enqueueFocus(getTabbableElements()[0]);\n        } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {\n          if (closeOnFocusOut) {\n            preventReturnFocusRef.current = true;\n          }\n          if (isOutsideEvent(event, portalContext.portalNode)) {\n            const prevTabbable = getPreviousTabbable(domReference);\n            prevTabbable == null || prevTabbable.focus();\n          } else {\n            var _portalContext$afterO;\n            (_portalContext$afterO = portalContext.afterOutsideRef.current) == null || _portalContext$afterO.focus();\n          }\n        }\n      }\n    })]\n  });\n}\n\nlet lockCount = 0;\nconst scrollbarProperty = '--floating-ui-scrollbar-width';\nfunction enableScrollLock() {\n  const platform = getPlatform();\n  const isIOS = /iP(hone|ad|od)|iOS/.test(platform) ||\n  // iPads can claim to be MacIntel\n  platform === 'MacIntel' && navigator.maxTouchPoints > 1;\n  const bodyStyle = document.body.style;\n  // RTL <body> scrollbar\n  const scrollbarX = Math.round(document.documentElement.getBoundingClientRect().left) + document.documentElement.scrollLeft;\n  const paddingProp = scrollbarX ? 'paddingLeft' : 'paddingRight';\n  const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n  const scrollX = bodyStyle.left ? parseFloat(bodyStyle.left) : window.scrollX;\n  const scrollY = bodyStyle.top ? parseFloat(bodyStyle.top) : window.scrollY;\n  bodyStyle.overflow = 'hidden';\n  bodyStyle.setProperty(scrollbarProperty, scrollbarWidth + \"px\");\n  if (scrollbarWidth) {\n    bodyStyle[paddingProp] = scrollbarWidth + \"px\";\n  }\n\n  // Only iOS doesn't respect `overflow: hidden` on document.body, and this\n  // technique has fewer side effects.\n  if (isIOS) {\n    var _window$visualViewpor, _window$visualViewpor2;\n    // iOS 12 does not support `visualViewport`.\n    const offsetLeft = ((_window$visualViewpor = window.visualViewport) == null ? void 0 : _window$visualViewpor.offsetLeft) || 0;\n    const offsetTop = ((_window$visualViewpor2 = window.visualViewport) == null ? void 0 : _window$visualViewpor2.offsetTop) || 0;\n    Object.assign(bodyStyle, {\n      position: 'fixed',\n      top: -(scrollY - Math.floor(offsetTop)) + \"px\",\n      left: -(scrollX - Math.floor(offsetLeft)) + \"px\",\n      right: '0'\n    });\n  }\n  return () => {\n    Object.assign(bodyStyle, {\n      overflow: '',\n      [paddingProp]: ''\n    });\n    bodyStyle.removeProperty(scrollbarProperty);\n    if (isIOS) {\n      Object.assign(bodyStyle, {\n        position: '',\n        top: '',\n        left: '',\n        right: ''\n      });\n      window.scrollTo(scrollX, scrollY);\n    }\n  };\n}\nlet cleanup = () => {};\n\n/**\n * Provides base styling for a fixed overlay element to dim content or block\n * pointer events behind a floating element.\n * It's a regular `<div>`, so it can be styled via any CSS solution you prefer.\n * @see https://floating-ui.com/docs/FloatingOverlay\n */\nconst FloatingOverlay = /*#__PURE__*/React.forwardRef(function FloatingOverlay(props, ref) {\n  const {\n    lockScroll = false,\n    ...rest\n  } = props;\n  useModernLayoutEffect(() => {\n    if (!lockScroll) return;\n    lockCount++;\n    if (lockCount === 1) {\n      cleanup = enableScrollLock();\n    }\n    return () => {\n      lockCount--;\n      if (lockCount === 0) {\n        cleanup();\n      }\n    };\n  }, [lockScroll]);\n  return /*#__PURE__*/jsx(\"div\", {\n    ref: ref,\n    ...rest,\n    style: {\n      position: 'fixed',\n      overflow: 'auto',\n      top: 0,\n      right: 0,\n      bottom: 0,\n      left: 0,\n      ...rest.style\n    }\n  });\n});\n\nfunction isButtonTarget(event) {\n  return isHTMLElement(event.target) && event.target.tagName === 'BUTTON';\n}\nfunction isAnchorTarget(event) {\n  return isHTMLElement(event.target) && event.target.tagName === 'A';\n}\nfunction isSpaceIgnored(element) {\n  return isTypeableElement(element);\n}\n/**\n * Opens or closes the floating element when clicking the reference element.\n * @see https://floating-ui.com/docs/useClick\n */\nfunction useClick(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    onOpenChange,\n    dataRef,\n    elements: {\n      domReference\n    }\n  } = context;\n  const {\n    enabled = true,\n    event: eventOption = 'click',\n    toggle = true,\n    ignoreMouse = false,\n    keyboardHandlers = true,\n    stickIfOpen = true\n  } = props;\n  const pointerTypeRef = React.useRef();\n  const didKeyDownRef = React.useRef(false);\n  const reference = React.useMemo(() => ({\n    onPointerDown(event) {\n      pointerTypeRef.current = event.pointerType;\n    },\n    onMouseDown(event) {\n      const pointerType = pointerTypeRef.current;\n\n      // Ignore all buttons except for the \"main\" button.\n      // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button\n      if (event.button !== 0) return;\n      if (eventOption === 'click') return;\n      if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;\n      if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === 'mousedown' : true)) {\n        onOpenChange(false, event.nativeEvent, 'click');\n      } else {\n        // Prevent stealing focus from the floating element\n        event.preventDefault();\n        onOpenChange(true, event.nativeEvent, 'click');\n      }\n    },\n    onClick(event) {\n      const pointerType = pointerTypeRef.current;\n      if (eventOption === 'mousedown' && pointerTypeRef.current) {\n        pointerTypeRef.current = undefined;\n        return;\n      }\n      if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;\n      if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === 'click' : true)) {\n        onOpenChange(false, event.nativeEvent, 'click');\n      } else {\n        onOpenChange(true, event.nativeEvent, 'click');\n      }\n    },\n    onKeyDown(event) {\n      pointerTypeRef.current = undefined;\n      if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event)) {\n        return;\n      }\n      if (event.key === ' ' && !isSpaceIgnored(domReference)) {\n        // Prevent scrolling\n        event.preventDefault();\n        didKeyDownRef.current = true;\n      }\n      if (isAnchorTarget(event)) {\n        return;\n      }\n      if (event.key === 'Enter') {\n        if (open && toggle) {\n          onOpenChange(false, event.nativeEvent, 'click');\n        } else {\n          onOpenChange(true, event.nativeEvent, 'click');\n        }\n      }\n    },\n    onKeyUp(event) {\n      if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event) || isSpaceIgnored(domReference)) {\n        return;\n      }\n      if (event.key === ' ' && didKeyDownRef.current) {\n        didKeyDownRef.current = false;\n        if (open && toggle) {\n          onOpenChange(false, event.nativeEvent, 'click');\n        } else {\n          onOpenChange(true, event.nativeEvent, 'click');\n        }\n      }\n    }\n  }), [dataRef, domReference, eventOption, ignoreMouse, keyboardHandlers, onOpenChange, open, stickIfOpen, toggle]);\n  return React.useMemo(() => enabled ? {\n    reference\n  } : {}, [enabled, reference]);\n}\n\nfunction createVirtualElement(domElement, data) {\n  let offsetX = null;\n  let offsetY = null;\n  let isAutoUpdateEvent = false;\n  return {\n    contextElement: domElement || undefined,\n    getBoundingClientRect() {\n      var _data$dataRef$current;\n      const domRect = (domElement == null ? void 0 : domElement.getBoundingClientRect()) || {\n        width: 0,\n        height: 0,\n        x: 0,\n        y: 0\n      };\n      const isXAxis = data.axis === 'x' || data.axis === 'both';\n      const isYAxis = data.axis === 'y' || data.axis === 'both';\n      const canTrackCursorOnAutoUpdate = ['mouseenter', 'mousemove'].includes(((_data$dataRef$current = data.dataRef.current.openEvent) == null ? void 0 : _data$dataRef$current.type) || '') && data.pointerType !== 'touch';\n      let width = domRect.width;\n      let height = domRect.height;\n      let x = domRect.x;\n      let y = domRect.y;\n      if (offsetX == null && data.x && isXAxis) {\n        offsetX = domRect.x - data.x;\n      }\n      if (offsetY == null && data.y && isYAxis) {\n        offsetY = domRect.y - data.y;\n      }\n      x -= offsetX || 0;\n      y -= offsetY || 0;\n      width = 0;\n      height = 0;\n      if (!isAutoUpdateEvent || canTrackCursorOnAutoUpdate) {\n        width = data.axis === 'y' ? domRect.width : 0;\n        height = data.axis === 'x' ? domRect.height : 0;\n        x = isXAxis && data.x != null ? data.x : x;\n        y = isYAxis && data.y != null ? data.y : y;\n      } else if (isAutoUpdateEvent && !canTrackCursorOnAutoUpdate) {\n        height = data.axis === 'x' ? domRect.height : height;\n        width = data.axis === 'y' ? domRect.width : width;\n      }\n      isAutoUpdateEvent = true;\n      return {\n        width,\n        height,\n        x,\n        y,\n        top: y,\n        right: x + width,\n        bottom: y + height,\n        left: x\n      };\n    }\n  };\n}\nfunction isMouseBasedEvent(event) {\n  return event != null && event.clientX != null;\n}\n/**\n * Positions the floating element relative to a client point (in the viewport),\n * such as the mouse position. By default, it follows the mouse cursor.\n * @see https://floating-ui.com/docs/useClientPoint\n */\nfunction useClientPoint(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    dataRef,\n    elements: {\n      floating,\n      domReference\n    },\n    refs\n  } = context;\n  const {\n    enabled = true,\n    axis = 'both',\n    x = null,\n    y = null\n  } = props;\n  const initialRef = React.useRef(false);\n  const cleanupListenerRef = React.useRef(null);\n  const [pointerType, setPointerType] = React.useState();\n  const [reactive, setReactive] = React.useState([]);\n  const setReference = useEffectEvent((x, y) => {\n    if (initialRef.current) return;\n\n    // Prevent setting if the open event was not a mouse-like one\n    // (e.g. focus to open, then hover over the reference element).\n    // Only apply if the event exists.\n    if (dataRef.current.openEvent && !isMouseBasedEvent(dataRef.current.openEvent)) {\n      return;\n    }\n    refs.setPositionReference(createVirtualElement(domReference, {\n      x,\n      y,\n      axis,\n      dataRef,\n      pointerType\n    }));\n  });\n  const handleReferenceEnterOrMove = useEffectEvent(event => {\n    if (x != null || y != null) return;\n    if (!open) {\n      setReference(event.clientX, event.clientY);\n    } else if (!cleanupListenerRef.current) {\n      // If there's no cleanup, there's no listener, but we want to ensure\n      // we add the listener if the cursor landed on the floating element and\n      // then back on the reference (i.e. it's interactive).\n      setReactive([]);\n    }\n  });\n\n  // If the pointer is a mouse-like pointer, we want to continue following the\n  // mouse even if the floating element is transitioning out. On touch\n  // devices, this is undesirable because the floating element will move to\n  // the dismissal touch point.\n  const openCheck = isMouseLikePointerType(pointerType) ? floating : open;\n  const addListener = React.useCallback(() => {\n    // Explicitly specified `x`/`y` coordinates shouldn't add a listener.\n    if (!openCheck || !enabled || x != null || y != null) return;\n    const win = getWindow(floating);\n    function handleMouseMove(event) {\n      const target = getTarget$1(event);\n      if (!contains$1(floating, target)) {\n        setReference(event.clientX, event.clientY);\n      } else {\n        win.removeEventListener('mousemove', handleMouseMove);\n        cleanupListenerRef.current = null;\n      }\n    }\n    if (!dataRef.current.openEvent || isMouseBasedEvent(dataRef.current.openEvent)) {\n      win.addEventListener('mousemove', handleMouseMove);\n      const cleanup = () => {\n        win.removeEventListener('mousemove', handleMouseMove);\n        cleanupListenerRef.current = null;\n      };\n      cleanupListenerRef.current = cleanup;\n      return cleanup;\n    }\n    refs.setPositionReference(domReference);\n  }, [openCheck, enabled, x, y, floating, dataRef, refs, domReference, setReference]);\n  React.useEffect(() => {\n    return addListener();\n  }, [addListener, reactive]);\n  React.useEffect(() => {\n    if (enabled && !floating) {\n      initialRef.current = false;\n    }\n  }, [enabled, floating]);\n  React.useEffect(() => {\n    if (!enabled && open) {\n      initialRef.current = true;\n    }\n  }, [enabled, open]);\n  useModernLayoutEffect(() => {\n    if (enabled && (x != null || y != null)) {\n      initialRef.current = false;\n      setReference(x, y);\n    }\n  }, [enabled, x, y, setReference]);\n  const reference = React.useMemo(() => {\n    function setPointerTypeRef(_ref) {\n      let {\n        pointerType\n      } = _ref;\n      setPointerType(pointerType);\n    }\n    return {\n      onPointerDown: setPointerTypeRef,\n      onPointerEnter: setPointerTypeRef,\n      onMouseMove: handleReferenceEnterOrMove,\n      onMouseEnter: handleReferenceEnterOrMove\n    };\n  }, [handleReferenceEnterOrMove]);\n  return React.useMemo(() => enabled ? {\n    reference\n  } : {}, [enabled, reference]);\n}\n\nconst bubbleHandlerKeys = {\n  pointerdown: 'onPointerDown',\n  mousedown: 'onMouseDown',\n  click: 'onClick'\n};\nconst captureHandlerKeys = {\n  pointerdown: 'onPointerDownCapture',\n  mousedown: 'onMouseDownCapture',\n  click: 'onClickCapture'\n};\nconst normalizeProp = normalizable => {\n  var _normalizable$escapeK, _normalizable$outside;\n  return {\n    escapeKey: typeof normalizable === 'boolean' ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,\n    outsidePress: typeof normalizable === 'boolean' ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true\n  };\n};\n/**\n * Closes the floating element when a dismissal is requested — by default, when\n * the user presses the `escape` key or outside of the floating element.\n * @see https://floating-ui.com/docs/useDismiss\n */\nfunction useDismiss(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    onOpenChange,\n    elements,\n    dataRef\n  } = context;\n  const {\n    enabled = true,\n    escapeKey = true,\n    outsidePress: unstable_outsidePress = true,\n    outsidePressEvent = 'pointerdown',\n    referencePress = false,\n    referencePressEvent = 'pointerdown',\n    ancestorScroll = false,\n    bubbles,\n    capture\n  } = props;\n  const tree = useFloatingTree();\n  const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === 'function' ? unstable_outsidePress : () => false);\n  const outsidePress = typeof unstable_outsidePress === 'function' ? outsidePressFn : unstable_outsidePress;\n  const endedOrStartedInsideRef = React.useRef(false);\n  const {\n    escapeKey: escapeKeyBubbles,\n    outsidePress: outsidePressBubbles\n  } = normalizeProp(bubbles);\n  const {\n    escapeKey: escapeKeyCapture,\n    outsidePress: outsidePressCapture\n  } = normalizeProp(capture);\n  const isComposingRef = React.useRef(false);\n  const closeOnEscapeKeyDown = useEffectEvent(event => {\n    var _dataRef$current$floa;\n    if (!open || !enabled || !escapeKey || event.key !== 'Escape') {\n      return;\n    }\n\n    // Wait until IME is settled. Pressing `Escape` while composing should\n    // close the compose menu, but not the floating element.\n    if (isComposingRef.current) {\n      return;\n    }\n    const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;\n    const children = tree ? getNodeChildren$1(tree.nodesRef.current, nodeId) : [];\n    if (!escapeKeyBubbles) {\n      event.stopPropagation();\n      if (children.length > 0) {\n        let shouldDismiss = true;\n        children.forEach(child => {\n          var _child$context;\n          if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {\n            shouldDismiss = false;\n            return;\n          }\n        });\n        if (!shouldDismiss) {\n          return;\n        }\n      }\n    }\n    onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, 'escape-key');\n  });\n  const closeOnEscapeKeyDownCapture = useEffectEvent(event => {\n    var _getTarget2;\n    const callback = () => {\n      var _getTarget;\n      closeOnEscapeKeyDown(event);\n      (_getTarget = getTarget$1(event)) == null || _getTarget.removeEventListener('keydown', callback);\n    };\n    (_getTarget2 = getTarget$1(event)) == null || _getTarget2.addEventListener('keydown', callback);\n  });\n  const closeOnPressOutside = useEffectEvent(event => {\n    var _dataRef$current$floa2;\n    // Given developers can stop the propagation of the synthetic event,\n    // we can only be confident with a positive value.\n    const insideReactTree = dataRef.current.insideReactTree;\n    dataRef.current.insideReactTree = false;\n\n    // When click outside is lazy (`click` event), handle dragging.\n    // Don't close if:\n    // - The click started inside the floating element.\n    // - The click ended inside the floating element.\n    const endedOrStartedInside = endedOrStartedInsideRef.current;\n    endedOrStartedInsideRef.current = false;\n    if (outsidePressEvent === 'click' && endedOrStartedInside) {\n      return;\n    }\n    if (insideReactTree) {\n      return;\n    }\n    if (typeof outsidePress === 'function' && !outsidePress(event)) {\n      return;\n    }\n    const target = getTarget$1(event);\n    const inertSelector = \"[\" + createAttribute('inert') + \"]\";\n    const markers = getDocument$1(elements.floating).querySelectorAll(inertSelector);\n    let targetRootAncestor = isElement(target) ? target : null;\n    while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {\n      const nextParent = getParentNode(targetRootAncestor);\n      if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {\n        break;\n      }\n      targetRootAncestor = nextParent;\n    }\n\n    // Check if the click occurred on a third-party element injected after the\n    // floating element rendered.\n    if (markers.length && isElement(target) && !isRootElement(target) &&\n    // Clicked on a direct ancestor (e.g. FloatingOverlay).\n    !contains$1(target, elements.floating) &&\n    // If the target root element contains none of the markers, then the\n    // element was injected after the floating element rendered.\n    Array.from(markers).every(marker => !contains$1(targetRootAncestor, marker))) {\n      return;\n    }\n\n    // Check if the click occurred on the scrollbar\n    if (isHTMLElement(target) && floating) {\n      const lastTraversableNode = isLastTraversableNode(target);\n      const style = getComputedStyle(target);\n      const scrollRe = /auto|scroll/;\n      const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);\n      const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);\n      const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;\n      const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;\n      const isRTL = style.direction === 'rtl';\n\n      // Check click position relative to scrollbar.\n      // In some browsers it is possible to change the <body> (or window)\n      // scrollbar to the left side, but is very rare and is difficult to\n      // check for. Plus, for modal dialogs with backdrops, it is more\n      // important that the backdrop is checked but not so much the window.\n      const pressedVerticalScrollbar = canScrollY && (isRTL ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);\n      const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;\n      if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {\n        return;\n      }\n    }\n    const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;\n    const targetIsInsideChildren = tree && getNodeChildren$1(tree.nodesRef.current, nodeId).some(node => {\n      var _node$context;\n      return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);\n    });\n    if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) {\n      return;\n    }\n    const children = tree ? getNodeChildren$1(tree.nodesRef.current, nodeId) : [];\n    if (children.length > 0) {\n      let shouldDismiss = true;\n      children.forEach(child => {\n        var _child$context2;\n        if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {\n          shouldDismiss = false;\n          return;\n        }\n      });\n      if (!shouldDismiss) {\n        return;\n      }\n    }\n    onOpenChange(false, event, 'outside-press');\n  });\n  const closeOnPressOutsideCapture = useEffectEvent(event => {\n    var _getTarget4;\n    const callback = () => {\n      var _getTarget3;\n      closeOnPressOutside(event);\n      (_getTarget3 = getTarget$1(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);\n    };\n    (_getTarget4 = getTarget$1(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);\n  });\n  React.useEffect(() => {\n    if (!open || !enabled) {\n      return;\n    }\n    dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;\n    dataRef.current.__outsidePressBubbles = outsidePressBubbles;\n    let compositionTimeout = -1;\n    function onScroll(event) {\n      onOpenChange(false, event, 'ancestor-scroll');\n    }\n    function handleCompositionStart() {\n      window.clearTimeout(compositionTimeout);\n      isComposingRef.current = true;\n    }\n    function handleCompositionEnd() {\n      // Safari fires `compositionend` before `keydown`, so we need to wait\n      // until the next tick to set `isComposing` to `false`.\n      // https://bugs.webkit.org/show_bug.cgi?id=165004\n      compositionTimeout = window.setTimeout(() => {\n        isComposingRef.current = false;\n      },\n      // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.\n      // Only apply to WebKit for the test to remain 0ms.\n      isWebKit() ? 5 : 0);\n    }\n    const doc = getDocument$1(elements.floating);\n    if (escapeKey) {\n      doc.addEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);\n      doc.addEventListener('compositionstart', handleCompositionStart);\n      doc.addEventListener('compositionend', handleCompositionEnd);\n    }\n    outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);\n    let ancestors = [];\n    if (ancestorScroll) {\n      if (isElement(elements.domReference)) {\n        ancestors = getOverflowAncestors(elements.domReference);\n      }\n      if (isElement(elements.floating)) {\n        ancestors = ancestors.concat(getOverflowAncestors(elements.floating));\n      }\n      if (!isElement(elements.reference) && elements.reference && elements.reference.contextElement) {\n        ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));\n      }\n    }\n\n    // Ignore the visual viewport for scrolling dismissal (allow pinch-zoom)\n    ancestors = ancestors.filter(ancestor => {\n      var _doc$defaultView;\n      return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);\n    });\n    ancestors.forEach(ancestor => {\n      ancestor.addEventListener('scroll', onScroll, {\n        passive: true\n      });\n    });\n    return () => {\n      if (escapeKey) {\n        doc.removeEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);\n        doc.removeEventListener('compositionstart', handleCompositionStart);\n        doc.removeEventListener('compositionend', handleCompositionEnd);\n      }\n      outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);\n      ancestors.forEach(ancestor => {\n        ancestor.removeEventListener('scroll', onScroll);\n      });\n      window.clearTimeout(compositionTimeout);\n    };\n  }, [dataRef, elements, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);\n  React.useEffect(() => {\n    dataRef.current.insideReactTree = false;\n  }, [dataRef, outsidePress, outsidePressEvent]);\n  const reference = React.useMemo(() => ({\n    onKeyDown: closeOnEscapeKeyDown,\n    ...(referencePress && {\n      [bubbleHandlerKeys[referencePressEvent]]: event => {\n        onOpenChange(false, event.nativeEvent, 'reference-press');\n      },\n      ...(referencePressEvent !== 'click' && {\n        onClick(event) {\n          onOpenChange(false, event.nativeEvent, 'reference-press');\n        }\n      })\n    })\n  }), [closeOnEscapeKeyDown, onOpenChange, referencePress, referencePressEvent]);\n  const floating = React.useMemo(() => ({\n    onKeyDown: closeOnEscapeKeyDown,\n    onMouseDown() {\n      endedOrStartedInsideRef.current = true;\n    },\n    onMouseUp() {\n      endedOrStartedInsideRef.current = true;\n    },\n    [captureHandlerKeys[outsidePressEvent]]: () => {\n      dataRef.current.insideReactTree = true;\n    }\n  }), [closeOnEscapeKeyDown, outsidePressEvent, dataRef]);\n  return React.useMemo(() => enabled ? {\n    reference,\n    floating\n  } : {}, [enabled, reference, floating]);\n}\n\nfunction useFloatingRootContext(options) {\n  const {\n    open = false,\n    onOpenChange: onOpenChangeProp,\n    elements: elementsProp\n  } = options;\n  const floatingId = useId();\n  const dataRef = React.useRef({});\n  const [events] = React.useState(() => createEventEmitter());\n  const nested = useFloatingParentNodeId() != null;\n  if (process.env.NODE_ENV !== \"production\") {\n    const optionDomReference = elementsProp.reference;\n    if (optionDomReference && !isElement(optionDomReference)) {\n      error('Cannot pass a virtual element to the `elements.reference` option,', 'as it must be a real DOM element. Use `refs.setPositionReference()`', 'instead.');\n    }\n  }\n  const [positionReference, setPositionReference] = React.useState(elementsProp.reference);\n  const onOpenChange = useEffectEvent((open, event, reason) => {\n    dataRef.current.openEvent = open ? event : undefined;\n    events.emit('openchange', {\n      open,\n      event,\n      reason,\n      nested\n    });\n    onOpenChangeProp == null || onOpenChangeProp(open, event, reason);\n  });\n  const refs = React.useMemo(() => ({\n    setPositionReference\n  }), []);\n  const elements = React.useMemo(() => ({\n    reference: positionReference || elementsProp.reference || null,\n    floating: elementsProp.floating || null,\n    domReference: elementsProp.reference\n  }), [positionReference, elementsProp.reference, elementsProp.floating]);\n  return React.useMemo(() => ({\n    dataRef,\n    open,\n    onOpenChange,\n    elements,\n    events,\n    floatingId,\n    refs\n  }), [open, onOpenChange, elements, events, floatingId, refs]);\n}\n\n/**\n * Provides data to position a floating element and context to add interactions.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    nodeId\n  } = options;\n  const internalRootContext = useFloatingRootContext({\n    ...options,\n    elements: {\n      reference: null,\n      floating: null,\n      ...options.elements\n    }\n  });\n  const rootContext = options.rootContext || internalRootContext;\n  const computedElements = rootContext.elements;\n  const [_domReference, setDomReference] = React.useState(null);\n  const [positionReference, _setPositionReference] = React.useState(null);\n  const optionDomReference = computedElements == null ? void 0 : computedElements.domReference;\n  const domReference = optionDomReference || _domReference;\n  const domReferenceRef = React.useRef(null);\n  const tree = useFloatingTree();\n  useModernLayoutEffect(() => {\n    if (domReference) {\n      domReferenceRef.current = domReference;\n    }\n  }, [domReference]);\n  const position = useFloating$1({\n    ...options,\n    elements: {\n      ...computedElements,\n      ...(positionReference && {\n        reference: positionReference\n      })\n    }\n  });\n  const setPositionReference = React.useCallback(node => {\n    const computedPositionReference = isElement(node) ? {\n      getBoundingClientRect: () => node.getBoundingClientRect(),\n      getClientRects: () => node.getClientRects(),\n      contextElement: node\n    } : node;\n    // Store the positionReference in state if the DOM reference is specified externally via the\n    // `elements.reference` option. This ensures that it won't be overridden on future renders.\n    _setPositionReference(computedPositionReference);\n    position.refs.setReference(computedPositionReference);\n  }, [position.refs]);\n  const setReference = React.useCallback(node => {\n    if (isElement(node) || node === null) {\n      domReferenceRef.current = node;\n      setDomReference(node);\n    }\n\n    // Backwards-compatibility for passing a virtual element to `reference`\n    // after it has set the DOM reference.\n    if (isElement(position.refs.reference.current) || position.refs.reference.current === null ||\n    // Don't allow setting virtual elements using the old technique back to\n    // `null` to support `positionReference` + an unstable `reference`\n    // callback ref.\n    node !== null && !isElement(node)) {\n      position.refs.setReference(node);\n    }\n  }, [position.refs]);\n  const refs = React.useMemo(() => ({\n    ...position.refs,\n    setReference,\n    setPositionReference,\n    domReference: domReferenceRef\n  }), [position.refs, setReference, setPositionReference]);\n  const elements = React.useMemo(() => ({\n    ...position.elements,\n    domReference: domReference\n  }), [position.elements, domReference]);\n  const context = React.useMemo(() => ({\n    ...position,\n    ...rootContext,\n    refs,\n    elements,\n    nodeId\n  }), [position, refs, elements, nodeId, rootContext]);\n  useModernLayoutEffect(() => {\n    rootContext.dataRef.current.floatingContext = context;\n    const node = tree == null ? void 0 : tree.nodesRef.current.find(node => node.id === nodeId);\n    if (node) {\n      node.context = context;\n    }\n  });\n  return React.useMemo(() => ({\n    ...position,\n    context,\n    refs,\n    elements\n  }), [position, refs, elements, context]);\n}\n\nfunction isMacSafari() {\n  return isMac() && isSafari();\n}\n/**\n * Opens the floating element while the reference element has focus, like CSS\n * `:focus`.\n * @see https://floating-ui.com/docs/useFocus\n */\nfunction useFocus(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    onOpenChange,\n    events,\n    dataRef,\n    elements\n  } = context;\n  const {\n    enabled = true,\n    visibleOnly = true\n  } = props;\n  const blockFocusRef = React.useRef(false);\n  const timeoutRef = React.useRef(-1);\n  const keyboardModalityRef = React.useRef(true);\n  React.useEffect(() => {\n    if (!enabled) return;\n    const win = getWindow(elements.domReference);\n\n    // If the reference was focused and the user left the tab/window, and the\n    // floating element was not open, the focus should be blocked when they\n    // return to the tab/window.\n    function onBlur() {\n      if (!open && isHTMLElement(elements.domReference) && elements.domReference === activeElement(getDocument$1(elements.domReference))) {\n        blockFocusRef.current = true;\n      }\n    }\n    function onKeyDown() {\n      keyboardModalityRef.current = true;\n    }\n    function onPointerDown() {\n      keyboardModalityRef.current = false;\n    }\n    win.addEventListener('blur', onBlur);\n    if (isMacSafari()) {\n      win.addEventListener('keydown', onKeyDown, true);\n      win.addEventListener('pointerdown', onPointerDown, true);\n    }\n    return () => {\n      win.removeEventListener('blur', onBlur);\n      if (isMacSafari()) {\n        win.removeEventListener('keydown', onKeyDown, true);\n        win.removeEventListener('pointerdown', onPointerDown, true);\n      }\n    };\n  }, [elements.domReference, open, enabled]);\n  React.useEffect(() => {\n    if (!enabled) return;\n    function onOpenChange(_ref) {\n      let {\n        reason\n      } = _ref;\n      if (reason === 'reference-press' || reason === 'escape-key') {\n        blockFocusRef.current = true;\n      }\n    }\n    events.on('openchange', onOpenChange);\n    return () => {\n      events.off('openchange', onOpenChange);\n    };\n  }, [events, enabled]);\n  React.useEffect(() => {\n    return () => {\n      clearTimeoutIfSet(timeoutRef);\n    };\n  }, []);\n  const reference = React.useMemo(() => ({\n    onMouseLeave() {\n      blockFocusRef.current = false;\n    },\n    onFocus(event) {\n      if (blockFocusRef.current) return;\n      const target = getTarget$1(event.nativeEvent);\n      if (visibleOnly && isElement(target)) {\n        // Safari fails to match `:focus-visible` if focus was initially\n        // outside the document.\n        if (isMacSafari() && !event.relatedTarget) {\n          if (!keyboardModalityRef.current && !isTypeableElement(target)) {\n            return;\n          }\n        } else if (!matchesFocusVisible(target)) {\n          return;\n        }\n      }\n      onOpenChange(true, event.nativeEvent, 'focus');\n    },\n    onBlur(event) {\n      blockFocusRef.current = false;\n      const relatedTarget = event.relatedTarget;\n      const nativeEvent = event.nativeEvent;\n\n      // Hit the non-modal focus management portal guard. Focus will be\n      // moved into the floating element immediately after.\n      const movedToFocusGuard = isElement(relatedTarget) && relatedTarget.hasAttribute(createAttribute('focus-guard')) && relatedTarget.getAttribute('data-type') === 'outside';\n\n      // Wait for the window blur listener to fire.\n      timeoutRef.current = window.setTimeout(() => {\n        var _dataRef$current$floa;\n        const activeEl = activeElement(elements.domReference ? elements.domReference.ownerDocument : document);\n\n        // Focus left the page, keep it open.\n        if (!relatedTarget && activeEl === elements.domReference) return;\n\n        // When focusing the reference element (e.g. regular click), then\n        // clicking into the floating element, prevent it from hiding.\n        // Note: it must be focusable, e.g. `tabindex=\"-1\"`.\n        // We can not rely on relatedTarget to point to the correct element\n        // as it will only point to the shadow host of the newly focused element\n        // and not the element that actually has received focus if it is located\n        // inside a shadow root.\n        if (contains$1((_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.refs.floating.current, activeEl) || contains$1(elements.domReference, activeEl) || movedToFocusGuard) {\n          return;\n        }\n        onOpenChange(false, nativeEvent, 'focus');\n      });\n    }\n  }), [dataRef, elements.domReference, onOpenChange, visibleOnly]);\n  return React.useMemo(() => enabled ? {\n    reference\n  } : {}, [enabled, reference]);\n}\n\nfunction mergeProps(userProps, propsList, elementKey) {\n  const map = new Map();\n  const isItem = elementKey === 'item';\n  let domUserProps = userProps;\n  if (isItem && userProps) {\n    const {\n      [ACTIVE_KEY]: _,\n      [SELECTED_KEY]: __,\n      ...validProps\n    } = userProps;\n    domUserProps = validProps;\n  }\n  return {\n    ...(elementKey === 'floating' && {\n      tabIndex: -1,\n      [FOCUSABLE_ATTRIBUTE]: ''\n    }),\n    ...domUserProps,\n    ...propsList.map(value => {\n      const propsOrGetProps = value ? value[elementKey] : null;\n      if (typeof propsOrGetProps === 'function') {\n        return userProps ? propsOrGetProps(userProps) : null;\n      }\n      return propsOrGetProps;\n    }).concat(userProps).reduce((acc, props) => {\n      if (!props) {\n        return acc;\n      }\n      Object.entries(props).forEach(_ref => {\n        let [key, value] = _ref;\n        if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {\n          return;\n        }\n        if (key.indexOf('on') === 0) {\n          if (!map.has(key)) {\n            map.set(key, []);\n          }\n          if (typeof value === 'function') {\n            var _map$get;\n            (_map$get = map.get(key)) == null || _map$get.push(value);\n            acc[key] = function () {\n              var _map$get2;\n              for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n                args[_key] = arguments[_key];\n              }\n              return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map(fn => fn(...args)).find(val => val !== undefined);\n            };\n          }\n        } else {\n          acc[key] = value;\n        }\n      });\n      return acc;\n    }, {})\n  };\n}\n/**\n * Merges an array of interaction hooks' props into prop getters, allowing\n * event handler functions to be composed together without overwriting one\n * another.\n * @see https://floating-ui.com/docs/useInteractions\n */\nfunction useInteractions(propsList) {\n  if (propsList === void 0) {\n    propsList = [];\n  }\n  const referenceDeps = propsList.map(key => key == null ? void 0 : key.reference);\n  const floatingDeps = propsList.map(key => key == null ? void 0 : key.floating);\n  const itemDeps = propsList.map(key => key == null ? void 0 : key.item);\n  const getReferenceProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  referenceDeps);\n  const getFloatingProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  floatingDeps);\n  const getItemProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'item'),\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  itemDeps);\n  return React.useMemo(() => ({\n    getReferenceProps,\n    getFloatingProps,\n    getItemProps\n  }), [getReferenceProps, getFloatingProps, getItemProps]);\n}\n\nconst ESCAPE = 'Escape';\nfunction doSwitch(orientation, vertical, horizontal) {\n  switch (orientation) {\n    case 'vertical':\n      return vertical;\n    case 'horizontal':\n      return horizontal;\n    default:\n      return vertical || horizontal;\n  }\n}\nfunction isMainOrientationKey(key, orientation) {\n  const vertical = key === ARROW_UP || key === ARROW_DOWN;\n  const horizontal = key === ARROW_LEFT || key === ARROW_RIGHT;\n  return doSwitch(orientation, vertical, horizontal);\n}\nfunction isMainOrientationToEndKey(key, orientation, rtl) {\n  const vertical = key === ARROW_DOWN;\n  const horizontal = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;\n  return doSwitch(orientation, vertical, horizontal) || key === 'Enter' || key === ' ' || key === '';\n}\nfunction isCrossOrientationOpenKey(key, orientation, rtl) {\n  const vertical = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;\n  const horizontal = key === ARROW_DOWN;\n  return doSwitch(orientation, vertical, horizontal);\n}\nfunction isCrossOrientationCloseKey(key, orientation, rtl, cols) {\n  const vertical = rtl ? key === ARROW_RIGHT : key === ARROW_LEFT;\n  const horizontal = key === ARROW_UP;\n  if (orientation === 'both' || orientation === 'horizontal' && cols && cols > 1) {\n    return key === ESCAPE;\n  }\n  return doSwitch(orientation, vertical, horizontal);\n}\n/**\n * Adds arrow key-based navigation of a list of items, either using real DOM\n * focus or virtual focus.\n * @see https://floating-ui.com/docs/useListNavigation\n */\nfunction useListNavigation(context, props) {\n  const {\n    open,\n    onOpenChange,\n    elements,\n    floatingId\n  } = context;\n  const {\n    listRef,\n    activeIndex,\n    onNavigate: unstable_onNavigate = () => {},\n    enabled = true,\n    selectedIndex = null,\n    allowEscape = false,\n    loop = false,\n    nested = false,\n    rtl = false,\n    virtual = false,\n    focusItemOnOpen = 'auto',\n    focusItemOnHover = true,\n    openOnArrowKeyDown = true,\n    disabledIndices = undefined,\n    orientation = 'vertical',\n    parentOrientation,\n    cols = 1,\n    scrollItemIntoView = true,\n    virtualItemRef,\n    itemSizes,\n    dense = false\n  } = props;\n  if (process.env.NODE_ENV !== \"production\") {\n    if (allowEscape) {\n      if (!loop) {\n        warn('`useListNavigation` looping must be enabled to allow escaping.');\n      }\n      if (!virtual) {\n        warn('`useListNavigation` must be virtual to allow escaping.');\n      }\n    }\n    if (orientation === 'vertical' && cols > 1) {\n      warn('In grid list navigation mode (`cols` > 1), the `orientation` should', 'be either \"horizontal\" or \"both\".');\n    }\n  }\n  const floatingFocusElement = getFloatingFocusElement(elements.floating);\n  const floatingFocusElementRef = useLatestRef(floatingFocusElement);\n  const parentId = useFloatingParentNodeId();\n  const tree = useFloatingTree();\n  useModernLayoutEffect(() => {\n    context.dataRef.current.orientation = orientation;\n  }, [context, orientation]);\n  const onNavigate = useEffectEvent(() => {\n    unstable_onNavigate(indexRef.current === -1 ? null : indexRef.current);\n  });\n  const typeableComboboxReference = isTypeableCombobox(elements.domReference);\n  const focusItemOnOpenRef = React.useRef(focusItemOnOpen);\n  const indexRef = React.useRef(selectedIndex != null ? selectedIndex : -1);\n  const keyRef = React.useRef(null);\n  const isPointerModalityRef = React.useRef(true);\n  const previousOnNavigateRef = React.useRef(onNavigate);\n  const previousMountedRef = React.useRef(!!elements.floating);\n  const previousOpenRef = React.useRef(open);\n  const forceSyncFocusRef = React.useRef(false);\n  const forceScrollIntoViewRef = React.useRef(false);\n  const disabledIndicesRef = useLatestRef(disabledIndices);\n  const latestOpenRef = useLatestRef(open);\n  const scrollItemIntoViewRef = useLatestRef(scrollItemIntoView);\n  const selectedIndexRef = useLatestRef(selectedIndex);\n  const [activeId, setActiveId] = React.useState();\n  const [virtualId, setVirtualId] = React.useState();\n  const focusItem = useEffectEvent(() => {\n    function runFocus(item) {\n      if (virtual) {\n        var _item$id;\n        if ((_item$id = item.id) != null && _item$id.endsWith('-fui-option')) {\n          item.id = floatingId + \"-\" + Math.random().toString(16).slice(2, 10);\n        }\n        setActiveId(item.id);\n        tree == null || tree.events.emit('virtualfocus', item);\n        if (virtualItemRef) {\n          virtualItemRef.current = item;\n        }\n      } else {\n        enqueueFocus(item, {\n          sync: forceSyncFocusRef.current,\n          preventScroll: true\n        });\n      }\n    }\n    const initialItem = listRef.current[indexRef.current];\n    const forceScrollIntoView = forceScrollIntoViewRef.current;\n    if (initialItem) {\n      runFocus(initialItem);\n    }\n    const scheduler = forceSyncFocusRef.current ? v => v() : requestAnimationFrame;\n    scheduler(() => {\n      const waitedItem = listRef.current[indexRef.current] || initialItem;\n      if (!waitedItem) return;\n      if (!initialItem) {\n        runFocus(waitedItem);\n      }\n      const scrollIntoViewOptions = scrollItemIntoViewRef.current;\n      const shouldScrollIntoView = scrollIntoViewOptions && item && (forceScrollIntoView || !isPointerModalityRef.current);\n      if (shouldScrollIntoView) {\n        // JSDOM doesn't support `.scrollIntoView()` but it's widely supported\n        // by all browsers.\n        waitedItem.scrollIntoView == null || waitedItem.scrollIntoView(typeof scrollIntoViewOptions === 'boolean' ? {\n          block: 'nearest',\n          inline: 'nearest'\n        } : scrollIntoViewOptions);\n      }\n    });\n  });\n\n  // Sync `selectedIndex` to be the `activeIndex` upon opening the floating\n  // element. Also, reset `activeIndex` upon closing the floating element.\n  useModernLayoutEffect(() => {\n    if (!enabled) return;\n    if (open && elements.floating) {\n      if (focusItemOnOpenRef.current && selectedIndex != null) {\n        // Regardless of the pointer modality, we want to ensure the selected\n        // item comes into view when the floating element is opened.\n        forceScrollIntoViewRef.current = true;\n        indexRef.current = selectedIndex;\n        onNavigate();\n      }\n    } else if (previousMountedRef.current) {\n      // Since the user can specify `onNavigate` conditionally\n      // (onNavigate: open ? setActiveIndex : setSelectedIndex),\n      // we store and call the previous function.\n      indexRef.current = -1;\n      previousOnNavigateRef.current();\n    }\n  }, [enabled, open, elements.floating, selectedIndex, onNavigate]);\n\n  // Sync `activeIndex` to be the focused item while the floating element is\n  // open.\n  useModernLayoutEffect(() => {\n    if (!enabled) return;\n    if (!open) return;\n    if (!elements.floating) return;\n    if (activeIndex == null) {\n      forceSyncFocusRef.current = false;\n      if (selectedIndexRef.current != null) {\n        return;\n      }\n\n      // Reset while the floating element was open (e.g. the list changed).\n      if (previousMountedRef.current) {\n        indexRef.current = -1;\n        focusItem();\n      }\n\n      // Initial sync.\n      if ((!previousOpenRef.current || !previousMountedRef.current) && focusItemOnOpenRef.current && (keyRef.current != null || focusItemOnOpenRef.current === true && keyRef.current == null)) {\n        let runs = 0;\n        const waitForListPopulated = () => {\n          if (listRef.current[0] == null) {\n            // Avoid letting the browser paint if possible on the first try,\n            // otherwise use rAF. Don't try more than twice, since something\n            // is wrong otherwise.\n            if (runs < 2) {\n              const scheduler = runs ? requestAnimationFrame : queueMicrotask;\n              scheduler(waitForListPopulated);\n            }\n            runs++;\n          } else {\n            indexRef.current = keyRef.current == null || isMainOrientationToEndKey(keyRef.current, orientation, rtl) || nested ? getMinListIndex(listRef, disabledIndicesRef.current) : getMaxListIndex(listRef, disabledIndicesRef.current);\n            keyRef.current = null;\n            onNavigate();\n          }\n        };\n        waitForListPopulated();\n      }\n    } else if (!isIndexOutOfListBounds(listRef, activeIndex)) {\n      indexRef.current = activeIndex;\n      focusItem();\n      forceScrollIntoViewRef.current = false;\n    }\n  }, [enabled, open, elements.floating, activeIndex, selectedIndexRef, nested, listRef, orientation, rtl, onNavigate, focusItem, disabledIndicesRef]);\n\n  // Ensure the parent floating element has focus when a nested child closes\n  // to allow arrow key navigation to work after the pointer leaves the child.\n  useModernLayoutEffect(() => {\n    var _nodes$find;\n    if (!enabled || elements.floating || !tree || virtual || !previousMountedRef.current) {\n      return;\n    }\n    const nodes = tree.nodesRef.current;\n    const parent = (_nodes$find = nodes.find(node => node.id === parentId)) == null || (_nodes$find = _nodes$find.context) == null ? void 0 : _nodes$find.elements.floating;\n    const activeEl = activeElement(getDocument$1(elements.floating));\n    const treeContainsActiveEl = nodes.some(node => node.context && contains$1(node.context.elements.floating, activeEl));\n    if (parent && !treeContainsActiveEl && isPointerModalityRef.current) {\n      parent.focus({\n        preventScroll: true\n      });\n    }\n  }, [enabled, elements.floating, tree, parentId, virtual]);\n  useModernLayoutEffect(() => {\n    if (!enabled) return;\n    if (!tree) return;\n    if (!virtual) return;\n    if (parentId) return;\n    function handleVirtualFocus(item) {\n      setVirtualId(item.id);\n      if (virtualItemRef) {\n        virtualItemRef.current = item;\n      }\n    }\n    tree.events.on('virtualfocus', handleVirtualFocus);\n    return () => {\n      tree.events.off('virtualfocus', handleVirtualFocus);\n    };\n  }, [enabled, tree, virtual, parentId, virtualItemRef]);\n  useModernLayoutEffect(() => {\n    previousOnNavigateRef.current = onNavigate;\n    previousOpenRef.current = open;\n    previousMountedRef.current = !!elements.floating;\n  });\n  useModernLayoutEffect(() => {\n    if (!open) {\n      keyRef.current = null;\n      focusItemOnOpenRef.current = focusItemOnOpen;\n    }\n  }, [open, focusItemOnOpen]);\n  const hasActiveIndex = activeIndex != null;\n  const item = React.useMemo(() => {\n    function syncCurrentTarget(currentTarget) {\n      if (!latestOpenRef.current) return;\n      const index = listRef.current.indexOf(currentTarget);\n      if (index !== -1 && indexRef.current !== index) {\n        indexRef.current = index;\n        onNavigate();\n      }\n    }\n    const props = {\n      onFocus(_ref) {\n        let {\n          currentTarget\n        } = _ref;\n        forceSyncFocusRef.current = true;\n        syncCurrentTarget(currentTarget);\n      },\n      onClick: _ref2 => {\n        let {\n          currentTarget\n        } = _ref2;\n        return currentTarget.focus({\n          preventScroll: true\n        });\n      },\n      // Safari\n      onMouseMove(_ref3) {\n        let {\n          currentTarget\n        } = _ref3;\n        forceSyncFocusRef.current = true;\n        forceScrollIntoViewRef.current = false;\n        if (focusItemOnHover) {\n          syncCurrentTarget(currentTarget);\n        }\n      },\n      onPointerLeave(_ref4) {\n        let {\n          pointerType\n        } = _ref4;\n        if (!isPointerModalityRef.current || pointerType === 'touch') {\n          return;\n        }\n        forceSyncFocusRef.current = true;\n        if (!focusItemOnHover) {\n          return;\n        }\n        indexRef.current = -1;\n        onNavigate();\n        if (!virtual) {\n          var _floatingFocusElement;\n          (_floatingFocusElement = floatingFocusElementRef.current) == null || _floatingFocusElement.focus({\n            preventScroll: true\n          });\n        }\n      }\n    };\n    return props;\n  }, [latestOpenRef, floatingFocusElementRef, focusItemOnHover, listRef, onNavigate, virtual]);\n  const getParentOrientation = React.useCallback(() => {\n    var _tree$nodesRef$curren;\n    return parentOrientation != null ? parentOrientation : tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.dataRef) == null ? void 0 : _tree$nodesRef$curren.current.orientation;\n  }, [parentId, tree, parentOrientation]);\n  const commonOnKeyDown = useEffectEvent(event => {\n    isPointerModalityRef.current = false;\n    forceSyncFocusRef.current = true;\n\n    // When composing a character, Chrome fires ArrowDown twice. Firefox/Safari\n    // don't appear to suffer from this. `event.isComposing` is avoided due to\n    // Safari not supporting it properly (although it's not needed in the first\n    // place for Safari, just avoiding any possible issues).\n    if (event.which === 229) {\n      return;\n    }\n\n    // If the floating element is animating out, ignore navigation. Otherwise,\n    // the `activeIndex` gets set to 0 despite not being open so the next time\n    // the user ArrowDowns, the first item won't be focused.\n    if (!latestOpenRef.current && event.currentTarget === floatingFocusElementRef.current) {\n      return;\n    }\n    if (nested && isCrossOrientationCloseKey(event.key, orientation, rtl, cols)) {\n      // If the nested list's close key is also the parent navigation key,\n      // let the parent navigate. Otherwise, stop propagating the event.\n      if (!isMainOrientationKey(event.key, getParentOrientation())) {\n        stopEvent(event);\n      }\n      onOpenChange(false, event.nativeEvent, 'list-navigation');\n      if (isHTMLElement(elements.domReference)) {\n        if (virtual) {\n          tree == null || tree.events.emit('virtualfocus', elements.domReference);\n        } else {\n          elements.domReference.focus();\n        }\n      }\n      return;\n    }\n    const currentIndex = indexRef.current;\n    const minIndex = getMinListIndex(listRef, disabledIndices);\n    const maxIndex = getMaxListIndex(listRef, disabledIndices);\n    if (!typeableComboboxReference) {\n      if (event.key === 'Home') {\n        stopEvent(event);\n        indexRef.current = minIndex;\n        onNavigate();\n      }\n      if (event.key === 'End') {\n        stopEvent(event);\n        indexRef.current = maxIndex;\n        onNavigate();\n      }\n    }\n\n    // Grid navigation.\n    if (cols > 1) {\n      const sizes = itemSizes || Array.from({\n        length: listRef.current.length\n      }, () => ({\n        width: 1,\n        height: 1\n      }));\n      // To calculate movements on the grid, we use hypothetical cell indices\n      // as if every item was 1x1, then convert back to real indices.\n      const cellMap = createGridCellMap(sizes, cols, dense);\n      const minGridIndex = cellMap.findIndex(index => index != null && !isListIndexDisabled(listRef, index, disabledIndices));\n      // last enabled index\n      const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isListIndexDisabled(listRef, index, disabledIndices) ? cellIndex : foundIndex, -1);\n      const index = cellMap[getGridNavigatedIndex({\n        current: cellMap.map(itemIndex => itemIndex != null ? listRef.current[itemIndex] : null)\n      }, {\n        event,\n        orientation,\n        loop,\n        rtl,\n        cols,\n        // treat undefined (empty grid spaces) as disabled indices so we\n        // don't end up in them\n        disabledIndices: getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || listRef.current.map((_, index) => isListIndexDisabled(listRef, index, disabledIndices) ? index : undefined)), undefined], cellMap),\n        minIndex: minGridIndex,\n        maxIndex: maxGridIndex,\n        prevIndex: getGridCellIndexOfCorner(indexRef.current > maxIndex ? minIndex : indexRef.current, sizes, cellMap, cols,\n        // use a corner matching the edge closest to the direction\n        // we're moving in so we don't end up in the same item. Prefer\n        // top/left over bottom/right.\n        event.key === ARROW_DOWN ? 'bl' : event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT) ? 'tr' : 'tl'),\n        stopEvent: true\n      })];\n      if (index != null) {\n        indexRef.current = index;\n        onNavigate();\n      }\n      if (orientation === 'both') {\n        return;\n      }\n    }\n    if (isMainOrientationKey(event.key, orientation)) {\n      stopEvent(event);\n\n      // Reset the index if no item is focused.\n      if (open && !virtual && activeElement(event.currentTarget.ownerDocument) === event.currentTarget) {\n        indexRef.current = isMainOrientationToEndKey(event.key, orientation, rtl) ? minIndex : maxIndex;\n        onNavigate();\n        return;\n      }\n      if (isMainOrientationToEndKey(event.key, orientation, rtl)) {\n        if (loop) {\n          indexRef.current = currentIndex >= maxIndex ? allowEscape && currentIndex !== listRef.current.length ? -1 : minIndex : findNonDisabledListIndex(listRef, {\n            startingIndex: currentIndex,\n            disabledIndices\n          });\n        } else {\n          indexRef.current = Math.min(maxIndex, findNonDisabledListIndex(listRef, {\n            startingIndex: currentIndex,\n            disabledIndices\n          }));\n        }\n      } else {\n        if (loop) {\n          indexRef.current = currentIndex <= minIndex ? allowEscape && currentIndex !== -1 ? listRef.current.length : maxIndex : findNonDisabledListIndex(listRef, {\n            startingIndex: currentIndex,\n            decrement: true,\n            disabledIndices\n          });\n        } else {\n          indexRef.current = Math.max(minIndex, findNonDisabledListIndex(listRef, {\n            startingIndex: currentIndex,\n            decrement: true,\n            disabledIndices\n          }));\n        }\n      }\n      if (isIndexOutOfListBounds(listRef, indexRef.current)) {\n        indexRef.current = -1;\n      }\n      onNavigate();\n    }\n  });\n  const ariaActiveDescendantProp = React.useMemo(() => {\n    return virtual && open && hasActiveIndex && {\n      'aria-activedescendant': virtualId || activeId\n    };\n  }, [virtual, open, hasActiveIndex, virtualId, activeId]);\n  const floating = React.useMemo(() => {\n    return {\n      'aria-orientation': orientation === 'both' ? undefined : orientation,\n      ...(!typeableComboboxReference ? ariaActiveDescendantProp : {}),\n      onKeyDown: commonOnKeyDown,\n      onPointerMove() {\n        isPointerModalityRef.current = true;\n      }\n    };\n  }, [ariaActiveDescendantProp, commonOnKeyDown, orientation, typeableComboboxReference]);\n  const reference = React.useMemo(() => {\n    function checkVirtualMouse(event) {\n      if (focusItemOnOpen === 'auto' && isVirtualClick(event.nativeEvent)) {\n        focusItemOnOpenRef.current = true;\n      }\n    }\n    function checkVirtualPointer(event) {\n      // `pointerdown` fires first, reset the state then perform the checks.\n      focusItemOnOpenRef.current = focusItemOnOpen;\n      if (focusItemOnOpen === 'auto' && isVirtualPointerEvent(event.nativeEvent)) {\n        focusItemOnOpenRef.current = true;\n      }\n    }\n    return {\n      ...ariaActiveDescendantProp,\n      onKeyDown(event) {\n        isPointerModalityRef.current = false;\n        const isArrowKey = event.key.startsWith('Arrow');\n        const isHomeOrEndKey = ['Home', 'End'].includes(event.key);\n        const isMoveKey = isArrowKey || isHomeOrEndKey;\n        const isCrossOpenKey = isCrossOrientationOpenKey(event.key, orientation, rtl);\n        const isCrossCloseKey = isCrossOrientationCloseKey(event.key, orientation, rtl, cols);\n        const isParentCrossOpenKey = isCrossOrientationOpenKey(event.key, getParentOrientation(), rtl);\n        const isMainKey = isMainOrientationKey(event.key, orientation);\n        const isNavigationKey = (nested ? isParentCrossOpenKey : isMainKey) || event.key === 'Enter' || event.key.trim() === '';\n        if (virtual && open) {\n          const rootNode = tree == null ? void 0 : tree.nodesRef.current.find(node => node.parentId == null);\n          const deepestNode = tree && rootNode ? getDeepestNode(tree.nodesRef.current, rootNode.id) : null;\n          if (isMoveKey && deepestNode && virtualItemRef) {\n            const eventObject = new KeyboardEvent('keydown', {\n              key: event.key,\n              bubbles: true\n            });\n            if (isCrossOpenKey || isCrossCloseKey) {\n              var _deepestNode$context, _deepestNode$context2;\n              const isCurrentTarget = ((_deepestNode$context = deepestNode.context) == null ? void 0 : _deepestNode$context.elements.domReference) === event.currentTarget;\n              const dispatchItem = isCrossCloseKey && !isCurrentTarget ? (_deepestNode$context2 = deepestNode.context) == null ? void 0 : _deepestNode$context2.elements.domReference : isCrossOpenKey ? listRef.current.find(item => (item == null ? void 0 : item.id) === activeId) : null;\n              if (dispatchItem) {\n                stopEvent(event);\n                dispatchItem.dispatchEvent(eventObject);\n                setVirtualId(undefined);\n              }\n            }\n            if ((isMainKey || isHomeOrEndKey) && deepestNode.context) {\n              if (deepestNode.context.open && deepestNode.parentId && event.currentTarget !== deepestNode.context.elements.domReference) {\n                var _deepestNode$context$;\n                stopEvent(event);\n                (_deepestNode$context$ = deepestNode.context.elements.domReference) == null || _deepestNode$context$.dispatchEvent(eventObject);\n                return;\n              }\n            }\n          }\n          return commonOnKeyDown(event);\n        }\n        // If a floating element should not open on arrow key down, avoid\n        // setting `activeIndex` while it's closed.\n        if (!open && !openOnArrowKeyDown && isArrowKey) {\n          return;\n        }\n        if (isNavigationKey) {\n          const isParentMainKey = isMainOrientationKey(event.key, getParentOrientation());\n          keyRef.current = nested && isParentMainKey ? null : event.key;\n        }\n        if (nested) {\n          if (isParentCrossOpenKey) {\n            stopEvent(event);\n            if (open) {\n              indexRef.current = getMinListIndex(listRef, disabledIndicesRef.current);\n              onNavigate();\n            } else {\n              onOpenChange(true, event.nativeEvent, 'list-navigation');\n            }\n          }\n          return;\n        }\n        if (isMainKey) {\n          if (selectedIndex != null) {\n            indexRef.current = selectedIndex;\n          }\n          stopEvent(event);\n          if (!open && openOnArrowKeyDown) {\n            onOpenChange(true, event.nativeEvent, 'list-navigation');\n          } else {\n            commonOnKeyDown(event);\n          }\n          if (open) {\n            onNavigate();\n          }\n        }\n      },\n      onFocus() {\n        if (open && !virtual) {\n          indexRef.current = -1;\n          onNavigate();\n        }\n      },\n      onPointerDown: checkVirtualPointer,\n      onPointerEnter: checkVirtualPointer,\n      onMouseDown: checkVirtualMouse,\n      onClick: checkVirtualMouse\n    };\n  }, [activeId, ariaActiveDescendantProp, cols, commonOnKeyDown, disabledIndicesRef, focusItemOnOpen, listRef, nested, onNavigate, onOpenChange, open, openOnArrowKeyDown, orientation, getParentOrientation, rtl, selectedIndex, tree, virtual, virtualItemRef]);\n  return React.useMemo(() => enabled ? {\n    reference,\n    floating,\n    item\n  } : {}, [enabled, reference, floating, item]);\n}\n\nconst componentRoleToAriaRoleMap = /*#__PURE__*/new Map([['select', 'listbox'], ['combobox', 'listbox'], ['label', false]]);\n\n/**\n * Adds base screen reader props to the reference and floating elements for a\n * given floating element `role`.\n * @see https://floating-ui.com/docs/useRole\n */\nfunction useRole(context, props) {\n  var _elements$domReferenc, _componentRoleToAriaR;\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    elements,\n    floatingId: defaultFloatingId\n  } = context;\n  const {\n    enabled = true,\n    role = 'dialog'\n  } = props;\n  const defaultReferenceId = useId();\n  const referenceId = ((_elements$domReferenc = elements.domReference) == null ? void 0 : _elements$domReferenc.id) || defaultReferenceId;\n  const floatingId = React.useMemo(() => {\n    var _getFloatingFocusElem;\n    return ((_getFloatingFocusElem = getFloatingFocusElement(elements.floating)) == null ? void 0 : _getFloatingFocusElem.id) || defaultFloatingId;\n  }, [elements.floating, defaultFloatingId]);\n  const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;\n  const parentId = useFloatingParentNodeId();\n  const isNested = parentId != null;\n  const reference = React.useMemo(() => {\n    if (ariaRole === 'tooltip' || role === 'label') {\n      return {\n        [\"aria-\" + (role === 'label' ? 'labelledby' : 'describedby')]: open ? floatingId : undefined\n      };\n    }\n    return {\n      'aria-expanded': open ? 'true' : 'false',\n      'aria-haspopup': ariaRole === 'alertdialog' ? 'dialog' : ariaRole,\n      'aria-controls': open ? floatingId : undefined,\n      ...(ariaRole === 'listbox' && {\n        role: 'combobox'\n      }),\n      ...(ariaRole === 'menu' && {\n        id: referenceId\n      }),\n      ...(ariaRole === 'menu' && isNested && {\n        role: 'menuitem'\n      }),\n      ...(role === 'select' && {\n        'aria-autocomplete': 'none'\n      }),\n      ...(role === 'combobox' && {\n        'aria-autocomplete': 'list'\n      })\n    };\n  }, [ariaRole, floatingId, isNested, open, referenceId, role]);\n  const floating = React.useMemo(() => {\n    const floatingProps = {\n      id: floatingId,\n      ...(ariaRole && {\n        role: ariaRole\n      })\n    };\n    if (ariaRole === 'tooltip' || role === 'label') {\n      return floatingProps;\n    }\n    return {\n      ...floatingProps,\n      ...(ariaRole === 'menu' && {\n        'aria-labelledby': referenceId\n      })\n    };\n  }, [ariaRole, floatingId, referenceId, role]);\n  const item = React.useCallback(_ref => {\n    let {\n      active,\n      selected\n    } = _ref;\n    const commonProps = {\n      role: 'option',\n      ...(active && {\n        id: floatingId + \"-fui-option\"\n      })\n    };\n\n    // For `menu`, we are unable to tell if the item is a `menuitemradio`\n    // or `menuitemcheckbox`. For backwards-compatibility reasons, also\n    // avoid defaulting to `menuitem` as it may overwrite custom role props.\n    switch (role) {\n      case 'select':\n      case 'combobox':\n        return {\n          ...commonProps,\n          'aria-selected': selected\n        };\n    }\n    return {};\n  }, [floatingId, role]);\n  return React.useMemo(() => enabled ? {\n    reference,\n    floating,\n    item\n  } : {}, [enabled, reference, floating, item]);\n}\n\n// Converts a JS style key like `backgroundColor` to a CSS transition-property\n// like `background-color`.\nconst camelCaseToKebabCase = str => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\nfunction execWithArgsOrReturn(valueOrFn, args) {\n  return typeof valueOrFn === 'function' ? valueOrFn(args) : valueOrFn;\n}\nfunction useDelayUnmount(open, durationMs) {\n  const [isMounted, setIsMounted] = React.useState(open);\n  if (open && !isMounted) {\n    setIsMounted(true);\n  }\n  React.useEffect(() => {\n    if (!open && isMounted) {\n      const timeout = setTimeout(() => setIsMounted(false), durationMs);\n      return () => clearTimeout(timeout);\n    }\n  }, [open, isMounted, durationMs]);\n  return isMounted;\n}\n/**\n * Provides a status string to apply CSS transitions to a floating element,\n * correctly handling placement-aware transitions.\n * @see https://floating-ui.com/docs/useTransition#usetransitionstatus\n */\nfunction useTransitionStatus(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    open,\n    elements: {\n      floating\n    }\n  } = context;\n  const {\n    duration = 250\n  } = props;\n  const isNumberDuration = typeof duration === 'number';\n  const closeDuration = (isNumberDuration ? duration : duration.close) || 0;\n  const [status, setStatus] = React.useState('unmounted');\n  const isMounted = useDelayUnmount(open, closeDuration);\n  if (!isMounted && status === 'close') {\n    setStatus('unmounted');\n  }\n  useModernLayoutEffect(() => {\n    if (!floating) return;\n    if (open) {\n      setStatus('initial');\n      const frame = requestAnimationFrame(() => {\n        // Ensure it opens before paint. With `FloatingDelayGroup`,\n        // this avoids a flicker when moving between floating elements\n        // to ensure one is always open with no missing frames.\n        ReactDOM.flushSync(() => {\n          setStatus('open');\n        });\n      });\n      return () => {\n        cancelAnimationFrame(frame);\n      };\n    }\n    setStatus('close');\n  }, [open, floating]);\n  return {\n    isMounted,\n    status\n  };\n}\n/**\n * Provides styles to apply CSS transitions to a floating element, correctly\n * handling placement-aware transitions. Wrapper around `useTransitionStatus`.\n * @see https://floating-ui.com/docs/useTransition#usetransitionstyles\n */\nfunction useTransitionStyles(context, props) {\n  if (props === void 0) {\n    props = {};\n  }\n  const {\n    initial: unstable_initial = {\n      opacity: 0\n    },\n    open: unstable_open,\n    close: unstable_close,\n    common: unstable_common,\n    duration = 250\n  } = props;\n  const placement = context.placement;\n  const side = placement.split('-')[0];\n  const fnArgs = React.useMemo(() => ({\n    side,\n    placement\n  }), [side, placement]);\n  const isNumberDuration = typeof duration === 'number';\n  const openDuration = (isNumberDuration ? duration : duration.open) || 0;\n  const closeDuration = (isNumberDuration ? duration : duration.close) || 0;\n  const [styles, setStyles] = React.useState(() => ({\n    ...execWithArgsOrReturn(unstable_common, fnArgs),\n    ...execWithArgsOrReturn(unstable_initial, fnArgs)\n  }));\n  const {\n    isMounted,\n    status\n  } = useTransitionStatus(context, {\n    duration\n  });\n  const initialRef = useLatestRef(unstable_initial);\n  const openRef = useLatestRef(unstable_open);\n  const closeRef = useLatestRef(unstable_close);\n  const commonRef = useLatestRef(unstable_common);\n  useModernLayoutEffect(() => {\n    const initialStyles = execWithArgsOrReturn(initialRef.current, fnArgs);\n    const closeStyles = execWithArgsOrReturn(closeRef.current, fnArgs);\n    const commonStyles = execWithArgsOrReturn(commonRef.current, fnArgs);\n    const openStyles = execWithArgsOrReturn(openRef.current, fnArgs) || Object.keys(initialStyles).reduce((acc, key) => {\n      acc[key] = '';\n      return acc;\n    }, {});\n    if (status === 'initial') {\n      setStyles(styles => ({\n        transitionProperty: styles.transitionProperty,\n        ...commonStyles,\n        ...initialStyles\n      }));\n    }\n    if (status === 'open') {\n      setStyles({\n        transitionProperty: Object.keys(openStyles).map(camelCaseToKebabCase).join(','),\n        transitionDuration: openDuration + \"ms\",\n        ...commonStyles,\n        ...openStyles\n      });\n    }\n    if (status === 'close') {\n      const styles = closeStyles || initialStyles;\n      setStyles({\n        transitionProperty: Object.keys(styles).map(camelCaseToKebabCase).join(','),\n        transitionDuration: closeDuration + \"ms\",\n        ...commonStyles,\n        ...styles\n      });\n    }\n  }, [closeDuration, closeRef, initialRef, openRef, commonRef, openDuration, status, fnArgs]);\n  return {\n    isMounted,\n    styles\n  };\n}\n\n/**\n * Provides a matching callback that can be used to focus an item as the user\n * types, often used in tandem with `useListNavigation()`.\n * @see https://floating-ui.com/docs/useTypeahead\n */\nfunction useTypeahead(context, props) {\n  var _ref;\n  const {\n    open,\n    dataRef\n  } = context;\n  const {\n    listRef,\n    activeIndex,\n    onMatch: unstable_onMatch,\n    onTypingChange: unstable_onTypingChange,\n    enabled = true,\n    findMatch = null,\n    resetMs = 750,\n    ignoreKeys = [],\n    selectedIndex = null\n  } = props;\n  const timeoutIdRef = React.useRef(-1);\n  const stringRef = React.useRef('');\n  const prevIndexRef = React.useRef((_ref = selectedIndex != null ? selectedIndex : activeIndex) != null ? _ref : -1);\n  const matchIndexRef = React.useRef(null);\n  const onMatch = useEffectEvent(unstable_onMatch);\n  const onTypingChange = useEffectEvent(unstable_onTypingChange);\n  const findMatchRef = useLatestRef(findMatch);\n  const ignoreKeysRef = useLatestRef(ignoreKeys);\n  useModernLayoutEffect(() => {\n    if (open) {\n      clearTimeoutIfSet(timeoutIdRef);\n      matchIndexRef.current = null;\n      stringRef.current = '';\n    }\n  }, [open]);\n  useModernLayoutEffect(() => {\n    // Sync arrow key navigation but not typeahead navigation.\n    if (open && stringRef.current === '') {\n      var _ref2;\n      prevIndexRef.current = (_ref2 = selectedIndex != null ? selectedIndex : activeIndex) != null ? _ref2 : -1;\n    }\n  }, [open, selectedIndex, activeIndex]);\n  const setTypingChange = useEffectEvent(value => {\n    if (value) {\n      if (!dataRef.current.typing) {\n        dataRef.current.typing = value;\n        onTypingChange(value);\n      }\n    } else {\n      if (dataRef.current.typing) {\n        dataRef.current.typing = value;\n        onTypingChange(value);\n      }\n    }\n  });\n  const onKeyDown = useEffectEvent(event => {\n    function getMatchingIndex(list, orderedList, string) {\n      const str = findMatchRef.current ? findMatchRef.current(orderedList, string) : orderedList.find(text => (text == null ? void 0 : text.toLocaleLowerCase().indexOf(string.toLocaleLowerCase())) === 0);\n      return str ? list.indexOf(str) : -1;\n    }\n    const listContent = listRef.current;\n    if (stringRef.current.length > 0 && stringRef.current[0] !== ' ') {\n      if (getMatchingIndex(listContent, listContent, stringRef.current) === -1) {\n        setTypingChange(false);\n      } else if (event.key === ' ') {\n        stopEvent(event);\n      }\n    }\n    if (listContent == null || ignoreKeysRef.current.includes(event.key) ||\n    // Character key.\n    event.key.length !== 1 ||\n    // Modifier key.\n    event.ctrlKey || event.metaKey || event.altKey) {\n      return;\n    }\n    if (open && event.key !== ' ') {\n      stopEvent(event);\n      setTypingChange(true);\n    }\n\n    // Bail out if the list contains a word like \"llama\" or \"aaron\". TODO:\n    // allow it in this case, too.\n    const allowRapidSuccessionOfFirstLetter = listContent.every(text => {\n      var _text$, _text$2;\n      return text ? ((_text$ = text[0]) == null ? void 0 : _text$.toLocaleLowerCase()) !== ((_text$2 = text[1]) == null ? void 0 : _text$2.toLocaleLowerCase()) : true;\n    });\n\n    // Allows the user to cycle through items that start with the same letter\n    // in rapid succession.\n    if (allowRapidSuccessionOfFirstLetter && stringRef.current === event.key) {\n      stringRef.current = '';\n      prevIndexRef.current = matchIndexRef.current;\n    }\n    stringRef.current += event.key;\n    clearTimeoutIfSet(timeoutIdRef);\n    timeoutIdRef.current = window.setTimeout(() => {\n      stringRef.current = '';\n      prevIndexRef.current = matchIndexRef.current;\n      setTypingChange(false);\n    }, resetMs);\n    const prevIndex = prevIndexRef.current;\n    const index = getMatchingIndex(listContent, [...listContent.slice((prevIndex || 0) + 1), ...listContent.slice(0, (prevIndex || 0) + 1)], stringRef.current);\n    if (index !== -1) {\n      onMatch(index);\n      matchIndexRef.current = index;\n    } else if (event.key !== ' ') {\n      stringRef.current = '';\n      setTypingChange(false);\n    }\n  });\n  const reference = React.useMemo(() => ({\n    onKeyDown\n  }), [onKeyDown]);\n  const floating = React.useMemo(() => {\n    return {\n      onKeyDown,\n      onKeyUp(event) {\n        if (event.key === ' ') {\n          setTypingChange(false);\n        }\n      }\n    };\n  }, [onKeyDown, setTypingChange]);\n  return React.useMemo(() => enabled ? {\n    reference,\n    floating\n  } : {}, [enabled, reference, floating]);\n}\n\nfunction getArgsWithCustomFloatingHeight(state, height) {\n  return {\n    ...state,\n    rects: {\n      ...state.rects,\n      floating: {\n        ...state.rects.floating,\n        height\n      }\n    }\n  };\n}\n/**\n * Positions the floating element such that an inner element inside of it is\n * anchored to the reference element.\n * @see https://floating-ui.com/docs/inner\n * @deprecated\n */\nconst inner = props => ({\n  name: 'inner',\n  options: props,\n  async fn(state) {\n    const {\n      listRef,\n      overflowRef,\n      onFallbackChange,\n      offset: innerOffset = 0,\n      index = 0,\n      minItemsVisible = 4,\n      referenceOverflowThreshold = 0,\n      scrollRef,\n      ...detectOverflowOptions\n    } = evaluate(props, state);\n    const {\n      rects,\n      elements: {\n        floating\n      }\n    } = state;\n    const item = listRef.current[index];\n    const scrollEl = (scrollRef == null ? void 0 : scrollRef.current) || floating;\n\n    // Valid combinations:\n    // 1. Floating element is the scrollRef and has a border (default)\n    // 2. Floating element is not the scrollRef, floating element has a border\n    // 3. Floating element is not the scrollRef, scrollRef has a border\n    // Floating > {...getFloatingProps()} wrapper > scrollRef > items is not\n    // allowed as VoiceOver doesn't work.\n    const clientTop = floating.clientTop || scrollEl.clientTop;\n    const floatingIsBordered = floating.clientTop !== 0;\n    const scrollElIsBordered = scrollEl.clientTop !== 0;\n    const floatingIsScrollEl = floating === scrollEl;\n    if (process.env.NODE_ENV !== \"production\") {\n      if (!state.placement.startsWith('bottom')) {\n        warn('`placement` side must be \"bottom\" when using the `inner`', 'middleware.');\n      }\n    }\n    if (!item) {\n      return {};\n    }\n    const nextArgs = {\n      ...state,\n      ...(await offset(-item.offsetTop - floating.clientTop - rects.reference.height / 2 - item.offsetHeight / 2 - innerOffset).fn(state))\n    };\n    const overflow = await detectOverflow(getArgsWithCustomFloatingHeight(nextArgs, scrollEl.scrollHeight + clientTop + floating.clientTop), detectOverflowOptions);\n    const refOverflow = await detectOverflow(nextArgs, {\n      ...detectOverflowOptions,\n      elementContext: 'reference'\n    });\n    const diffY = max(0, overflow.top);\n    const nextY = nextArgs.y + diffY;\n    const isScrollable = scrollEl.scrollHeight > scrollEl.clientHeight;\n    const rounder = isScrollable ? v => v : round;\n    const maxHeight = rounder(max(0, scrollEl.scrollHeight + (floatingIsBordered && floatingIsScrollEl || scrollElIsBordered ? clientTop * 2 : 0) - diffY - max(0, overflow.bottom)));\n    scrollEl.style.maxHeight = maxHeight + \"px\";\n    scrollEl.scrollTop = diffY;\n\n    // There is not enough space, fallback to standard anchored positioning\n    if (onFallbackChange) {\n      const shouldFallback = scrollEl.offsetHeight < item.offsetHeight * min(minItemsVisible, listRef.current.length) - 1 || refOverflow.top >= -referenceOverflowThreshold || refOverflow.bottom >= -referenceOverflowThreshold;\n      ReactDOM.flushSync(() => onFallbackChange(shouldFallback));\n    }\n    if (overflowRef) {\n      overflowRef.current = await detectOverflow(getArgsWithCustomFloatingHeight({\n        ...nextArgs,\n        y: nextY\n      }, scrollEl.offsetHeight + clientTop + floating.clientTop), detectOverflowOptions);\n    }\n    return {\n      y: nextY\n    };\n  }\n});\n/**\n * Changes the `inner` middleware's `offset` upon a `wheel` event to\n * expand the floating element's height, revealing more list items.\n * @see https://floating-ui.com/docs/inner\n * @deprecated\n */\nfunction useInnerOffset(context, props) {\n  const {\n    open,\n    elements\n  } = context;\n  const {\n    enabled = true,\n    overflowRef,\n    scrollRef,\n    onChange: unstable_onChange\n  } = props;\n  const onChange = useEffectEvent(unstable_onChange);\n  const controlledScrollingRef = React.useRef(false);\n  const prevScrollTopRef = React.useRef(null);\n  const initialOverflowRef = React.useRef(null);\n  React.useEffect(() => {\n    if (!enabled) return;\n    function onWheel(e) {\n      if (e.ctrlKey || !el || overflowRef.current == null) {\n        return;\n      }\n      const dY = e.deltaY;\n      const isAtTop = overflowRef.current.top >= -0.5;\n      const isAtBottom = overflowRef.current.bottom >= -0.5;\n      const remainingScroll = el.scrollHeight - el.clientHeight;\n      const sign = dY < 0 ? -1 : 1;\n      const method = dY < 0 ? 'max' : 'min';\n      if (el.scrollHeight <= el.clientHeight) {\n        return;\n      }\n      if (!isAtTop && dY > 0 || !isAtBottom && dY < 0) {\n        e.preventDefault();\n        ReactDOM.flushSync(() => {\n          onChange(d => d + Math[method](dY, remainingScroll * sign));\n        });\n      } else if (/firefox/i.test(getUserAgent())) {\n        // Needed to propagate scrolling during momentum scrolling phase once\n        // it gets limited by the boundary. UX improvement, not critical.\n        el.scrollTop += dY;\n      }\n    }\n    const el = (scrollRef == null ? void 0 : scrollRef.current) || elements.floating;\n    if (open && el) {\n      el.addEventListener('wheel', onWheel);\n\n      // Wait for the position to be ready.\n      requestAnimationFrame(() => {\n        prevScrollTopRef.current = el.scrollTop;\n        if (overflowRef.current != null) {\n          initialOverflowRef.current = {\n            ...overflowRef.current\n          };\n        }\n      });\n      return () => {\n        prevScrollTopRef.current = null;\n        initialOverflowRef.current = null;\n        el.removeEventListener('wheel', onWheel);\n      };\n    }\n  }, [enabled, open, elements.floating, overflowRef, scrollRef, onChange]);\n  const floating = React.useMemo(() => ({\n    onKeyDown() {\n      controlledScrollingRef.current = true;\n    },\n    onWheel() {\n      controlledScrollingRef.current = false;\n    },\n    onPointerMove() {\n      controlledScrollingRef.current = false;\n    },\n    onScroll() {\n      const el = (scrollRef == null ? void 0 : scrollRef.current) || elements.floating;\n      if (!overflowRef.current || !el || !controlledScrollingRef.current) {\n        return;\n      }\n      if (prevScrollTopRef.current !== null) {\n        const scrollDiff = el.scrollTop - prevScrollTopRef.current;\n        if (overflowRef.current.bottom < -0.5 && scrollDiff < -1 || overflowRef.current.top < -0.5 && scrollDiff > 1) {\n          ReactDOM.flushSync(() => onChange(d => d + scrollDiff));\n        }\n      }\n\n      // [Firefox] Wait for the height change to have been applied.\n      requestAnimationFrame(() => {\n        prevScrollTopRef.current = el.scrollTop;\n      });\n    }\n  }), [elements.floating, onChange, overflowRef, scrollRef]);\n  return React.useMemo(() => enabled ? {\n    floating\n  } : {}, [enabled, floating]);\n}\n\nfunction getNodeChildren(nodes, id, onlyOpenChildren) {\n  if (onlyOpenChildren === void 0) {\n    onlyOpenChildren = true;\n  }\n  const directChildren = nodes.filter(node => {\n    var _node$context;\n    return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));\n  });\n  return directChildren.flatMap(child => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\n\nfunction isPointInPolygon(point, polygon) {\n  const [x, y] = point;\n  let isInside = false;\n  const length = polygon.length;\n  for (let i = 0, j = length - 1; i < length; j = i++) {\n    const [xi, yi] = polygon[i] || [0, 0];\n    const [xj, yj] = polygon[j] || [0, 0];\n    const intersect = yi >= y !== yj >= y && x <= (xj - xi) * (y - yi) / (yj - yi) + xi;\n    if (intersect) {\n      isInside = !isInside;\n    }\n  }\n  return isInside;\n}\nfunction isInside(point, rect) {\n  return point[0] >= rect.x && point[0] <= rect.x + rect.width && point[1] >= rect.y && point[1] <= rect.y + rect.height;\n}\n/**\n * Generates a safe polygon area that the user can traverse without closing the\n * floating element once leaving the reference element.\n * @see https://floating-ui.com/docs/useHover#safepolygon\n */\nfunction safePolygon(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    buffer = 0.5,\n    blockPointerEvents = false,\n    requireIntent = true\n  } = options;\n  const timeoutRef = {\n    current: -1\n  };\n  let hasLanded = false;\n  let lastX = null;\n  let lastY = null;\n  let lastCursorTime = typeof performance !== 'undefined' ? performance.now() : 0;\n  function getCursorSpeed(x, y) {\n    const currentTime = performance.now();\n    const elapsedTime = currentTime - lastCursorTime;\n    if (lastX === null || lastY === null || elapsedTime === 0) {\n      lastX = x;\n      lastY = y;\n      lastCursorTime = currentTime;\n      return null;\n    }\n    const deltaX = x - lastX;\n    const deltaY = y - lastY;\n    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n    const speed = distance / elapsedTime; // px / ms\n\n    lastX = x;\n    lastY = y;\n    lastCursorTime = currentTime;\n    return speed;\n  }\n  const fn = _ref => {\n    let {\n      x,\n      y,\n      placement,\n      elements,\n      onClose,\n      nodeId,\n      tree\n    } = _ref;\n    return function onMouseMove(event) {\n      function close() {\n        clearTimeoutIfSet(timeoutRef);\n        onClose();\n      }\n      clearTimeoutIfSet(timeoutRef);\n      if (!elements.domReference || !elements.floating || placement == null || x == null || y == null) {\n        return;\n      }\n      const {\n        clientX,\n        clientY\n      } = event;\n      const clientPoint = [clientX, clientY];\n      const target = getTarget(event);\n      const isLeave = event.type === 'mouseleave';\n      const isOverFloatingEl = contains(elements.floating, target);\n      const isOverReferenceEl = contains(elements.domReference, target);\n      const refRect = elements.domReference.getBoundingClientRect();\n      const rect = elements.floating.getBoundingClientRect();\n      const side = placement.split('-')[0];\n      const cursorLeaveFromRight = x > rect.right - rect.width / 2;\n      const cursorLeaveFromBottom = y > rect.bottom - rect.height / 2;\n      const isOverReferenceRect = isInside(clientPoint, refRect);\n      const isFloatingWider = rect.width > refRect.width;\n      const isFloatingTaller = rect.height > refRect.height;\n      const left = (isFloatingWider ? refRect : rect).left;\n      const right = (isFloatingWider ? refRect : rect).right;\n      const top = (isFloatingTaller ? refRect : rect).top;\n      const bottom = (isFloatingTaller ? refRect : rect).bottom;\n      if (isOverFloatingEl) {\n        hasLanded = true;\n        if (!isLeave) {\n          return;\n        }\n      }\n      if (isOverReferenceEl) {\n        hasLanded = false;\n      }\n      if (isOverReferenceEl && !isLeave) {\n        hasLanded = true;\n        return;\n      }\n\n      // Prevent overlapping floating element from being stuck in an open-close\n      // loop: https://github.com/floating-ui/floating-ui/issues/1910\n      if (isLeave && isElement(event.relatedTarget) && contains(elements.floating, event.relatedTarget)) {\n        return;\n      }\n\n      // If any nested child is open, abort.\n      if (tree && getNodeChildren(tree.nodesRef.current, nodeId).length) {\n        return;\n      }\n\n      // If the pointer is leaving from the opposite side, the \"buffer\" logic\n      // creates a point where the floating element remains open, but should be\n      // ignored.\n      // A constant of 1 handles floating point rounding errors.\n      if (side === 'top' && y >= refRect.bottom - 1 || side === 'bottom' && y <= refRect.top + 1 || side === 'left' && x >= refRect.right - 1 || side === 'right' && x <= refRect.left + 1) {\n        return close();\n      }\n\n      // Ignore when the cursor is within the rectangular trough between the\n      // two elements. Since the triangle is created from the cursor point,\n      // which can start beyond the ref element's edge, traversing back and\n      // forth from the ref to the floating element can cause it to close. This\n      // ensures it always remains open in that case.\n      let rectPoly = [];\n      switch (side) {\n        case 'top':\n          rectPoly = [[left, refRect.top + 1], [left, rect.bottom - 1], [right, rect.bottom - 1], [right, refRect.top + 1]];\n          break;\n        case 'bottom':\n          rectPoly = [[left, rect.top + 1], [left, refRect.bottom - 1], [right, refRect.bottom - 1], [right, rect.top + 1]];\n          break;\n        case 'left':\n          rectPoly = [[rect.right - 1, bottom], [rect.right - 1, top], [refRect.left + 1, top], [refRect.left + 1, bottom]];\n          break;\n        case 'right':\n          rectPoly = [[refRect.right - 1, bottom], [refRect.right - 1, top], [rect.left + 1, top], [rect.left + 1, bottom]];\n          break;\n      }\n      function getPolygon(_ref2) {\n        let [x, y] = _ref2;\n        switch (side) {\n          case 'top':\n            {\n              const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];\n              const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];\n              const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.bottom - buffer : isFloatingWider ? rect.bottom - buffer : rect.top], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.bottom - buffer : rect.top : rect.bottom - buffer]];\n              return [cursorPointOne, cursorPointTwo, ...commonPoints];\n            }\n          case 'bottom':\n            {\n              const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];\n              const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];\n              const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.top + buffer : isFloatingWider ? rect.top + buffer : rect.bottom], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.top + buffer : rect.bottom : rect.top + buffer]];\n              return [cursorPointOne, cursorPointTwo, ...commonPoints];\n            }\n          case 'left':\n            {\n              const cursorPointOne = [x + buffer + 1, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n              const cursorPointTwo = [x + buffer + 1, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n              const commonPoints = [[cursorLeaveFromBottom ? rect.right - buffer : isFloatingTaller ? rect.right - buffer : rect.left, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.right - buffer : rect.left : rect.right - buffer, rect.bottom]];\n              return [...commonPoints, cursorPointOne, cursorPointTwo];\n            }\n          case 'right':\n            {\n              const cursorPointOne = [x - buffer, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n              const cursorPointTwo = [x - buffer, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n              const commonPoints = [[cursorLeaveFromBottom ? rect.left + buffer : isFloatingTaller ? rect.left + buffer : rect.right, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.left + buffer : rect.right : rect.left + buffer, rect.bottom]];\n              return [cursorPointOne, cursorPointTwo, ...commonPoints];\n            }\n        }\n      }\n      if (isPointInPolygon([clientX, clientY], rectPoly)) {\n        return;\n      }\n      if (hasLanded && !isOverReferenceRect) {\n        return close();\n      }\n      if (!isLeave && requireIntent) {\n        const cursorSpeed = getCursorSpeed(event.clientX, event.clientY);\n        const cursorSpeedThreshold = 0.1;\n        if (cursorSpeed !== null && cursorSpeed < cursorSpeedThreshold) {\n          return close();\n        }\n      }\n      if (!isPointInPolygon([clientX, clientY], getPolygon([x, y]))) {\n        close();\n      } else if (!hasLanded && requireIntent) {\n        timeoutRef.current = window.setTimeout(close, 40);\n      }\n    };\n  };\n  fn.__options = {\n    blockPointerEvents\n  };\n  return fn;\n}\n\nexport { Composite, CompositeItem, FloatingArrow, FloatingDelayGroup, FloatingFocusManager, FloatingList, FloatingNode, FloatingOverlay, FloatingPortal, FloatingTree, NextFloatingDelayGroup, inner, safePolygon, useClick, useClientPoint, useDelayGroup, useDelayGroupContext, useDismiss, useFloating, useFloatingNodeId, useFloatingParentNodeId, useFloatingPortalNode, useFloatingRootContext, useFloatingTree, useFocus, useHover, useId, useInnerOffset, useInteractions, useListItem, useListNavigation, useMergeRefs, useNextDelayGroup, useRole, useTransitionStatus, useTransitionStyles, useTypeahead };\n","import { autoUpdate, flip, offset, type Placement, size, useFloating } from '@floating-ui/react'\n\nexport interface UseFloatingDropdownOptions {\n  placement?: Placement\n  offsetPx?: number\n  enabled?: boolean\n}\n\n/**\n * Hook for dropdown positioning using @floating-ui/react.\n * Handles viewport boundary detection and auto-positioning.\n */\nexport function useFloatingDropdown({\n  placement = 'bottom-start',\n  offsetPx = 4,\n  enabled = true,\n}: UseFloatingDropdownOptions = {}) {\n  const { refs, floatingStyles, context } = useFloating({\n    placement,\n    middleware: [\n      offset(offsetPx),\n      flip({\n        fallbackAxisSideDirection: 'end',\n        padding: 8,\n      }),\n      size({\n        apply({ rects, elements, availableHeight }) {\n          // Match dropdown width to trigger width, and cap its height to whatever\n          // room is actually available on the side `flip` picked — without this,\n          // a dropdown that flips upward (not enough space below the trigger) can\n          // render taller than the space above it and get clipped/cut off instead\n          // of shrinking to fit. `.lookup-field__options` fills the rest via flex.\n          Object.assign(elements.floating.style, {\n            minWidth: `${rects.reference.width}px`,\n            maxHeight: `${Math.max(availableHeight, 0)}px`,\n          })\n        },\n        padding: 8,\n      }),\n    ],\n    whileElementsMounted: enabled ? autoUpdate : undefined,\n  })\n\n  return {\n    refs,\n    floatingStyles,\n    context,\n  }\n}\n","import React, { useState, useEffect, useCallback, Fragment } from 'react';\nimport { createPortal } from 'react-dom';\nimport { Listbox, Transition } from '@headlessui/react';\nimport { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/20/solid';\nimport type { SelectProps, SelectOption } from './Select.types';\nimport { cn } from '../../lib/utils';\nimport { labelVariants } from '../Input/Input';\nimport { useFloatingDropdown } from '../LookupField/hooks/useFloatingDropdown';\n\nexport const Select: React.FC<SelectProps> = ({\n  options = [],\n  value,\n  defaultValue,\n  placeholder = 'Seleccionar...',\n  disabled = false,\n  error = false,\n  label,\n  description,\n  helperText,\n  errorMessage,\n  showLabel = true,\n  showDescription = true,\n  menuHeader,\n  onChange,\n  onBlur,\n  className = '',\n  id,\n  name,\n  required = false,\n  selectSize = 'base',\n  startIcon,\n  readOnly = false,\n  menuPosition = 'bottom',\n}) => {\n  const [selected, setSelected] = useState<SelectOption | undefined>(\n    options.find(opt => opt.value === value || opt.value === defaultValue)\n  );\n\n  useEffect(() => {\n    if (value !== undefined) {\n      setSelected(options.find(opt => opt.value === value));\n    }\n  }, [value, options]);\n\n  const handleChange = (option: SelectOption) => {\n    if (readOnly) return;\n    setSelected(option);\n    if (onChange) {\n      onChange(option.value);\n    }\n  };\n\n  const containerClasses = `\n    relative\n    w-full\n    ${className}\n  `.trim();\n\n  const sizeClasses = {\n    xs: \"h-7 px-2 py-1 text-xs\",\n    sm: \"h-8 px-2 py-1 text-sm\",\n    base: \"h-9 px-3 py-1.5 text-base\",\n    l: \"h-10 px-3 py-2 text-lg\",\n    xl: \"h-11 px-4 py-2 text-xl\",\n  };\n\n  const iconSizeMap = {\n    xs: \"w-3 h-3\",\n    sm: \"w-3.5 h-3.5\",\n    base: \"w-4 h-4\",\n    l: \"w-5 h-5\",\n    xl: \"w-6 h-6\",\n  };\n\n  const isDisabledState = disabled && !readOnly;\n\n  // Floating UI positioning — same pattern as LookupField (useFloatingDropdown +\n  // portal to document.body). Without this, `Listbox.Options` positions itself with\n  // `absolute` relative to its own wrapper, so a Select embedded in a constrained\n  // container (a table cell/column, a flex row with no overflow) doesn't overlay on\n  // top of it — the container grows/reflows to make room for the dropdown instead.\n  const [isOpen, setIsOpen] = useState(false);\n  const { refs: floatingRefs, floatingStyles } = useFloatingDropdown({\n    placement: menuPosition === 'top' ? 'top-start' : 'bottom-start',\n    enabled: isOpen,\n  });\n  // `Listbox.Options` unmounts (calls this ref with `null`) when Headless UI closes the\n  // dropdown, and mounts it again (real node) when it opens — using that as the signal\n  // for `isOpen` avoids re-deriving open state via a second, possibly-desynced source.\n  const setFloatingPanelRef = useCallback(\n    (node: HTMLUListElement | null) => {\n      floatingRefs.setFloating(node);\n      setIsOpen(node !== null);\n    },\n    [floatingRefs]\n  );\n\n  const buttonClasses = `\n    w-full flex items-center justify-between rounded-md border border-input transition-colors\n    focus:outline-none focus:ring-1 focus:ring-primary-400 focus:border-primary-400\n    ${readOnly ? 'bg-zinc-100 dark:bg-zinc-800/80 text-zinc-500 dark:text-zinc-400 focus:ring-0 focus:border-input focus:ring-offset-0 cursor-default' : 'bg-transparent'}\n    ${isDisabledState ? 'opacity-50 cursor-not-allowed bg-zinc-100 dark:bg-zinc-800/80 text-zinc-500 dark:text-zinc-400' : ''}\n    ${sizeClasses[selectSize]}\n    ${startIcon ? 'pl-9' : ''}\n    ${error ? 'border-destructive ring-1 ring-destructive focus:ring-destructive focus:border-destructive text-destructive' : ''}\n  `.trim();\n\n  return (\n    <div className={cn(\"grid w-full items-center gap-2\", className)}>\n      {(showLabel && label) || (showDescription && description) ? (\n        <div className=\"flex flex-col gap-2 w-full\">\n          {showLabel && label && (\n            <div className=\"flex items-center justify-between w-full\">\n              <label\n                htmlFor={id}\n                className={cn(\"text-content-primary dark:text-dark-content-primary\", labelVariants({ size: selectSize }))}\n              >\n                {label}\n                {required && <span className=\"text-destructive ml-1\">*</span>}\n              </label>\n            </div>\n          )}\n          {showDescription && description && (\n            <p className={cn(selectSize === 'xs' ? 'text-xs' : 'text-sm', error ? 'text-destructive' : 'text-muted-foreground')}>\n              {description}\n            </p>\n          )}\n        </div>\n      ) : null}\n\n      <Listbox value={selected} onChange={handleChange} disabled={disabled || readOnly} name={name}>\n        <div className=\"relative w-full\">\n          {startIcon && (\n            <div className={`absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none flex items-center justify-center z-10 ${error ? 'text-destructive' : 'text-muted-foreground'} ${iconSizeMap[selectSize]}`}>\n              {React.cloneElement(startIcon as React.ReactElement<any>, {\n                className: cn((startIcon as React.ReactElement<any>).props.className, iconSizeMap[selectSize])\n              })}\n            </div>\n          )}\n          <Listbox.Button\n            ref={floatingRefs.setReference}\n            className={buttonClasses}\n            id={id}\n            onBlur={onBlur as any}\n          >\n            <span className={`block truncate text-left w-full pr-6 ${!selected ? (error ? 'text-destructive/60' : 'text-muted-foreground') : ''} ${readOnly || disabled ? 'text-zinc-500 dark:text-zinc-400' : ''}`}>\n              {selected ? selected.label : placeholder}\n            </span>\n            <span className={`pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 flex items-center justify-center z-10 ${error ? 'text-destructive' : 'text-muted-foreground'} ${readOnly || disabled ? 'text-zinc-500 dark:text-zinc-400' : ''} ${iconSizeMap[selectSize]}`}>\n              <ChevronUpDownIcon\n                className={iconSizeMap[selectSize]}\n                aria-hidden=\"true\"\n              />\n            </span>\n          </Listbox.Button>\n          {createPortal(\n            <Transition\n              as={Fragment}\n              leave=\"transition ease-in duration-100\"\n              leaveFrom=\"opacity-100\"\n              leaveTo=\"opacity-0\"\n            >\n              <Listbox.Options\n                ref={setFloatingPanelRef}\n                style={{ ...floatingStyles, zIndex: 9999 }}\n                className=\"max-h-60 overflow-auto rounded-md border border-input bg-zinc-100 dark:bg-zinc-800 text-popover-foreground py-1 shadow-md ring-1 ring-black/5 focus:outline-none\"\n              >\n                {menuHeader && (\n                  <div className=\"px-3 py-1 text-xs font-medium text-muted-foreground tracking-wider\">\n                    {menuHeader}\n                  </div>\n                )}\n                {options.length === 0 ? (\n                  <div className=\"relative cursor-default select-none px-3 py-2 text-muted-foreground text-sm\">\n                    No hay opciones\n                  </div>\n                ) : (\n                  options.map((option) => (\n                    <Listbox.Option\n                      key={option.value}\n                      className={({ active }) =>\n                        `relative cursor-default select-none py-2 pl-3 pr-9 text-sm outline-none transition-colors ${\n                          active ? 'bg-primary-100 text-primary dark:bg-primary-950 dark:text-primary-300' : ''\n                        } ${option.disabled ? 'opacity-50 cursor-not-allowed' : ''}`\n                      }\n                      value={option}\n                      disabled={option.disabled}\n                    >\n                      {({ selected, active }) => (\n                        <>\n                          <span\n                            className={`block truncate ${\n                              selected ? 'font-medium' : 'font-normal'\n                            }`}\n                          >\n                            {option.label}\n                          </span>\n                          {selected ? (\n                            <span\n                              className=\"absolute inset-y-0 right-0 flex items-center pr-3 text-primary dark:text-primary-300\"\n                            >\n                              <CheckIcon className=\"h-4 w-4\" aria-hidden=\"true\" />\n                            </span>\n                          ) : null}\n                        </>\n                      )}\n                    </Listbox.Option>\n                  ))\n                )}\n              </Listbox.Options>\n            </Transition>,\n            document.body\n          )}\n        </div>\n      </Listbox>\n      {(helperText || errorMessage) && (\n        <p className={cn(selectSize === 'xs' ? 'text-xs' : 'text-sm', error ? 'text-destructive' : 'text-muted-foreground')}>\n          {error && errorMessage ? errorMessage : helperText}\n        </p>\n      )}\n    </div>\n  );\n};\n","import React from 'react';\nimport type { NavigationRailProps, NavigationRailItemProps } from './NavigationRail.types';\n\n/**\n * NavigationRail del sistema de diseño Siesa\n *\n * Componente de navegación vertical (rail) para aplicaciones. Proporciona acceso\n * rápido a destinos principales mediante iconos y labels opcionales.\n *\n * **Características:**\n * - Ancho fijo de 80px para navegación compacta\n * - Soporte para FAB (Floating Action Button) en la parte superior\n * - Estados: normal, hover, selected, disabled\n * - Badges de notificación con contador opcional\n * - Alineación flexible: top, center, bottom\n * - Dark mode completo\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Tipografía Label XXSmall (10px Bold) según sistema de diseño\n * - Estados interactivos completos (hover, focus, active)\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Label XXSmall)\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * // Navigation Rail básico\n * <NavigationRail\n *   items={[\n *     { id: 'home', icon: <HomeIcon />, label: 'Inicio', selected: true },\n *     { id: 'search', icon: <SearchIcon />, label: 'Buscar' },\n *     { id: 'notifications', icon: <BellIcon />, label: 'Notificaciones', badgeCount: 5 },\n *   ]}\n *   alignment=\"top\"\n * />\n *\n * // Con FAB button\n * <NavigationRail\n *   showFab\n *   fabIcon={<PlusIcon />}\n *   onFabClick={() => console.log('Create new')}\n *   items={[...]}\n * />\n * ```\n */\n\n/**\n * NavigationRailItem - Componente interno para items individuales\n */\nconst NavigationRailItem: React.FC<NavigationRailItemProps> = ({\n  icon,\n  label,\n  selected = false,\n  disabled = false,\n  badge = false,\n  badgeCount,\n  onClick,\n  ariaLabel,\n  id,\n}) => {\n  // ===== CLASES DEL ICON CONTAINER =====\n  // Estado selected usa background con overlay según Figma\n  const iconContainerClasses = [\n    // Base\n    'flex',\n    'flex-col',\n    'items-center',\n    'justify-center',\n    'px-4',\n    'py-1',\n    'rounded-full',\n    'overflow-hidden',\n    'shrink-0',\n\n    // Estados\n    selected\n      ? // Selected: bg-primary-100 con overlay de rgba(0,0,0,0.024)\n        'bg-primary-100 dark:bg-primary-600/30'\n      : // Default/Hover: transparent → hover:bg-primary-100\n        'bg-transparent hover:bg-primary-100 dark:hover:bg-primary-600/20',\n\n    // Transiciones\n    'transition-colors',\n    'duration-150',\n  ].join(' ');\n\n  // ===== CLASES DEL ICONO =====\n  const iconClasses = [\n    'w-4',\n    'h-4',\n    'shrink-0',\n\n    // Colores según estado\n    selected || !disabled\n      ? // Selected o habilitado con hover: content-primary → hover:primary-600\n        selected\n          ? 'text-primary-600 dark:text-white'\n          : 'text-content-primary hover:text-primary-600 dark:text-dark-content-primary dark:hover:text-white'\n      : // Disabled\n        'text-content-tertiary dark:text-content-tertiary',\n\n    'transition-colors',\n    'duration-150',\n  ].join(' ');\n\n  // ===== CLASES DEL LABEL =====\n  const labelClasses = [\n    // Tipografía: Label XXSmall (10px Bold, leading 12px)\n    'text-[10px]',\n    'leading-3',\n    'font-bold',\n    'text-center',\n    'w-full',\n    'min-w-full',\n\n    // Colores\n    'text-content-primary',\n    'dark:text-dark-content-primary',\n  ].join(' ');\n\n  // ===== CLASES DEL CONTENEDOR PRINCIPAL =====\n  const containerClasses = [\n    'relative',\n    'flex',\n    'flex-col',\n    'items-center',\n    'gap-1',\n    'px-0.5',\n    'py-0',\n    'w-14', // 56px según Figma\n    'shrink-0',\n\n    // Interactividad\n    disabled\n      ? 'cursor-not-allowed opacity-50 pointer-events-none'\n      : 'cursor-pointer',\n\n    // Focus\n    'focus:outline-hidden',\n    'focus-visible:ring-2',\n    'focus-visible:ring-primary-400',\n    'focus-visible:ring-offset-2',\n    'dark:focus-visible:ring-dark-border-custom',\n    'dark:focus-visible:ring-offset-dark-bg-primary',\n    'rounded-lg',\n  ].join(' ');\n\n  // ===== RENDERIZAR BADGE =====\n  const renderBadge = () => {\n    if (!badge && badgeCount === undefined) return null;\n\n    // Badge con número\n    if (badgeCount !== undefined) {\n      return (\n        <span\n          className=\"\n            absolute\n            -top-0.5\n            left-[34px]\n            flex\n            items-center\n            justify-center\n            min-w-[13px]\n            h-[13px]\n            px-1\n            rounded-full\n            text-[10px]\n            font-bold\n            leading-none\n            bg-red-700\n            text-white\n            dark:bg-red-700\n            dark:text-white\n            pointer-events-none\n          \"\n          aria-label={`${badgeCount} notificaciones`}\n        >\n          {badgeCount > 99 ? '99+' : badgeCount}\n        </span>\n      );\n    }\n\n    // Badge dot simple\n    return (\n      <span\n        className=\"\n          absolute\n          -top-0.5\n          left-[34px]\n          w-[13px]\n          h-[13px]\n          rounded-full\n          bg-red-700\n          dark:bg-red-700\n          pointer-events-none\n        \"\n        aria-label=\"Notificación\"\n      />\n    );\n  };\n\n  return (\n    <button\n      type=\"button\"\n      className={containerClasses}\n      disabled={disabled}\n      onClick={onClick}\n      aria-label={ariaLabel || label}\n      aria-current={selected ? 'page' : undefined}\n      data-item-id={id}\n    >\n      {/* Icon Container */}\n      <div className={iconContainerClasses}>\n        <span className={iconClasses}>\n          {icon}\n        </span>\n      </div>\n\n      {/* Label */}\n      <p className={labelClasses}>\n        {label}\n      </p>\n\n      {/* Badge */}\n      {renderBadge()}\n    </button>\n  );\n};\n\n/**\n * NavigationRail - Componente principal\n */\nexport const NavigationRail: React.FC<NavigationRailProps> = ({\n  items,\n  alignment = 'top',\n  showFab = false,\n  fabIcon,\n  onFabClick,\n  fabAriaLabel = 'Crear nuevo',\n  className = '',\n  selectedId,\n  onItemSelect,\n}) => {\n  // ===== CLASES DEL CONTENEDOR PRINCIPAL =====\n  const containerClasses = [\n    // Layout\n    'flex',\n    'flex-col',\n    'items-center',\n    'relative',\n\n    // Tamaño fijo según Figma\n    'w-20', // 80px\n    'h-full',\n\n    // Fondo y bordes\n    'bg-white',\n    'dark:bg-dark-bg-primary',\n    'border-r',\n    'border-border-primary',\n    'dark:border-dark-border-primary',\n\n    className,\n  ].join(' ');\n\n  // ===== CLASES DEL WRAPPER CON PADDING =====\n  // Según Figma, cada alineación funciona diferente:\n  // - top: flujo normal desde arriba\n  // - center: wrapper con grow y items absolutamente centrados\n  // - bottom: wrapper con grow y items con justify-end\n  const wrapperClasses = [\n    'flex',\n    'flex-col',\n    'items-center',\n    'gap-10', // 40px entre FAB y items según Figma\n    'w-20', // 80px\n    'pb-10', // 40px padding bottom según Figma\n    'pt-2', // 8px padding top según Figma\n\n    // Para center y bottom, el wrapper debe crecer para ocupar espacio\n    alignment !== 'top' && 'grow',\n    alignment !== 'top' && 'basis-0',\n    alignment !== 'top' && 'min-h-0',\n  ].filter(Boolean).join(' ');\n\n  // ===== CLASES DEL CONTENEDOR DE ITEMS =====\n  // Para cada alineación, los items se posicionan diferente\n  const getItemsContainerClasses = () => {\n    const baseClasses = [\n      'flex',\n      'flex-col',\n      'items-center',\n      'gap-3', // 12px según Figma\n      'w-20', // 80px\n    ];\n\n    if (alignment === 'top') {\n      return [...baseClasses, 'shrink-0'].join(' ');\n    }\n\n    if (alignment === 'center') {\n      // Items absolutamente centrados según Figma\n      return [\n        ...baseClasses,\n        'absolute',\n        'left-1/2',\n        'top-1/2',\n        '-translate-x-1/2',\n        '-translate-y-1/2',\n      ].join(' ');\n    }\n\n    if (alignment === 'bottom') {\n      // Items al final con grow y justify-end según Figma\n      return [\n        ...baseClasses,\n        'grow',\n        'basis-0',\n        'min-h-0',\n        'justify-end',\n        'shrink-0',\n      ].join(' ');\n    }\n\n    return baseClasses.join(' ');\n  };\n\n  const itemsContainerClasses = getItemsContainerClasses();\n\n  // ===== CLASES DEL FAB BUTTON =====\n  const fabClasses = [\n    // Layout\n    'flex',\n    'items-center',\n    'justify-center',\n    'p-3', // 12px padding según Figma\n    'shrink-0',\n\n    // Estilo\n    'rounded-md',\n    'bg-primary-600',\n    'text-primary-inverse-content',\n    'border',\n    'border-primary-600',\n    'shadow-button-inset',\n\n    // Estados\n    'hover:bg-primary-500',\n    'active:scale-95',\n    'focus:outline-hidden',\n    'focus:ring-2',\n    'focus:ring-primary-400',\n    'focus:ring-offset-2',\n\n    // Dark mode\n    'dark:bg-dark-bg-inverse',\n    'dark:text-dark-content-inverse',\n    'dark:border-dark-bg-inverse',\n    'dark:hover:bg-dark-bg-inverse/90',\n    'dark:focus:ring-dark-border-custom',\n    'dark:focus:ring-offset-dark-bg-primary',\n\n    // Transiciones\n    'transition-all',\n    'duration-150',\n  ].join(' ');\n\n  // ===== MANEJAR SELECCIÓN DE ITEM =====\n  const handleItemClick = (item: NavigationRailItemProps) => {\n    if (item.disabled) return;\n\n    if (item.onClick) {\n      item.onClick();\n    }\n\n    if (onItemSelect && item.id) {\n      onItemSelect(item.id);\n    }\n  };\n\n  return (\n    <nav className={containerClasses} aria-label=\"Navegación principal\">\n      <div className={wrapperClasses}>\n        {/* FAB Button (opcional) */}\n        {showFab && (\n          <div className=\"flex items-start gap-2.5 shrink-0\">\n            <button\n              type=\"button\"\n              className={fabClasses}\n              onClick={onFabClick}\n              aria-label={fabAriaLabel}\n            >\n              <span className=\"w-4 h-4 flex items-center justify-center\">\n                {fabIcon}\n              </span>\n            </button>\n          </div>\n        )}\n\n        {/* Navigation Items */}\n        <div className={itemsContainerClasses}>\n          {items.map((item, index) => (\n            <NavigationRailItem\n              key={item.id || index}\n              {...item}\n              selected={item.selected || (selectedId !== undefined && item.id === selectedId)}\n              onClick={() => handleItemClick(item)}\n            />\n          ))}\n        </div>\n      </div>\n    </nav>\n  );\n};\n","import React, { useState } from 'react';\nimport type { NavigationRailPanelProps } from './NavigationRailPanel.types';\nimport { DropdownItemHeading } from '../DropdownItemHeading';\nimport { DropdownItemCollapsible } from '../DropdownItemCollapsible';\nimport { Input } from '../Input';\nimport { Divider } from '../Divider/Divider';\n\n/**\n * Componente NavigationRailPanel del sistema de diseño Siesa\n *\n * Panel de navegación vertical (rail) que puede contener múltiples secciones\n * de items, búsqueda y encabezados. Se usa típicamente en aplicaciones con\n * navegación compleja que requieren una estructura jerárquica.\n *\n * **Estructura principal:**\n * 1. Encabezado (DropdownItemHeading) - Opcional\n * 2. Input de búsqueda - Opcional\n * 3. Divisor - Siempre presente después de búsqueda/encabezado\n * 4. Body con secciones de items:\n *    - Heading de sección (Paragraph/Tiny, content-tertiary)\n *    - Items colapsables (DropdownItemCollapsible) o simples\n *    - Divisor entre secciones\n *\n * **Dimensiones según Figma:**\n * - Altura: Variable (por defecto 900px)\n * - Ancho del panel: 248px (con padding 12px)\n * - Ancho de contenido: 224px\n * - Padding del panel: 12px\n * - Padding del body: 12px\n * - Border: 1px left (border-primary)\n * - Border radius: 0px (es un panel recto)\n *\n * **Tipografía:**\n * - Heading (DropdownItemHeading): Label/Small (14px Bold)\n * - Section heading: Paragraph/Tiny (12px Regular) - content-tertiary\n * - Items: Paragraph/Small (14px Regular)\n *\n * **Colores (Light Mode):**\n * - Background: #ffffff (white)\n * - Border: #e4e4e7 (border-primary)\n * - Heading text: #18181b (content-primary)\n * - Section heading: #71717a (content-tertiary)\n * - Item text: #18181b (content-primary)\n * - Icon color: #a1a1aa (content-secondary)\n *\n * **Colores (Dark Mode):**\n * - Background: #18181b (dark bg)\n * - Border: #3f3f46 (border-primary/dark)\n * - Heading text: #fafafa (content-primary/dark)\n * - Section heading: #a1a1aa (content-tertiary/dark)\n * - Item text: #fafafa (content-primary/dark)\n * - Icon color: #a1a1aa (content-secondary/dark)\n *\n * **Estados:**\n * - Default: Sin interacción\n * - Hover: Items con hover overlay sutil\n * - Focus: Focus ring adaptativo\n * - Disabled: Opacidad 50%\n * - Active (items colapsables): Expanded state\n *\n * **Espaciado interno:**\n * - Gap entre section heading e items: 0.5 (2px)\n * - Gap entre items: 0.5 (2px)\n * - Gap entre elemento y contenido: 3 (12px)\n * - Padding vertical section heading: pt-3 pb-1 (12px top, 4px bottom)\n * - Padding items: py-2 px-4 (8px vertical, 16px horizontal)\n *\n * **Scroll:**\n * - El body es scrolleable verticalmente (overflow-y-auto)\n * - El encabezado y búsqueda se mantienen fijos en el tope\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n * @see ../DropdownItemHeading - Componente reutilizado para encabezado\n * @see ../DropdownItemCollapsible - Componente reutilizado para items colapsables\n * @see ../Input - Componente reutilizado para búsqueda\n * @see ../Divider - Componente reutilizado para separadores\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=6134-34415 - Diseño Figma\n *\n * @example\n * ```tsx\n * // Ejemplo simple con secciones\n * <NavigationRailPanel\n *   height={900}\n *   showHeading={true}\n *   heading={{\n *     label: 'Settings',\n *     description: 'Configure your preferences',\n *     iconName: 'cog-6-tooth',\n *     actionLabel: 'Clear',\n *     showAction: true,\n *   }}\n *   showSearch={true}\n *   search={{\n *     placeholder: 'Buscar módulo',\n *   }}\n *   sections={[\n *     {\n *       heading: 'Section 1',\n *       items: [\n *         { label: 'Item 1', isCollapsible: true, children: [...] },\n *         { label: 'Item 2', isCollapsible: false },\n *       ],\n *     },\n *     {\n *       heading: 'Section 2',\n *       items: [\n *         { label: 'Item 3' },\n *       ],\n *     },\n *   ]}\n * />\n *\n * // Ejemplo con items simples sin secciones\n * <NavigationRailPanel\n *   showHeading={false}\n *   showSearch={true}\n *   items={[\n *     { label: 'Dashboard', icon: <DashboardIcon /> },\n *     { label: 'Users', icon: <UserIcon /> },\n *     { label: 'Settings', icon: <SettingsIcon /> },\n *   ]}\n * />\n * ```\n */\nexport const NavigationRailPanel: React.FC<NavigationRailPanelProps> = ({\n  height = 900,\n  width = 248,\n  showHeading = true,\n  heading,\n  showSearch = true,\n  search,\n  sections,\n  items,\n  className = '',\n  panelClassName = '',\n}) => {\n  const [searchValue, setSearchValue] = useState(search?.value || '');\n\n  const handleSearchChange = (value: string) => {\n    setSearchValue(value);\n    search?.onChange?.(value);\n  };\n\n  // Construir clase de altura dinámicamente\n  const containerStyle = {\n    height: typeof height === 'number' ? `${height}px` : height,\n  };\n\n  const panelStyle = {\n    width: typeof width === 'number' ? `${width}px` : width,\n  };\n\n  return (\n    <div\n      className={`flex items-start relative ${className}`}\n      style={containerStyle}\n      data-testid=\"navigation-rail-panel-container\"\n    >\n      <div\n        className={`bg-bg-primary dark:bg-dark-bg-primary border-border-primary dark:border-dark-border-primary border-b-0 border-l border-r border-solid border-t-0 flex flex-col h-full items-start overflow-clip relative shrink-0 ${panelClassName}`}\n        style={panelStyle}\n        data-testid=\"navigation-rail-panel\"\n      >\n        {/* Encabezado (DropdownItemHeading) */}\n        {showHeading && heading && (\n          <div className=\"flex flex-col items-start p-3 relative shrink-0 w-full\">\n            <DropdownItemHeading\n              label={heading.label}\n              description={heading.description}\n              showDescription={heading.showDescription !== false}\n              iconName={heading.iconName}\n              showIcon={true}\n              actionLabel={heading.actionLabel}\n              showAction={heading.showAction}\n              onActionClick={heading.onActionClick}\n              className=\"w-full\"\n            />\n          </div>\n        )}\n\n        {/* Input de búsqueda */}\n        {showSearch && (\n          <div\n            className=\"flex flex-col items-start p-3 relative shrink-0 w-full\"\n            data-testid=\"navigation-rail-search\"\n          >\n            <Input\n              placeholder={search?.placeholder || 'Buscar módulo'}\n              value={searchValue}\n              onChange={(e) => handleSearchChange(e.target.value)}\n              className=\"w-full\"\n            />\n          </div>\n        )}\n\n        {/* Divisor */}\n        <Divider className=\"w-full\" />\n\n        {/* Body con items */}\n        <div\n          className={`\n            flex flex-1 flex-col gap-0.5 items-start min-h-px min-w-px p-3 relative shrink-0 overflow-y-auto w-full\n            scrollbar-thin\n            [&::-webkit-scrollbar]:w-1.5\n            [&::-webkit-scrollbar-track]:bg-transparent\n            [&::-webkit-scrollbar-thumb]:bg-gray-200\n            [&::-webkit-scrollbar-thumb]:rounded-full\n            dark:[&::-webkit-scrollbar-thumb]:bg-gray-700\n            hover:[&::-webkit-scrollbar-thumb]:bg-gray-300\n            dark:hover:[&::-webkit-scrollbar-thumb]:bg-gray-600\n          `}\n          data-testid=\"navigation-rail-body\"\n        >\n          {/* Renderizar secciones */}\n          {sections && sections.length > 0\n            ? sections.map((section, sectionIndex) => (\n                <div key={`section-${sectionIndex}`} className=\"w-full\">\n                  {/* Section Heading */}\n                  {section.heading && (\n                    <div\n                      className=\"flex flex-col gap-0 items-start pb-1 pt-3 px-0 relative shrink-0 w-full\"\n                      data-testid={`section-heading-${sectionIndex}`}\n                    >\n                      <p className=\"font-['Inter:Regular',sans-serif] font-normal text-xs leading-4 not-italic relative shrink-0 text-content-tertiary dark:text-content-tertiary w-full whitespace-pre-wrap\">\n                        {section.heading}\n                      </p>\n                    </div>\n                  )}\n\n                  {/* Section Items */}\n                  <div\n                    className=\"flex flex-col gap-0.5 items-start relative shrink-0 w-full\"\n                    data-testid={`section-items-${sectionIndex}`}\n                  >\n                    {section.items.map((item, itemIndex) => (\n                      <NavigationRailPanelItem\n                        key={`item-${sectionIndex}-${itemIndex}`}\n                        item={item}\n                      />\n                    ))}\n                  </div>\n\n                  {/* Section Divider */}\n                  {section.showDivider !== false && sectionIndex < sections.length - 1 && (\n                    <Divider className=\"mt-3 w-full\" />\n                  )}\n                </div>\n              ))\n            : null}\n\n          {/* Renderizar items simples (sin secciones) */}\n          {items && items.length > 0 && !sections\n            ? items.map((item, itemIndex) => (\n                <NavigationRailPanelItem\n                  key={`item-${itemIndex}`}\n                  item={item}\n                />\n              ))\n            : null}\n        </div>\n      </div>\n    </div>\n  );\n};\n\n/**\n * Componente interno para renderizar un item del NavigationRailPanel\n * Puede ser un item simple o colapsable\n */\ninterface NavigationRailPanelItemComponentProps {\n  item: NonNullable<NavigationRailPanelProps['items']>[0];\n}\n\nconst NavigationRailPanelItem: React.FC<NavigationRailPanelItemComponentProps> = ({ item }) => {\n  if (item.isCollapsible) {\n    return (\n      <DropdownItemCollapsible\n        label={item.label}\n        icon={item.icon}\n        children={item.children}\n        defaultOpen={item.defaultOpen}\n        disabled={item.disabled}\n        onClick={item.onClick}\n        onOpenChange={item.onOpenChange}\n        className={item.className}\n        showDivider={false}\n        showHeading={false}\n      />\n    );\n  }\n\n  return (\n    <button\n      onClick={item.onClick}\n      disabled={item.disabled}\n      className={[\n        // Base\n        'flex items-center gap-3 px-4 py-2 w-full',\n        'rounded-lg cursor-pointer',\n        'transition-colors duration-150',\n\n        // Colores y estados (Light Mode)\n        !item.disabled && 'text-content-primary',\n        !item.disabled && 'hover:bg-primary-100',\n\n        // Dark Mode\n        !item.disabled && 'dark:text-content-primary',\n        !item.disabled && 'dark:hover:bg-dark-bg-custom',\n\n        // Focus ring\n        !item.disabled && 'focus:outline-hidden',\n        !item.disabled && 'focus:ring-2',\n        !item.disabled && 'focus:ring-offset-2',\n        !item.disabled && 'focus:ring-primary-400',\n        !item.disabled && 'focus:ring-offset-bg-primary',\n        !item.disabled && 'dark:focus:ring-offset-dark-bg-primary',\n\n        // Disabled\n        item.disabled && 'opacity-50',\n        item.disabled && 'cursor-not-allowed',\n\n        item.className,\n      ]\n        .filter(Boolean)\n        .join(' ')}\n      data-testid={`navigation-rail-item-${item.label}`}\n      aria-disabled={item.disabled}\n    >\n      {item.icon && (\n        <div className=\"flex items-center justify-center w-4 h-4 shrink-0 text-content-secondary dark:text-content-secondary\">\n          {item.icon}\n        </div>\n      )}\n      <p className=\"font-['Inter:Regular',sans-serif] text-sm font-normal leading-5 not-italic relative shrink-0 text-left\">\n        {item.label}\n      </p>\n    </button>\n  );\n};\n","import React from 'react';\n// Importamos de 24/outline solo para el ClockIcon\nimport { ClockIcon as HeroClockOutline } from '@heroicons/react/24/outline';\n\n// Importamos de 20/solid para los demás\nimport {\n  ChevronRightIcon as HeroChevronRight,\n  ChevronLeftIcon as HeroChevronLeft,\n  MagnifyingGlassIcon as HeroSearch,\n  HomeIcon as HeroHome,\n  UsersIcon as HeroUsers,\n  Cog6ToothIcon as HeroSettings,\n} from '@heroicons/react/20/solid';\n\n/**\n * Props comunes para los iconos\n */\ninterface IconProps {\n  className?: string;\n}\n\n/**\n * Icono Chevron Right (apunta hacia la derecha)\n * Usado en el botón de collapse\n */\nexport const ChevronRightIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroChevronRight className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono Chevron Left (apunta hacia la izquierda)\n * Usado en el botón de expand\n */\nexport const ChevronLeftIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroChevronLeft className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono Clock (reloj) - Estilo OUTLINE 24\n * Usado en el botón \"Recientes\"\n */\nexport const ClockIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroClockOutline className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono Magnifying Glass (búsqueda)\n * Usado en el botón de búsqueda\n */\nexport const MagnifyingGlassIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroSearch className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono Home\n * Ejemplo para items de navegación\n */\nexport const HomeIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroHome className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono Users\n * Ejemplo para items de navegación\n */\nexport const UsersIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroUsers className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono Settings\n * Ejemplo para items de navegación\n */\nexport const SettingsIcon: React.FC<IconProps> = ({ className = 'size-5' }) => (\n  <HeroSettings className={className} aria-hidden=\"true\" />\n);\n","import React, { useState, useRef, useEffect } from 'react';\nimport type { NavigationRailTypesProps, NavigationRailItem } from './NavigationRailTypes.types';\nimport { ChevronRightIcon, ChevronLeftIcon, ClockIcon, MagnifyingGlassIcon } from './icons';\nimport { Button } from '../Button/Button';\nimport { Divider } from '../Divider/Divider';\nimport { DropdownItemCollapsible } from '../DropdownItemCollapsible/DropdownItemCollapsible';\nimport { NavigationRailItem as NavigationRailItemComponent } from '../NavigationRailItem/NavigationRailItem';\nimport { Input } from '../Input/Input';\nimport { NavigationRailPanel } from '../NavigationRailPanel/NavigationRailPanel';\n\n/**\n * Componente NavigationRailTypes del sistema de diseño Siesa\n *\n * Barra de navegación lateral que permite dos modos visuales:\n * - **Collapsed (Colapsado)**: 80px width, solo iconos con botón de búsqueda\n * - **Expanded (Expandido)**: 215px width, con labels y búsqueda integrada\n *\n * **Características:**\n * - Dos modos: collapsed e expanded (toggle con botón \"Colapsar\")\n * - Soporta items con badges de notificación\n * - Items colapsables para agrupar navegación relacionada\n * - Botón \"Recientes\" en footer\n * - Búsqueda integrada (solo en modo expanded)\n * - Dark mode completo\n * - Focus rings adaptativos\n *\n * **Especificaciones de Figma:**\n * - Collapsed: 80px width, items con height 44px + gap 12px\n * - Expanded: 215px width, items reutilizan DropdownItemCollapsible\n * - Icono search: 16x16px, azul (#0e79fd)\n * - Borde derecho: 1px solid #e4e4e7 (collapsed)\n * - Borde izquierdo: 1px solid #e4e4e7 (expanded)\n * - Height total: 900px (scroll si necesario)\n *\n * **Estructura:**\n * 1. Header (Search en expanded) - altura variable\n * 2. Menu & Destinations - flex 1 con items scrollables\n * 3. Footer - Actions con divider y botones\n *\n * **Estados de Items:**\n * - `default`: Text color content-primary\n * - `hover`: Fondo hover-overlay, icon color content-custom-primary\n * - `active`: Fondo custom-primary, text color custom-primary\n * - `disabled`: Opacity 50%, sin interacción\n *\n * **Colores (Light Mode):**\n * - Background: background-primary (#ffffff)\n * - Borders: border-primary (#e4e4e7)\n * - Text: content-primary (#18181b)\n * - Icons: content-secondary (#a1a1aa)\n * - Icon hover: content-custom-primary (#0e79fd)\n * - Divider: border-primary (#e4e4e7)\n * - Search input: bg-primary, border-primary, placeholder: content-tertiary\n *\n * **Colores (Dark Mode):**\n * - Background: background-primary/dark (#09090b)\n * - Borders: border-primary/dark (#3f3f46)\n * - Text: content-primary/dark (#fafafa)\n * - Icons: content-secondary/dark (#a1a1aa)\n * - Icon hover: content-custom-primary/dark (#bfe2fe)\n * - Divider: border-primary/dark (#3f3f46)\n *\n * **Tipografía:**\n * - Items labels: Paragraph/Small (14px, Regular, line-height 20px)\n * - Heading: Paragraph/Tiny (12px, Regular, line-height 16px) - si aplica\n * - Button labels: Label Small (14px, Bold)\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado (gap-3, px-4, py-2, etc)\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=6135-36219\n *\n * @example\n * ```tsx\n * const navItems: NavigationRailItem[] = [\n *   {\n *     id: 'home',\n *     label: 'Home',\n *     icon: <HomeIcon />,\n *     active: true,\n *     onClick: () => navigate('/home'),\n *   },\n *   {\n *     id: 'users',\n *     label: 'Users',\n *     icon: <UsersIcon />,\n *     badge: true,\n *     onClick: () => navigate('/users'),\n *   },\n * ];\n *\n * const [isCollapsed, setIsCollapsed] = useState(true);\n *\n * <NavigationRailTypes\n *   collapsed={isCollapsed}\n *   items={navItems}\n *   showRecentButton={true}\n *   onCollapsedChange={setIsCollapsed}\n *   onItemClick={(index, item) => console.log('Selected:', item.id)}\n * />\n * ```\n *\n * @see NavigationRailTypes.types.ts - Props e interfaces\n */\nexport const NavigationRailTypes = React.forwardRef<\n  HTMLDivElement,\n  NavigationRailTypesProps\n>(\n  (\n    {\n      collapsed = true,\n      items = [],\n      showRecentButton = true,\n      showSearchButton = true,\n      onCollapsedChange,\n      onItemClick,\n      onItemHover,\n      className,\n      labels = {},\n      onSearch,\n    },\n    ref\n  ) => {\n    const [searchQuery, setSearchQuery] = useState('');\n    const [isSearchPanelOpen, setIsSearchPanelOpen] = useState(false);\n    const panelRef = useRef<HTMLDivElement>(null);\n    const searchButtonRef = useRef<HTMLDivElement>(null);\n\n    // Cerrar panel al hacer click fuera\n    useEffect(() => {\n      function handleClickOutside(event: MouseEvent) {\n        if (\n          isSearchPanelOpen &&\n          panelRef.current &&\n          !panelRef.current.contains(event.target as Node) &&\n          searchButtonRef.current &&\n          !searchButtonRef.current.contains(event.target as Node)\n        ) {\n          setIsSearchPanelOpen(false);\n        }\n      }\n\n      document.addEventListener('mousedown', handleClickOutside);\n      return () => {\n        document.removeEventListener('mousedown', handleClickOutside);\n      };\n    }, [isSearchPanelOpen]);\n\n    // Labels con valores por defecto\n    const finalLabels = {\n      searchButton: labels.searchButton ?? 'Search',\n      searchPlaceholder: labels.searchPlaceholder ?? 'Buscar módulo',\n      recentButton: labels.recentButton ?? 'Recientes',\n      collapseButton: labels.collapseButton ?? 'Colapsar',\n      expandButton: labels.expandButton ?? 'Expandir',\n    };\n\n    const handleCollapsedToggle = () => {\n      // Si expandimos el rail, cerramos el panel de búsqueda flotante\n      if (collapsed) {\n        setIsSearchPanelOpen(false);\n      }\n      onCollapsedChange?.(!collapsed);\n    };\n\n    const handleSearchButtonClick = () => {\n      setIsSearchPanelOpen(!isSearchPanelOpen);\n    };\n\n    const handleItemClick = (index: number, item: NavigationRailItem) => {\n      item.onClick?.(new Event('click') as any);\n      onItemClick?.(index, item);\n      // Cerrar panel si se selecciona un item\n      if (isSearchPanelOpen) {\n        setIsSearchPanelOpen(false);\n      }\n    };\n\n    const handleItemHover = (index: number, item: NavigationRailItem) => {\n      onItemHover?.(index, item);\n    };\n\n    const handleSearchChange = (value: string) => {\n      setSearchQuery(value);\n      onSearch?.(value);\n    };\n\n    const handleInputSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n      handleSearchChange(e.target.value);\n    };\n\n    // Transformar items para el panel\n    const panelItems = items.map((item, index) => ({\n      label: item.label,\n      icon: item.icon,\n      disabled: item.disabled,\n      // Adaptar children si existen (usando lógica simple por ahora)\n      isCollapsible: (item as any).children && (item as any).children.length > 0,\n      children: (item as any).children,\n      defaultOpen: (item as any).defaultOpen,\n      onClick: () => handleItemClick(index, item),\n    }));\n\n    return (\n      <div\n        ref={ref}\n        className={`\n          ${collapsed ? 'w-[80px]' : 'w-[215px]'}\n          h-full\n          bg-background-primary dark:bg-background-primary\n          ${collapsed ? 'border-r border-border-primary dark:border-border-primary' : 'border-l border-r border-border-primary dark:border-border-primary'}\n          border-solid\n          flex flex-col\n          items-center\n          relative\n          transition-all duration-300\n          ${className || ''}\n        `}\n      >\n        {/* Panel de búsqueda flotante (solo visible en modo collapsed + open) */}\n        {collapsed && isSearchPanelOpen && (\n          <div\n            ref={panelRef}\n            className=\"absolute left-[80px] top-0 h-full z-50 shadow-xl\"\n          >\n            <NavigationRailPanel\n              height=\"100%\"\n              width={248}\n              showHeading={true}\n              heading={{\n                label: 'Buscar',\n                showDescription: false,\n                showAction: true,\n                actionLabel: 'Cerrar',\n                onActionClick: () => setIsSearchPanelOpen(false),\n              }}\n              showSearch={true}\n              search={{\n                placeholder: finalLabels.searchPlaceholder,\n                value: searchQuery,\n                onChange: handleSearchChange,\n              }}\n              items={panelItems}\n              className=\"h-full border-l border-border-primary dark:border-border-primary\"\n            />\n          </div>\n        )}\n\n        {/* Sección de búsqueda - solo en modo expandido */}\n        {!collapsed && (\n          <div className=\"w-full flex flex-col gap-3 px-3 py-3 relative shrink-0\">\n            <Input\n              placeholder={finalLabels.searchPlaceholder}\n              value={searchQuery}\n              onChange={handleInputSearchChange}\n              startIcon={<MagnifyingGlassIcon className=\"size-4 text-content-secondary dark:text-content-secondary\" />}\n            />\n            <Divider className=\"w-full\" />\n          </div>\n        )}\n\n        {/* Main content - Menu & Destinations */}\n        <div\n          className={`\n            flex-1 flex flex-col\n            items-center min-h-px min-w-px\n            relative shrink-0\n            px-0\n            ${collapsed\n              ? 'gap-7 py-2 w-[80px]'\n              : 'gap-0.5 px-3 pb-3 pt-0 w-full bg-background-primary dark:bg-background-primary border-l dark:border-border-primary border-border-primary border-solid'\n            }\n          `}\n        >\n          {/* Botón Search en collapsed */}\n          {collapsed && showSearchButton && (\n            <div ref={searchButtonRef}>\n              <Button\n                type=\"default\" // Highlight visual si está abierto se maneja con className\n                size=\"xl\"\n                iconOnly\n                leftIcon={<MagnifyingGlassIcon className=\"overflow-clip relative shrink-0 size-4 text-primary-inverse-content dark:text-primary-inverse-content\" />}\n                ariaLabel={finalLabels.searchButton}\n                onClick={handleSearchButtonClick}\n                className={isSearchPanelOpen ? 'bg-primary-500 ring-2 ring-offset-2 ring-primary-400' : ''}\n              />\n            </div>\n          )}\n\n          {/* Items container */}\n          <div\n            className={`\n              flex flex-col items-center min-h-px min-w-px\n              relative shrink-0\n              flex-1\n              overflow-y-auto\n              scrollbar-thin\n              [&::-webkit-scrollbar]:w-1.5\n              [&::-webkit-scrollbar-track]:bg-transparent\n              [&::-webkit-scrollbar-thumb]:bg-gray-200\n              [&::-webkit-scrollbar-thumb]:rounded-full\n              dark:[&::-webkit-scrollbar-thumb]:bg-gray-700\n              hover:[&::-webkit-scrollbar-thumb]:bg-gray-300\n              dark:hover:[&::-webkit-scrollbar-thumb]:bg-gray-600\n              ${collapsed\n                ? 'gap-3 leading-none w-[80px]'\n                : 'gap-0.5 px-3 pb-3 pt-0 w-full'\n              }\n            `}\n          >\n            {/* Espaciador superior para mantener estética sin afectar sticky headers */}\n            {!collapsed && <div className=\"h-3 shrink-0\" />}\n\n            {collapsed ? (\n              // Items reales - collapsed mode\n              <>\n                {items.map((item, idx) => (\n                  <NavigationRailItemComponent\n                    key={item.id}\n                    id={item.id}\n                    label={item.label}\n                    icon={item.icon}\n                    selected={item.active}\n                    disabled={item.disabled}\n                    badge={item.badge}\n                    badgeCount={item.badgeCount}\n                    ariaLabel={item.ariaLabel}\n                    showLabelText={false}\n                    onClick={() => handleItemClick(idx, item)}\n                    onMouseEnter={() => handleItemHover(idx, item)}\n                    onMouseLeave={item.onMouseLeave}\n                  />\n                ))}\n              </>\n            ) : (\n              // Items reales - expanded mode\n              <>\n                {items.map((item, idx) => {\n                  const isCollapsible = (item as any).children && (item as any).children.length > 0;\n                  return (\n                    <div key={item.id} className=\"w-full\">\n                      <DropdownItemCollapsible\n                        label={item.label}\n                        icon={item.icon}\n                        selected={item.active}\n                        disabled={item.disabled}\n                        badge={item.badge}\n                        badgeCount={item.badgeCount}\n                        badgeColor={item.badgeColor as any}\n                        showDivider={false}\n                        showHeading={false}\n                        isCollapsible={isCollapsible}\n                        defaultOpen={(item as any).defaultOpen}\n                        children={isCollapsible ? (item as any).children : undefined}\n                        onClick={() => handleItemClick(idx, item)}\n                        stickyHeader={true}\n                      />\n                    </div>\n                  );\n                })}\n              </>\n            )}\n          </div>\n\n          {/* Footer - Actions */}\n          <div className={`w-full flex flex-col gap-3 items-center relative shrink-0 ${!collapsed ? 'px-3' : ''}`}>\n            <Divider className=\"w-full\" />\n\n            <div\n              className={`\n                flex flex-col gap-3 relative shrink-0 w-full\n                ${collapsed ? 'items-stretch px-3' : 'items-stretch'}\n              `}\n            >\n              {/* Botón Recientes */}\n              {showRecentButton && collapsed && (\n                <Button\n                  type=\"outline\"\n                  size=\"base\"\n                  fullWidth\n                  leftIcon={<ClockIcon className=\"size-4 text-primary-600 dark:text-primary-600\" />}\n                  ariaLabel={finalLabels.recentButton}\n                />\n              )}\n\n              {showRecentButton && !collapsed && (\n                <Button\n                  type=\"outline\"\n                  size=\"base\"\n                  leftIcon={<ClockIcon className=\"size-4 text-primary-600 dark:text-primary-600\" />}\n                  fullWidth\n                >\n                  {finalLabels.recentButton}\n                </Button>\n              )}\n\n              {/* Botón Colapsar/Expandir */}\n              {collapsed ? (\n                <Button\n                  type=\"plain\"\n                  size=\"base\"\n                  fullWidth\n                  leftIcon={<ChevronRightIcon className=\"overflow-clip relative shrink-0 size-4 text-background-inverse-custom-primary dark:text-background-inverse-custom-primary\" />}\n                  onClick={handleCollapsedToggle}\n                  ariaLabel={finalLabels.expandButton}\n                />\n              ) : (\n                <Button\n                  type=\"outline\"\n                  size=\"base\"\n                  leftIcon={<ChevronLeftIcon className=\"overflow-clip relative shrink-0 size-4 text-content-custom-primary dark:text-content-custom-primary\" />}\n                  onClick={handleCollapsedToggle}\n                  fullWidth\n                >\n                  {finalLabels.collapseButton}\n                </Button>\n              )}\n            </div>\n          </div>\n        </div>\n      </div>\n    );\n  }\n);\n\nNavigationRailTypes.displayName = 'NavigationRailTypes';\n\nexport default NavigationRailTypes;\n","import React from 'react';\n// Importamos de 24/outline solo para el ClockIcon\nimport { ClockIcon as HeroClockOutline } from '@heroicons/react/24/outline';\n\n// Importamos de 20/solid para los demás iconos\nimport {\n  MagnifyingGlassIcon as HeroMagnifyingGlass,\n  ChevronRightIcon as HeroChevronRight,\n  ChevronLeftIcon as HeroChevronLeft,\n  Cog6ToothIcon as HeroCog6Tooth,\n  ShoppingCartIcon as HeroShoppingCart,\n  CubeIcon as HeroCube,\n  DocumentIcon as HeroDocument,\n} from '@heroicons/react/20/solid';\n\n/**\n * Iconos estándar para NavigationRailGroup\n * Basados en Heroicons 20x20 solid (excepto ClockIcon que es 24x24 outline)\n * Consistente con NavigationRailTypes\n *\n * @see docs/icons.md - Sistema de iconos del proyecto\n */\n\nexport const MagnifyingGlassIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroMagnifyingGlass className={className} aria-hidden=\"true\" />\n);\n\nexport const ChevronRightIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroChevronRight className={className} aria-hidden=\"true\" />\n);\n\nexport const ChevronLeftIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroChevronLeft className={className} aria-hidden=\"true\" />\n);\n\nexport const Cog6ToothIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroCog6Tooth className={className} aria-hidden=\"true\" />\n);\n\nexport const ShoppingCartIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroShoppingCart className={className} aria-hidden=\"true\" />\n);\n\nexport const CubeIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroCube className={className} aria-hidden=\"true\" />\n);\n\nexport const DocumentIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroDocument className={className} aria-hidden=\"true\" />\n);\n\nexport const ClockIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroClockOutline className={className} aria-hidden=\"true\" />\n);\n","import React, { useState, useRef, useEffect } from 'react';\nimport type {\n  NavigationRailGroupProps,\n  NavigationRailGroupMenuItem,\n} from './NavigationRailGroup.types';\nimport { NavigationRailTypes } from '../NavigationRailTypes/NavigationRailTypes';\nimport { NavigationRailPanel } from '../NavigationRailPanel/NavigationRailPanel';\nimport { MagnifyingGlassIcon } from './icons';\n\n/**\n * NavigationRailGroup del sistema de diseño Siesa\n *\n * Componente de navegación lateral agrupado que combina NavigationRailTypes\n * y NavigationRailPanel para crear una experiencia de navegación completa\n * con múltiples estados:\n *\n * - **Collapsed**: Barra compacta de 80px con solo iconos\n * - **Expanded**: Barra expandida de 215px con labels\n * - **Hover**: Panel lateral con submenú del item (se muestra al hacer hover)\n * - **Searcher**: Panel lateral con búsqueda y recientes\n *\n * **Características:**\n * - Reutiliza NavigationRailTypes para la barra lateral principal\n * - Reutiliza NavigationRailPanel para los paneles de hover y búsqueda\n * - Gestión de estado integrada (collapsed, expanded, hover, searcher)\n * - Dark mode completo en todos los elementos\n * - Focus rings adaptativos\n * - Transiciones suaves entre estados\n *\n * **Especificaciones de Figma:**\n * - NavigationRailTypes: 80px (collapsed) / 215px (expanded)\n * - NavigationRailPanel: 248px width, altura variable\n * - Posición panel: left 80px desde el rail\n * - Transiciones: 300ms ease-in-out\n *\n * **Estructura:**\n * ```\n * ┌────────────────────────────────────┐\n * │  NavigationRailGroup               │\n * │  ┌──────────┬─────────────────┐   │\n * │  │  Rail    │  Panel          │   │\n * │  │  Types   │  (hover/search) │   │\n * │  │  (base)  │  (opcional)     │   │\n * │  └──────────┴─────────────────┘   │\n * └────────────────────────────────────┘\n * ```\n *\n * **Estados de Items:**\n * - `default`: Sin interacción\n * - `hover`: Muestra panel con submenú (si tiene children)\n * - `active`: Item seleccionado, fondo custom-primary\n * - `disabled`: Opacity 50%, sin interacción\n *\n * **Colores (Light Mode):**\n * - Background rail: #ffffff (bg-primary)\n * - Background panel: #ffffff (bg-primary)\n * - Borders: #e4e4e7 (border-primary)\n * - Text: #18181b (content-primary)\n * - Icons: #a1a1aa (content-secondary)\n * - Search button: #0e79fd (primary-600)\n *\n * **Colores (Dark Mode):**\n * - Background rail: #18181b (dark-bg-primary)\n * - Background panel: #18181b (dark-bg-primary)\n * - Borders: #71717a (dark-border-primary)\n * - Text: #f4f4f5 (dark-content-primary)\n * - Icons: #a1a1aa (content-secondary)\n *\n * **Tipografía:**\n * - Items: Paragraph/Small (14px Regular, line-height 20px)\n * - Panel heading: Label/Small (14px Bold)\n * - Section headings: Paragraph/Tiny (12px Regular)\n *\n * **Implementación de Estados:**\n * - `collapsed` + hover en item → state='hover' + muestra panel\n * - `collapsed` + click en search → state='searcher' + muestra panel búsqueda\n * - `expanded` → NavigationRailTypes expandido con Input integrado\n * - Click en \"Colapsar\" → vuelve a collapsed\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see ../NavigationRailTypes - Componente reutilizado para barra lateral\n * @see ../NavigationRailPanel - Componente reutilizado para paneles\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=6146-34487\n *\n * @example\n * ```tsx\n * // Uso básico en modo collapsed\n * const items = [\n *   {\n *     id: 'admin',\n *     label: 'Administración',\n *     icon: <Cog6ToothIcon />,\n *     isCollapsible: true,\n *     children: [\n *       { id: 'users', label: 'Usuarios' },\n *       { id: 'roles', label: 'Roles' },\n *     ],\n *   },\n *   {\n *     id: 'sales',\n *     label: 'Ventas',\n *     icon: <ShoppingCartIcon />,\n *   },\n * ];\n *\n * <NavigationRailGroup\n *   state=\"collapsed\"\n *   items={items}\n *   onItemClick={(item) => console.log('Clicked:', item.label)}\n *   onItemHover={(item) => console.log('Hover:', item.label)}\n * />\n *\n * // Uso con control de estado externo\n * const [state, setState] = useState('collapsed');\n *\n * <NavigationRailGroup\n *   state={state}\n *   items={items}\n *   onStateChange={setState}\n * />\n * ```\n *\n * @see NavigationRailGroup.types.ts - Props e interfaces\n */\nexport const NavigationRailGroup = React.forwardRef<\n  HTMLDivElement,\n  NavigationRailGroupProps\n>(\n  (\n    {\n      state = 'collapsed',\n      items = [],\n      onStateChange,\n      onItemClick,\n      onItemHover,\n      labels = {},\n      className,\n      showSearchButton = true,\n      onSearch,\n      t = (key, def) => def || key,\n    },\n    ref\n  ) => {\n    // Estado local para controlar el panel\n    const [showPanel, setShowPanel] = useState(false);\n    const [panelType, setPanelType] = useState<'hover' | 'searcher'>('hover');\n    const [hoveredItem, setHoveredItem] = useState<NavigationRailGroupMenuItem | null>(null);\n\n    // Ref para manejar el timeout de ocultación del panel\n    const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n\n    // Fallbacks para labels si no se proveen\n    const finalLabels = {\n      searchPlaceholder: labels.searchPlaceholder ?? t('search', 'Buscar módulo'),\n      collapseButton: labels.collapseButton ?? t('collapse', 'Colapsar'),\n      recentSection: labels.recentSection ?? t('recent', 'Recientes'),\n      frequentSection: labels.frequentSection ?? t('frequent', 'Opciones frecuentes'),\n    };\n\n\n    // Controlar el estado collapsed/expanded\n    const isCollapsed = state === 'collapsed' || state === 'hover' || state === 'searcher';\n\n    // Cleanup del timeout al desmontar el componente\n    useEffect(() => {\n      return () => {\n        if (hideTimeoutRef.current) {\n          clearTimeout(hideTimeoutRef.current);\n        }\n      };\n    }, []);\n\n    // Manejar cambio de estado collapsed/expanded\n    const handleCollapsedChange = (collapsed: boolean) => {\n      const newState = collapsed ? 'collapsed' : 'expanded';\n      onStateChange?.(newState);\n    };\n\n    // Manejar click en item\n    const handleItemClick = (index: number) => {\n      const commercialItem = items[index];\n      if (commercialItem) {\n        onItemClick?.(commercialItem);\n      }\n    };\n\n    // Manejar hover en item desde NavigationRailTypes\n    const handleItemHoverFromRail = (index: number) => {\n      const commercialItem = items[index];\n      if (commercialItem && isCollapsed) {\n        handleItemHover(commercialItem);\n      }\n    };\n\n    // Manejar hover en item (solo en modo collapsed)\n    const handleItemHover = (item: NavigationRailGroupMenuItem) => {\n      if (isCollapsed && item.isCollapsible && item.children) {\n        // Cancelar cualquier timeout pendiente\n        if (hideTimeoutRef.current) {\n          clearTimeout(hideTimeoutRef.current);\n          hideTimeoutRef.current = null;\n        }\n\n        setHoveredItem(item);\n        setPanelType('hover');\n        setShowPanel(true);\n        onItemHover?.(item);\n      }\n    };\n\n    // Manejar cuando el cursor sale de un item\n    const handleItemMouseLeave = () => {\n      // Programar ocultación del panel con delay para permitir transición al panel\n      if (isCollapsed && panelType === 'hover') {\n        hideTimeoutRef.current = setTimeout(() => {\n          setShowPanel(false);\n          setHoveredItem(null);\n        }, 150); // Delay de 150ms para permitir transición suave\n      }\n    };\n\n    // Manejar cuando el cursor entra al panel\n    const handlePanelMouseEnter = () => {\n      // Cancelar la ocultación programada\n      if (hideTimeoutRef.current) {\n        clearTimeout(hideTimeoutRef.current);\n        hideTimeoutRef.current = null;\n      }\n    };\n\n    // Manejar cuando el cursor sale del panel\n    const handlePanelMouseLeave = () => {\n      if (isCollapsed && panelType === 'hover') {\n        setShowPanel(false);\n        setHoveredItem(null);\n      }\n    };\n\n    // Manejar click en botón de búsqueda\n\n\n    // Convertir items a formato NavigationRailTypes\n    const railItems = items.map((item) => ({\n      id: item.id,\n      label: item.label,\n      icon: item.icon,\n      active: item.active,\n      disabled: item.disabled,\n      badge: item.badge,\n      badgeCount: item.badgeCount,\n      children: item.children,\n      defaultOpen: item.defaultOpen,\n      onClick: () => {\n        item.onClick?.();\n      },\n      onMouseLeave: () => handleItemMouseLeave(), // Corregir la llamada\n    }));\n\n    return (\n      <div\n        ref={ref}\n        className={`relative flex items-start h-full ${className || ''}`}\n        data-testid=\"navigation-rail-group\"\n      >\n        {/* NavigationRailTypes - Barra lateral principal */}\n        <NavigationRailTypes\n          collapsed={isCollapsed}\n          items={railItems}\n          showRecentButton={false}\n          showSearchButton={showSearchButton}\n          onCollapsedChange={handleCollapsedChange}\n          onItemClick={handleItemClick}\n          onItemHover={handleItemHoverFromRail}\n          onSearch={onSearch}\n          labels={{\n            searchButton: finalLabels.searchPlaceholder,\n            searchPlaceholder: finalLabels.searchPlaceholder,\n            collapseButton: finalLabels.collapseButton,\n          }}\n        />\n\n        {/* NavigationRailPanel - Panel lateral (hover o searcher) */}\n        {showPanel && isCollapsed && (\n          <div\n            className=\"absolute left-[80px] top-0 z-10 h-full\"\n            onMouseEnter={handlePanelMouseEnter}\n            onMouseLeave={handlePanelMouseLeave}\n          >\n            <NavigationRailPanel\n              height=\"100%\"\n              width={248}\n              showHeading={panelType === 'hover' && hoveredItem !== null}\n              heading={\n                panelType === 'hover' && hoveredItem\n                  ? {\n                    label: hoveredItem.label,\n                    iconName: 'cog-6-tooth',\n                    showDescription: false,\n                    showAction: false,\n                  }\n                  : undefined\n              }\n              showSearch={panelType === 'searcher'}\n              search={{\n                placeholder: finalLabels.searchPlaceholder,\n              }}\n              sections={\n                panelType === 'hover' && hoveredItem?.children\n                  ? [\n                    {\n                      items: hoveredItem.children.map((child) => ({\n                        label: child.label,\n                        icon: child.icon,\n                        onClick: child.onClick,\n                        disabled: child.disabled,\n                      })),\n                    },\n                  ]\n                  : panelType === 'searcher'\n                    ? [\n                      {\n                        heading: finalLabels.recentSection,\n                        items: [\n                          {\n                            label: 'Configuración',\n                            icon: <MagnifyingGlassIcon className=\"size-4\" />,\n                          },\n                        ],\n                      },\n                      {\n                        heading: finalLabels.frequentSection,\n                        items: [\n                          {\n                            label: 'Item',\n                          },\n                        ],\n                      },\n                    ]\n                    : []\n              }\n            />\n          </div>\n        )}\n      </div>\n    );\n  }\n);\n\nNavigationRailGroup.displayName = 'NavigationRailGroup';\n\nexport default NavigationRailGroup;\n","import React, { useCallback, useEffect, useRef, useState } from 'react';\nimport type {\n  TableProps,\n  TableHeaderProps,\n  TableCellProps,\n  SortDirection,\n  PaginationProps,\n} from './Table.types';\n\n/**\n * Iconos para sort\n */\nconst ChevronUpIcon = () => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className=\"transition-transform\"\n  >\n    <path\n      d=\"M12 10L8 6L4 10\"\n      stroke=\"currentColor\"\n      strokeWidth=\"2\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\nconst ChevronDownIcon = () => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className=\"transition-transform\"\n  >\n    <path\n      d=\"M4 6L8 10L12 6\"\n      stroke=\"currentColor\"\n      strokeWidth=\"2\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\nconst ChevronUpDownIcon = () => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      d=\"M4 6L8 2.5L12 6\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n    <path\n      d=\"M4 10L8 13.5L12 10\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n/**\n * Iconos para paginación\n */\nconst ArrowLeftIcon = () => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      d=\"M14 8H2M2 8L6.5 3.5M2 8L6.5 12.5\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\nconst ArrowRightIcon = () => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      d=\"M2 8H14M14 8L9.5 3.5M14 8L9.5 12.5\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n// Iconos de paginación (chevron simples y dobles) — mismos paths que el prototipo (lucide).\nconst ChevronLeftIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m15 18-6-6 6-6\" /></svg>\n);\nconst ChevronRightIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m9 18 6-6-6-6\" /></svg>\n);\nconst ChevronsLeftIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m11 17-5-5 5-5\" /><path d=\"m18 17-5-5 5-5\" /></svg>\n);\nconst ChevronsRightIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m6 17 5-5-5-5\" /><path d=\"m13 17 5-5-5-5\" /></svg>\n);\n\n/**\n * TableHeader - Componente para el header de una columna\n */\nconst TableHeader = <T,>({\n  column,\n  sortable,\n  sorted,\n  sortDirection,\n  onSort,\n  stickyHeader = false,\n  headerBand = false,\n  dense = false,\n}: TableHeaderProps<T>) => {\n  // Clases base del header. En modo compacto (`dense`) el alto del header iguala EXACTO\n  // el de las filas compactas (py-2 + min-h-[44px]) para un remate pixel-exact.\n  const baseClasses = `\n    flex\n    items-center\n    gap-3\n    ${dense ? 'px-4 py-2 min-h-[44px]' : 'px-4 py-2.5 min-h-[40px]'}\n    w-full\n    border-b\n    border-border-primary\n    dark:border-dark-border-primary\n    transition-colors\n    duration-150\n  `;\n\n  // Clases según sortable\n  const sortableClasses = sortable\n    ? `\n      cursor-pointer\n      hover:bg-background-secondary\n      dark:hover:bg-dark-bg-primary/50\n      select-none\n    `\n    : '';\n\n  // Clases de alineación del contenedor flex\n  const alignClasses = {\n    left: 'justify-start',\n    center: 'justify-center',\n    right: 'justify-end',\n  };\n\n  // Clases de alineación interna del span de contenido del header\n  // Necesario porque flex-1 ocupa todo el ancho y justify-* del padre no centra el contenido interno\n  const spanAlignClasses = {\n    left: '',\n    center: 'flex justify-center items-center',\n    right: 'flex justify-end items-center',\n  };\n\n  // \"Banda de título\": alto EXACTO del área útil de la celda (alto de fila menos el padding\n  // vertical). El título se centra (items-center) dentro de esta banda, de modo que queda\n  // perfectamente centrado en vertical cuando el header está cerrado; y como la banda se ancla\n  // arriba, al abrir un filtro (que crece la fila) los títulos siguen alineados entre columnas.\n  // dense: 44px - 2×8px(py-2) = 28px · normal: 40px - 2×10px(py-2.5) = 20px.\n  const titleBand = dense ? 'min-h-[28px]' : 'min-h-[20px]';\n\n  // Clases según stickyRight y/o stickyHeader (header fijo vertical).\n  // Cuando stickyHeader está activo, el fondo del header pasa a #f8f9fc (tablehead del prototipo)\n  // y debe ser opaco para cubrir el contenido al scrollear.\n  // La BANDA (el fondo gris) y el FIJADO son cosas distintas y ya no viajan juntas:\n  // `headerBand` pinta el gris del canon sin convertir la tabla en contenedor de\n  // scroll, que es lo que `stickyHeader` arrastra consigo.\n  const conBanda = stickyHeader || headerBand;\n  let stickyClasses = '';\n  if (column.stickyRight && stickyHeader) {\n    // Esquina superior-derecha: fija en ambos ejes, por encima de todo.\n    stickyClasses = 'sticky top-0 right-0 z-30 bg-[#f8f9fc] dark:bg-dark-bg-secondary shadow-[-2px_0_5px_rgba(0,0,0,0.05)]';\n  } else if (column.stickyRight) {\n    // Con banda, la celda pegada a la derecha tiene que llevar el MISMO gris: en\n    // blanco se recortaba contra sus vecinas y parecía otra columna.\n    stickyClasses = conBanda\n      ? 'sticky right-0 z-10 bg-[#f8f9fc] dark:bg-dark-bg-secondary shadow-[-2px_0_5px_rgba(0,0,0,0.05)]'\n      : 'sticky right-0 z-10 bg-white dark:bg-dark-bg-primary shadow-[-2px_0_5px_rgba(0,0,0,0.05)]';\n  } else if (stickyHeader) {\n    stickyClasses = 'sticky top-0 z-20 bg-[#f8f9fc] dark:bg-dark-bg-secondary';\n  } else if (headerBand) {\n    stickyClasses = 'bg-[#f8f9fc] dark:bg-dark-bg-secondary';\n  }\n\n  // Con stickyHeader (listado MasterCrud) las cabeceras se alinean ARRIBA (como el prototipo,\n  // cuyos `th` son `align-top`): así, cuando una columna abre su filtro y su fila crece, los\n  // títulos de las demás columnas no quedan centrados verticalmente respecto a ella.\n  const combinedBase = stickyHeader ? baseClasses.replace('items-center', 'items-start') : baseClasses;\n\n  const combinedClasses = [combinedBase, sortableClasses, stickyClasses, alignClasses[column.align || 'left']]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // Header \"crudo\": el ReactNode controla todo su layout (título + filtro por columna),\n  // sin el span truncante ni los iconos de orden internos. Alineado arriba (items-start)\n  // para que, al abrir el filtro, la fila de título no se descentre respecto a las demás columnas.\n  // El crecimiento de la fila al abrir un filtro lo resuelve el contenedor grid con\n  // `auto-rows-min` (grid-auto-rows: min-content), de modo que TODAS las celdas de cabecera se\n  // estiran a la altura del track y el fondo #f8f9fc forma una banda continua a lo ancho de la\n  // tabla (como el prototipo), aunque solo la columna pulsada muestre su input.\n  if (column.headerRaw) {\n    const rawClasses = [baseClasses.replace('items-center', 'items-start'), stickyClasses]\n      .join(' ')\n      .replace(/\\s+/g, ' ')\n      .trim();\n    return (\n      <div\n        role=\"columnheader\"\n        className={rawClasses}\n        // El ReactNode gobierna el LAYOUT de esta cabecera, pero la semántica de orden no es\n        // layout. Sin estas tres líneas una columna `sortable` con cabecera cruda se queda sin\n        // `aria-sort` y sin ninguna vía de teclado: el contenido crudo suele traer solo un `div`\n        // con `onClick`, que el ratón alcanza y el teclado no (WCAG 2.1.1, nivel A).\n        aria-sort={sorted ? (sortDirection === 'asc' ? 'ascending' : 'descending') : undefined}\n        tabIndex={sortable ? 0 : undefined}\n        onKeyDown={\n          sortable\n            ? (e) => {\n                // Solo si el foco está en la cabecera misma. Dentro del contenido crudo suele ir\n                // el filtro por columna, y su Enter debe filtrar, no reordenar la tabla.\n                if (e.target !== e.currentTarget) return;\n                if (e.key === 'Enter' || e.key === ' ') {\n                  e.preventDefault();\n                  onSort();\n                }\n              }\n            : undefined\n        }\n      >\n        {column.header}\n      </div>\n    );\n  }\n\n  return (\n    <div\n      className={combinedClasses}\n      onClick={sortable ? onSort : undefined}\n      // `columnheader` siempre: el `button` que llevaba cuando es ordenable dejaba la\n      // columna sin anunciarse como encabezado. La accion de ordenar se comunica con\n      // `aria-sort` y el `tabIndex`, que ya estaban.\n      role=\"columnheader\"\n      aria-sort={sorted ? (sortDirection === 'asc' ? 'ascending' : 'descending') : undefined}\n      tabIndex={sortable ? 0 : undefined}\n      onKeyDown={\n        sortable\n          ? (e) => {\n              if (e.key === 'Enter' || e.key === ' ') {\n                e.preventDefault();\n                onSort();\n              }\n            }\n          : undefined\n      }\n    >\n      {/* Banda de título de alto = área útil: centra el texto en vertical pixel-exact */}\n      <div className={`flex items-center gap-3 w-full ${titleBand}`}>\n        {/* Texto del header */}\n        <span\n          className={`\n            flex-1\n            min-w-0\n            text-sm\n            font-semibold\n            text-content-primary\n            dark:text-dark-content-primary\n            text-ellipsis\n            overflow-hidden\n            whitespace-nowrap\n            ${spanAlignClasses[column.align || 'left']}\n          `}\n        >\n          {column.header}\n        </span>\n\n        {/* Iconos de sort */}\n        {sortable && (\n          <span className={`shrink-0 transition-colors duration-150 ${\n            sorted\n              ? 'text-primary-custom-600 dark:text-primary-custom-600'\n              : 'text-content-secondary dark:text-content-secondary opacity-40'\n          }`}>\n            {sorted && sortDirection === 'asc' && <ChevronUpIcon />}\n            {sorted && sortDirection === 'desc' && <ChevronDownIcon />}\n            {!sorted && <ChevronUpDownIcon />}\n          </span>\n        )}\n      </div>\n    </div>\n  );\n};\n\n/**\n * TableCell - Componente para una celda de datos\n */\nconst TableCell: React.FC<TableCellProps & {\n  isStriped?: boolean;\n  rowIndex?: number;\n  isStickyRight?: boolean;\n  className?: string;\n  isSelected?: boolean;\n  isFirst?: boolean;\n  isLast?: boolean;\n  clickable?: boolean;\n  accentHover?: boolean;\n  dense?: boolean;\n}> = ({\n  children,\n  align = 'left',\n  width,\n  isStriped = false,\n  rowIndex = 0,\n  isStickyRight = false,\n  className = '',\n  isSelected = false,\n  isFirst = false,\n  isLast = false,\n  clickable = false,\n  accentHover = false,\n  dense = false,\n}) => {\n  // Clases de alineación horizontal\n  const alignClasses = {\n    left: 'justify-start',\n    center: 'justify-center',\n    right: 'justify-end',\n  };\n\n  // Lógica de fondo: prioridad selección > zebra > base\n  const bgClass = isSelected\n    ? 'bg-[#f7fcff] dark:bg-primary-900/20'\n    : isStriped && rowIndex % 2 === 1\n      ? 'bg-background-secondary dark:bg-dark-bg-primary/30'\n      : 'bg-white dark:bg-dark-bg-primary';\n\n  // Clases para sticky column\n  const stickyClasses = isStickyRight\n    ? 'sticky right-0 z-10 shadow-[-2px_0_5px_rgba(0,0,0,0.05)]'\n    : '';\n\n  // Redondeo solo si está seleccionado\n  const roundedClasses = isSelected\n    ? `${isFirst ? 'rounded-l-lg' : ''} ${isLast ? 'rounded-r-lg' : ''}`\n    : '';\n\n  // Hover del prototipo (N2): fondo #f0f7ff en toda la fila + acento izquierdo #0066ff\n  // en la PRIMERA celda (sin salto de layout: el borde ocupa 3px siempre, solo cambia el color).\n  const hoverBgClass = !isSelected\n    ? (accentHover\n        ? 'group-hover:bg-[#f0f7ff] dark:group-hover:bg-primary-900/10'\n        : 'group-hover:bg-[#f9fafb] dark:group-hover:bg-white/[0.02]')\n    : '';\n  // El acento reserva 3px SIEMPRE y solo cambia de color en hover (así no hay salto de\n  // layout), pero para que el reposo sea transparente el color del separador inferior tiene\n  // que pintarse POR LADO (ver el `border-b-border-secondary` de abajo):\n  // `border-border-secondary` pinta `border-color` de los CUATRO lados y se comía este\n  // `border-l-transparent`, dejando una franja gris fija de 3px en la primera celda\n  // (medido en dev el 2026-08-21: rgb(244,244,245) en reposo Y en hover).\n  //\n  // PENDIENTE, fuera de este componente: el fondo de hover de la fila\n  // (`group-hover:bg-[#f0f7ff]`, el `bg-rowhover` del prototipo) sigue sin aplicarse. Lo tapa\n  // `master-pattern-view.css`, que redeclara ~98 utilidades genéricas —`.bg-white` entre\n  // ellas— SIN capa de cascada: lo que va sin capa gana a lo que va en `@layer utilities`,\n  // que es donde el consumidor emite sus variantes, por muy específicas que sean. Medido:\n  // hover deja el fondo en rgb(255,255,255) en vez de rgb(240,247,255). Se arregla metiendo\n  // ese bloque en `@layer utilities`, y no se hace aquí a propósito para no tocar\n  // MasterPatternView.\n  const accentBorderClass = accentHover && isFirst\n    ? 'border-l-[3px] border-l-transparent group-hover:border-l-[#0066ff]'\n    : '';\n\n  return (\n    <div\n      role=\"cell\"\n      className={`\n        flex\n        items-center\n        ${alignClasses[align]}\n        ${dense ? 'px-4 py-2 min-h-[44px]' : 'px-4 py-4 min-h-[56px]'}\n        w-full\n        ${isSelected ? 'border-b-transparent' : 'border-b border-b-border-secondary dark:border-b-dark-border-primary'}\n        ${bgClass}\n        ${stickyClasses}\n        ${roundedClasses}\n        ${accentBorderClass}\n        ${clickable ? 'cursor-pointer' : ''}\n        ${hoverBgClass}\n        transition-colors\n        duration-150\n        ${className}\n      `}\n    >\n      <div\n        className={`\n          text-sm\n          text-content-primary\n          dark:text-dark-content-primary\n          flex\n          ${alignClasses[align]}\n          w-full\n        `}\n      >\n        {children}\n      </div>\n    </div>\n  );\n};\n\n\n/**\n * Pagination - Componente de paginación\n */\nconst Pagination: React.FC<PaginationProps> = ({\n  currentPage,\n  totalPages,\n  onPageChange,\n  showPageNumbers = false,\n  previousLabel = 'Anterior',\n  nextLabel = 'Siguiente',\n  pageSize,\n  pageSizeOptions,\n  onPageSizeChange,\n  totalRecords,\n  perPageLabel = 'por pág.',\n  recordsLabel = 'registros',\n  goToPageLabel = 'Pág.',\n  goToPageAriaLabel = 'Ir a página',\n  firstPageLabel = 'Primera página',\n  lastPageLabel = 'Última página',\n}) => {\n  /**\n   * Lo escrito en el campo «ir a página», o `null` mientras nadie lo está editando.\n   *\n   * <para>`null` NO es lo mismo que cadena vacía: con `null` el campo muestra la página ACTUAL, y\n   * con `''` muestra el campo vacío porque el usuario acaba de borrarlo. Antes el estado era `''`\n   * en los dos casos y el campo quedaba permanentemente en blanco: la página actual sólo se\n   * insinuaba como `placeholder`, que el navegador esconde en cuanto hay valor y que además no es\n   * el dato, sino una pista. Con la barra en su forma por omisión —sin números de página, sólo\n   * flechas— el usuario se quedaba sin ninguna forma de saber en qué página estaba.</para>\n   */\n  const [goToValue, setGoToValue] = useState<string | null>(null);\n\n  const showExtras = !!(pageSizeOptions && pageSizeOptions.length > 0 && onPageSizeChange && pageSize);\n  const multiPage = totalPages > 1;\n\n  // ===== LÓGICA DE NÚMEROS DE PÁGINA =====\n  // Solo se pintan si el consumidor los pide con `showPageNumbers` (por defecto NO). Cuando se\n  // piden: hasta 3 páginas se muestran todas; con más de 3, una ventana deslizante de 3 números\n  // CENTRADA en la página actual. Primera/última se cubren con los botones de chevron doble,\n  // así que no se usan puntos suspensivos.\n  const MAX_NUMEROS_VISIBLES = 3;\n  const getPageNumbers = (): number[] => {\n    if (totalPages <= MAX_NUMEROS_VISIBLES) {\n      return Array.from({ length: totalPages }, (_, i) => i + 1);\n    }\n    // La ventana se ancla para que quepan siempre 3 números sin desbordar por ninguno de los\n    // dos extremos: pegada a 1 en las primeras páginas y a `totalPages` en las últimas.\n    const start = Math.min(\n      Math.max(currentPage - 1, 1),\n      totalPages - (MAX_NUMEROS_VISIBLES - 1),\n    );\n    return Array.from({ length: MAX_NUMEROS_VISIBLES }, (_, i) => start + i);\n  };\n\n  const pageNumbers = getPageNumbers();\n\n  // ===== IR A PÁGINA =====\n  const handleGoTo = () => {\n    const n = parseInt(goToValue ?? '', 10);\n    if (!isNaN(n) && n >= 1 && n <= totalPages) onPageChange(n);\n    // Vuelve a \"nadie está editando\", con lo que el campo pasa a mostrar la página vigente —la\n    // nueva si el salto fue válido, la de antes si no—. Antes se vaciaba, y el usuario terminaba\n    // el gesto con menos información en pantalla de la que tenía al empezarlo.\n    setGoToValue(null);\n  };\n\n  // ===== TOKEN DE ESTILOS — idéntico para botones y controles =====\n  // Todos los elementos interactivos de la barra comparten: color, peso, hover y transición.\n  const interactiveBase = `\n    text-sm font-semibold\n    text-primary-600 dark:text-primary-600\n    hover:bg-blue-50 dark:hover:bg-blue-900/20\n    transition-colors duration-150\n  `;\n\n  // Botones de navegación (Anterior / Siguiente)\n  const navBtnCls = `\n    ${interactiveBase}\n    flex items-center gap-1.5 px-3 py-1.5 rounded-md\n    disabled:opacity-40 disabled:cursor-not-allowed\n  `;\n\n  // Número de página activo\n  const pageActiveCls = `\n    flex items-center justify-center min-w-[32px] px-2 py-1.5 rounded-md\n    text-sm font-semibold text-primary-600 dark:text-primary-600\n    bg-blue-100 dark:bg-blue-900/30\n    transition-colors duration-150\n  `;\n\n  // Número de página inactivo\n  const pageInactiveCls = `\n    flex items-center justify-center min-w-[32px] px-2 py-1.5 rounded-md\n    text-sm font-semibold text-primary-600 dark:text-primary-600\n    hover:bg-blue-50 dark:hover:bg-blue-900/20\n    transition-colors duration-150\n  `;\n\n  // Select e Input de la barra (prototipo): neutrales (borde `line`, texto `ink`, fondo blanco),\n  // NO azules ni en negrita.\n  const formControlCls = `\n    text-sm text-content-primary dark:text-dark-content-primary\n    bg-white dark:bg-dark-bg-primary\n    border border-border-primary dark:border-dark-border-primary\n    rounded py-1\n    focus:outline-none focus:border-[#93d1fd]\n    transition-colors\n    disabled:opacity-40 disabled:cursor-not-allowed\n    cursor-pointer\n  `;\n\n  // ===== SECCIÓN DE NAVEGACIÓN (compartida) — diseño del prototipo =====\n  // Primera · Anterior · [números máx. 2] · Siguiente · Última (solo iconos, sin texto).\n  const navIconBtnCls = `\n    inline-flex items-center justify-center w-8 h-8 rounded-md cursor-pointer\n    text-primary-600 dark:text-primary-600\n    hover:bg-primary-100 dark:hover:bg-primary-900/20\n    active:scale-95 transition-all duration-150\n    disabled:opacity-40 disabled:cursor-not-allowed\n  `.replace(/\\s+/g, ' ').trim();\n  const navNumBtnCls = (active: boolean) => `\n    inline-flex items-center justify-center min-w-8 h-8 px-3 rounded-md cursor-pointer\n    text-sm font-bold transition-all duration-150\n    ${active\n      ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-600'\n      : 'text-primary-600 dark:text-primary-600 hover:bg-primary-100 dark:hover:bg-primary-900/20 active:scale-95'}\n  `.replace(/\\s+/g, ' ').trim();\n\n  const navSection = (\n    <nav className=\"flex items-center gap-0.5\" aria-label={previousLabel === 'Anterior' ? 'Paginación' : previousLabel}>\n      <button type=\"button\" title={firstPageLabel} aria-label={firstPageLabel} onClick={() => currentPage > 1 && onPageChange(1)} disabled={!multiPage || currentPage === 1} className={navIconBtnCls}>\n        <ChevronsLeftIcon />\n      </button>\n      <button type=\"button\" title={previousLabel} aria-label={previousLabel} onClick={() => currentPage > 1 && onPageChange(currentPage - 1)} disabled={!multiPage || currentPage === 1} className={navIconBtnCls}>\n        <ChevronLeftIcon />\n      </button>\n\n      {showPageNumbers && multiPage && pageNumbers.map((page) => (\n        <button\n          key={page}\n          type=\"button\"\n          onClick={() => onPageChange(page)}\n          aria-current={page === currentPage ? 'page' : undefined}\n          className={navNumBtnCls(page === currentPage)}\n        >\n          {page}\n        </button>\n      ))}\n\n      <button type=\"button\" title={nextLabel} aria-label={nextLabel} onClick={() => currentPage < totalPages && onPageChange(currentPage + 1)} disabled={!multiPage || currentPage === totalPages} className={navIconBtnCls}>\n        <ChevronRightIcon />\n      </button>\n      <button type=\"button\" title={lastPageLabel} aria-label={lastPageLabel} onClick={() => currentPage < totalPages && onPageChange(totalPages)} disabled={!multiPage || currentPage === totalPages} className={navIconBtnCls}>\n        <ChevronsRightIcon />\n      </button>\n    </nav>\n  );\n\n  // ===== LAYOUT CON EXTRAS =====\n  if (showExtras) {\n    return (\n      <div className=\"flex items-center justify-between w-full gap-4 flex-wrap\">\n\n        {/* IZQUIERDA — Selector de registros por página + total */}\n        <div className=\"flex items-center gap-1.5 flex-none\">\n          <select\n            value={pageSize}\n            onChange={(e) => onPageSizeChange!(Number(e.target.value))}\n            aria-label=\"Registros por página\"\n            className={`${formControlCls} px-2`}\n          >\n            {pageSizeOptions!.map((size) => (\n              <option key={size} value={size}>{size}</option>\n            ))}\n          </select>\n          {/* En OSCURO los tres textos de esta barra van un paso más claros que su equivalente en\n              claro: `dark-content-tertiary` (#71717A) sobre `dark-bg-secondary` (#27272A) da 3.08\n              y no alcanza el 4.5 que WCAG AA exige para texto pequeño; `dark-content-secondary`\n              (#A1A1AA) da 5.81. El TOKEN no se toca —lo usa medio kit—: sólo cambia cuál usa esta\n              barra, y sólo en oscuro. */}\n          <span className=\"text-sm text-content-tertiary dark:text-dark-content-secondary whitespace-nowrap\">\n            {perPageLabel}\n          </span>\n          {totalRecords !== undefined && (\n            <>\n              <span className=\"text-content-secondary dark:text-content-secondary select-none px-0.5\">·</span>\n              <span className=\"text-sm text-content-tertiary dark:text-dark-content-secondary whitespace-nowrap\">\n                {totalRecords.toLocaleString()} {recordsLabel}\n              </span>\n            </>\n          )}\n        </div>\n\n        {/* CENTRO — Navegación */}\n        {navSection}\n\n        {/* DERECHA — Ir a página */}\n        <div className=\"flex items-center gap-2 flex-none\">\n          <span className=\"text-sm text-content-tertiary dark:text-dark-content-secondary whitespace-nowrap\">\n            {goToPageLabel}\n          </span>\n          <input\n            type=\"number\"\n            min={1}\n            max={totalPages || 1}\n            value={goToValue ?? String(currentPage)}\n            onChange={(e) => setGoToValue(e.target.value)}\n            onKeyDown={(e) => { if (e.key === 'Enter') handleGoTo(); }}\n            onBlur={handleGoTo}\n            disabled={!multiPage}\n            aria-label={goToPageAriaLabel}\n            className={`${formControlCls} w-16 text-center px-2`}\n          />\n        </div>\n      </div>\n    );\n  }\n\n  // ===== LAYOUT ORIGINAL (sin extras — backward compatible) =====\n  return (\n    <div className=\"flex items-center justify-center w-full h-9\">\n      {navSection}\n    </div>\n  );\n};\n\n/**\n * Table - Componente principal de tabla\n *\n * Características implementadas:\n * - Definición de columnas flexible con accessor y render custom\n * - Sorting en columnas (controlado o no controlado)\n * - Variantes: basic, fullWidth, striped, grid\n * - Dark mode completo en todos los estados\n * - Estados de loading y empty\n * - Filas clickeables\n * - Accesibilidad con roles y keyboard navigation\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto y generics\n * - Accesibilidad con ARIA labels y keyboard support\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Label/Small para headers, Paragraph/Small para cells)\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * // Uso básico\n * <Table\n *   title=\"Usuarios\"\n *   columns={[\n *     { header: 'Nombre', accessor: 'name' },\n *     { header: 'Email', accessor: 'email' },\n *     { header: 'Rol', accessor: 'role', sortable: true },\n *   ]}\n *   data={users}\n * />\n *\n * // Con render custom\n * <Table\n *   columns={[\n *     {\n *       header: 'Estado',\n *       accessor: 'status',\n *       render: (value) => (\n *         <Badge color={value === 'active' ? 'green' : 'red'}>\n *           {value}\n *         </Badge>\n *       ),\n *     },\n *   ]}\n *   data={data}\n * />\n *\n * // Variante striped\n * <Table\n *   variant=\"striped\"\n *   columns={columns}\n *   data={data}\n * />\n * ```\n */\nexport const Table = <T extends Record<string, any>>({\n  title,\n  columns,\n  data,\n  variant = 'basic',\n  showBorder = true,\n  showShadow = true,\n  showPadding = true,\n  onRowClick,\n  onRowDoubleClick,\n  disableRowTextSelection = false,\n  suppressRowClickOnDoubleClick = false,\n  doubleClickDelay = 250,\n  onSort,\n  sortColumn: externalSortColumn,\n  sortDirection: externalSortDirection,\n  fullWidth = false,\n  emptyMessage = 'No hay datos disponibles',\n  loading = false,\n  loadingRows = 5,\n  pagination,\n  isRowSelected,\n  className = '',\n  id,\n  stickyHeader = false,\n  headerBand = false,\n  minGridHeight,\n  accentHover = false,\n  dense = false,\n}: TableProps<T>) => {\n  // ===== ESTADO INTERNO DE SORT =====\n  const [internalSortColumn, setInternalSortColumn] = useState<keyof T | string | null>(null);\n  const [internalSortDirection, setInternalSortDirection] = useState<SortDirection>(null);\n\n  // Usar sort externo si está controlado, sino usar interno\n  const sortColumn = externalSortColumn !== undefined ? externalSortColumn : internalSortColumn;\n  const sortDirection = externalSortDirection !== undefined ? externalSortDirection : internalSortDirection;\n\n  // ===== MANEJAR SORT =====\n  const handleSort = (columnAccessor: keyof T | string) => {\n    let newDirection: SortDirection = 'asc';\n\n    // Si ya está ordenado por esta columna, cambiar dirección\n    if (sortColumn === columnAccessor) {\n      if (sortDirection === 'asc') {\n        newDirection = 'desc';\n      } else if (sortDirection === 'desc') {\n        newDirection = null;\n      }\n    }\n\n    // Si sort es controlado, llamar callback\n    if (onSort) {\n      onSort(columnAccessor, newDirection);\n    } else {\n      // Sino, actualizar estado interno\n      setInternalSortColumn(newDirection ? columnAccessor : null);\n      setInternalSortDirection(newDirection);\n    }\n  };\n\n  // ===== INTERACCION DE FILA (CLIC / DOBLE CLIC) =====\n  // `onRowDoubleClick` es opt-in: sin esa prop (y sin `disableRowTextSelection`) la fila se\n  // comporta exactamente igual que antes —texto seleccionable incluido—, que es lo que necesitan\n  // las tablas de consulta donde el usuario copia el contenido de una celda.\n  //\n  // Con la prop puesta, la fila deja de ser texto seleccionable. Sin eso el gesto real es inerte:\n  // el segundo clic del doble clic selecciona la palabra bajo el cursor, y el guardia de seleccion\n  // del `onClick` de abajo —que existe para no navegar cuando el usuario arrastra para copiar—\n  // descarta el clic. Se midio en navegador real inyectando solo CSS: con `user-select: none` el\n  // gesto funciona, al retirarlo vuelve a fallar.\n  const hasRowClick = !!onRowClick;\n  const hasRowDoubleClick = !!onRowDoubleClick;\n  const isRowInteractive = hasRowClick || hasRowDoubleClick;\n  // El doble clic aplaza el clic simple solo si el consumidor lo pide Y hay ambos callbacks: con\n  // uno solo no hay nada que desambiguar y meter un timer cambiaria el momento de la invocacion.\n  const deferRowClick = suppressRowClickOnDoubleClick && hasRowClick && hasRowDoubleClick;\n\n  // `select-none` de Tailwind emite `-webkit-user-select: none` y `user-select: none`. La fila es\n  // `display: contents`, pero `user-select` se hereda, así que llega igual a las celdas.\n  const rowTextSelectionOff = hasRowDoubleClick || disableRowTextSelection;\n  const rowSelectNoneClass = rowTextSelectionOff ? ' select-none' : '';\n\n  // Timers pendientes del clic aplazado, por indice de fila. Se limpian al desmontar para no\n  // invocar el callback del consumidor sobre un arbol que ya no existe.\n  const pendingClickTimers = useRef(new Map<number, ReturnType<typeof setTimeout>>());\n  useEffect(() => {\n    const timers = pendingClickTimers.current;\n    return () => {\n      timers.forEach((timer) => clearTimeout(timer));\n      timers.clear();\n    };\n  }, []);\n\n  const handleRowClick = useCallback(\n    (row: T, rowIndex: number) => {\n      if (!onRowClick) return;\n      // Un click-drag para seleccionar/copiar el texto de una celda también dispara este \"click\"\n      // al soltar el mouse. Si el usuario dejó una selección de texto activa, es que quería\n      // copiar, no navegar al detalle.\n      //\n      // El guardia no aplica cuando la fila ya no es seleccionable: ahí no hay copia que proteger\n      // y una selección residual de otra parte de la página no debe tragarse el clic (era\n      // justamente lo que dejaba inerte el doble clic).\n      if (!rowTextSelectionOff) {\n        const selection = window.getSelection?.();\n        if (selection && selection.toString().length > 0) return;\n      }\n\n      if (!deferRowClick) {\n        onRowClick(row, rowIndex);\n        return;\n      }\n\n      const timers = pendingClickTimers.current;\n      const previous = timers.get(rowIndex);\n      if (previous) clearTimeout(previous);\n      timers.set(\n        rowIndex,\n        setTimeout(() => {\n          timers.delete(rowIndex);\n          onRowClick(row, rowIndex);\n        }, doubleClickDelay),\n      );\n    },\n    [onRowClick, deferRowClick, doubleClickDelay, rowTextSelectionOff],\n  );\n\n  const handleRowDoubleClick = useCallback(\n    (row: T, rowIndex: number) => {\n      if (!onRowDoubleClick) return;\n      const timers = pendingClickTimers.current;\n      const pending = timers.get(rowIndex);\n      if (pending) {\n        clearTimeout(pending);\n        timers.delete(rowIndex);\n      }\n      onRowDoubleClick(row, rowIndex);\n    },\n    [onRowDoubleClick],\n  );\n\n  // Activación por teclado. `onRowClick` manda cuando existe (no cambia el comportamiento previo);\n  // si `onRowDoubleClick` es el único callback, es él quien responde a Enter/Espacio, para que el\n  // gesto no quede sin ruta accesible.\n  const handleRowKeyActivate = useCallback(\n    (row: T, rowIndex: number) => {\n      if (onRowClick) {\n        // El teclado no puede producir un doble clic: aquí no se aplaza nada.\n        onRowClick(row, rowIndex);\n        return;\n      }\n      onRowDoubleClick?.(row, rowIndex);\n    },\n    [onRowClick, onRowDoubleClick],\n  );\n\n  // ===== OBTENER VALOR DE CELDA =====\n  const getCellValue = (row: T, accessor: keyof T | ((row: T) => any)) => {\n    if (typeof accessor === 'function') {\n      return accessor(row);\n    }\n    return row[accessor];\n  };\n\n  // ===== CLASES DEL CONTAINER =====\n  // Con stickyHeader el container llena la altura disponible (flex-1 min-h-0) y sin gap,\n  // para que el grid scrollee internamente y la paginación quede como footer fijo.\n  const containerBaseClasses = `\n    flex\n    flex-col\n    ${stickyHeader ? 'flex-1 min-h-0 gap-0' : 'gap-4'}\n    bg-white\n    dark:bg-dark-bg-primary\n    rounded-xl\n    transition-all\n    duration-150\n  `;\n\n  const containerBorderClasses = showBorder\n    ? 'border border-border-primary dark:border-dark-border-primary'\n    : '';\n\n  const containerShadowClasses = showShadow ? 'shadow-base' : '';\n\n  const containerPaddingClasses = showPadding ? 'p-8' : 'p-0';\n\n  const containerWidthClasses = fullWidth || variant === 'fullWidth' ? 'w-full' : '';\n\n  const containerClasses = [\n    containerBaseClasses,\n    containerBorderClasses,\n    containerShadowClasses,\n    containerPaddingClasses,\n    containerWidthClasses,\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== CLASES DE LA TABLA =====\n  const tableGridClasses = variant === 'grid'\n    ? `\n      border\n      border-border-primary\n      dark:border-dark-border-primary\n      rounded-lg\n      overflow-hidden\n    `\n    : '';\n\n  // ===== RENDER =====\n  return (\n    <div className={containerClasses} id={id}>\n      {/* Título opcional */}\n      {title && (\n        <div className=\"flex items-center justify-center w-full\">\n          <h3\n            className=\"\n              text-base\n              font-semibold\n              text-content-primary\n              dark:text-dark-content-primary\n              text-ellipsis\n              overflow-hidden\n              whitespace-nowrap\n            \"\n          >\n            {title}\n          </h3>\n        </div>\n      )}\n\n      {/* Tabla */}\n      {/* Con stickyHeader el propio grid es el contenedor de scroll (flex-1 min-h-0 overflow-auto):\n          el header (sticky top-0) se ancla a él y queda fijo, mientras la paginación —hermana\n          fuera del scroll— permanece como footer fijo. Sin stickyHeader se conserva el\n          comportamiento previo (overflow-x-auto). */}\n      <div\n        // La tabla se maqueta con CSS grid, no con <table>, así que sin estos roles\n        // el árbol de accesibilidad la aplana a texto suelto: ni filas, ni encabezados\n        // de columna. Verificado en Chrome que los roles SÍ se respetan aunque las\n        // filas lleven `display: contents`, así que no hace falta cambiar la maqueta.\n        role=\"table\"\n        className={`grid ${stickyHeader ? 'flex-1 min-h-0 overflow-auto grid-rows-[min-content] content-start auto-rows-min' : 'overflow-x-auto'} ${tableGridClasses}`}\n        style={{\n          display: 'grid',\n          width: '100%',\n          minWidth: '100%',\n          // Suelo de alto de la caja de filas (ver `minGridHeight`). `content-start`\n          // ya está en las clases del grid, así que las filas se quedan arriba y el\n          // hueco sobra por abajo en vez de estirarlas.\n          ...(minGridHeight ? { minHeight: minGridHeight, alignContent: 'start' } : {}),\n          gridTemplateColumns: columns.map(c => {\n            const width = c.width || '1fr';\n            const widthStr = String(width);\n\n            // Columna de ancho FIJO (opt-in): se queda exactamente en `width`, no se expande\n            // para repartir el espacio sobrante (columnas utilitarias: acciones, selección, etc.).\n            if (c.fixedWidth && c.width) {\n              return /^\\d+$/.test(widthStr) ? `${widthStr}px` : widthStr;\n            }\n\n            // Si el ancho no es flexible (fr, %) ni es 'auto',\n            // lo transformamos en minmax para forzar expansión.\n            if (!widthStr.includes('fr') && !widthStr.includes('%') && widthStr !== 'auto') {\n              const finalWidth = /^\\d+$/.test(widthStr) ? `${widthStr}px` : widthStr;\n              return `minmax(${finalWidth}, 1fr)`;\n            }\n            return width;\n          }).join(' '),\n        }}\n      >\n        {/* Headers. El envoltorio va con `display: contents` para que las celdas sigan\n            siendo hijas directas del grid y el dimensionado por `gridTemplateColumns` no\n            cambie; solo aporta el `role=\"row\"` que faltaba. */}\n        <div role=\"row\" className=\"contents\">\n        {columns.map((column, colIndex) => {\n          const accessor = typeof column.accessor === 'function'\n            ? `column_${colIndex}`\n            : String(column.accessor);\n\n          return (\n            <TableHeader\n              key={`header-${accessor}`}\n              column={column}\n              sortable={column.sortable || false}\n              sorted={sortColumn === accessor}\n              sortDirection={sortColumn === accessor ? sortDirection : null}\n              onSort={() => handleSort(accessor)}\n              stickyHeader={stickyHeader}\n              headerBand={headerBand}\n              dense={dense}\n            />\n          );\n        })}\n        </div>\n\n        {/* Loading skeleton */}\n        {loading && (\n          <>\n            {Array.from({ length: loadingRows }).map((_, rowIndex) => (\n              columns.map((column, colIndex) => {\n                const accessor = typeof column.accessor === 'function'\n                  ? `column_${colIndex}`\n                  : String(column.accessor);\n\n                return (\n                  <TableCell\n                    key={`loading-${rowIndex}-${accessor}`}\n                    align={column.align}\n                    isStriped={variant === 'striped'}\n                    rowIndex={rowIndex}\n                    dense={dense}\n                  >\n                    <div\n                      className=\"\n                        h-4\n                        w-full\n                        bg-background-secondary\n                        dark:bg-dark-border-primary\n                        rounded\n                        animate-pulse\n                      \"\n                    />\n                  </TableCell>\n                );\n              })\n            ))}\n          </>\n        )}\n\n        {/* Datos reales */}\n        {!loading && data.length > 0 && (\n          <>\n            {data.map((row, rowIndex) => {\n              const isSelected = isRowSelected?.(row, rowIndex);\n              const isClickable = isRowInteractive;\n              return (\n                <div\n                  key={`row-${rowIndex}`}\n                  // `select-none` solo en las filas que lo piden (doble clic o la prop\n                  // explícita): sin eso, la clase se llevaría por delante el copiar/pegar de\n                  // las tablas que hoy no manejan el gesto.\n                  className={`contents group${rowSelectNoneClass}`}\n                  // `row` siempre. Cuando la fila es clicable el rol de boton la sacaba\n                  // de la tabla para el lector de pantalla; el comportamiento de clic lo\n                  // siguen dando el tabIndex y el onKeyDown de abajo.\n                  role=\"row\"\n                  tabIndex={isClickable ? 0 : undefined}\n                  onClick={\n                    hasRowClick\n                      ? () => handleRowClick(row, rowIndex)\n                      : undefined\n                  }\n                  onDoubleClick={\n                    hasRowDoubleClick\n                      ? () => handleRowDoubleClick(row, rowIndex)\n                      : undefined\n                  }\n                  onKeyDown={\n                    isClickable\n                      ? (e) => {\n                          if (e.key === 'Enter' || e.key === ' ') {\n                            e.preventDefault();\n                            handleRowKeyActivate(row, rowIndex);\n                          }\n                        }\n                      : undefined\n                  }\n                >\n                  {columns.map((column, colIndex) => {\n                    const accessor = typeof column.accessor === 'function'\n                      ? `column_${colIndex}`\n                      : String(column.accessor);\n                    const value = getCellValue(row, column.accessor);\n                    const content = column.render\n                      ? column.render(value, row, rowIndex)\n                      : value;\n\n                    return (\n                      <TableCell\n                        key={`cell-${rowIndex}-${accessor}`}\n                        align={column.align}\n                        isStriped={variant === 'striped'}\n                        rowIndex={rowIndex}\n                        isStickyRight={column.stickyRight}\n                        isSelected={isSelected}\n                        isFirst={colIndex === 0}\n                        isLast={colIndex === columns.length - 1}\n                        clickable={isClickable}\n                        accentHover={accentHover}\n                        dense={dense}\n                      >\n                        {content}\n                      </TableCell>\n                    );\n                  })}\n                </div>\n              );\n            })}\n          </>\n        )}\n\n        {/* Estado empty */}\n        {!loading && data.length === 0 && (\n          <div\n            className=\"\n              flex\n              items-center\n              justify-center\n              px-6\n              py-12\n              text-sm\n              text-content-secondary\n              dark:text-content-secondary\n            \"\n            style={{ gridColumn: `1 / ${columns.length + 1}` }}\n          >\n            {emptyMessage}\n          </div>\n        )}\n      </div>\n\n      {/* Paginación */}\n      {pagination && (\n        <div className={`${stickyHeader ? 'flex-shrink-0 px-4 py-2 bg-[#f8f9fc] dark:bg-dark-bg-secondary border-t border-border-primary dark:border-dark-border-primary' : (!showPadding ? 'p-4 border-t border-border-secondary dark:border-dark-border-primary' : '')}`}>\n          <Pagination\n            currentPage={pagination.currentPage}\n            totalPages={pagination.totalPages}\n            onPageChange={pagination.onPageChange}\n            showPageNumbers={pagination.showPageNumbers}\n            previousLabel={pagination.previousLabel}\n            nextLabel={pagination.nextLabel}\n            firstPageLabel={pagination.firstPageLabel}\n            lastPageLabel={pagination.lastPageLabel}\n            pageSize={pagination.pageSize}\n            pageSizeOptions={pagination.pageSizeOptions}\n            onPageSizeChange={pagination.onPageSizeChange}\n            totalRecords={pagination.totalRecords}\n            perPageLabel={pagination.perPageLabel}\n            recordsLabel={pagination.recordsLabel}\n            goToPageLabel={pagination.goToPageLabel}\n            goToPageAriaLabel={pagination.goToPageAriaLabel}\n          />\n        </div>\n      )}\n    </div>\n  );\n};\n","import React from 'react';\nimport {\n  XMarkIcon as HeroXMarkIcon,\n  ExclamationCircleIcon as HeroExclamationCircleIcon,\n  ComputerDesktopIcon as HeroComputerDesktopIcon,\n} from '@heroicons/react/24/outline';\n\n/** Icono de monitor / escritorio */\nexport const ComputerDesktopIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroComputerDesktopIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de advertencia en círculo */\nexport const ExclamationCircleIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroExclamationCircleIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de X para cerrar/cancelar */\nexport const CloseIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroXMarkIcon className={className} aria-hidden=\"true\" />\n);\n","import type { TranslationArg } from '../types';\n\n/**\n * Marcador de interpolación: `{{nombre}}`, con espacios opcionales alrededor del nombre.\n *\n * Se admiten los espacios porque quien escribe el catálogo no siempre los omite, y una clave con\n * `{{ count }}` que no sustituye es indistinguible de un defecto del motor para quien la reporta.\n */\nconst MARCADOR = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Sustituye los marcadores `{{nombre}}` de un texto ya traducido.\n *\n * <para><b>Por qué vive aquí y no en el motor.</b> `TranslationEngine` es un contrato PÚBLICO que\n * implementan motores de terceros: ampliar su `translate` obligaría a cambiar cada implementación\n * existente. La interpolación es, además, independiente del catálogo — opera sobre el resultado—,\n * así que su sitio es la capa del provider, donde se aplica por igual a cualquier motor.</para>\n *\n * <para><b>Un marcador sin valor se deja INTACTO.</b> Borrarlo produce una frase que se lee bien y\n * miente («0 línea(s)» cuando no se sabe cuántas hay); dejarlo visible se reconoce al instante como\n * lo que es. El mismo criterio que sigue `translate` al devolver la llave cuando no la encuentra.</para>\n *\n * @example\n * interpolate('{{count}} línea(s) · saldo {{balance}}', { count: 3, balance: '265,00' })\n * // '3 línea(s) · saldo 265,00'\n */\nexport function interpolate(text: string, arg?: TranslationArg): string {\n  // Una CADENA no interpola: es el valor por omisión, y lo aplica `resolveTranslation`, que es quien\n  // sabe si la llave se encontró. Aquí sólo se deja el texto intacto.\n  if (!arg || typeof arg === 'string') return text;\n\n  return text.replace(MARCADOR, (marcador, nombre: string) => {\n    const valor = arg[nombre];\n    return valor === null || valor === undefined ? marcador : String(valor);\n  });\n}\n\n/**\n * Resuelve el segundo argumento de `t`: interpola si es un objeto, y aplica el respaldo si es una\n * cadena y la llave no estaba en el catálogo.\n *\n * <para>El motor devuelve la PROPIA LLAVE cuando no la encuentra; ésa es la señal por la que se\n * decide aplicar el respaldo, y es la misma que el kit ya usaba antes de que `t` tuviera segundo\n * argumento.</para>\n */\nexport function resolveTranslation(key: string, translated: string, arg?: TranslationArg): string {\n  if (typeof arg === 'string') return translated === key ? arg : translated;\n  return interpolate(translated, arg);\n}\n","import type { TranslationEngine, TranslationLookup, TranslationResources } from '../types';\n\n/**\n * Motor de traducción predeterminado\n * Permite manejar múltiples recursos cargados en memoria y realizar fallbacks\n */\nexport class DefaultTranslationEngine implements TranslationEngine {\n  private resources: { [lang: string]: TranslationResources } = {};\n  private currentLanguage: string = 'es';\n  private defaultLanguage: string = 'es';\n\n  constructor(defaultLang: string = 'es') {\n    this.defaultLanguage = defaultLang;\n    this.currentLanguage = defaultLang;\n  }\n\n  /**\n   * Resuelve una llave indicando en qué idioma se encontró, o `null` si no está\n   * en ningún catálogo. Misma búsqueda que `translate()` (idioma actual, luego\n   * fallback al default) pero sin colapsar ambos casos en una cadena.\n   *\n   * @param key Llave del mensaje (ej: 'saludo.bienvenida')\n   */\n  resolve(key: string): TranslationLookup | null {\n    // Se comprueba la EXISTENCIA de la llave (`in`), no que su valor sea truthy.\n    // Con un chequeo por truthiness, una traducción legítimamente vacía —una\n    // cabecera de columna sin título, por ejemplo— se trataba como inexistente y\n    // el motor devolvía la propia llave, que terminaba renderizada en la UI.\n    // 1. Intentar en idioma actual\n    const currentResources = this.resources[this.currentLanguage];\n    if (currentResources && key in currentResources) {\n      return { value: currentResources[key], lang: this.currentLanguage };\n    }\n\n    // 2. Intentar en idioma default (fallback)\n    const defaultResources = this.resources[this.defaultLanguage];\n    if (\n      this.currentLanguage !== this.defaultLanguage &&\n      defaultResources &&\n      key in defaultResources\n    ) {\n      return { value: defaultResources[key], lang: this.defaultLanguage };\n    }\n\n    // 3. No existe en ninguna parte\n    return null;\n  }\n\n  /**\n   * Traduce una llave. Busca en el idioma actual y hace fallback al default si falla.\n   * @param key Llave del mensaje (ej: 'saludo.bienvenida')\n   */\n  translate(key: string): string {\n    // Devuelve la llave si no existe en ninguna parte, para no romper la UI.\n    return this.resolve(key)?.value ?? key;\n  }\n\n  /**\n   * Registra recursos en el motor\n   */\n  loadResources(lang: string, resources: TranslationResources): void {\n    // Mergeamos si ya existen recursos para ese idioma\n    this.resources[lang] = {\n      ...(this.resources[lang] || {}),\n      ...resources,\n    };\n  }\n\n  /**\n   * Indica si el motor ya tiene recursos en memoria para un idioma.\n   * Permite al provider decidir si puede revalidar en segundo plano (ya hay algo\n   * que pintar) o si debe esperar la respuesta del backend.\n   */\n  hasResources(lang: string): boolean {\n    const resources = this.resources[lang];\n    return Boolean(resources) && Object.keys(resources).length > 0;\n  }\n\n  /**\n   * Cambia el idioma activo en el motor\n   */\n  changeLanguage(lang: string): void {\n    this.currentLanguage = lang;\n  }\n\n  /**\n   * Obtiene el código del idioma activo\n   */\n  getCurrentLanguage(): string {\n    return this.currentLanguage;\n  }\n}\n","import type { TranslationResources, Language } from '../types';\n\nconst APP_LANGUAGE_KEY = 'app_language';\nconst TRANSLATIONS_PREFIX = 'translations_';\nconst AVAILABLE_LANGS_KEY = 'app_available_langs';\n\n/**\n * Persistencia en localStorage para internacionalización\n */\nexport const languageStorage = {\n  /**\n   * Guarda el idioma activo en localStorage\n   */\n  setLanguage: (lang: string): void => {\n    localStorage.setItem(APP_LANGUAGE_KEY, lang);\n  },\n\n  /**\n   * Obtiene el idioma guardado o null\n   */\n  getLanguage: (): string | null => {\n    return localStorage.getItem(APP_LANGUAGE_KEY);\n  },\n\n  /**\n   * Guarda las traducciones de un idioma en localStorage\n   */\n  setTranslations: (lang: string, resources: TranslationResources): void => {\n    localStorage.setItem(`${TRANSLATIONS_PREFIX}${lang}`, JSON.stringify(resources));\n  },\n\n  /**\n   * Obtiene las traducciones cacheadas o null\n   */\n  getTranslations: (lang: string): TranslationResources | null => {\n    const data = localStorage.getItem(`${TRANSLATIONS_PREFIX}${lang}`);\n    if (!data) return null;\n    try {\n      return JSON.parse(data);\n    } catch {\n      return null;\n    }\n  },\n\n  /**\n   * Elimina las traducciones cacheadas de un idioma concreto.\n   * Usado por la invalidación explícita (`refreshTranslations`) para forzar\n   * que la siguiente carga venga del backend y no de la caché.\n   */\n  removeTranslations: (lang: string): void => {\n    localStorage.removeItem(`${TRANSLATIONS_PREFIX}${lang}`);\n  },\n\n  /**\n   * Guarda la lista de idiomas disponibles\n   */\n  setAvailableLanguages: (languages: Language[]): void => {\n    localStorage.setItem(AVAILABLE_LANGS_KEY, JSON.stringify(languages));\n  },\n\n  /**\n   * Obtiene los idiomas disponibles cacheados\n   */\n  getAvailableLanguages: (): Language[] | null => {\n    const data = localStorage.getItem(AVAILABLE_LANGS_KEY);\n    if (!data) return null;\n    try {\n      return JSON.parse(data);\n    } catch {\n      return null;\n    }\n  },\n\n  /**\n   * Limpia toda la cache de traducciones\n   */\n  clearCache: (): void => {\n    Object.keys(localStorage).forEach((key) => {\n      if (key.startsWith(TRANSLATIONS_PREFIX) || key === AVAILABLE_LANGS_KEY) {\n        localStorage.removeItem(key);\n      }\n    });\n  }\n};\n","import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport type {\n  TranslationProviderProps,\n  TranslationResources,\n  TranslationLookup,\n  TranslationArg,\n  Language,\n} from '../types';\nimport { interpolate, resolveTranslation } from './interpolate';\nimport { DefaultTranslationEngine } from '../engines/DefaultTranslationEngine';\nimport { languageStorage } from '../storage/languageStorage';\n\n/**\n * Interfaz del contexto interno de traducción\n */\ninterface TranslationContextType {\n  /**\n   * Traduce una llave y, si se pasan `params`, sustituye sus marcadores `{{nombre}}`.\n   *\n   * <para>`params` es OPCIONAL y el parámetro se añadió sin cambiar la forma de un solo argumento,\n   * así que todas las llamadas existentes siguen valiendo. Antes de esto el kit no tenía forma de\n   * interpolar: una clave del catálogo con marcadores llegaba a la pantalla con el marcador crudo\n   * («Detalle — {{number}}»), y cada consumidor lo rodeaba con `t(...).replace('{{x}}', v)` — un\n   * `replace` por marcador, que es exactamente donde se olvida el segundo.</para>\n   */\n  translate: (key: string, arg?: TranslationArg) => string;\n  t: (key: string, arg?: TranslationArg) => string; // Alias común\n  /**\n   * Resolución con procedencia: devuelve el valor y el idioma en el que se\n   * encontró, o `null` si la clave no está registrada. Permite a un consumidor\n   * con diccionarios propios distinguir una traducción del idioma activo de un\n   * fallback al idioma base. Ver `TranslationEngine.resolve`.\n   *\n   * Es opcional: un motor de terceros puede no implementarlo.\n   */\n  resolve?: (key: string) => TranslationLookup | null;\n  setLanguage: (lang: string) => Promise<void>;\n  currentLanguage: string;\n  languages: Language[];\n  isReady: boolean;\n  error: string | null;\n  /**\n   * Invalidación explícita: borra la caché del idioma activo (y del idioma por\n   * defecto, que se usa como fallback) y vuelve a pedir el catálogo al backend.\n   */\n  refreshTranslations: () => Promise<void>;\n  /**\n   * Contador que se incrementa cada vez que el motor recibe recursos nuevos.\n   *\n   * El motor de traducción es un objeto mutable, así que cargarle recursos NO\n   * re-renderiza a los consumidores. Este contador viaja en el `value` del\n   * contexto para invalidarlos cuando llega un catálogo fresco.\n   */\n  resourceVersion: number;\n}\n\nconst TranslationContext = createContext<TranslationContextType | undefined>(undefined);\n\n/**\n * Claves en las que un host puede envolver el código de idioma dentro del `detail` del broadcast.\n * El contrato tipado es un string plano (`CustomEvent<string>`), pero los shells reales difunden\n * `{ language: 'en-US' }`, así que también se aceptan las envolturas equivalentes.\n */\nconst LANGUAGE_CODE_KEYS = ['language', 'lang', 'codigo', 'code'] as const;\n\n/**\n * Extrae el código de idioma de un valor que NO controla el kit.\n *\n * El `detail` del evento `broadcastEventName` lo produce el host (el Shell), no el provider, y hasta\n * ahora entraba VERBATIM al estado: un objeto ahí se propagaba a `currentLanguage`, al motor de\n * traducción, al path de `apiAdapter.getTranslations()` y a la cabecera `Accept-Language`. Del lado\n * del consumidor eso reventaba cualquier `currentLanguage.toLowerCase()` — el tipo promete `string` —\n * y con ello el render completo del microfrontend.\n *\n * Ley de Postel: se acepta tanto el string del contrato como la envoltura que difunden los shells, y\n * cualquier otra cosa devuelve `null` para que el llamador la descarte sin tocar el estado.\n */\nconst readLanguageCode = (value: unknown): string | null => {\n  if (typeof value === 'string') return value !== '' ? value : null;\n\n  if (value !== null && typeof value === 'object') {\n    for (const key of LANGUAGE_CODE_KEYS) {\n      const candidate = (value as Record<string, unknown>)[key];\n      if (typeof candidate === 'string' && candidate !== '') return candidate;\n    }\n  }\n\n  return null;\n};\n\n/**\n * Provider principal para la internacionalización de Siesa\n *\n * ## Política de caché: stale-while-revalidate\n *\n * El catálogo cacheado en `localStorage` se sirve al instante (para no bloquear\n * el primer render) y *además* se revalida contra el backend. Cuando llegan los\n * datos frescos se mergean en el motor, se reescribe la caché y se re-renderiza\n * a los consumidores. Así las claves nuevas añadidas en el backend aparecen en\n * la siguiente carga de la app sin limpiar la caché a mano.\n *\n * La revalidación automática ocurre una vez por idioma y carga de la app.\n * Para forzarla en caliente existe `refreshTranslations()`, y un evento de\n * cambio de sesión (`sessionChangeEventName`) limpia la caché completa.\n *\n * En modo `mfe` se mantiene la optimización de red: si el microfrontend ya tiene\n * catálogo (caché o memoria) no llama al API; solo el Shell revalida y difunde\n * el resultado por `broadcastEventName`.\n */\nexport const TranslationProvider: React.FC<TranslationProviderProps> = ({\n  children,\n  mode = 'standalone',\n  broadcastEventName = 'siesa:language-changed',\n  sessionChangeEventName = 'siesa:session-changed',\n  apiAdapter,\n  staticLanguages,\n  staticResources,\n  defaultLanguage = 'es',\n  autoSetAxiosHeader = false,\n  axiosInstance,\n}) => {\n  const [currentLanguage, setCurrentLanguage] = useState<string>(\n    () => languageStorage.getLanguage() || defaultLanguage\n  );\n  const [languages, setLanguages] = useState<Language[]>(staticLanguages || []);\n  const [isReady, setIsReady] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  // Ver `resourceVersion` en TranslationContextType: fuerza el re-render de los\n  // consumidores cuando el motor (objeto mutable) recibe recursos nuevos.\n  const [resourceVersion, setResourceVersion] = useState(0);\n\n  // Instanciamos el motor de traducción (una sola vez)\n  const engine = useMemo(() => {\n    const instance = new DefaultTranslationEngine(defaultLanguage);\n    // Fijamos el idioma activo ANTES del primer render: la caché se sirve de\n    // inmediato y debe resolverse en el idioma persistido, no en el default.\n    instance.changeLanguage(languageStorage.getLanguage() || defaultLanguage);\n    return instance;\n  }, [defaultLanguage]);\n\n  // Peticiones de revalidación en vuelo, por idioma. Evita que dos llamadas\n  // concurrentes para el mismo idioma disparen dos fetches.\n  const inFlightRef = useRef<Map<string, Promise<void>>>(new Map());\n\n  // Idiomas ya revalidados en esta carga de la app. Evita que un re-render con\n  // `apiAdapter` inline (identidad nueva en cada render) provoque una tormenta\n  // de peticiones. La invalidación explícita no pasa por este control.\n  const revalidatedRef = useRef<Set<string>>(new Set());\n\n  // Idioma vigente legible desde código asíncrono. `currentLanguage` no sirve para\n  // eso: quien lo lea dentro de una función `async` ve el valor congelado en el\n  // closure del render que la creó, y aplicarlo al terminar revierte cualquier\n  // `setLanguage` que haya ocurrido mientras tanto. Es exactamente lo que pasaba\n  // al arrancar: los efectos de los hijos corren antes que los del padre, así que\n  // un hijo que pedía otro idioma al montarse perdía siempre la carrera contra el\n  // efecto de inicialización, y el motor quedaba en un idioma distinto al del\n  // estado — textos viejos con fechas y números del idioma nuevo.\n  const idiomaVigenteRef = useRef(currentLanguage);\n\n  const isMountedRef = useRef(true);\n  useEffect(() => {\n    isMountedRef.current = true;\n    return () => {\n      isMountedRef.current = false;\n    };\n  }, []);\n\n  // Actualizar header de axios si es necesario\n  const updateAxiosHeader = useCallback(\n    (lang: string) => {\n      if (autoSetAxiosHeader && axiosInstance) {\n        if (axiosInstance.defaults && axiosInstance.defaults.headers) {\n          axiosInstance.defaults.headers.common['Accept-Language'] = lang;\n        }\n      }\n    },\n    [autoSetAxiosHeader, axiosInstance]\n  );\n\n  /**\n   * Registra recursos en el motor y notifica a los consumidores.\n   */\n  const applyResources = useCallback(\n    (lang: string, resources: TranslationResources | null | undefined) => {\n      if (!resources || Object.keys(resources).length === 0) return;\n\n      engine.loadResources(lang, resources);\n      if (isMountedRef.current) {\n        setResourceVersion((v) => v + 1);\n      }\n    },\n    [engine]\n  );\n\n  /**\n   * Pide el catálogo al backend y lo mergea en el motor.\n   *\n   * Deduplica por idioma: si ya hay una petición en vuelo se reutiliza su promesa.\n   * Propaga el error al llamador, que decide si es fatal (no había nada que pintar)\n   * o si basta con avisar por consola (ya se sirvió caché).\n   */\n  const revalidateResources = useCallback(\n    (lang: string): Promise<void> => {\n      if (!apiAdapter) return Promise.resolve();\n\n      const inFlight = inFlightRef.current;\n      const pending = inFlight.get(lang);\n      if (pending) return pending;\n\n      const request = (async () => {\n        try {\n          const fresh = await apiAdapter.getTranslations(lang);\n          applyResources(lang, fresh);\n          // Solo el Shell o un Standalone escriben la caché compartida\n          // (evita sobre-escrituras cruzadas entre MFEs).\n          if (mode !== 'mfe' && fresh && Object.keys(fresh).length > 0) {\n            languageStorage.setTranslations(lang, fresh);\n          }\n        } finally {\n          inFlight.delete(lang);\n        }\n      })();\n\n      inFlight.set(lang, request);\n      return request;\n    },\n    [apiAdapter, applyResources, mode]\n  );\n\n  /**\n   * Carga los recursos de un idioma: estáticos, o caché + revalidación.\n   */\n  const loadLanguageResources = useCallback(\n    async (lang: string) => {\n      // 1. Intentar desde staticResources (Modo Desconectado): no hay red que revalidar\n      if (staticResources && staticResources[lang]) {\n        applyResources(lang, staticResources[lang]);\n        return;\n      }\n\n      // 2. Servir la caché al instante (stale) para no bloquear el primer render\n      const cached = languageStorage.getTranslations(lang);\n      if (cached) {\n        applyResources(lang, cached);\n      }\n\n      if (!apiAdapter) return;\n\n      const hasSomethingToRender = Boolean(cached) || engine.hasResources(lang);\n\n      // 3. OPTIMIZACIÓN MFE: si somos un microfrontend y ya tenemos catálogo,\n      // no tocamos la red. Solo el Shell revalida y difunde por `broadcastEventName`.\n      if (mode === 'mfe' && hasSomethingToRender) return;\n\n      // 4. Revalidación automática: una vez por idioma y carga de la app.\n      if (revalidatedRef.current.has(lang) && hasSomethingToRender) return;\n      revalidatedRef.current.add(lang);\n\n      if (hasSomethingToRender) {\n        // Ya hay algo que pintar: revalidamos en segundo plano sin bloquear el render.\n        void revalidateResources(lang).catch((err) => {\n          console.warn(\n            `[i18n] No se pudo revalidar el catálogo de [${lang}]. Se mantiene la versión en caché.`,\n            err\n          );\n        });\n        return;\n      }\n\n      // 5. Sin nada que pintar: hay que esperar la respuesta del backend.\n      try {\n        await revalidateResources(lang);\n      } catch (err) {\n        console.error(`Error cargando recursos de idioma [${lang}]:`, err);\n        if (isMountedRef.current) {\n          setError(`No se pudieron cargar las traducciones para el idioma: ${lang}`);\n        }\n      }\n    },\n    [staticResources, applyResources, apiAdapter, engine, mode, revalidateResources]\n  );\n\n  /**\n   * Carga la lista de idiomas disponibles\n   */\n  const loadAvailableLanguages = useCallback(async () => {\n    try {\n      // 1. Si ya tenemos idiomas estáticos, usarlos directamente\n      if (staticLanguages && staticLanguages.length > 0) {\n        setLanguages(staticLanguages);\n        return;\n      }\n\n      // 2. Intentar cargar desde cache para disponibilidad inmediata\n      const availableLangs = languageStorage.getAvailableLanguages();\n      if (availableLangs) {\n        setLanguages(availableLangs);\n      }\n\n      // 3. Refrescar desde el API si hay adaptador\n      // OPTIMIZACIÓN MFE: Si somos un microfrontend y ya tenemos caché, omitimos la llamada a la API\n      // para que solo el Shell sea el que interactúe con la red\n      if (apiAdapter && !(mode === 'mfe' && availableLangs)) {\n        const freshLangs = await apiAdapter.getLanguages();\n        if (freshLangs && JSON.stringify(freshLangs) !== JSON.stringify(availableLangs)) {\n          if (isMountedRef.current) {\n            setLanguages(freshLangs);\n          }\n          if (mode !== 'mfe') {\n            languageStorage.setAvailableLanguages(freshLangs);\n          }\n        }\n      }\n    } catch (err) {\n      console.error('Error cargando idiomas disponibles:', err);\n    }\n  }, [staticLanguages, apiAdapter, mode]);\n\n  /**\n   * Cambia el idioma activo de la aplicación\n   */\n  const setLanguage = useCallback(\n    async (langInput: string, fromBroadcast = false) => {\n      // Si somos MFE y el cambio no viene del broadcast, ignoramos o avisamos.\n      // Solo el Shell o un Standalone deberían cambiar el idioma por acción del usuario directamente\n      // Pero permitimos el cambio si es forzado por el broadcast global\n      if (mode === 'mfe' && !fromBroadcast) {\n        console.warn('Los MFEs no deberían cambiar el idioma manualmente. Use el Shell para cambiar el idioma global.');\n        return;\n      }\n\n      // ÚNICO punto de escritura del idioma: aquí se normaliza para que nada que no sea un código\n      // string llegue al estado, al motor, al path del catálogo ni a `Accept-Language`. Vale tanto\n      // para el broadcast del shell como para un consumidor que llame `setLanguage` con un objeto.\n      const lang = readLanguageCode(langInput);\n      if (lang === null) {\n        console.warn(\n          '[i18n] setLanguage recibió un idioma que no es un código válido; se ignora el cambio.',\n          langInput\n        );\n        return;\n      }\n\n      // Se marca el idioma vigente ANTES de esperar por los recursos: desde este\n      // punto es la intención en firme, y cualquier trabajo asíncrono que aún esté\n      // en vuelo (el arranque, sobre todo) debe respetarla en vez de reimponer el\n      // idioma con el que empezó.\n      idiomaVigenteRef.current = lang;\n\n      setIsReady(false);\n\n      // 1. Asegurar recursos cargados (sirve caché y revalida en segundo plano)\n      await loadLanguageResources(lang);\n\n      // 2. Actualizar estado y motor\n      setCurrentLanguage(lang);\n      engine.changeLanguage(lang);\n\n      if (mode !== 'mfe') {\n        languageStorage.setLanguage(lang);\n      }\n\n      updateAxiosHeader(lang);\n\n      setIsReady(true);\n\n      // 3. BROADCAST (Si somos Shell, avisar al ecosistema)\n      if (mode === 'shell' && !fromBroadcast) {\n        const event = new CustomEvent(broadcastEventName, { detail: lang });\n        window.dispatchEvent(event);\n      }\n    },\n    [mode, loadLanguageResources, engine, updateAxiosHeader, broadcastEventName]\n  );\n\n  /**\n   * Invalidación explícita del catálogo.\n   *\n   * Borra la caché del idioma activo (y del default, que alimenta los fallbacks)\n   * y vuelve a pedirlos al backend. No pasa por el control de \"una revalidación\n   * por carga\": si el llamador la invoca, quiere datos frescos.\n   */\n  const refreshTranslations = useCallback(async () => {\n    const targets =\n      currentLanguage === defaultLanguage ? [currentLanguage] : [currentLanguage, defaultLanguage];\n\n    // Los MFEs no escriben ni borran la caché compartida: la gestiona el Shell.\n    if (mode !== 'mfe') {\n      targets.forEach((lang) => languageStorage.removeTranslations(lang));\n    }\n\n    // Modo desconectado (staticResources / sin adaptador): no hay backend que consultar.\n    if (!apiAdapter) return;\n\n    const results = await Promise.allSettled(targets.map((lang) => revalidateResources(lang)));\n    const failed = results.find((r): r is PromiseRejectedResult => r.status === 'rejected');\n    if (failed) {\n      console.warn('[i18n] refreshTranslations: no se pudo refrescar el catálogo.', failed.reason);\n    }\n  }, [currentLanguage, defaultLanguage, mode, apiAdapter, revalidateResources]);\n\n  /**\n   * Inicialización del sistema\n   */\n  useEffect(() => {\n    const init = async () => {\n      // 1. Cargar lista de idiomas en paralelo\n      loadAvailableLanguages();\n\n      // 2. Cargar recursos del idioma actual. Se lee de la ref y no de\n      // `currentLanguage`: un hijo que haya pedido otro idioma al montarse ya lo\n      // dejó anotado ahí, y cargar el del closure traería el catálogo equivocado.\n      await loadLanguageResources(idiomaVigenteRef.current);\n\n      // 3. Si el actual no es el default, precargar el default para fallbacks\n      if (idiomaVigenteRef.current !== defaultLanguage) {\n        await loadLanguageResources(defaultLanguage);\n      }\n\n      // 4. Sincronizar motor y header con el idioma vigente AHORA, no con el que\n      // había cuando arrancó este efecto: los dos `await` de arriba dan margen a\n      // que `setLanguage` cambie el idioma mientras estaban en vuelo. Si el\n      // arranque llega tarde, esto es un no-op idempotente; si llega primero, deja\n      // el motor donde el estado de React ya lo espera.\n      const vigente = idiomaVigenteRef.current;\n      engine.changeLanguage(vigente);\n      updateAxiosHeader(vigente);\n\n      if (isMountedRef.current) {\n        setIsReady(true);\n      }\n    };\n\n    init();\n    // La inicialización debe correr una vez por adaptador/modo, NO cuando cambian\n    // las identidades de los callbacks (un `apiAdapter` o `staticResources` inline\n    // cambia de identidad en cada render y re-lanzaría el arranque en bucle).\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [apiAdapter, defaultLanguage, mode]);\n\n  /**\n   * Suscripción a eventos de Microfrontends (Modo MFE)\n   */\n  useEffect(() => {\n    if (mode !== 'mfe') return;\n\n    const handleLanguageChange = (e: Event) => {\n      // El `detail` es del host: se normaliza antes de compararlo o propagarlo (ver readLanguageCode).\n      const customEvent = e as CustomEvent<unknown>;\n      const newLang = readLanguageCode(customEvent.detail);\n\n      if (newLang !== null && newLang !== currentLanguage) {\n        // Forzar cambio viniendo del evento global\n        setLanguage(newLang, true);\n      }\n    };\n\n    window.addEventListener(broadcastEventName, handleLanguageChange);\n\n    return () => {\n      window.removeEventListener(broadcastEventName, handleLanguageChange);\n    };\n  }, [mode, broadcastEventName, currentLanguage, setLanguage]);\n\n  /**\n   * Cambio de sesión (login / logout): el catálogo cacheado pertenece al usuario\n   * anterior, así que se limpia la caché y se revalida contra el backend.\n   */\n  useEffect(() => {\n    if (!sessionChangeEventName) return;\n\n    const handleSessionChange = () => {\n      languageStorage.clearCache();\n      revalidatedRef.current.clear();\n      loadAvailableLanguages();\n      void refreshTranslations();\n    };\n\n    window.addEventListener(sessionChangeEventName, handleSessionChange);\n\n    return () => {\n      window.removeEventListener(sessionChangeEventName, handleSessionChange);\n    };\n  }, [sessionChangeEventName, refreshTranslations, loadAvailableLanguages]);\n\n  const value = useMemo<TranslationContextType>(\n    () => ({\n      translate: (key: string, arg?: TranslationArg) =>\n        resolveTranslation(key, engine.translate(key), arg),\n      t: (key: string, arg?: TranslationArg) => resolveTranslation(key, engine.translate(key), arg),\n      resolve: (key: string) => engine.resolve(key),\n      setLanguage,\n      currentLanguage,\n      languages,\n      isReady,\n      error,\n      refreshTranslations,\n      resourceVersion,\n    }),\n    [\n      engine,\n      setLanguage,\n      currentLanguage,\n      languages,\n      isReady,\n      error,\n      refreshTranslations,\n      resourceVersion,\n    ]\n  );\n\n  return (\n    <TranslationContext.Provider value={value}>\n      {children}\n    </TranslationContext.Provider>\n  );\n};\n\n/**\n * Hook para acceder al contexto de traducción\n * Implementa una política de \"Fallo Amistoso\" (Graceful Fallback):\n * Si no hay un TranslationProvider en la raíz, no rompe la aplicación,\n * sino que devuelve un estado seguro por defecto.\n */\nexport const useTranslationInternal = () => {\n  const context = useContext(TranslationContext);\n\n  if (context === undefined) {\n    // Intentar recuperar idiomas del localStorage como último recurso\n    const cachedLangs = languageStorage.getAvailableLanguages() || [\n      { codigo: 'es', nombre: 'Español' },\n      { codigo: 'en', nombre: 'English' }\n    ];\n\n    const currentLang = languageStorage.getLanguage() || 'es';\n\n    return {\n      translate: (key: string, arg?: TranslationArg) => resolveTranslation(key, key, arg),\n      t: (key: string, arg?: TranslationArg) => resolveTranslation(key, key, arg),\n      // Sin provider no hay motor ni catálogo: ninguna clave está registrada.\n      resolve: () => null,\n      setLanguage: async (langInput: string) => {\n        console.warn('TranslationProvider no encontrado. Usando fallback básico (solo LocalStorage).');\n        // Se normaliza igual que en el provider: sin este filtro un valor que no es código se\n        // persistía en `localStorage` como \"[object Object]\" y sobrevivía al reload, dejando la app\n        // clavada en un idioma inexistente.\n        const lang = readLanguageCode(langInput);\n        if (lang === null) {\n          console.warn('[i18n] setLanguage recibió un idioma que no es un código válido; se ignora.', langInput);\n          return;\n        }\n        languageStorage.setLanguage(lang);\n        // Forzar un reload simple si estamos en modo fallback extremo para aplicar el cambio\n        window.location.reload();\n      },\n      currentLanguage: currentLang,\n      languages: cachedLangs,\n      isReady: true,\n      error: null,\n      refreshTranslations: async () => {\n        console.warn('TranslationProvider no encontrado. No hay catálogo que refrescar.');\n      },\n      resourceVersion: 0,\n    } as TranslationContextType;\n  }\n\n  return context;\n};\n","import { useTranslationInternal } from '../core/TranslationProvider';\n\n/**\n * Hook para obtener la función de traducción\n * Uso: const { translate, t } = useTranslation();\n *\n * `translate`/`t` aceptan un segundo argumento OPCIONAL con los valores de los marcadores\n * `{{nombre}}` de la traducción: `t('grid.detail', { number: 7 })`. Sin él se comportan igual que\n * siempre, así que ninguna llamada existente cambia.\n *\n * Además de `translate`/`t` expone:\n * - `currentLanguage`: idioma activo, útil para resolver diccionarios locales.\n * - `resolve`: resolución con procedencia (`{ value, lang }` o `null`). A\n *   diferencia de `t`, distingue una traducción del idioma activo de un fallback\n *   al idioma base; es lo que permite a un consumidor con diccionarios propios\n *   priorizar su traducción del idioma activo. Ver `TranslationEngine.resolve`.\n * - `refreshTranslations`: invalida la caché y recarga el catálogo del backend.\n * - `resourceVersion`: cambia cuando llega un catálogo fresco (útil como\n *   dependencia de `useMemo`/`useCallback` que memoricen textos traducidos).\n */\nexport const useTranslation = () => {\n  const {\n    translate,\n    t,\n    resolve,\n    isReady,\n    error,\n    currentLanguage,\n    refreshTranslations,\n    resourceVersion,\n  } = useTranslationInternal();\n\n  return {\n    translate,\n    t,\n    resolve,\n    isReady,\n    error,\n    currentLanguage,\n    refreshTranslations,\n    resourceVersion,\n  };\n};\n","import { useMemo } from 'react';\nimport { useTranslation } from '../LanguageManagement/hooks/useTranslation';\n\n/**\n * Factory de hooks de traducción para MasterDocument y sus sub-paneles.\n *\n * Antes existían cinco copias literales de este helper (una por panel), todas\n * con el mismo defecto: el fallback resolvía siempre contra el diccionario ES,\n * ignorando el idioma activo. Eso dejaba muertos los diccionarios `_EN` del kit\n * — un host en inglés que no registrara las claves veía el panel en español.\n *\n * Orden de resolución (las «fuentes», de mayor a menor precedencia):\n *   1. Motor del kit **en el idioma activo** (catálogo servido por el backend /\n *      registrado por el host). El host manda sobre el kit.\n *   2. Diccionario local del idioma activo.\n *   3. Motor del kit con su fallback al idioma base.\n *   4. Diccionario local ES como último respaldo, para no mostrar nunca la clave cruda.\n *\n * El paso 1 usa `resolve()` —que informa en qué idioma encontró la clave— y no\n * `t()`, que colapsa traducción y fallback en una misma cadena. Con `t()` a\n * secas, un host que registrara solo el catálogo español convertía cualquier\n * clave en un acierto aparente y el paso 2 no llegaba a ejecutarse nunca: los\n * diccionarios `_EN` del kit quedaban inalcanzables y el usuario en inglés veía\n * texto español con números y fechas inglesas. Mantener el paso 3 por delante\n * del 4 preserva el comportamiento previo para los hosts que sí registran el\n * catálogo completo.\n *\n * Si el motor no implementa `resolve` (implementación de terceros), no hay forma\n * de distinguir traducción de fallback: se usa el orden histórico —motor,\n * diccionario del idioma activo, diccionario ES— para no arrebatarle el control\n * del texto a un host con motor propio que sí tenga la clave en el idioma activo.\n *\n * Las claves siguen el formato plano (no anidado) que espera\n * `DefaultTranslationEngine`.\n *\n * ## Pluralización\n *\n * El motor del kit no pluraliza, así que el helper lo resuelve por convención de\n * sufijos: cuando se pasa `count` numérico, se busca primero `<clave>_one` o\n * `<clave>_other` y solo se cae a `<clave>` si no hay variantes declaradas.\n *\n * La variante se prueba **dentro de cada fuente** antes de pasar a la siguiente,\n * no en todas las fuentes antes que la clave base. Con el orden inverso —el que\n * tenía el helper— un host que registrara `master_document.list.recordCount` en su\n * backend quedaba silenciosamente ignorado: el kit declara las variantes en su\n * diccionario local y esas se resolvían antes de mirar la clave base del motor.\n * Un host que quiera personalizar un texto con plural debe registrar las claves\n * **sufijadas** (`…recordCount_one` / `…_other`); si solo registra la base, esa\n * base gana igualmente sobre el diccionario local, pero pierde la distinción de\n * número.\n *\n * ```ts\n * 'master_document.list.recordCount_one':   '{count} registro',\n * 'master_document.list.recordCount_other': '{count} registros',\n * // en el componente:\n * t('master_document.list.recordCount', { count: total })\n * ```\n *\n * Esto reemplaza el patrón `'línea(s)'` que el kit usaba antes: una cadena con\n * `(s)` no es traducible a idiomas con otras reglas de plural, y en español\n * tampoco es aceptable en texto de producto. Las claves con plural NO se\n * referencian por su nombre sufijado en el código: siempre se llama a la clave\n * base con `count`.\n *\n * @see src/components/LanguageManagement/README.md - Arquitectura de traducción\n *\n * @example\n * ```ts\n * export const useWithholdingsTranslation = createTranslationHook(WITHHOLDINGS_TRANSLATIONS);\n * // en el componente:\n * const { t } = useWithholdingsTranslation();\n * t('withholdings.panel.title');\n * t('withholdings.origin.originalTooltip', { value: '1.000' });\n * ```\n */\n\n/** Función de traducción con interpolación `{var}`. */\nexport type TranslateFn = (key: string, vars?: Record<string, string | number>) => string;\n\n/**\n * Diccionarios locales indexados por código de idioma corto (`es`, `en`, …).\n * `es` es obligatorio: es el idioma base del kit y el último respaldo.\n */\nexport interface TranslationDictionaries {\n  es: Record<string, string>;\n  [language: string]: Record<string, string>;\n}\n\n/**\n * Crea el hook de traducción de un feature a partir de sus diccionarios locales.\n *\n * @param dictionaries Diccionarios de respaldo por idioma. Debe incluir `es`.\n * @returns Hook que expone `{ t }`, memoizado por `t` del motor y por idioma activo.\n */\nexport function createTranslationHook(\n  dictionaries: TranslationDictionaries,\n): () => { t: TranslateFn } {\n  return function useLocalTranslation(): { t: TranslateFn } {\n    const { t: baseT, resolve: resolveEnMotor, currentLanguage } = useTranslation();\n\n    // `baseT` cambia de identidad cuando cambian `currentLanguage` o\n    // `resourceVersion` (TranslationProvider), así que el memo se invalida solo.\n    const t = useMemo<TranslateFn>(() => {\n      /** Motor, restringido al idioma activo (descarta los fallbacks). */\n      const enMotorActivo = (key: string): string | undefined => {\n        const encontrado = resolveEnMotor?.(key);\n        return encontrado && encontrado.lang === currentLanguage ? encontrado.value : undefined;\n      };\n\n      /** Motor con su fallback al idioma base. */\n      const enMotorConFallback = (key: string): string | undefined => {\n        const valor = baseT(key);\n        return valor === key ? undefined : valor;\n      };\n\n      /** Diccionario local. `in` y no truthiness: una traducción vacía es una traducción. */\n      const enDiccionario =\n        (diccionario: Record<string, string> | undefined) =>\n        (key: string): string | undefined =>\n          diccionario && key in diccionario ? diccionario[key] : undefined;\n\n      // Fuentes en orden de precedencia. Sin `resolve` se conserva el orden\n      // histórico (motor primero), ver el JSDoc del módulo.\n      const fuentes = resolveEnMotor\n        ? [\n            enMotorActivo,\n            enDiccionario(dictionaries[currentLanguage]),\n            enMotorConFallback,\n            enDiccionario(dictionaries.es),\n          ]\n        : [\n            enMotorConFallback,\n            enDiccionario(dictionaries[currentLanguage]),\n            enDiccionario(dictionaries.es),\n          ];\n\n      return (key, vars) => {\n        // Pluralización por convención de sufijos. La variante se prueba dentro de\n        // CADA fuente antes de pasar a la siguiente: con el orden inverso, un host\n        // que registrara la clave base en su backend quedaba ignorado porque las\n        // variantes locales del kit le ganaban.\n        const sufijo =\n          vars && typeof vars.count === 'number' ? (vars.count === 1 ? '_one' : '_other') : null;\n\n        let value: string | undefined;\n        for (const fuente of fuentes) {\n          value = (sufijo ? fuente(key + sufijo) : undefined) ?? fuente(key);\n          if (value !== undefined) break;\n        }\n\n        // La clave cruda solo si no se pudo resolver en ninguna fuente, para no\n        // romper la UI.\n        value ??= key;\n\n        if (vars) {\n          // `replaceAll`: una traducción puede repetir el mismo placeholder.\n          for (const [name, replacement] of Object.entries(vars)) {\n            value = value.replaceAll(`{${name}}`, String(replacement));\n          }\n        }\n\n        return value;\n      };\n    }, [baseT, resolveEnMotor, currentLanguage]);\n\n    return { t };\n  };\n}\n","import { createTranslationHook } from '../MasterDocument/i18nFactory';\nimport type { TranslateFn } from '../MasterDocument/i18nFactory';\n\n/**\n * i18n del MatchModal.\n *\n * Sigue el mismo patrón que el resto del kit: `createTranslationHook` resuelve\n * contra el motor del host y cae al diccionario local del idioma activo cuando\n * la clave no está registrada. Claves en formato plano (no anidado).\n *\n * La factory vive en `MasterDocument/i18nFactory` pero no es privada de ese\n * feature: el kit la exporta públicamente como factory compartida\n * (`src/index.ts`). Se reutiliza aquí para no duplicar la lógica de precedencia\n * motor → diccionario → respaldo, que ya fue auditada.\n *\n * ## Título con y sin `fieldName`\n *\n * Hay dos claves de título, no una con placeholder opcional:\n *\n * - `match_modal.title` — se usa cuando el consumidor pasa `fieldName`. El\n *   componente interpola el nombre **ya en minúsculas**, para preservar el texto\n *   que el modal venía mostrando.\n * - `match_modal.titleFallback` — se usa cuando `fieldName` no llega. Antes ese\n *   caso lanzaba un `TypeError` que tumbaba la vista completa; ahora degrada a\n *   un encabezado genérico y el modal sigue siendo utilizable.\n *\n * Una sola clave con `{fieldName}` vacío dejaría la frase colgando («…en el »),\n * que en ningún idioma es aceptable.\n *\n * @see src/components/LanguageManagement/README.md - Arquitectura de traducción\n * @see MatchModal.types - `viewLabel` / `continueLabel` para sobrescribir sin i18n\n *\n * @example\n * ```ts\n * const { t } = useMatchModalTranslation();\n * t('match_modal.title', { fieldName: 'nombre' });\n * t('match_modal.view');\n * ```\n */\n\n/** Diccionario base del kit (idioma base: español). */\nexport const MATCH_MODAL_TRANSLATIONS_ES: Record<string, string> = {\n  'match_modal.title': 'Hemos detectado algunas coincidencias en el {fieldName}',\n  'match_modal.titleFallback': 'Hemos detectado algunas coincidencias',\n  'match_modal.view': 'Ver',\n  'match_modal.continue': 'Continuar creando',\n};\n\n/** Diccionario en inglés. */\nexport const MATCH_MODAL_TRANSLATIONS_EN: Record<string, string> = {\n  'match_modal.title': 'We found some matches in the {fieldName}',\n  'match_modal.titleFallback': 'We found some matches',\n  'match_modal.view': 'View',\n  'match_modal.continue': 'Continue creating',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const MATCH_MODAL_TRANSLATIONS = {\n  es: MATCH_MODAL_TRANSLATIONS_ES,\n  en: MATCH_MODAL_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción con interpolación `{var}`. */\nexport type MatchModalT = TranslateFn;\n\n/**\n * Hook de traducción del MatchModal. Usa `useTranslation` del kit; si la clave\n * no está registrada en el host, cae al diccionario local del idioma activo.\n *\n * No requiere `TranslationProvider`: sin él, `useTranslation` aplica su política\n * de fallo amistoso y el hook resuelve contra los diccionarios locales.\n */\nexport const useMatchModalTranslation = createTranslationHook(MATCH_MODAL_TRANSLATIONS);\n","import React from 'react';\nimport { Button } from '../Button/Button';\nimport { ExclamationCircleIcon, ComputerDesktopIcon } from './icons';\nimport type { MatchModalProps } from './MatchModal.types';\nimport { useMatchModalTranslation } from './i18n';\n\n/**\n * MatchModal - Componente para mostrar coincidencias encontradas al validar datos en tiempo real.\n *\n * Este componente es útil para prevenir la creación de duplicados en el sistema,\n * permitiendo al usuario ver registros existentes con datos similares.\n *\n * ## Degradación del encabezado\n *\n * `fieldName` solo alimenta el título por defecto, así que su ausencia no impide\n * usar el modal: se muestra un encabezado genérico y las coincidencias y el\n * botón de acción siguen operativos. El contrato lo declaraba obligatorio y el\n * título llamaba a `.toLowerCase()` sin guarda, de modo que un campo mal\n * configurado —o un texto que llega vacío desde i18n— lanzaba un `TypeError` en\n * render y activaba el error boundary del consumidor: un dato decorativo tumbaba\n * la pantalla completa.\n *\n * Por la misma razón el componente no confía en que `matches` sea un arreglo:\n * TypeScript no protege en runtime y `.map()` sobre un valor ausente reproduce\n * exactamente el mismo fallo desproporcionado.\n *\n * @see i18n.ts - Claves de traducción y diccionarios ES/EN\n * @see MatchModal.types - `viewLabel` / `continueLabel` para sobrescribir textos\n *\n * @example\n * ```tsx\n * <MatchModal\n *   isOpen={showMatches}\n *   onClose={() => setShowMatches(false)}\n *   fieldName=\"Nombre\"\n *   matches={results}\n *   onView={(match) => handleView(match)}\n *   onContinue={() => handleContinue()}\n * />\n * ```\n */\nexport const MatchModal: React.FC<MatchModalProps> = ({\n  isOpen,\n  // `onClose` no se desestructura a propósito: el modal no ofrece ningún control\n  // de cierre (decisión de diseño, ver MatchModal.types). Sigue en el contrato\n  // para no romper a los consumidores que ya la pasan.\n  matches,\n  fieldName,\n  onView,\n  onContinue,\n  title,\n  viewLabel,\n  continueLabel,\n  className = '',\n}) => {\n  // El hook va antes del retorno temprano: llamarlo después lo volvería\n  // condicional y React fallaría al alternar `isOpen`.\n  const { t } = useMatchModalTranslation();\n\n  if (!isOpen) return null;\n\n  // ===== DATOS BLINDADOS =====\n  // `typeof` y no truthiness: el consumidor puede pasar en runtime cualquier cosa\n  // que el tipo `string` no garantiza (un `header` sin definir, un número, null).\n  const nombreCampo = typeof fieldName === 'string' ? fieldName.trim() : '';\n  const coincidencias = Array.isArray(matches) ? matches : [];\n\n  // ===== TEXTOS =====\n  // `||` y no `??`: una cadena vacía —clave de i18n sin resolver en el host— se\n  // trata como ausente, para no dejar un encabezado o un botón en blanco.\n  const tituloModal =\n    title ||\n    (nombreCampo\n      ? t('match_modal.title', { fieldName: nombreCampo.toLowerCase() })\n      : t('match_modal.titleFallback'));\n  const textoVer = viewLabel || t('match_modal.view');\n  const textoContinuar = continueLabel || t('match_modal.continue');\n\n  return (\n    <div className={`fixed inset-0 z-[80] flex items-center justify-center bg-black/50 p-4 animate-in fade-in duration-200 ${className}`}>\n      <div className=\"bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-2xl flex flex-col w-full max-w-2xl overflow-hidden relative\">\n        \n        {/* Header - Icono + Título */}\n        <div className=\"p-[20px] flex gap-5 items-center\">\n          <div className=\"bg-[#fcedc9] dark:bg-amber-900/20 flex items-center justify-center rounded-full shrink-0 size-[40px]\">\n            <ExclamationCircleIcon className=\"size-[24px] text-amber-600 dark:text-amber-400\" />\n          </div>\n          <div className=\"flex flex-col justify-center pr-8\">\n            <h3 className=\"text-[20px] font-bold leading-[28px] tracking-tight text-content-primary dark:text-dark-content-primary\">\n              {tituloModal}\n            </h3>\n          </div>\n        </div>\n\n        {/* Body - Lista de coincidencias */}\n        <div className=\"px-[20px] pb-[20px] flex flex-col gap-[20px] overflow-y-auto max-h-[385px] scrollbar-thin scrollbar-thumb-border-primary dark:scrollbar-thumb-dark-border-primary\">\n          <div className=\"flex flex-col items-start w-full\">\n            {coincidencias.map((match) => (\n              <div \n                key={match.id}\n                className=\"border border-border-primary dark:border-dark-border-primary h-[64px] px-[8px] flex items-center justify-between rounded-[8px] w-full mb-3 last:mb-0 transition-colors hover:bg-background-secondary dark:hover:bg-dark-bg-inverse/5\"\n              >\n                <div className=\"flex items-center gap-[8px]\">\n                  {/* Icono de Computador/Desktop */}\n                  <div className=\"bg-[#dbeefe] dark:bg-primary-900/20 flex items-center justify-center rounded-[16px] shrink-0 size-[32px]\">\n                    <ComputerDesktopIcon className=\"size-[18px] text-primary-600 dark:text-primary-400\" />\n                  </div>\n                  <div className=\"flex flex-col\">\n                    <span className=\"text-[16px] font-medium leading-[24px] text-content-primary dark:text-dark-content-primary truncate max-w-[300px]\">\n                      {match.name}\n                    </span>\n                  </div>\n                </div>\n                \n                {/* Botón Ver */}\n                <Button \n                  type=\"outline\" \n                  size=\"xs\" \n                  onClick={() => onView(match)}\n                  className=\"w-[85.5px] h-[32px] !text-[12px] !font-medium\"\n                >\n                  {textoVer}\n                </Button>\n              </div>\n            ))}\n          </div>\n        </div>\n\n        {/* Footer */}\n        <div className=\"px-[24px] py-[16px] pb-[24px] flex items-center justify-end gap-[12px] shrink-0 w-full border-t border-border-secondary dark:border-dark-border-primary bg-background-secondary/30 dark:bg-dark-bg-inverse/5\">\n          <Button type=\"default\" size=\"l\" onClick={onContinue}>\n            {textoContinuar}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React, { useState } from 'react';\nimport type { TabProps, TabsProps } from './Tabs.types';\n\n/**\n * Componente Tab individual del sistema de diseño Siesa\n *\n * Representa un único tab dentro de un grupo de tabs. Incluye soporte para:\n * - Estado activo/inactivo con indicador visual (línea inferior)\n * - Icono opcional a la izquierda del texto\n * - Badge de notificación con contador\n * - Estados hover, focus y disabled\n * - Dark mode completo\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * <Tab\n *   label=\"Inicio\"\n *   active={true}\n *   icon={<HomeIcon />}\n *   badge={3}\n *   onClick={() => setActiveTab('home')}\n * />\n * ```\n */\nexport const Tab: React.FC<TabProps> = ({\n  label,\n  active = false,\n  icon,\n  badge,\n  disabled = false,\n  onClick,\n  className = '',\n  ariaLabel,\n}) => {\n  // ===== CLASES BASE DEL BOTÓN =====\n  // El contenedor es relativo para posicionar el indicador absoluto\n  const baseClasses = `\n    relative\n    flex\n    flex-col\n    items-center\n    cursor-pointer\n    outline-hidden\n    transition-all\n    duration-150\n    p-0\n    border-0\n    bg-transparent\n  `;\n\n  // ===== CLASES DE FOCUS =====\n  // El focus outline se desactiva aquí, el shadow se aplica al Content div\n  const focusClasses = '';\n\n  // ===== CLASES DE DISABLED =====\n  const disabledClasses = disabled\n    ? 'opacity-50 cursor-not-allowed pointer-events-none'\n    : '';\n\n  // ===== CLASES DEL CONTENIDO INTERIOR =====\n  // El hover y focus background se aplica aquí\n  const contentBaseClasses = `\n    flex\n    items-center\n    justify-center\n    gap-1\n    p-2\n    rounded-lg\n    overflow-hidden\n    transition-all\n    duration-150\n    w-full\n  `;\n\n  // ===== CLASES DE ESTADO HOVER Y FOCUS PARA CONTENIDO =====\n  // Light: bg-[rgba(0,0,0,0.03)], Dark: bg-white/5\n  // Según Figma, tanto hover como focus tienen el background overlay\n  // El shadow de focus también se aplica aquí (al Content div), no al botón\n  const contentStateClasses = disabled\n    ? ''\n    : `\n      group-hover:bg-[rgba(0,0,0,0.03)]\n      group-focus-visible:bg-[rgba(0,0,0,0.03)]\n      group-focus-visible:shadow-lg\n      dark:group-hover:bg-white/5\n      dark:group-focus-visible:bg-white/5\n      dark:group-focus-visible:shadow-2xl\n    `;\n\n  // ===== CLASES DE TEXTO =====\n  // Activo: primary-600 (#0e79fd), Inactivo: content-primary (#18181b)\n  const textClasses = active\n    ? `\n      text-primary-600\n      dark:text-primary-600\n    `\n    : `\n      text-content-primary\n      dark:text-dark-content-primary\n    `;\n\n  // ===== CLASES DE ICONO =====\n  // El icono hereda el color del texto\n  const iconClasses = `\n    w-3\n    h-3\n    shrink-0\n  `;\n\n  // ===== CLASES DEL BADGE =====\n  // Activo: bg-primary-600 (#0e79fd), Inactivo: bg-content-primary (#18181b)\n  const badgeClasses = active\n    ? `\n      bg-primary-600\n      dark:bg-primary-600\n    `\n    : `\n      bg-content-primary\n      dark:bg-dark-content-primary\n    `;\n\n  // ===== CLASES DEL INDICADOR INFERIOR =====\n  // Solo visible cuando está activo, 2px de alto, rounded-full\n  // Posicionado al fondo del contenedor de Tabs (alineado con el border)\n  const indicatorClasses = active\n    ? `\n      absolute\n      -bottom-2.5\n      left-0\n      right-0\n      h-0.5\n      rounded-full\n      bg-primary-600\n      dark:bg-primary-600\n      z-10\n    `\n    : 'hidden';\n\n  // ===== COMBINAR CLASES DEL BOTÓN =====\n  const finalClasses = [\n    baseClasses,\n    focusClasses,\n    disabledClasses,\n    'group', // Para usar group-hover y group-focus-visible\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== COMBINAR CLASES DEL CONTENIDO =====\n  const contentFinalClasses = [\n    contentBaseClasses,\n    contentStateClasses,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <button\n      type=\"button\"\n      role=\"tab\"\n      aria-selected={active}\n      aria-disabled={disabled}\n      aria-label={ariaLabel || label}\n      tabIndex={disabled ? -1 : 0}\n      className={finalClasses}\n      onClick={disabled ? undefined : onClick}\n      disabled={disabled}\n    >\n      {/* Contenido del Tab */}\n      <div className={contentFinalClasses}>\n        {/* Icono (opcional) */}\n        {icon && (\n          <span className={`${iconClasses} ${textClasses}`.trim()}>\n            {icon}\n          </span>\n        )}\n\n        {/* Texto */}\n        <span\n          className={`\n            text-sm\n            font-bold\n            leading-5\n            whitespace-nowrap\n            ${textClasses}\n          `\n            .replace(/\\s+/g, ' ')\n            .trim()}\n        >\n          {label}\n        </span>\n\n        {/* Badge de notificación (opcional) */}\n        {badge !== undefined && badge > 0 && (\n          <span\n            className={`\n              flex\n              items-center\n              justify-center\n              h-3\n              min-w-[12px]\n              px-0.5\n              rounded-xs\n              text-xs\n              font-normal\n              leading-4\n              text-primary-inverse-content\n              dark:text-dark-bg-primary\n              ${badgeClasses}\n            `\n              .replace(/\\s+/g, ' ')\n              .trim()}\n            aria-label={`${badge} notificaciones`}\n          >\n            {badge > 99 ? '99+' : badge}\n          </span>\n        )}\n      </div>\n\n      {/* Indicador inferior (línea activa) */}\n      <div className={indicatorClasses} />\n    </button>\n  );\n};\n\n/**\n * Componente Tabs contenedor del sistema de diseño Siesa\n *\n * Agrupa múltiples tabs permitiendo navegación entre diferentes secciones.\n * Soporta modo controlado (con activeId y onChange) y no controlado (con defaultActiveId).\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA roles y keyboard navigation\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * // Modo controlado\n * const [activeTab, setActiveTab] = useState('home');\n *\n * <Tabs\n *   items={[\n *     { id: 'home', label: 'Inicio', icon: <HomeIcon /> },\n *     { id: 'profile', label: 'Perfil', badge: 3 },\n *     { id: 'settings', label: 'Configuración' },\n *   ]}\n *   activeId={activeTab}\n *   onChange={setActiveTab}\n * />\n *\n * // Modo no controlado\n * <Tabs\n *   items={[...]}\n *   defaultActiveId=\"home\"\n * />\n * ```\n */\nexport const Tabs: React.FC<TabsProps> = ({\n  items,\n  activeId,\n  defaultActiveId,\n  onChange,\n  className = '',\n  fullWidth = false,\n  size = 'base',\n  showBorder = true,\n}) => {\n  // Estado interno para modo no controlado\n  const [internalActiveId, setInternalActiveId] = useState(\n    defaultActiveId || (items.length > 0 ? items[0].id : '')\n  );\n\n  // Determinar si es controlado o no controlado\n  const isControlled = activeId !== undefined;\n  const currentActiveId = isControlled ? activeId : internalActiveId;\n\n  // Handler para cambio de tab\n  const handleTabClick = (id: string) => {\n    if (!isControlled) {\n      setInternalActiveId(id);\n    }\n    onChange?.(id);\n  };\n\n  // ===== CLASES DE TAMAÑO =====\n  const sizeClasses = {\n    sm: 'gap-0',\n    base: 'gap-1',\n    lg: 'gap-2',\n  };\n\n  // ===== CLASES DEL CONTENEDOR =====\n  // El padding-bottom (pb-2.5 = 10px) deja espacio para el indicador del tab activo\n  // El border-b se dibuja debajo del padding, alineándose con el indicador\n  const containerClasses = `\n    flex\n    items-end\n    pb-2.5\n    ${sizeClasses[size]}\n    ${fullWidth ? 'w-full' : ''}\n    ${showBorder ? 'border-b border-border-primary dark:border-dark-border-primary' : ''}\n  `;\n\n  // ===== CLASES FULL WIDTH PARA ITEMS =====\n  const itemWidthClass = fullWidth ? 'flex-1' : '';\n\n  const finalClasses = [\n    containerClasses,\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <div\n      role=\"tablist\"\n      aria-label=\"Pestañas de navegación\"\n      className={finalClasses}\n    >\n      {items.map((item) => (\n        <Tab\n          key={item.id}\n          label={item.label}\n          active={currentActiveId === item.id}\n          icon={item.icon}\n          badge={item.badge}\n          disabled={item.disabled}\n          onClick={() => handleTabClick(item.id)}\n          className={itemWidthClass}\n        />\n      ))}\n    </div>\n  );\n};\n","import { useTranslationInternal } from '../core/TranslationProvider';\n\n/**\n * Hook para gestionar el idioma actual\n * Uso: const { currentLanguage, languages, setLanguage } = useLanguage();\n *\n * `refreshTranslations` permite forzar la recarga del catálogo desde el backend\n * (por ejemplo tras publicar traducciones nuevas) sin recargar la página.\n */\nexport const useLanguage = () => {\n  const { currentLanguage, languages, setLanguage, isReady, refreshTranslations } =\n    useTranslationInternal();\n\n  return {\n    currentLanguage,\n    languages,\n    setLanguage,\n    isLanguageChanging: !isReady,\n    refreshTranslations,\n  };\n};\n","import React from 'react';\nimport { useLanguage } from '../hooks/useLanguage';\nimport { Dropdown } from '../../Dropdown/Dropdown';\nimport { GlobeAltIcon, ChevronDownIcon } from '@heroicons/react/24/outline';\n\n/**\n * Iconos de banderas circulares (SVG) para una UI profesional.\n * Se utilizan rectángulos full-bleed para asegurar que rounded-full cree un círculo perfecto.\n */\nconst FlagIcon: React.FC<{ code: string; className?: string }> = ({ code, className = 'w-5 h-5' }) => {\n  const flags: Record<string, React.ReactNode> = {\n    es: (\n      <svg viewBox=\"0 0 36 36\" className={`${className} aspect-square overflow-hidden`} xmlns=\"http://www.w3.org/2000/svg\">\n        <rect fill=\"#FFD700\" width=\"36\" height=\"36\" />\n        <rect fill=\"#C60B1E\" width=\"36\" height=\"10\" />\n        <rect fill=\"#C60B1E\" y=\"26\" width=\"36\" height=\"10\" />\n      </svg>\n    ),\n    en: (\n      <svg viewBox=\"0 0 36 36\" className={`${className} aspect-square overflow-hidden`} xmlns=\"http://www.w3.org/2000/svg\">\n        <rect fill=\"#00247D\" width=\"36\" height=\"36\" />\n        <path fill=\"#FFF\" d=\"M36 15H21V0h-6v15H0v6h15v15h6V21h15z\" />\n        <path fill=\"#CF142B\" d=\"M36 17H19V0h-2v17H0v2h17v17h2V19h15z\" />\n        <path fill=\"#FFF\" d=\"M0 0l13.5 9V5.5L4.5 0H0zm22.5 0L36 9V5.5L27 0h-4.5zM0 36l13.5-9v3.5L4.5 36H0zm22.5 0L36 27v3.5L27 36h-4.5z\" />\n        <path fill=\"#CF142B\" d=\"M0 0l12 8V6L3 0H0zm24 0L36 8V6L27 0h-3zM0 36l12-8v2L3 36H0zm24 0L36 28v2L27 36h-3z\" />\n      </svg>\n    ),\n    pt: (\n      <svg viewBox=\"0 0 36 36\" className={`${className} aspect-square overflow-hidden`} xmlns=\"http://www.w3.org/2000/svg\">\n        <rect fill=\"#E42518\" width=\"36\" height=\"36\" />\n        <rect fill=\"#046A38\" width=\"14\" height=\"36\" />\n        <circle fill=\"#FFD700\" cx=\"14\" cy=\"18\" r=\"6\" />\n      </svg>\n    ),\n  };\n\n  return flags[code] || <GlobeAltIcon className={className} />;\n};\n\nexport interface LanguageSelectorProps {\n  /** Variante visual del selector */\n  variant?: 'default' | 'minimalist' | 'menu-item';\n  /** Clases CSS adicionales */\n  className?: string;\n}\n\n/**\n * Componente Selector de Idioma Profesional (Siesa UI Kit)\n *\n * Implementa una arquitectura limpia y pixel-perfect con soporte para\n * una variante minimalista que solo muestra la bandera y una variante\n * de item de menú para integración en dropdowns.\n *\n * @see src/components/LanguageManagement/README.md\n */\nexport const LanguageSelector: React.FC<LanguageSelectorProps> = ({\n  variant = 'default',\n  className = '',\n}) => {\n  const { currentLanguage, languages: ctxLanguages, setLanguage, isLanguageChanging } = useLanguage();\n\n  // Fallback de seguridad: Si por alguna razón la API o el caché fallan y languages está vacío,\n  // proveemos un arreglo mínimo funcional para evitar items \"fantasma\" y valores undefined.\n  const safeLanguages = ctxLanguages && ctxLanguages.length > 0 ? ctxLanguages : [\n    { code: 'es', name: 'Español' },\n    { code: 'en', name: 'English' }\n  ];\n\n  // Helper para obtener el código y nombre del idioma de forma segura\n  // Soporta la estructura original (codigo, nombre) y la de la API real (code, name)\n  const getLangId = (l: any) => l.codigo || l.code || '';\n  const getLangName = (l: any) => l.nombre || l.nativeName || l.name || '';\n\n  const selectedLanguage = safeLanguages.find((l) => getLangId(l) === currentLanguage);\n\n  // Mapear los idiomas a items del Dropdown con iconos de banderas\n  const dropdownItems = safeLanguages.map((lang) => {\n    const langId = getLangId(lang);\n    const langName = getLangName(lang);\n    \n    return {\n      children: langName,\n      onClick: () => setLanguage(langId),\n      selected: langId === currentLanguage,\n      disabled: isLanguageChanging,\n      icon: <FlagIcon code={langId} className=\"w-4 h-4 rounded-full shadow-sm\" />,\n    };\n  });\n\n  return (\n    <Dropdown\n      className={variant === 'menu-item' ? `w-full ${className}` : className}\n      items={dropdownItems}\n      disabled={isLanguageChanging}\n      placeholder=\"Idioma\"\n      renderTrigger={(isOpen) => {\n        // Variante para items de menú (ej: dentro del dropdown de usuario en Navbar)\n        if (variant === 'menu-item') {\n          return (\n            <div\n              title={`Idioma actual: ${selectedLanguage?.nombre || currentLanguage}`}\n              aria-label={`Cambiar idioma, actual: ${selectedLanguage?.nombre || currentLanguage}`}\n              className={`\n                flex items-center gap-3 px-4 py-2 rounded-lg text-sm font-normal w-full text-left\n                text-content-primary dark:text-dark-content-primary \n                hover:bg-bg-primary dark:hover:bg-dark-bg-secondary\n                transition-all duration-150 cursor-pointer\n                ${isOpen ? 'bg-bg-primary dark:bg-dark-bg-secondary' : ''}\n                ${isLanguageChanging ? 'opacity-50' : ''}\n              `.trim().replace(/\\s+/g, ' ')}\n            >\n              {/* Icono de Bandera */}\n              <div className=\"relative shrink-0 w-4 h-4\">\n                <FlagIcon\n                  code={currentLanguage}\n                  className=\"w-4 h-4 rounded-full shadow-sm object-cover\"\n                />\n                {isLanguageChanging && (\n                  <div className=\"absolute -inset-1 border border-primary-600 border-t-transparent rounded-full animate-spin\" />\n                )}\n              </div>\n              \n              {/* Texto y Chevron */}\n              <div className=\"flex-1 min-w-0\">\n                <div className=\"text-content-primary dark:text-dark-content-primary\">\n                  {selectedLanguage ? getLangName(selectedLanguage) : `Idioma: ${currentLanguage.toUpperCase()}`}\n                </div>\n              </div>\n\n              <ChevronDownIcon\n                className={`w-3.5 h-3.5 text-content-tertiary transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}\n              />\n            </div>\n          );\n        }\n\n        // Variantes estándar (default y minimalist)\n        return (\n          <button\n            type=\"button\"\n            title={`Idioma actual: ${selectedLanguage ? getLangName(selectedLanguage) : currentLanguage}`}\n            aria-label={`Cambiar idioma, actual: ${selectedLanguage ? getLangName(selectedLanguage) : currentLanguage}`}\n            className={`\n              relative inline-flex items-center justify-center transition-all duration-200\n              ${\n                variant === 'minimalist'\n                  ? 'w-10 h-10 rounded-full hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'\n                  : 'px-3 py-1.5 rounded-lg border border-border-primary bg-white text-content-primary hover:bg-background-secondary dark:bg-dark-bg-primary dark:text-dark-content-primary dark:border-dark-border-primary dark:hover:bg-dark-bg-secondary gap-2'\n              }\n              ${isOpen ? 'ring-2 ring-primary-400 dark:ring-dark-border-custom' : ''}\n              ${isLanguageChanging ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}\n            `}\n          >\n            {/* Icono de Bandera Principal */}\n            <div className=\"relative\">\n              <FlagIcon\n                code={currentLanguage}\n                className={`${variant === 'minimalist' ? 'w-6 h-6' : 'w-4 h-4'} rounded-full shadow-sm object-cover`}\n              />\n              {isLanguageChanging && (\n                <div className=\"absolute -inset-1 border-2 border-primary-600 border-t-transparent rounded-full animate-spin\" />\n              )}\n            </div>\n\n            {/* Texto (Solo en versión default) */}\n            {variant === 'default' && (\n              <>\n                <span className=\"text-sm font-medium\">\n                  {selectedLanguage ? getLangName(selectedLanguage) : currentLanguage.toUpperCase()}\n                </span>\n                <ChevronDownIcon\n                  className={`w-3.5 h-3.5 text-content-tertiary transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}\n                />\n              </>\n            )}\n\n            {/* Indicador sutil para minimalist */}\n            {variant === 'minimalist' && !isLanguageChanging && (\n              <div className=\"absolute bottom-1 right-1 w-2 h-2 bg-white dark:bg-dark-bg-primary rounded-full border border-border-primary dark:border-dark-border-primary flex items-center justify-center\">\n                <div className=\"w-1 h-1 bg-content-tertiary rounded-full\" />\n              </div>\n            )}\n          </button>\n        );\n      }}\n    />\n  );\n};\n","import { languageStorage } from '../storage/languageStorage';\n\n/**\n * Utilidad para inyectar el header de idioma en una instancia de Axios\n * @param axiosInstance La instancia de axios a configurar\n * @param defaultLang Idioma por defecto si no hay nada en cache\n */\nexport const setLanguageHeader = (axiosInstance: any, defaultLang: string = 'es') => {\n  if (!axiosInstance) return;\n\n  const currentLang = languageStorage.getLanguage() || defaultLang;\n\n  // Si axios tiene un objeto de configuración de headers\n  if (axiosInstance.defaults && axiosInstance.defaults.headers) {\n    axiosInstance.defaults.headers.common['Accept-Language'] = currentLang;\n  }\n};\n\n/**\n * Sincroniza el idioma en Axios tras un cambio manual\n */\nexport const syncAxiosLanguage = (axiosInstance: any, lang: string) => {\n  if (axiosInstance?.defaults?.headers?.common) {\n    axiosInstance.defaults.headers.common['Accept-Language'] = lang;\n  }\n};\n","import React from 'react';\nimport {\n  ShoppingCartIcon as HeroShoppingCartIcon,\n  BellIcon as HeroBellIcon,\n  MagnifyingGlassIcon as HeroMagnifyingGlassIcon,\n  ChevronDownIcon as HeroChevronDownIcon,\n  ExclamationTriangleIcon as HeroExclamationTriangleIcon,\n  ArrowLeftStartOnRectangleIcon as HeroArrowLeftStartOnRectangleIcon,\n  Squares2X2Icon as HeroSquares2X2Icon,\n} from '@heroicons/react/24/outline';\n\n/**\n * Iconos para el componente Navbar\n * Basados en Heroicons 24/outline\n *\n * @see docs/icons.md - Sistema de iconos\n */\n\n/** Icono de carrito de compras */\nexport const ShoppingCartIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroShoppingCartIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de campana para notificaciones */\nexport const BellIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroBellIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de lupa para búsqueda */\nexport const MagnifyingGlassIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroMagnifyingGlassIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de chevron abajo para el dropdown de usuario */\nexport const ChevronDownIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroChevronDownIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de advertencia para el badge de ambiente */\nexport const ExclamationTriangleIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroExclamationTriangleIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de cerrar sesión / navegación */\nexport const ArrowLeftStartOnRectangleIcon: React.FC<{ className?: string }> = ({ className = 'size-4' }) => (\n  <HeroArrowLeftStartOnRectangleIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de cuadrícula 2x2 para el lanzador de aplicaciones (AppLauncher) */\nexport const Squares2X2Icon: React.FC<{ className?: string }> = ({ className = 'size-6' }) => (\n  <HeroSquares2X2Icon className={className} aria-hidden=\"true\" />\n);\n\n/** Punto indicador de notificación */\nexport const NotificationDot: React.FC<{ className?: string }> = ({ className = 'size-2' }) => (\n  <svg className={className} viewBox=\"0 0 8 8\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n    <circle cx=\"4\" cy=\"4\" r=\"4\" fill=\"currentColor\" />\n  </svg>\n);","import React, { useState, useEffect, useMemo } from 'react';\nimport type { NavbarProps } from './Navbar.types';\nimport { Badge } from '../Badge/Badge';\nimport { Dropdown } from '../Dropdown/Dropdown';\nimport { Button } from '../Button/Button';\nimport { LanguageSelector } from '../LanguageManagement';\nimport {\n  ShoppingCartIcon,\n  BellIcon,\n  MagnifyingGlassIcon,\n  ChevronDownIcon,\n  ExclamationTriangleIcon,\n  ArrowLeftStartOnRectangleIcon,\n  Squares2X2Icon,\n} from './icons';\nimport {\n  UserIcon,\n  CogIcon,\n  CreditCardIcon,\n  MoonIcon,\n  ArrowRightOnRectangleIcon,\n} from '@heroicons/react/24/outline';\n\n/**\n * Componente Navbar del sistema de diseño Siesa\n * Basado en especificaciones de Figma con Tailwind CSS\n *\n * Barra de navegación principal con soporte completo para responsive y dark mode.\n * Incluye logo, nombre de producto, badge de ambiente, botones de acción y dropdown de usuario.\n *\n * **Variantes de dispositivo:**\n * - `responsive`: Se adapta automáticamente al viewport (por defecto)\n * - `desktop`: Versión completa (1360x64px) con todos los elementos\n * - `tablet`: Versión tablet (1024x64px) con elementos reducidos\n * - `mobile`: Versión simplificada (428x40px) con logo icono y avatar circular\n *\n * **Elementos incluidos:**\n * - Botón de navegación (solo desktop/tablet) - Usa shadow-button-inset\n * - Logo del negocio (solo desktop/tablet)\n * - Dividers verticales (solo desktop/tablet)\n * - Logo Siesa (completo en desktop/tablet, icono en mobile)\n * - Nombre del producto (solo desktop/tablet) - Heading/Tiny (20px Bold)\n * - Badge de ambiente con icono de advertencia (yellow)\n * - Botones de acción (search solo mobile, cart, notifications)\n * - Dropdown de usuario con avatar, nombre y email\n * - Logo Siesa trailing (solo desktop)\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación (NO colores hardcodeados)\n * - Focus rings adaptativos para light y dark mode\n * - Type safety con TypeScript estricto\n * - Responsive design con breakpoints md: y lg:\n * - Tipografía del sistema: Heading/Tiny, Paragraph/Small, Paragraph/Tiny\n * - Spacing del sistema (4px, 8px, 12px, 16px, 32px)\n *\n * @see docs/colors.md - Sistema de colores y tokens dark mode\n * @see docs/typography.md - Sistema tipográfico (Heading, Paragraph)\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras (button-inset)\n *\n * @example\n * ```tsx\n * <Navbar\n *   productName=\"Mi Producto\"\n *   environmentBadge=\"Ambiente de Pruebas\"\n *   userDropdown={{\n *     avatar: \"/path/to/avatar.jpg\",\n *     name: \"Juan Pérez\",\n *     email: \"juan@ejemplo.com\",\n *   }}\n *   notifications={{\n *     cart: 99,\n *     bell: true,\n *   }}\n *   onNavigationClick={() => router.back()}\n *   onCartClick={() => openCart()}\n *   onNotificationsClick={() => openNotifications()}\n * />\n * ```\n */\nexport const Navbar: React.FC<NavbarProps> = ({\n  logo,\n  darkLogo,\n  productName = 'Nombre Producto',\n  environmentBadge,\n  userDropdown,\n  actions,\n  notifications,\n  className = '',\n  variant = 'responsive',\n  hideActionButtons = false,\n  showNavigationButton = false,\n  navigationButtonProps = {},\n  leadingAction,\n  siesaLogo,\n  showBusinessLogo = false,\n  showSiesaLogoLeading = true,\n  showSiesaLogoTrailing = false,\n  isAppShell = false,\n  microfrontends,\n  onMicrofrontendClick,\n  activeMicrofrontendName,\n  onNavigationClick,\n  onSearchClick,\n  onCartClick,\n  onNotificationsClick,\n  languageSelector = true,\n  t = (key, def) => def || key,\n}) => {\n  // ===== ESTADO INTERNO PARA LA SELECCIÓN DEL MICROFRONTEND =====\n  const [selectedMicrofrontend, setSelectedMicrofrontend] = useState<string | undefined>(\n    activeMicrofrontendName\n  );\n\n  // Sincronizar estado si la prop activeMicrofrontendName cambia externamente\n  useEffect(() => {\n    if (activeMicrofrontendName !== undefined) {\n      setSelectedMicrofrontend(activeMicrofrontendName);\n    }\n  }, [activeMicrofrontendName]);\n\n  // ===== CLASES COMUNES PARA BOTONES DE ACCIÓN =====\n  const actionButtonClasses = `\n    box-border\n    flex\n    flex-col\n    items-center\n    justify-center\n    p-1\n    relative\n    rounded-md\n    shrink-0\n    text-primary-600\n    hover:bg-background-secondary\n    active:scale-95\n    focus:outline-hidden\n    focus:ring-2\n    focus:ring-primary-400\n    focus:ring-offset-2\n    dark:text-primary-600\n    dark:hover:bg-dark-bg-secondary\n    dark:active:scale-95\n    dark:focus:ring-dark-border-custom\n    dark:focus:ring-offset-dark-bg-primary\n    transition-all\n    duration-150\n  `;\n\n  // ===== CLASES PARA BOTÓN DE NAVEGACIÓN PRIMARIO =====\n  const navigationButtonClasses = `\n    bg-primary-600\n    text-primary-inverse-content\n    border\n    border-primary-600\n    shadow-button-inset\n    hover:bg-primary-500\n    active:scale-95\n    focus:outline-hidden\n    focus:ring-2\n    focus:ring-primary-400\n    focus:ring-offset-2\n    dark:bg-dark-bg-inverse\n    dark:text-dark-content-inverse\n    dark:border-dark-bg-inverse\n    dark:hover:bg-dark-bg-inverse/90\n    dark:active:scale-95\n    dark:focus:ring-dark-border-custom\n    dark:focus:ring-offset-dark-bg-primary\n    box-border\n    flex\n    flex-col\n    items-center\n    justify-center\n    p-3\n    relative\n    rounded-md\n    shrink-0\n    transition-all\n    duration-150\n  `;\n\n  // ===== HELPER: Es mobile (variante o responsive en mobile breakpoint) =====\n  const isMobile = variant === 'mobile';\n  const isDesktop = variant === 'desktop';\n  const isTablet = variant === 'tablet';\n  const isResponsive = variant === 'responsive';\n\n  // ===== APP LAUNCHER (Menú de Microfrontends) =====\n  const AppLauncher = () => {\n    if (!isAppShell || !microfrontends || microfrontends.length === 0) return null;\n\n    const items = microfrontends.map((mfe) => ({\n      children: mfe.name,\n      icon: mfe.icon,\n      onClick: () => {\n        // Actualizar estado interno para mostrar en el label\n        setSelectedMicrofrontend(mfe.name);\n        \n        // Manejar navegación\n        if (onMicrofrontendClick) {\n          onMicrofrontendClick(mfe);\n        } else {\n          // Comportamiento por defecto: Navegación relativa\n          window.location.href = mfe.baseUrl;\n        }\n      },\n    }));\n\n    // Trigger del dropdown (botón waffle)\n    const renderTrigger = (isOpen: boolean) => (\n      <button\n        className={`\n          ${actionButtonClasses}\n          ${isOpen ? 'bg-background-secondary dark:bg-dark-bg-secondary' : ''}\n          flex items-center justify-center\n        `.trim()}\n        aria-label={t('appMenu', 'Menú de Aplicaciones')}\n      >\n        <Squares2X2Icon />\n      </button>\n    );\n\n    return (\n      <div className=\"flex items-center justify-center shrink-0 mr-2\">\n        <Dropdown items={items} renderTrigger={renderTrigger} />\n      </div>\n    );\n  };\n\n  // ===== BOTÓN DE NAVEGACIÓN =====\n  const NavigationButton = () => {\n    if (isMobile || !showNavigationButton) return null;\n\n    const defaultButtonProps = {\n      type: 'default' as const,\n      size: 'base' as const,\n      iconOnly: true,\n      leftIcon: <ArrowLeftStartOnRectangleIcon />,\n      ariaLabel: t('back', 'Volver'),\n      onClick: onNavigationClick,\n      ...navigationButtonProps, // Permite sobrescribir las props por defecto\n    };\n\n    if (isDesktop || isTablet) {\n      return <Button {...defaultButtonProps} />;\n    }\n\n    // Responsive: Solo visible en md: y superiores\n    return (\n      <div className=\"hidden md:block\">\n        <Button {...defaultButtonProps} />\n      </div>\n    );\n  };\n\n  // ===== BUSINESS LOGO (Logo del cliente/producto) =====\n  // Solo se muestra si showBusinessLogo es true\n  const BusinessLogo = () => {\n    if (isMobile || !showBusinessLogo) return null;\n\n    const logoContent = (\n      <img\n        src=\"/Business Logo.png\"\n        alt=\"Business Logo\"\n        className=\"w-full h-full object-contain\"\n      />\n    );\n\n    if (isDesktop) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[168px] h-[30px]\">\n          {logoContent}\n        </div>\n      );\n    }\n\n    if (isTablet) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[140px] h-[25px]\">\n          {logoContent}\n        </div>\n      );\n    }\n\n    // Responsive: Visible en md: con tamaño desktop, lg: con tamaño completo\n    return (\n      <div className=\"hidden md:block overflow-hidden relative shrink-0 w-[140px] lg:w-[168px] h-[25px] lg:h-[30px]\">\n        {logoContent}\n      </div>\n    );\n  };\n\n  // ===== SIESA LOGO (Logo de Siesa - Leading) =====\n  // Se controla con showSiesaLogoLeading\n  // En mobile siempre se muestra el icono de Siesa en leading\n  const SiesaLogoLeading = () => {\n    const logoFull = (\n      <img\n        src=\"/Siesa Logo.png\"\n        alt=\"Siesa\"\n        className=\"w-full h-full object-contain\"\n      />\n    );\n\n    const logoMobile = (\n      <img\n        src=\"/siesa_logo_mobile.png\"\n        alt=\"Siesa\"\n        className=\"w-full h-full object-contain\"\n      />\n    );\n\n    // En mobile siempre se muestra el icono de Siesa\n    if (isMobile) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[30px] h-[30px]\">\n          {logoMobile}\n        </div>\n      );\n    }\n\n    // En desktop/tablet: Se controla con showSiesaLogoLeading\n    if (!showSiesaLogoLeading) return null;\n\n    if (isDesktop) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[120px] h-[30px]\">\n          {logoFull}\n        </div>\n      );\n    }\n\n    if (isTablet) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[100px] h-[25px]\">\n          {logoFull}\n        </div>\n      );\n    }\n\n    // Responsive\n    return (\n      <>\n        {/* Mobile: Logo icono (30x30) - siempre visible */}\n        <div className=\"md:hidden overflow-hidden relative shrink-0 w-[30px] h-[30px]\">\n          {logoMobile}\n        </div>\n        {/* Tablet/Desktop: Se controla con showSiesaLogoLeading */}\n        {showSiesaLogoLeading && (\n          <>\n            {/* Tablet: Logo completo (100x25) */}\n            <div className=\"hidden md:block lg:hidden overflow-hidden relative shrink-0 w-[100px] h-[25px]\">\n              {logoFull}\n            </div>\n            {/* Desktop: Logo completo (120x30) */}\n            <div className=\"hidden lg:block overflow-hidden relative shrink-0 w-[120px] h-[30px]\">\n              {logoFull}\n            </div>\n          </>\n        )}\n      </>\n    );\n  };\n\n  // ===== SIESA LOGO (Trailing) =====\n  // Se controla con showSiesaLogoTrailing\n  const SiesaLogoTrailing = () => {\n    // Se controla con showSiesaLogoTrailing\n    if (!showSiesaLogoTrailing || isMobile) return null;\n\n    const logoFull = (\n      <img\n        src=\"/Siesa Logo.png\"\n        alt=\"Siesa\"\n        className=\"w-full h-full object-contain\"\n      />\n    );\n\n    if (isDesktop) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[120px] h-[30px]\">\n          {logoFull}\n        </div>\n      );\n    }\n\n    if (isTablet) {\n      return (\n        <div className=\"overflow-hidden relative shrink-0 w-[100px] h-[25px]\">\n          {logoFull}\n        </div>\n      );\n    }\n\n    // Responsive: Visible en md: (tablet y desktop)\n    return (\n      <>\n        {/* Tablet: Logo completo (100x25) */}\n        <div className=\"hidden md:block lg:hidden overflow-hidden relative shrink-0 w-[100px] h-[25px]\">\n          {logoFull}\n        </div>\n        {/* Desktop: Logo completo (120x30) */}\n        <div className=\"hidden lg:block overflow-hidden relative shrink-0 w-[120px] h-[30px]\">\n          {logoFull}\n        </div>\n      </>\n    );\n  };\n\n  // ===== DIVIDER COMPONENT =====\n  const Divider = ({ responsive = true }: { responsive?: boolean }) => {\n    const dividerContent = (\n      <div className=\"grow shrink-0 w-px min-h-px bg-border-primary dark:bg-dark-border-primary\" />\n    );\n\n    if (isMobile) return null;\n\n    if (isDesktop || isTablet) {\n      return (\n        <div className=\"flex flex-col gap-2 h-8 items-start px-0 py-1 relative shrink-0\">\n          {dividerContent}\n        </div>\n      );\n    }\n\n    // Responsive\n    if (responsive) {\n      return (\n        <div className=\"hidden md:flex flex-col gap-2 h-8 items-start px-0 py-1 relative shrink-0\">\n          {dividerContent}\n        </div>\n      );\n    }\n\n    return null;\n  };\n\n  // ===== PRODUCT NAME (con soporte para label de AppShell) =====\n  const ProductName = () => {\n    if (isMobile || !productName) return null;\n\n    // Contenido base del nombre del producto\n    const baseName = (\n      <span className=\"font-bold leading-7 text-xl text-content-primary dark:text-dark-content-primary tracking-[-0.5px] whitespace-nowrap\">\n        {productName}\n      </span>\n    );\n\n    // Si es AppShell y hay un microfrontend seleccionado, mostrar el breadcrumb\n    const content = isAppShell && selectedMicrofrontend ? (\n      <div className=\"flex items-center gap-2\">\n        {baseName}\n        <span className=\"text-content-secondary dark:text-content-secondary\">/</span>\n        <span className=\"font-normal leading-7 text-xl text-content-primary dark:text-dark-content-primary tracking-[-0.5px] whitespace-nowrap\">\n          {selectedMicrofrontend}\n        </span>\n      </div>\n    ) : (\n      baseName\n    );\n\n    if (isDesktop || isTablet) {\n      return <div className=\"flex items-center\">{content}</div>;\n    }\n\n    // Responsive: Solo visible en md:\n    return (\n      <div className=\"hidden md:flex items-center\">\n        {content}\n      </div>\n    );\n  };\n\n  // ===== ENVIRONMENT BADGE =====\n  const EnvironmentBadge = () => {\n    if (!environmentBadge) return null;\n\n    if (isMobile) {\n      return (\n        <Badge\n          color=\"yellow\"\n          leftIcon={<ExclamationTriangleIcon />}\n          label=\"Pruebas\"\n        />\n      );\n    }\n\n    if (isDesktop || isTablet) {\n      return (\n        <Badge\n          color=\"yellow\"\n          leftIcon={<ExclamationTriangleIcon />}\n          label={environmentBadge}\n        />\n      );\n    }\n\n    // Responsive: Mostrar badge corto en mobile, completo en desktop\n    return (\n      <>\n        <div className=\"md:hidden\">\n          <Badge\n            color=\"yellow\"\n            leftIcon={<ExclamationTriangleIcon />}\n            label=\"Pruebas\"\n          />\n        </div>\n        <div className=\"hidden md:block\">\n          <Badge\n            color=\"yellow\"\n            leftIcon={<ExclamationTriangleIcon />}\n            label={environmentBadge}\n          />\n        </div>\n      </>\n    );\n  };\n\n  // ===== SEARCH BUTTON (Solo mobile) =====\n  const SearchButton = () => {\n    if (hideActionButtons) return null;\n\n    if (isMobile) {\n      return (\n        <button\n          className={actionButtonClasses}\n          aria-label={t('search', 'Buscar')}\n          onClick={onSearchClick}\n        >\n          <MagnifyingGlassIcon />\n        </button>\n      );\n    }\n\n    if (isResponsive) {\n      return (\n        <button\n          className={`md:hidden ${actionButtonClasses}`}\n          aria-label=\"Buscar\"\n          onClick={onSearchClick}\n        >\n          <MagnifyingGlassIcon />\n        </button>\n      );\n    }\n\n    return null;\n  };\n\n  // ===== CART BUTTON =====\n  const CartButton = () => {\n    if (hideActionButtons) return null;\n\n    return (\n      <div className=\"relative\">\n        <button\n          className={actionButtonClasses}\n          aria-label={t('cart', 'Carrito de compras')}\n          onClick={onCartClick}\n        >\n          <ShoppingCartIcon />\n        </button>\n        {/* Badge de notificación con número */}\n        {notifications?.cart !== undefined && notifications.cart > 0 && (\n          <div className=\"absolute bg-error-content dark:bg-error-content flex flex-col gap-2.5 h-4 items-center justify-center left-[calc(50%+8px)] px-1 py-0 rounded-full top-[calc(50%-8px)] -translate-x-1/2 -translate-y-1/2 pointer-events-none min-w-[16px]\">\n            <p className=\"font-bold leading-3 text-[10px] text-white text-center whitespace-nowrap\">\n              {notifications.cart > 99 ? '+99' : notifications.cart}\n            </p>\n          </div>\n        )}\n      </div>\n    );\n  };\n\n  // ===== NOTIFICATIONS BUTTON =====\n  const NotificationsButton = () => {\n    if (hideActionButtons) return null;\n\n    return (\n      <div className=\"relative\">\n        <button\n          className={actionButtonClasses}\n          aria-label={t('notifications', 'Notificaciones')}\n          onClick={onNotificationsClick}\n        >\n          <BellIcon />\n        </button>\n        {/* Badge de notificación dot */}\n        {notifications?.bell && (\n          <div className=\"absolute w-2 h-2 bg-error-content dark:bg-error-content rounded-full left-[calc(50%+4px)] top-[calc(50%-8px)] -translate-x-1/2 pointer-events-none\" />\n        )}\n      </div>\n    );\n  };\n\n  // ===== USER DROPDOWN ITEMS (Memorizados para rendimiento y reactividad) =====\n  const userMenuItems = useMemo(() => {\n    if (!userDropdown) return [];\n\n    // 1. Obtener items base (personalizados o por defecto)\n    let items = userDropdown.menuItems;\n    \n    if (!items) {\n      items = [\n        {\n          children: t('account', 'Cuenta'),\n          icon: <UserIcon className=\"size-4\" />,\n          onClick: userDropdown.onAccountClick,\n        },\n        {\n          children: t('notifications', 'Notificaciones'),\n          icon: <BellIcon className=\"size-4\" />,\n          onClick: userDropdown.onNotificationsClick,\n        },\n        {\n          children: t('billing', 'Facturación'),\n          icon: <CreditCardIcon className=\"size-4\" />,\n          onClick: userDropdown.onBillingClick,\n        },\n        { isDivider: true },\n        {\n          children: t('darkMode', 'Modo oscuro'),\n          icon: <MoonIcon className=\"size-4\" />,\n          onClick: userDropdown.onDarkModeClick,\n        },\n        { isDivider: true },\n        {\n          children: t('logout', 'Cerrar sesión'),\n          icon: <ArrowRightOnRectangleIcon className=\"size-4\" />,\n          onClick: userDropdown.onSignOutClick,\n        },\n      ];\n    }\n\n    // 2. Si languageSelector está desactivado explícitamente, retornar los items tal cual\n    if (languageSelector === false) return items;\n\n    // 3. Inyectar languageSelector (incluso en menús personalizados, a menos que se pase false)\n    const result = [...items];\n    const selectorItem = {\n      customContent:\n        typeof languageSelector === 'boolean' ? (\n          <LanguageSelector variant=\"menu-item\" />\n        ) : (\n          languageSelector\n        ),\n    };\n\n    // Intentar encontrar el mejor lugar (antes del logout o al final)\n    // Buscamos un item que parezca ser el de \"Cerrar sesión\"\n    const logoutIndex = result.findIndex(item => \n      !item.isDivider && !item.isHeading && (\n        (typeof item.children === 'string' && (\n          item.children.toLowerCase().includes('cerrar') || \n          item.children.toLowerCase().includes('salir') ||\n          item.children.toLowerCase().includes('logout') ||\n          item.children.toLowerCase().includes('sign out')\n        )) || \n        item.onClick === userDropdown.onSignOutClick\n      )\n    );\n\n    if (logoutIndex !== -1) {\n      // Si el item anterior no es un divisor, añadir uno\n      const hasDividerBefore = logoutIndex > 0 && result[logoutIndex - 1].isDivider;\n      if (!hasDividerBefore) {\n        result.splice(logoutIndex, 0, { isDivider: true }, selectorItem);\n      } else {\n        result.splice(logoutIndex, 0, selectorItem);\n      }\n    } else {\n      // Si no hay logout, simplemente añadir al final con un divisor\n      if (result.length > 0 && !result[result.length - 1].isDivider) {\n        result.push({ isDivider: true });\n      }\n      result.push(selectorItem);\n    }\n\n    return result;\n  }, [userDropdown, languageSelector, t]);\n\n  // ===== USER DROPDOWN COMPONENT =====\n  const UserDropdown = () => {\n    if (!userDropdown) return null;\n\n    // Mobile: Solo avatar circular con dropdown\n    if (isMobile) {\n      return (\n        <Dropdown\n          items={userMenuItems}\n          renderTrigger={(isOpen) => (\n            <button\n              className={`\n                box-border\n                flex\n                items-center\n                justify-center\n                overflow-hidden\n                p-0\n                relative\n                shrink-0\n                hover:bg-background-secondary\n                focus:outline-none\n                focus:ring-2\n                focus:ring-primary-400\n                focus:ring-offset-2\n                dark:hover:bg-dark-bg-secondary\n                dark:focus:ring-dark-border-custom\n                dark:focus:ring-offset-dark-bg-primary\n                rounded-lg\n                transition-all\n                duration-150\n                ${isOpen ? 'bg-background-secondary dark:bg-dark-bg-secondary' : ''}\n              `.trim().replace(/\\s+/g, ' ')}\n              aria-label=\"Menú de usuario\"\n            >\n              <div className=\"relative rounded-full shrink-0 w-8 h-8\">\n                <img\n                  alt={userDropdown.name}\n                  className=\"absolute inset-0 max-w-none object-center object-cover pointer-events-none rounded-full w-full h-full\"\n                  src={userDropdown.avatar}\n                />\n              </div>\n            </button>\n          )}\n        />\n      );\n    }\n\n    // Desktop/Tablet: Avatar + info + chevron con dropdown\n    const renderFullDropdown = () => (\n      <Dropdown\n        items={userMenuItems}\n        renderTrigger={(isOpen) => (\n          <button\n            className={`\n              box-border\n              flex\n              items-center\n              justify-center\n              overflow-hidden\n              p-0\n              relative\n              shrink-0\n              hover:bg-background-secondary\n              focus:outline-none\n              focus:ring-2\n              focus:ring-primary-400\n              focus:ring-offset-2\n              dark:hover:bg-dark-bg-secondary\n              dark:focus:ring-dark-border-custom\n              dark:focus:ring-offset-dark-bg-primary\n              rounded-lg\n              transition-all\n              duration-150\n              ${isOpen ? 'bg-background-secondary dark:bg-dark-bg-secondary' : ''}\n            `.trim().replace(/\\s+/g, ' ')}\n            aria-label=\"Menú de usuario\"\n          >\n            <div className=\"box-border flex gap-3 items-center justify-center overflow-hidden px-3 py-2 relative rounded-lg shrink-0\">\n              <div className=\"flex gap-3 items-center justify-center relative shrink-0\">\n                {/* Avatar */}\n                <div className=\"flex items-center justify-center relative shrink-0\">\n                  <div className=\"relative rounded-md shrink-0 w-10 h-10\">\n                    <img\n                      alt={userDropdown.name}\n                      className=\"absolute inset-0 max-w-none object-center object-cover pointer-events-none rounded-md w-full h-full\"\n                      src={userDropdown.avatar}\n                    />\n                  </div>\n                </div>\n                {/* Nombre y email/rol */}\n                <div className=\"flex flex-col gap-0.5 items-start justify-center relative shrink-0 w-[123px]\">\n                  <p className=\"leading-5 relative shrink-0 text-sm text-content-primary dark:text-dark-content-primary whitespace-nowrap font-normal text-start\">\n                    {userDropdown.name}\n                  </p>\n                  {(userDropdown.email || userDropdown.role) && (\n                    <p className=\"leading-4 min-w-full relative shrink-0 text-xs text-content-secondary dark:text-content-secondary w-min whitespace-nowrap overflow-hidden text-ellipsis text-start\">\n                      {userDropdown.email || userDropdown.role}\n                    </p>\n                  )}\n                </div>\n              </div>\n              {/* Chevron down icon */}\n              <ChevronDownIcon className=\"size-5 text-content-secondary dark:text-content-secondary\" />\n            </div>\n          </button>\n        )}\n      />\n    );\n\n    if (isDesktop || isTablet) {\n      return renderFullDropdown();\n    }\n\n    // Responsive\n    return (\n      <>\n        {/* Mobile: Solo avatar circular con dropdown */}\n        <div className=\"md:hidden\">\n          <Dropdown\n            items={userMenuItems}\n            renderTrigger={(isOpen) => (\n              <button\n                className={`\n                  box-border\n                  flex\n                  items-center\n                  justify-center\n                  overflow-hidden\n                  p-0\n                  relative\n                  shrink-0\n                  hover:bg-background-secondary\n                  focus:outline-none\n                  focus:ring-2\n                  focus:ring-primary-400\n                  focus:ring-offset-2\n                  dark:hover:bg-dark-bg-secondary\n                  dark:focus:ring-dark-border-custom\n                  dark:focus:ring-offset-dark-bg-primary\n                  rounded-lg\n                  transition-all\n                  duration-150\n                  ${isOpen ? 'bg-background-secondary dark:bg-dark-bg-secondary' : ''}\n                `.trim().replace(/\\s+/g, ' ')}\n                aria-label=\"Menú de usuario\"\n              >\n                <div className=\"relative rounded-full shrink-0 w-8 h-8\">\n                  <img\n                    alt={userDropdown.name}\n                    className=\"absolute inset-0 max-w-none object-center object-cover pointer-events-none rounded-full w-full h-full\"\n                    src={userDropdown.avatar}\n                  />\n                </div>\n              </button>\n            )}\n          />\n        </div>\n        {/* Desktop/Tablet: Avatar + info + chevron con dropdown */}\n        <div className=\"hidden md:flex\">\n          <Dropdown\n            items={userMenuItems}\n            renderTrigger={(isOpen) => (\n              <button\n                className={`\n                  box-border\n                  flex\n                  items-center\n                  justify-center\n                  overflow-hidden\n                  p-0\n                  relative\n                  shrink-0\n                  hover:bg-background-secondary\n                  focus:outline-none\n                  focus:ring-2\n                  focus:ring-primary-400\n                  focus:ring-offset-2\n                  dark:hover:bg-dark-bg-secondary\n                  dark:focus:ring-dark-border-custom\n                  dark:focus:ring-offset-dark-bg-primary\n                  rounded-lg\n                  transition-all\n                  duration-150\n                  ${isOpen ? 'bg-background-secondary dark:bg-dark-bg-secondary' : ''}\n                `.trim().replace(/\\s+/g, ' ')}\n                aria-label=\"Menú de usuario\"\n              >\n                <div className=\"box-border flex gap-3 items-center justify-center overflow-hidden px-3 py-2 relative rounded-lg shrink-0\">\n                  <div className=\"flex gap-3 items-center justify-center relative shrink-0\">\n                    {/* Avatar */}\n                    <div className=\"flex items-center justify-center relative shrink-0\">\n                      <div className=\"relative rounded-md shrink-0 w-10 h-10\">\n                        <img\n                          alt={userDropdown.name}\n                          className=\"absolute inset-0 max-w-none object-center object-cover pointer-events-none rounded-md w-full h-full\"\n                          src={userDropdown.avatar}\n                        />\n                      </div>\n                    </div>\n                    {/* Nombre y email/rol */}\n                    <div className=\"flex flex-col gap-0.5 items-start justify-center relative shrink-0 w-[123px]\">\n                      <p className=\"leading-5 relative shrink-0 text-sm text-content-primary dark:text-dark-content-primary whitespace-nowrap font-normal\">\n                        {userDropdown.name}\n                      </p>\n                      {(userDropdown.email || userDropdown.role) && (\n                        <p className=\"leading-4 min-w-full relative shrink-0 text-xs text-content-secondary dark:text-content-secondary w-min whitespace-nowrap overflow-hidden text-ellipsis\">\n                          {userDropdown.email || userDropdown.role}\n                        </p>\n                      )}\n                    </div>\n                  </div>\n                  {/* Chevron down icon */}\n                  <div className=\"overflow-hidden relative shrink-0 w-5 h-5 text-content-secondary dark:text-content-secondary\">\n                    <ChevronDownIcon />\n                  </div>\n                </div>\n              </button>\n            )}\n          />\n        </div>\n      </>\n    );\n  };\n\n  // ===== CLASES BASE DEL NAVBAR =====\n  const baseClasses = `\n    box-border\n    flex\n    gap-8\n    items-center\n    px-4\n    py-1\n    relative\n    w-full\n    bg-background-primary\n    dark:bg-dark-bg-primary\n  `;\n\n  // ===== CLASES PARA VARIANTES DE ALTURA =====\n  const variantClasses = {\n    responsive: 'h-[40px] md:h-16',\n    desktop: 'h-16',\n    tablet: 'h-16',\n    mobile: 'h-[40px]',\n  };\n\n  // ===== COMBINAR CLASES =====\n  const finalClasses = [baseClasses, variantClasses[variant], className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== BUSINESS LOGO RENDERER =====\n  // Maneja la lógica de visualización del logo personalizado (light/dark) o el logo por defecto\n  const renderBusinessLogo = () => {\n    // Caso 1: Usuario proporciona ambos logos (Light y Dark)\n    if (logo && darkLogo) {\n      return (\n        <>\n          <div className=\"block dark:hidden w-full h-full\">{logo}</div>\n          <div className=\"hidden dark:block w-full h-full\">{darkLogo}</div>\n        </>\n      );\n    }\n\n    // Caso 2: Usuario proporciona solo un logo (comportamiento estándar)\n    if (logo) {\n      return logo;\n    }\n\n    // Caso 3: No hay logo personalizado, usar el componente interno por defecto\n    return <BusinessLogo />;\n  };\n\n  return (\n    <nav className={finalClasses}>\n      {/* ===== SECCIÓN LEADING (IZQUIERDA) ===== */}\n      <div className=\"flex gap-4 items-center relative shrink-0\">\n        {/* App Launcher (Solo AppShell) */}\n        <AppLauncher />\n\n        {/* Botón de navegación o acción leading personalizada (solo desktop/tablet) */}\n        {!isMobile && (leadingAction || (showNavigationButton && <NavigationButton />))}\n\n        {/* Business Logo (logo del cliente) - Puede ser custom (light/dark) o default */}\n        {renderBusinessLogo()}\n\n        {/* Divider después de Business Logo - Solo cuando hay Business Logo Y hay Siesa Logo en leading */}\n        {showBusinessLogo && showSiesaLogoLeading && !isMobile && <Divider />}\n\n        {/* Siesa Logo en leading - Se controla con showSiesaLogoLeading */}\n        {siesaLogo || <SiesaLogoLeading />}\n\n        {/* Divider antes del nombre - Solo cuando hay Siesa Logo en leading y nombre de producto */}\n        {productName && showSiesaLogoLeading && !isMobile && <Divider />}\n\n        {/* Nombre del Producto - Solo desktop/tablet */}\n        <ProductName />\n      </div>\n\n      {/* ===== SECCIÓN TRAILING (DERECHA) ===== */}\n      <div className=\"flex gap-4 items-center justify-end grow min-h-px min-w-px relative shrink-0\">\n        {/* Badge de Ambiente */}\n        <EnvironmentBadge />\n\n        {/* Botón de búsqueda - Solo mobile */}\n        <SearchButton />\n\n        {/* Botón de carrito de compras */}\n        <CartButton />\n\n        {/* Botón de notificaciones */}\n        <NotificationsButton />\n\n        {/* Divider antes del dropdown - Solo desktop/tablet */}\n        {userDropdown && !hideActionButtons && <Divider />}\n\n        {/* Dropdown de usuario */}\n        <UserDropdown />\n\n        {/* Divider antes del logo Siesa trailing - Solo cuando showSiesaLogoTrailing=true */}\n        {showSiesaLogoTrailing && userDropdown && !isMobile && <Divider />}\n\n        {/* Logo Siesa trailing - Solo desktop */}\n        <SiesaLogoTrailing />\n\n        {/* Actions adicionales */}\n        {actions && <div className=\"flex gap-2 items-center\">{actions}</div>}\n      </div>\n    </nav>\n  );\n};\n","import React from 'react';\nimport type { NavigationBarProps, NavigationBarItem } from './NavigationBar.types';\n\n/**\n * NavigationBar del sistema de diseño Siesa\n *\n * **Componente de navegación inferior (Bottom Navigation Bar) para móvil.**\n * Permite al usuario navegar entre vistas principales de la aplicación.\n * Diseñado para contener 3-5 ítems de navegación.\n *\n * **🔄 Navegación Responsive:**\n * El NavigationRail (navegación lateral vertical) se convierte en NavigationBar\n * (navegación inferior horizontal) cuando la pantalla es móvil. Esta es una\n * práctica recomendada de UX para aprovechar mejor el espacio en diferentes\n * dispositivos:\n * - **Desktop/Tablet**: Usar NavigationRail (lateral)\n * - **Mobile**: Usar NavigationBar (inferior)\n *\n * **Características:**\n * - Soporta hasta 5 ítems de navegación (recomendado: 3-5)\n * - Cada ítem tiene icono + label\n * - Indicador visual de ítem activo (fondo azul claro)\n * - Estados: active, hover, disabled\n * - Dark mode completo\n * - Accesibilidad con ARIA labels\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Tipografía Label XXSmall (10px Bold) según sistema de diseño\n * - Iconos de 16x16px según especificaciones de Figma\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Label XXSmall)\n * @see docs/spacing.md - Sistema de espaciado\n * @see NavigationRail - Componente de navegación lateral para desktop\n *\n * @example\n * ```tsx\n * const items = [\n *   { id: 'home', icon: <HomeIcon />, label: 'Inicio', active: true },\n *   { id: 'search', icon: <SearchIcon />, label: 'Buscar' },\n *   { id: 'profile', icon: <ProfileIcon />, label: 'Perfil' },\n * ];\n *\n * <NavigationBar\n *   items={items}\n *   activeItemId=\"home\"\n *   onItemClick={(id) => console.log('Clicked:', id)}\n * />\n * ```\n *\n * @example\n * // Patrón responsive: NavigationRail en desktop, NavigationBar en mobile\n * ```tsx\n * function ResponsiveNav() {\n *   return (\n *     <>\n *       // NavigationRail para desktop/tablet\n *       <div className=\"hidden md:block\">\n *         <NavigationRail items={items} />\n *       </div>\n *\n *       // NavigationBar para móvil\n *       <div className=\"md:hidden fixed bottom-0 left-0 right-0 z-50\">\n *         <NavigationBar items={items} />\n *       </div>\n *     </>\n *   );\n * }\n * ```\n */\nexport const NavigationBar: React.FC<NavigationBarProps> = ({\n  items,\n  activeItemId,\n  onItemClick,\n  className = '',\n  ariaLabel = 'Navegación Principal',\n}) => {\n  // ===== VALIDACIÓN: Máximo 5 ítems =====\n  if (items.length > 5) {\n    console.warn('NavigationBar: Se recomienda un máximo de 5 ítems para mejor UX');\n  }\n\n  // ===== HANDLER DE CLICK =====\n  const handleItemClick = (item: NavigationBarItem) => {\n    if (item.disabled) return;\n\n    // Llamar onClick del ítem individual si existe\n    if (item.onClick) {\n      item.onClick(item.id);\n    }\n\n    // Llamar onItemClick global si existe\n    if (onItemClick) {\n      onItemClick(item.id);\n    }\n  };\n\n  // ===== RENDERIZAR ÍTEM =====\n  const renderItem = (item: NavigationBarItem) => {\n    const isActive = item.active || item.id === activeItemId;\n\n    // ===== CLASES DEL CONTENEDOR DEL ÍTEM =====\n    const itemContainerClasses = `\n      flex-1\n      flex\n      flex-col\n      items-center\n      gap-1\n      px-0.5\n      py-0\n      min-w-0\n      cursor-pointer\n      transition-all\n      duration-150\n      ${item.disabled ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}\n    `\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    // ===== CLASES DEL ICON CONTAINER =====\n    // Fondo azul claro cuando está activo (rgb(219, 238, 254) = #dbeefe = primary-100)\n    // En dark mode usa el mismo color opaco según Figma\n    const iconContainerClasses = `\n      flex\n      items-center\n      justify-center\n      px-4\n      py-1\n      rounded-full\n      overflow-hidden\n      transition-all\n      duration-150\n      ${\n        isActive\n          ? 'bg-primary-100 dark:bg-primary-100'\n          : 'bg-transparent hover:bg-hover-overlay dark:hover:bg-hover-overlay-dark'\n      }\n    `\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    // ===== CLASES DEL LABEL =====\n    // Label XXSmall: 10px Bold, line-height 12px (según typography.md y Figma)\n    const labelClasses = `\n      font-['Inter:Bold',sans-serif]\n      text-[10px]\n      leading-[12px]\n      font-bold\n      text-center\n      w-full\n      min-w-0\n      text-content-primary\n      dark:text-dark-content-primary\n      transition-colors\n      duration-150\n    `\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    // ===== CLASES DEL ICONO =====\n    // Iconos de 16x16px según Figma\n    const iconClasses = `\n      w-4\n      h-4\n      shrink-0\n      text-content-primary\n      dark:text-dark-content-primary\n      transition-colors\n      duration-150\n    `\n      .replace(/\\s+/g, ' ')\n      .trim();\n\n    return (\n      <button\n        key={item.id}\n        type=\"button\"\n        className={itemContainerClasses}\n        onClick={() => handleItemClick(item)}\n        disabled={item.disabled}\n        aria-label={item.ariaLabel || item.label}\n        aria-current={isActive ? 'page' : undefined}\n      >\n        {/* Icon Container */}\n        <div className={iconContainerClasses}>\n          <span className={iconClasses}>{item.icon}</span>\n        </div>\n\n        {/* Label */}\n        <span className={labelClasses}>{item.label}</span>\n      </button>\n    );\n  };\n\n  // ===== CLASES DEL CONTENEDOR PRINCIPAL =====\n  const containerClasses = `\n    bg-bg-primary\n    dark:bg-dark-bg-primary\n    p-4\n    w-full\n    transition-colors\n    duration-150\n  `\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== CLASES DEL MENU (Contenedor de ítems) =====\n  const menuClasses = `\n    flex\n    items-start\n    justify-center\n    w-full\n  `\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== CLASES DEL DESTINATIONS (Contenedor con gap) =====\n  const destinationsClasses = `\n    flex-1\n    flex\n    items-start\n    gap-2\n    min-h-0\n    min-w-0\n  `\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <nav\n      className={`${containerClasses} ${className}`.trim()}\n      role=\"navigation\"\n      aria-label={ariaLabel}\n    >\n      <div className={menuClasses}>\n        <div className={destinationsClasses}>\n          {items.map((item) => renderItem(item))}\n        </div>\n      </div>\n    </nav>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono de convención para POSConvention\n *\n * Círculo SVG de 16x16px con colores diferentes para Light y Dark mode.\n * Basado en especificaciones de Figma:\n * - Light mode: node-id 4418-40139\n * - Dark mode: node-id 4418-40349\n *\n * Usa dos círculos superpuestos con clases CSS para alternar entre modos.\n *\n * @param lightColor - Color hexadecimal para Light mode\n * @param darkColor - Color hexadecimal para Dark mode\n * @param className - Clases CSS adicionales (opcional)\n */\nexport const ConventionIcon: React.FC<{\n  lightColor: string;\n  darkColor: string;\n  className?: string;\n}> = ({ lightColor, darkColor, className = '' }) => (\n  <svg\n    className={`w-4 h-4 shrink-0 ${className}`.trim()}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    aria-hidden=\"true\"\n  >\n    {/* Círculo para Light mode - visible por defecto, oculto en dark */}\n    <circle\n      cx=\"8\"\n      cy=\"8\"\n      r=\"8\"\n      fill={lightColor}\n      className=\"dark:hidden\"\n    />\n    {/* Círculo para Dark mode - oculto por defecto, visible en dark */}\n    <circle\n      cx=\"8\"\n      cy=\"8\"\n      r=\"8\"\n      fill={darkColor}\n      className=\"hidden dark:block\"\n    />\n  </svg>\n);\n","import React from 'react';\nimport type { POSConventionProps } from './POSConvention.types';\nimport { ConventionIcon } from './icons';\n\n/**\n * POSConvention - Componente de leyenda/convención para estados de mesas POS\n *\n * Muestra un indicador circular de color con su respectiva etiqueta según el diseño de Figma.\n * Se usa típicamente para crear leyendas que explican el significado de colores en el sistema POS.\n *\n * **Colores según Figma (node-id: 4418-40139):**\n *\n * | Estado | Light Mode | Dark Mode |\n * |--------|------------|-----------|\n * | Available | #0e79fd (azul) | #93d1fd (azul claro) |\n * | Occupied | #af460e (naranja) | #f5a927 (amarillo) |\n * | Reserved | #7e22ce (morado) | #c084fc (morado claro) |\n * | Out of Service | #3f3f46 (gris) | #a1a1aa (gris claro) |\n *\n * **Dimensiones según Figma:**\n * - Icono: 16x16px (círculo con fill)\n * - Texto: 12px (Paragraph/Tiny - text-xs)\n * - Gap: 4px (gap-1)\n * - Line-height: 16px (leading-4)\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Colores exactos de Figma para Light y Dark mode\n * - Type safety con TypeScript estricto\n * - Accesibilidad con aria-label\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Paragraph Tiny)\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * // Indicador de disponible\n * <POSConvention status=\"available\" />\n *\n * // Indicador de ocupada\n * <POSConvention status=\"occupied\" />\n *\n * // Leyenda completa en contenedor\n * <div className=\"p-5 rounded-lg border border-dashed border-primary-300\">\n *   <div className=\"flex flex-col gap-9\">\n *     <POSConvention status=\"available\" />\n *     <POSConvention status=\"occupied\" />\n *     <POSConvention status=\"reserved\" />\n *     <POSConvention status=\"outOfService\" />\n *   </div>\n * </div>\n * ```\n */\nexport const POSConvention: React.FC<POSConventionProps> = ({\n  status = 'available',\n  className = '',\n}) => {\n  // ===== CONFIGURACIÓN DE COLORES Y LABELS SEGÚN FIGMA =====\n  // Colores extraídos del nodo 4418-40139 (Light) y 4418-40349 (Dark) de Figma\n  // Variables de Figma: contentCustomPrimary, contentYellow, contentPurple, contentZinc\n  const conventionConfig = {\n    available: {\n      lightColor: '#0e79fd', // Azul - contentCustomPrimary Light\n      darkColor: '#93d1fd',  // Azul claro - contentCustomPrimary Dark\n      label: 'Disponible',\n    },\n    occupied: {\n      lightColor: '#af460e', // Naranja - contentOrange Light\n      darkColor: '#f5a927',  // Amarillo - contentYellow Dark\n      label: 'Ocupada',\n    },\n    reserved: {\n      lightColor: '#7e22ce', // Morado - contentPurple Light\n      darkColor: '#c084fc',  // Morado claro - contentPurple Dark\n      label: 'Reservada',\n    },\n    outOfService: {\n      lightColor: '#3f3f46', // Gris - contentZinc Light (zinc-700)\n      darkColor: '#a1a1aa',  // Gris claro - contentZinc Dark (zinc-400)\n      label: 'Fuera de Servicio',\n    },\n  };\n\n  const config = conventionConfig[status];\n\n  // ===== CLASES BASE =====\n  const baseClasses = `\n    inline-flex\n    items-center\n    gap-1\n    shrink-0\n  `;\n\n  // ===== COMBINAR CLASES =====\n  const finalClasses = [baseClasses, className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <div\n      className={finalClasses}\n      role=\"presentation\"\n      aria-label={`Estado: ${config.label}`}\n    >\n      {/* Icono circular 16x16 con colores para Light y Dark mode */}\n      <ConventionIcon lightColor={config.lightColor} darkColor={config.darkColor} />\n\n      {/* Label de texto según Figma: Paragraph/Tiny 12px */}\n      {/* Light: contentPrimary #18181b, Dark: contentPrimary #f4f4f5 */}\n      <span\n        className={`\n          text-xs\n          leading-4\n          font-normal\n          text-content-primary\n          dark:text-dark-content-primary\n          whitespace-nowrap\n        `\n          .replace(/\\s+/g, ' ')\n          .trim()}\n      >\n        {config.label}\n      </span>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono Check (✓) para estado Available\n * Tamaño: 12x12px\n */\nexport const CheckIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"12\"\n    height=\"12\"\n    viewBox=\"0 0 12 12\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M10 3L4.5 8.5L2 6\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n/**\n * Icono X Mark para estado Occupied\n * Tamaño: 12x12px\n */\nexport const XMarkIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"12\"\n    height=\"12\"\n    viewBox=\"0 0 12 12\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M9 3L3 9M3 3L9 9\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n/**\n * Icono Calendar para estado Reserved\n * Tamaño: 12x12px\n */\nexport const CalendarIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"12\"\n    height=\"12\"\n    viewBox=\"0 0 12 12\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M10.5 5H1.5M8.5 1V3M3.5 1V3M3.25 11H8.75C9.57843 11 10.25 10.3284 10.25 9.5V3.5C10.25 2.67157 9.57843 2 8.75 2H3.25C2.42157 2 1.75 2.67157 1.75 3.5V9.5C1.75 10.3284 2.42157 11 3.25 11Z\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n/**\n * Icono No Symbol (Prohibido) para estado Out of Service\n * Tamaño: 12x12px\n */\nexport const NoSymbolIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"12\"\n    height=\"12\"\n    viewBox=\"0 0 12 12\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M10.5 6C10.5 8.48528 8.48528 10.5 6 10.5C3.51472 10.5 1.5 8.48528 1.5 6C1.5 3.51472 3.51472 1.5 6 1.5C8.48528 1.5 10.5 3.51472 10.5 6Z\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n    />\n    <path\n      d=\"M9.18198 2.81802L2.81802 9.18198\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n    />\n  </svg>\n);\n\n/**\n * Icono de Usuario/Personas para mostrar capacidad\n * Tamaño: 13x10px (según especificaciones de Figma)\n */\nexport const UsersIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"13\"\n    height=\"10\"\n    viewBox=\"0 0 13 10\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n  >\n    <path\n      d=\"M9.25 9V8C9.25 6.89543 8.35457 6 7.25 6H2.75C1.64543 6 0.75 6.89543 0.75 8V9M12.25 9V8C12.25 6.89543 11.3546 6 10.25 6H9.75M7 2.5C7 3.60457 6.10457 4.5 5 4.5C3.89543 4.5 3 3.60457 3 2.5C3 1.39543 3.89543 0.5 5 0.5C6.10457 0.5 7 1.39543 7 2.5ZM10 2C10 2.82843 9.32843 3.5 8.5 3.5C7.67157 3.5 7 2.82843 7 2C7 1.17157 7.67157 0.5 8.5 0.5C9.32843 0.5 10 1.17157 10 2Z\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n","import React from 'react';\nimport type { POSLocationButtonProps } from './POSLocationButton.types';\nimport { CheckIcon, XMarkIcon, CalendarIcon, NoSymbolIcon, UsersIcon } from './icons';\n\n/**\n * POSLocationButton del sistema de diseño Siesa\n *\n * Botón especializado para punto de venta (POS) que muestra el estado de disponibilidad\n * de una ubicación física (mesa, salón, terraza, etc.) con indicadores visuales claros.\n *\n * **Estados de disponibilidad (status):**\n * - `available`: Disponible (verde/lime) con icono ✓\n * - `occupied`: Ocupada (naranja/yellow) con icono ✗\n * - `reserved`: Reservada (morado/purple) con icono 📅\n * - `outOfService`: Fuera de servicio (gris/zinc) con icono 🚫\n *\n * **Estados visuales (state):**\n * - `enabled`: Estado normal con fondo blanco/dark\n * - `actived`: Estado seleccionado con fondo coloreado\n *\n * **Características:**\n * - Ancho flexible: por defecto ocupa el 100% del contenedor (fullWidth=true)\n * - Altura fija: 68px (optimizado para interfaces POS)\n * - Muestra nombre de ubicación y capacidad (ej: \"1/8 mesas\")\n * - Badge visual con icono y texto del estado\n * - Dark mode completo en todos los estados\n * - Focus ring adaptativo\n * - Transiciones suaves\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * // Ubicación disponible\n * <POSLocationButton\n *   locationName=\"Antejardín\"\n *   status=\"available\"\n *   capacity={{ current: 1, total: 8 }}\n *   onClick={() => console.log('Seleccionado')}\n * />\n *\n * // Ubicación ocupada y seleccionada\n * <POSLocationButton\n *   locationName=\"Terraza\"\n *   status=\"occupied\"\n *   state=\"actived\"\n *   capacity={{ current: 5, total: 8 }}\n * />\n *\n * // Ubicación reservada\n * <POSLocationButton\n *   locationName=\"Salón Principal\"\n *   status=\"reserved\"\n *   capacity={{ current: 3, total: 12 }}\n * />\n *\n * // Fuera de servicio\n * <POSLocationButton\n *   locationName=\"Bar\"\n *   status=\"outOfService\"\n *   disabled\n * />\n * ```\n */\nexport const POSLocationButton: React.FC<POSLocationButtonProps> = ({\n  locationName,\n  status = 'available',\n  state = 'enabled',\n  capacity,\n  onClick,\n  disabled = false,\n  className = '',\n  ariaLabel,\n  fullWidth = true,\n}) => {\n  // ===== CONFIGURACIÓN DE COLORES POR STATUS =====\n  // Mapeo de colores según especificaciones de Figma (pixel-perfect)\n  const statusConfig = {\n    available: {\n      // Azul Primary Custom (según Figma: #0e79fd)\n      textColor: 'text-primary-600 dark:text-primary-600',\n      badgeBg: 'bg-primary-100 dark:bg-blue-900/30',\n      badgeText: 'text-primary-600 dark:text-blue-400',\n      activedBg: 'bg-primary-100 dark:bg-blue-900/30',\n      icon: CheckIcon,\n      badgeLabel: 'Disponible',\n    },\n    occupied: {\n      // Naranja/Yellow (según Figma: #af460e para texto, #fcedc9 para fondo)\n      textColor: 'text-[#af460e] dark:text-orange-400',\n      badgeBg: 'bg-[#fcedc9] dark:bg-yellow-900/30',\n      badgeText: 'text-[#af460e] dark:text-orange-400',\n      activedBg: 'bg-[#fcedc9] dark:bg-yellow-900/30',\n      icon: XMarkIcon,\n      badgeLabel: 'Ocupada',\n    },\n    reserved: {\n      // Morado/Purple (según Figma: #7e22ce para texto, #f3e8ff para fondo)\n      textColor: 'text-[#7e22ce] dark:text-fuchsia-400',\n      badgeBg: 'bg-[#f3e8ff] dark:bg-purple-900/30',\n      badgeText: 'text-[#7e22ce] dark:text-purple-400',\n      activedBg: 'bg-[#f3e8ff] dark:bg-purple-900/30',\n      icon: CalendarIcon,\n      badgeLabel: 'Reservada',\n    },\n    outOfService: {\n      // Gris/Zinc (según Figma: #3f3f46 para texto, #f4f4f5 para fondo)\n      textColor: 'text-[#3f3f46] dark:text-zinc-400',\n      badgeBg: 'bg-[#f4f4f5] dark:bg-zinc-800/30',\n      badgeText: 'text-content-tertiary dark:text-zinc-400',\n      activedBg: 'bg-[#f4f4f5] dark:bg-zinc-800/30',\n      icon: NoSymbolIcon,\n      badgeLabel: 'F. de Servicio',\n    },\n  };\n\n  const config = statusConfig[status];\n  const StatusIcon = config.icon;\n\n  // ===== CLASES DE FONDO SEGÚN STATE =====\n  const backgroundClasses =\n    state === 'actived'\n      ? config.activedBg // Fondo coloreado cuando está activo\n      : 'bg-white dark:bg-dark-bg-primary'; // Fondo blanco/dark cuando está enabled\n\n  // ===== CLASES DE ANCHO =====\n  const widthClasses = fullWidth ? 'w-full' : 'w-[189px]';\n\n  // ===== CLASES BASE =====\n  const baseClasses = `\n    flex\n    flex-col\n    items-stretch\n    justify-between\n    ${widthClasses}\n    h-[68px]\n    p-2\n    rounded-lg\n    cursor-pointer\n    transition-all\n    duration-150\n    focus:outline-hidden\n    focus:ring-2\n    focus:ring-primary-400\n    focus:ring-offset-2\n    dark:focus:ring-dark-border-custom\n    dark:focus:ring-offset-dark-bg-primary\n    hover:shadow-md\n    active:scale-[0.98]\n    disabled:opacity-50\n    disabled:cursor-not-allowed\n    disabled:pointer-events-none\n  `;\n\n  // ===== COMBINAR CLASES =====\n  const buttonClasses = [baseClasses, backgroundClasses, className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== FORMATEAR TEXTO DE CAPACIDAD =====\n  const capacityText = capacity\n    ? `${capacity.current}/${capacity.total} mesas`\n    : null;\n\n  return (\n    <button\n      className={buttonClasses}\n      onClick={onClick}\n      disabled={disabled}\n      aria-label={ariaLabel || `${locationName} - ${config.badgeLabel}`}\n      type=\"button\"\n    >\n      {/* ===== TÍTULO (Nombre de ubicación) ===== */}\n      <div\n        className={`\n          text-base\n          font-bold\n          leading-6\n          ${config.textColor}\n        `\n          .replace(/\\s+/g, ' ')\n          .trim()}\n      >\n        {locationName}\n      </div>\n\n      {/* ===== CONTENIDO (Capacidad + Badge) ===== */}\n      <div className=\"flex items-center justify-between\">\n        {/* Capacidad (izquierda) */}\n        {capacityText && (\n          <div className=\"flex items-center gap-1\">\n            <UsersIcon className={config.textColor} />\n            <span\n              className={`\n                text-[10px]\n                leading-[12px]\n                ${config.textColor}\n              `\n                .replace(/\\s+/g, ' ')\n                .trim()}\n            >\n              {capacityText}\n            </span>\n          </div>\n        )}\n\n        {/* Badge (derecha) */}\n        <div\n          className={`\n            inline-flex\n            items-center\n            gap-1\n            px-1.5\n            py-1\n            rounded-md\n            ${config.badgeBg}\n          `\n            .replace(/\\s+/g, ' ')\n            .trim()}\n        >\n          <StatusIcon className={config.badgeText} />\n          <span\n            className={`\n              text-xs\n              leading-4\n              ${config.badgeText}\n            `\n              .replace(/\\s+/g, ' ')\n              .trim()}\n          >\n            {config.badgeLabel}\n          </span>\n        </div>\n      </div>\n    </button>\n  );\n};\n","import React from 'react';\nimport type { POSNumberButtonProps } from './POSNumberButton.types';\n\n/**\n * Componente POSNumberButton del sistema de diseño Siesa\n * Botón numérico especializado para sistemas POS (Point of Sale)\n *\n * Basado en especificaciones de Figma con Tailwind CSS\n *\n * **Características principales:**\n * - Diseñado para pantallas táctiles y POS\n * - Tipografía Display Tiny (48px Bold) para números grandes\n * - Tres tamaños: Small (40x40), Medium (65x65), Large (80x80)\n * - Opción de borde visible o sin borde\n * - Estados: Default, Hover, Active, Disabled\n * - Touch-friendly: active:scale-95 para feedback táctil\n *\n * **Variantes:**\n * - `border=false`: Botón sin borde, hover cambia a primary\n * - `border=true`: Botón con borde, hover resalta el borde\n *\n * **Tamaños:**\n * - `s` (40x40px): Compacto, para teclados numéricos pequeños\n * - `m` (65x65px): Mediano, tamaño intermedio\n * - `l` (80x80px): Grande, tamaño por defecto para POS\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n * - Feedback visual inmediato con active:scale-95\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Display Tiny)\n * @see docs/spacing.md - Sistema de espaciado\n * @see src/components/Button/Button.tsx - Componente Button de referencia\n *\n * @example\n * ```tsx\n * // Botón numérico grande (POS)\n * <POSNumberButton size=\"l\">1</POSNumberButton>\n *\n * // Botón con borde\n * <POSNumberButton size=\"l\" border>2</POSNumberButton>\n *\n * // Botón compacto\n * <POSNumberButton size=\"s\">3</POSNumberButton>\n *\n * // Teclado numérico completo\n * <div className=\"grid grid-cols-3 gap-2\">\n *   {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((num) => (\n *     <POSNumberButton key={num} size=\"m\" onClick={() => handleInput(num)}>\n *       {num}\n *     </POSNumberButton>\n *   ))}\n * </div>\n * ```\n */\nexport const POSNumberButton: React.FC<POSNumberButtonProps> = ({\n  size = 'l',\n  border = false,\n  children,\n  disabled = false,\n  className = '',\n  onClick,\n  ariaLabel,\n  htmlType = 'button',\n  ...rest\n}) => {\n  // ===== CLASES DE TAMAÑO =====\n  // Basado en especificaciones de Figma: L=80x80, M=65x65, S=40x40\n  const sizeClasses = {\n    s: 'w-10 h-10', // 40x40px\n    m: 'w-[65px] h-[65px]', // 65x65px\n    l: 'w-20 h-20', // 80x80px\n  };\n\n  // ===== CLASES DE TEXTO =====\n  // Display Tiny (48px Bold) según typography.md → text-5xl\n  // Para tamaño small, reducimos a text-2xl (24px)\n  const textSizeClasses = {\n    s: 'text-2xl', // 24px para botones pequeños\n    m: 'text-5xl', // 48px Display Tiny\n    l: 'text-5xl', // 48px Display Tiny\n  };\n\n  // ===== CLASES DE ESTADO (Sin Borde) =====\n  const noBorderStateClasses = `\n    bg-white\n    text-content-primary\n    hover:bg-primary-600\n    hover:text-primary-inverse-content\n    active:bg-primary-600\n    active:text-primary-inverse-content\n    active:scale-95\n    dark:bg-dark-bg-primary\n    dark:text-dark-content-primary\n    dark:hover:bg-dark-bg-inverse\n    dark:hover:text-dark-content-inverse\n    dark:active:bg-dark-bg-inverse\n    dark:active:text-dark-content-inverse\n    dark:active:scale-95\n  `;\n\n  // ===== CLASES DE ESTADO (Con Borde) =====\n  const withBorderStateClasses = `\n    bg-white\n    text-content-primary\n    border\n    border-border-primary\n    hover:bg-primary-600\n    hover:text-primary-inverse-content\n    hover:border-primary-inverse-border\n    active:bg-primary-600\n    active:text-primary-inverse-content\n    active:border-primary-inverse-border\n    active:scale-95\n    dark:bg-dark-bg-primary\n    dark:text-dark-content-primary\n    dark:border-dark-border-primary\n    dark:hover:bg-dark-bg-inverse\n    dark:hover:text-dark-content-inverse\n    dark:hover:border-primary-inverse-border\n    dark:active:bg-dark-bg-inverse\n    dark:active:text-dark-content-inverse\n    dark:active:border-primary-inverse-border\n    dark:active:scale-95\n  `;\n\n  // ===== CLASES BASE =====\n  const baseClasses = `\n    inline-flex\n    items-center\n    justify-center\n    rounded-lg\n    font-bold\n    tracking-tighter\n    whitespace-nowrap\n    cursor-pointer\n    focus:outline-hidden\n    focus:ring-2\n    focus:ring-primary-400\n    focus:ring-offset-2\n    dark:focus:ring-dark-border-custom\n    dark:focus:ring-offset-dark-bg-primary\n    disabled:opacity-50\n    disabled:cursor-not-allowed\n    disabled:pointer-events-none\n    transition-all\n    duration-150\n  `;\n\n  // ===== COMBINAR TODAS LAS CLASES =====\n  const buttonClasses = [\n    baseClasses,\n    sizeClasses[size],\n    textSizeClasses[size],\n    border ? withBorderStateClasses : noBorderStateClasses,\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <button\n      type={htmlType}\n      className={buttonClasses}\n      disabled={disabled}\n      onClick={onClick}\n      aria-label={ariaLabel || `Número ${children}`}\n      {...rest}\n    >\n      {children}\n    </button>\n  );\n};\n","import React from 'react';\nimport type { POSProductButtonProps } from './POSProductButton.types';\n\n/**\n * Componente POSProductButton del sistema de diseño Siesa\n *\n * Botón especializado para sistemas POS que combina una imagen de producto\n * con un label descriptivo. Diseñado para selección rápida de productos.\n *\n * **Estados disponibles:**\n * - `default`: Estado normal con fondo blanco\n * - `active`: Estado seleccionado con fondo azul claro y texto azul\n * - `disabled`: Estado deshabilitado con opacidad reducida\n *\n * **Características:**\n * - Imagen con aspect ratio 158:80 (proporción de Figma)\n * - Label con tipografía Label Small (14px Bold)\n * - Soporte completo de dark mode\n * - Estados hover, active y focus\n * - Transiciones suaves\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Focus rings adaptativos para light y dark mode\n * - Tokens de color consistentes con la documentación\n * - Estados hover y active completos\n * - Tipografía Label Small (14px Bold) según sistema de diseño\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico (Label)\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/border-radius.md - Border radius\n *\n * @example\n * ```tsx\n * // Botón de producto normal\n * <POSProductButton\n *   image=\"/images/parrilla.jpg\"\n *   label=\"A la parrilla\"\n *   onClick={() => console.log('Producto seleccionado')}\n * />\n *\n * // Botón de producto activo/seleccionado\n * <POSProductButton\n *   image=\"/images/parrilla.jpg\"\n *   label=\"A la parrilla\"\n *   active={true}\n * />\n *\n * // Botón de producto deshabilitado\n * <POSProductButton\n *   image=\"/images/parrilla.jpg\"\n *   label=\"A la parrilla\"\n *   disabled={true}\n * />\n * ```\n */\nexport const POSProductButton: React.FC<POSProductButtonProps> = ({\n  image,\n  label,\n  active = false,\n  disabled = false,\n  onClick,\n  className = '',\n  ariaLabel,\n}) => {\n  // ===== CLASES BASE =====\n  const baseClasses = `\n    flex\n    flex-col\n    gap-2\n    p-3\n    rounded-lg\n    font-bold\n    text-sm\n    transition-all\n    duration-150\n    focus:outline-hidden\n    focus:ring-2\n    focus:ring-primary-400\n    focus:ring-offset-2\n    dark:focus:ring-dark-border-custom\n    dark:focus:ring-offset-dark-bg-primary\n  `;\n\n  // ===== CLASES DE ESTADO =====\n  const stateClasses = disabled\n    ? `\n      bg-white\n      text-content-primary\n      opacity-55\n      cursor-not-allowed\n      pointer-events-none\n      dark:bg-dark-bg-primary\n      dark:text-dark-content-primary\n    `\n    : active\n    ? `\n      bg-primary-100\n      text-primary-600\n      cursor-pointer\n      hover:bg-primary-100\n      active:scale-95\n      dark:bg-primary-100/20\n      dark:text-primary-600\n      dark:hover:bg-primary-100/30\n      dark:active:scale-95\n    `\n    : `\n      bg-white\n      text-content-primary\n      cursor-pointer\n      hover:bg-background-secondary\n      active:scale-95\n      dark:bg-dark-bg-primary\n      dark:text-dark-content-primary\n      dark:hover:bg-dark-bg-primary/80\n      dark:active:scale-95\n    `;\n\n  // ===== COMBINAR TODAS LAS CLASES =====\n  const buttonClasses = [baseClasses, stateClasses, className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <button\n      type=\"button\"\n      className={buttonClasses}\n      disabled={disabled}\n      onClick={onClick}\n      aria-label={ariaLabel || label}\n      aria-pressed={active}\n    >\n      {/* Imagen del producto */}\n      <div className=\"aspect-158/80 w-full rounded-lg overflow-hidden\">\n        <img\n          src={image}\n          alt={label}\n          className=\"w-full h-full object-cover\"\n        />\n      </div>\n\n      {/* Label del producto */}\n      <div className=\"w-full text-left leading-5\">\n        {label}\n      </div>\n    </button>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono Plus (heroicons-micro/plus)\n * Usado en el botón \"Agregar\" del POSProductCard\n * Tamaño: 16x16px según especificación de Figma\n */\nexport const PlusIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    className={className}\n    aria-hidden=\"true\"\n  >\n    <path\n      d=\"M8 3V13M3 8H13\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n","import React from 'react';\nimport type { POSProductCardProps } from './POSProductCard.types';\nimport { Button } from '../Button';\nimport { PlusIcon } from './icons';\n\n/**\n * Componente POSProductCard del sistema de diseño Siesa\n *\n * Card especializado para sistemas POS que muestra información de producto\n * con imagen, nombre, precio y botón de agregar. Diseñado para catálogos\n * de productos y selección rápida en punto de venta.\n *\n * **Estados disponibles:**\n * - `enabled`: Estado normal\n *   - Light: fondo blanco (#ffffff), texto negro (#18181b)\n *   - Dark: fondo oscuro (#18181b), texto claro (#f4f4f5)\n * - `active`: Estado seleccionado\n *   - Light: fondo azul claro (#dbeefe), texto azul (#0e79fd)\n *   - Dark: fondo azul oscuro (#112d57), texto celeste (#93d1fd)\n * - `disabled`: Estado deshabilitado con opacidad reducida\n *\n * **Características:**\n * - Imagen de producto con aspect ratio fijo y rounded-lg\n * - Nombre del producto con tipografía Label Small (14px Bold)\n * - Precio con tipografía Heading Small (24px Bold) y letter-spacing -2.5%\n * - Botón \"Agregar\" reutiliza el componente Button del sistema\n * - Soporte completo de dark mode pixel-perfect\n * - Transiciones suaves\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Focus rings adaptativos para light y dark mode\n * - Tokens de color consistentes con Figma\n * - Estados hover y active completos\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4368-31336 - Diseño Figma\n *\n * @example\n * ```tsx\n * // Card de producto normal\n * <POSProductCard\n *   image=\"/images/caprese.jpg\"\n *   productName=\"Ensalada Caprese\"\n *   price=\"$ 40.000\"\n *   onAddClick={() => console.log('Producto agregado')}\n * />\n *\n * // Card de producto activo/seleccionado\n * <POSProductCard\n *   image=\"/images/caprese.jpg\"\n *   productName=\"Ensalada Caprese\"\n *   price=\"$ 40.000\"\n *   active={true}\n * />\n *\n * // Card de producto deshabilitado\n * <POSProductCard\n *   image=\"/images/caprese.jpg\"\n *   productName=\"Ensalada Caprese\"\n *   price=\"$ 40.000\"\n *   disabled={true}\n * />\n * ```\n */\nexport const POSProductCard: React.FC<POSProductCardProps> = ({\n  image,\n  productName,\n  price,\n  buttonText = 'Agregar',\n  active = false,\n  disabled = false,\n  onAddClick,\n  onCardClick,\n  className = '',\n  ariaLabel,\n}) => {\n  // ===== CLASES BASE DEL CARD =====\n  const baseClasses = `\n    flex\n    flex-col\n    gap-2\n    p-3\n    rounded-lg\n    w-[170px]\n    transition-all\n    duration-150\n    focus:outline-hidden\n    focus:ring-2\n    focus:ring-primary-400\n    focus:ring-offset-2\n    dark:focus:ring-dark-border-custom\n    dark:focus:ring-offset-dark-bg-primary\n  `;\n\n  // ===== CLASES DE ESTADO DEL CARD =====\n  // Light: enabled=#ffffff, active=#dbeefe\n  // Dark: enabled=#18181b, active=#112d57\n  const stateClasses = disabled\n    ? `\n      bg-white\n      opacity-55\n      cursor-not-allowed\n      dark:bg-dark-bg-primary\n    `\n    : active\n      ? `\n      bg-primary-100\n      cursor-pointer\n      dark:bg-dark-bg-custom\n    `\n      : `\n      bg-white\n      cursor-pointer\n      dark:bg-dark-bg-primary\n    `;\n\n  // ===== CLASES DE TEXTO SEGÚN ESTADO =====\n  // Light: enabled=#18181b, active=#0e79fd\n  // Dark: enabled=#f4f4f5, active=#93d1fd\n  const textClasses = disabled\n    ? `\n      text-content-primary\n      dark:text-dark-content-primary\n    `\n    : active\n      ? `\n      text-primary-600\n      dark:text-dark-content-custom\n    `\n      : `\n      text-content-primary\n      dark:text-dark-content-primary\n    `;\n\n  // ===== COMBINAR CLASES DEL CARD =====\n  const cardClasses = [baseClasses, stateClasses, className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== HANDLER DEL CLICK EN EL CARD =====\n  const handleCardClick = (event: React.MouseEvent<HTMLDivElement>) => {\n    if (disabled) return;\n    // Solo propagar si no se hizo clic en el botón\n    if ((event.target as HTMLElement).closest('button')) return;\n    onCardClick?.(event);\n  };\n\n  // ===== HANDLER DEL CLICK EN EL BOTÓN =====\n  const handleButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {\n    event.stopPropagation();\n    if (disabled) return;\n    onAddClick?.(event);\n  };\n\n  return (\n    <div\n      className={cardClasses}\n      onClick={handleCardClick}\n      role=\"article\"\n      aria-label={ariaLabel || `${productName} - ${price}`}\n      tabIndex={disabled ? -1 : 0}\n    >\n      {/* Sección de información del producto */}\n      <div className=\"flex flex-col gap-3 w-full\">\n        {/* Imagen del producto */}\n        <div className=\"h-[88px] w-full rounded-lg overflow-hidden\">\n          <img\n            src={image}\n            alt={productName}\n            className=\"w-full h-full object-cover\"\n          />\n        </div>\n\n        {/* Datos del producto (nombre y precio) */}\n        <div className={`flex flex-col w-full font-bold ${textClasses}`.trim().replace(/\\s+/g, ' ')}>\n          {/* Nombre del producto - Label Small (14px) */}\n          <div className=\"text-sm leading-5\">\n            {productName}\n          </div>\n\n          {/* Precio - Heading Small (24px) con letter-spacing -2.5% (tracking-tighter) */}\n          <div className=\"text-2xl leading-8 tracking-tighter\">\n            {price}\n          </div>\n        </div>\n      </div>\n\n      {/* Botón Agregar - Reutiliza el componente Button del sistema */}\n      <Button\n        type=\"default\"\n        size=\"sm\"\n        leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n        onClick={handleButtonClick}\n        disabled={disabled}\n        fullWidth\n        ariaLabel={`${buttonText} ${productName}`}\n      >\n        {buttonText}\n      </Button>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * TrashIcon - Icono de papelera para eliminar items\n * Basado en Heroicons Micro (16x16px)\n */\nexport const TrashIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M5 3.25V4H2.75a.75.75 0 0 0 0 1.5h.3l.815 8.15A1.5 1.5 0 0 0 5.357 15h5.285a1.5 1.5 0 0 0 1.493-1.35l.815-8.15h.3a.75.75 0 0 0 0-1.5H11v-.75A2.25 2.25 0 0 0 8.75 1h-1.5A2.25 2.25 0 0 0 5 3.25Zm2.25-.75a.75.75 0 0 0-.75.75V4h3v-.75a.75.75 0 0 0-.75-.75h-1.5ZM6.05 6a.75.75 0 0 1 .787.713l.275 5.5a.75.75 0 0 1-1.498.075l-.275-5.5A.75.75 0 0 1 6.05 6Zm3.9 0a.75.75 0 0 1 .712.787l-.275 5.5a.75.75 0 0 1-1.498-.075l.275-5.5a.75.75 0 0 1 .786-.711Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n","import React from 'react';\nimport type { POSProductSidebarItemsProps } from './POSProductSidebarItems.types';\nimport { InputNumber } from '../InputNumber/InputNumber';\nimport { TrashIcon } from './icons';\n\n/**\n * POSProductSidebarItems - Componente de item de producto para sidebar POS\n *\n * Componente pixel-perfect basado en Figma (node 4507-28013) para mostrar\n * productos en el sidebar de un sistema POS con soporte completo para dark mode.\n *\n * **Características:**\n * - Badge de categoría con 19 colores configurables\n * - Referencia del producto (text-[10px]/leading-3)\n * - Precio total (text-xs/font-bold)\n * - Nombre del producto (text-xs/font-bold)\n * - Descripción con items opcionales (fondo terciario)\n * - Control de cantidad integrado (Quantity component)\n * - Botón de eliminar con color de error\n *\n * **Especificaciones de Figma:**\n * - Ancho base: 272px\n * - Spacing: gap-1 (4px) entre elementos del producto, gap-2 (8px) entre secciones\n * - Badge: rounded-md (6px), px-1.5, py-1, text-xs/leading-4\n * - Description section: bg-background-tertiary, p-2, rounded-lg\n * - Delete icon: 24x24px, color red-700\n *\n * **Dark Mode:**\n * Los colores se adaptan automáticamente en dark mode:\n * - Textos principales: text-content-primary → dark:text-dark-content-primary\n * - Description background: bg-background-tertiary → dark:bg-zinc-700\n * - Badge colores: Mantienen contraste en ambos modos\n * - Delete button: text-red-700 → dark:text-red-500\n *\n * **Orden de modificadores:** {responsive}:{dark}:{state}:{utility}\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see https://www.figma.com/design/5XNqf2YTxvwemxwo1LMQ6j/Siesa-UI-Kit?node-id=4507-28013 - Diseño Figma\n *\n * @example\n * ```tsx\n * <POSProductSidebarItems\n *   categoryLabel=\"Entradas\"\n *   productRef=\"00147258369\"\n *   price=\"$ 40,000.00\"\n *   productName=\"Nombre producto\"\n *   descriptionItems={[\n *     { description: \"Papas limón mediana\", price: \"$ 40,000.00\" },\n *     { description: \"Papas limón mediana\", price: \"$ 40,000.00\" },\n *   ]}\n *   quantity={0}\n *   onQuantityChange={(qty) => console.log(qty)}\n *   onDelete={() => console.log('Eliminar')}\n * />\n * ```\n */\nexport const POSProductSidebarItems: React.FC<POSProductSidebarItemsProps> = ({\n  categoryLabel,\n  categoryColor = 'lime',\n  productRef,\n  price,\n  productName,\n  descriptionItems = [],\n  showDescription = true,\n  quantity = 0,\n  minQuantity = 0,\n  maxQuantity,\n  onQuantityChange,\n  onDelete,\n  disabled = false,\n  className = '',\n  deleteIcon,\n}) => {\n  // ===== MAPA DE COLORES PARA BADGES =====\n  // Basado en Figma node 4507-28432: bg lime-100 (#ecfccb) y text lime-700 (#4d7c0f)\n  // Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n  const categoryColorClasses: Record<string, { bg: string; text: string }> = {\n    lime: {\n      bg: 'bg-lime-100 dark:bg-lime-900/40',\n      text: 'text-lime-700 dark:text-lime-300'\n    },\n    red: {\n      bg: 'bg-red-100 dark:bg-red-900/40',\n      text: 'text-red-700 dark:text-red-300'\n    },\n    orange: {\n      bg: 'bg-orange-100 dark:bg-orange-900/40',\n      text: 'text-orange-700 dark:text-orange-300'\n    },\n    amber: {\n      bg: 'bg-amber-100 dark:bg-amber-900/40',\n      text: 'text-amber-700 dark:text-amber-300'\n    },\n    yellow: {\n      bg: 'bg-yellow-100 dark:bg-yellow-900/40',\n      text: 'text-yellow-700 dark:text-yellow-300'\n    },\n    green: {\n      bg: 'bg-green-100 dark:bg-green-900/40',\n      text: 'text-green-700 dark:text-green-300'\n    },\n    emerald: {\n      bg: 'bg-emerald-100 dark:bg-emerald-900/40',\n      text: 'text-emerald-700 dark:text-emerald-300'\n    },\n    teal: {\n      bg: 'bg-teal-100 dark:bg-teal-900/40',\n      text: 'text-teal-700 dark:text-teal-300'\n    },\n    cyan: {\n      bg: 'bg-cyan-100 dark:bg-cyan-900/40',\n      text: 'text-cyan-700 dark:text-cyan-300'\n    },\n    sky: {\n      bg: 'bg-sky-100 dark:bg-sky-900/40',\n      text: 'text-sky-700 dark:text-sky-300'\n    },\n    blue: {\n      bg: 'bg-blue-100 dark:bg-blue-900/40',\n      text: 'text-blue-700 dark:text-blue-300'\n    },\n    indigo: {\n      bg: 'bg-indigo-100 dark:bg-indigo-900/40',\n      text: 'text-indigo-700 dark:text-indigo-300'\n    },\n    violet: {\n      bg: 'bg-violet-100 dark:bg-violet-900/40',\n      text: 'text-violet-700 dark:text-violet-300'\n    },\n    purple: {\n      bg: 'bg-purple-100 dark:bg-purple-900/40',\n      text: 'text-purple-700 dark:text-purple-300'\n    },\n    fuchsia: {\n      bg: 'bg-fuchsia-100 dark:bg-fuchsia-900/40',\n      text: 'text-fuchsia-700 dark:text-fuchsia-300'\n    },\n    pink: {\n      bg: 'bg-pink-100 dark:bg-pink-900/40',\n      text: 'text-pink-700 dark:text-pink-300'\n    },\n    rose: {\n      bg: 'bg-rose-100 dark:bg-rose-900/40',\n      text: 'text-rose-700 dark:text-rose-300'\n    },\n    zinc: {\n      bg: 'bg-zinc-100 dark:bg-zinc-800/50',\n      text: 'text-zinc-600 dark:text-zinc-300'\n    },\n    primary: {\n      bg: 'bg-primary-100 dark:bg-primary-600/30',\n      text: 'text-primary-600 dark:text-primary-300'\n    },\n  };\n\n  const colors = categoryColorClasses[categoryColor] || categoryColorClasses.lime;\n\n  // Handler para cambio de cantidad\n  const handleQuantityChange = (newQuantity: number) => {\n    if (!disabled && onQuantityChange) {\n      onQuantityChange(newQuantity);\n    }\n  };\n\n  // Handler para eliminar\n  const handleDelete = () => {\n    if (!disabled && onDelete) {\n      onDelete();\n    }\n  };\n\n  return (\n    <div\n      className={`\n        flex\n        flex-col\n        gap-2\n        w-full\n        ${disabled ? 'opacity-50 pointer-events-none' : ''}\n        ${className}\n      `.trim().replace(/\\s+/g, ' ')}\n      data-component=\"POSProductSidebarItems\"\n    >\n      {/* ===== BODY SECTION ===== */}\n      <div className=\"flex flex-col gap-2 w-full\">\n        {/* ===== PRODUCT INFO ===== */}\n        <div className=\"flex flex-col gap-1 w-full\">\n          {/* Row: Badge + Ref + Price - Figma node 4507:28398 */}\n          <div className=\"flex items-center gap-1 w-full\">\n            {/* Col: Badge + Ref - Figma node 4507:28399 */}\n            <div className=\"flex items-center gap-2 flex-1 min-w-0\">\n              {/* Category Badge - Figma node 4507:28432 */}\n              <div\n                className={`\n                  inline-flex\n                  items-center\n                  px-1.5\n                  py-1\n                  rounded-md\n                  transition-colors\n                  duration-150\n                  ${colors.bg}\n                `.trim().replace(/\\s+/g, ' ')}\n              >\n                <span\n                  className={`\n                    text-xs\n                    leading-4\n                    font-normal\n                    text-center\n                    whitespace-nowrap\n                    ${colors.text}\n                  `.trim().replace(/\\s+/g, ' ')}\n                >\n                  {categoryLabel}\n                </span>\n              </div>\n\n              {/* Product Reference - Figma node 4507:28401 - Paragraph/XXSmall 10px */}\n              <span className=\"text-[10px] leading-3 font-normal text-content-primary dark:text-dark-content-primary whitespace-nowrap\">\n                {productRef}\n              </span>\n            </div>\n\n            {/* Col: Price - Figma node 4507:28450 - Label/Tiny 12px Bold */}\n            <div className=\"flex items-center shrink-0\">\n              <span className=\"text-xs leading-4 font-bold text-content-primary dark:text-dark-content-primary whitespace-nowrap text-right\">\n                {price}\n              </span>\n            </div>\n          </div>\n\n          {/* Row: Product Name - Figma node 4507:28404 - Label/Tiny 12px Bold */}\n          <div className=\"flex items-start w-full\">\n            <span className=\"text-xs leading-4 font-bold text-content-primary dark:text-dark-content-primary flex-1 min-w-0\">\n              {productName}\n            </span>\n          </div>\n        </div>\n\n        {/* ===== DESCRIPTION SECTION ===== */}\n        {/* Figma node 4507:28405 - Background tertiary con items de descripción */}\n        {showDescription && descriptionItems.length > 0 && (\n          <div\n            className={`\n              flex\n              flex-col\n              gap-2\n              p-2\n              rounded-lg\n              bg-background-secondary\n              dark:bg-zinc-700\n              w-full\n              transition-colors\n              duration-150\n            `.trim().replace(/\\s+/g, ' ')}\n          >\n            {descriptionItems.map((item, index) => (\n              <div\n                key={index}\n                className=\"flex items-center gap-1 w-full\"\n              >\n                {/* Description text - Figma Body/Small 12px Regular */}\n                <span className=\"flex-1 min-w-0 text-xs leading-3 font-normal text-content-primary dark:text-dark-content-primary\">\n                  {item.description}\n                </span>\n                {/* Price - Figma Body/Small Bold 12px */}\n                <span className=\"text-xs leading-3 font-bold text-content-primary dark:text-dark-content-primary whitespace-nowrap text-right shrink-0\">\n                  {item.price}\n                </span>\n              </div>\n            ))}\n          </div>\n        )}\n      </div>\n\n      {/* ===== ACTIONS SECTION ===== */}\n      {/* Figma node 4507:28412 - Quantity control + Delete button */}\n      <div className=\"flex items-center justify-between w-full\">\n        {/* Quantity Control - Figma width: 118px */}\n        <div className=\"w-[118px]\">\n          <InputNumber\n            value={quantity}\n            min={minQuantity}\n            max={maxQuantity}\n            onChange={(e) => handleQuantityChange(Number(e.target.value))}\n            disabled={disabled}\n          />\n        </div>\n\n        {/* Delete Button - Figma node 4514:28258 - 24x24px, color red-700 (#b91c1c) */}\n        <button\n          type=\"button\"\n          onClick={handleDelete}\n          disabled={disabled}\n          className={`\n            flex\n            items-center\n            justify-center\n            w-6\n            h-6\n            rounded-md\n            text-red-700\n            dark:text-red-500\n            hover:text-red-800\n            dark:hover:text-red-400\n            hover:bg-red-50\n            dark:hover:bg-red-900/20\n            focus:outline-hidden\n            focus:ring-2\n            focus:ring-red-500/50\n            dark:focus:ring-red-400/50\n            focus:ring-offset-1\n            focus:ring-offset-white\n            dark:focus:ring-offset-dark-bg-primary\n            active:scale-95\n            transition-all\n            duration-150\n            ${disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}\n          `.trim().replace(/\\s+/g, ' ')}\n          aria-label=\"Eliminar producto\"\n        >\n          {deleteIcon || <TrashIcon className=\"w-[18px] h-[21px]\" />}\n        </button>\n      </div>\n    </div>\n  );\n};\n\nPOSProductSidebarItems.displayName = 'POSProductSidebarItems';\n","import React from 'react';\nimport type { POSTableProps } from './POSTable.types';\n\n/**\n * POSTable - Sistema de visualización de mesas de restaurante\n *\n * Componente para mostrar mesas de restaurante con diferentes estados\n * (disponible, ocupada, reservada) y configuraciones de sillas según diseño de Figma.\n *\n * ⚠️ IMPORTANTE - COLORES PERSONALIZADOS DEL CLIENTE:\n * Este componente usa colores específicos hardcodeados según el diseño del cliente.\n * Estos NO son tokens del sistema de diseño general, sino colores únicos para POSTable.\n * Esta es una EXCEPCIÓN JUSTIFICADA similar a los iconos personalizados de POSTable.\n *\n * ESPECIFICACIONES PIXEL-PERFECT DE FIGMA:\n *\n * Colores exactos (ESPECÍFICOS DEL CLIENTE):\n *\n * LIGHT MODE:\n * - Available (Azul): #0e79fd (border, mesa, silla, texto) - Azul primario del sistema\n * - Available Active: Bg #dbeefe + Border #bce4ff (cuando isActive=true)\n * - Busy (Naranja): #af460e (border, mesa, silla, texto)\n * - Busy Active: Bg #fed7aa + Border #fed7aa (cuando isActive=true)\n * - Reserved (Púrpura): #7e22ce (border, mesa, silla, texto)\n * - Reserved Active: Bg #e9d5ff + Border #e9d5ff (cuando isActive=true)\n *\n * DARK MODE (colores más brillantes para mejor visibilidad):\n * - Available (Azul claro): #93d1fd (border, mesa, silla, texto)\n * - Available Active: Bg #1e3a5f + Border #1e3a5f (cuando isActive=true)\n * - Busy (Naranja/Amarillo): #f5a927 (border, mesa, silla, texto)\n * - Busy Active: Bg #5c3a1e + Border #5c3a1e (cuando isActive=true)\n * - Reserved (Púrpura claro): #c084fc (border, mesa, silla, texto)\n * - Reserved Active: Bg #3b1f5c + Border #3b1f5c (cuando isActive=true)\n *\n * - Texto del label: Mismo color del estado (está FUERA de la mesa según Figma)\n *\n * Dimensiones exactas:\n * - Container: 160x160px, border-radius: 8px, border: 2px\n * - Inner container: 134x134px, gap: 4px\n * - Mesa Square: 64x64px, border-radius: 4px\n * - Mesa Circle: 64x64px, border-radius: 9999px\n * - Mesa Rectangle: 80x64px, border-radius: 4px\n * - Mesa Oval: 80x64px, border-radius: 24px\n * - Silla: 28x22px, border-radius: 4px\n * - Silla Respaldo (top): 28x16px (72.73% height)\n * - Silla Asiento (bottom): 24x14px (85.71% width, 63.64% height)\n * - Gap: 4px entre todos los elementos\n *\n * Tipografía:\n * - Label: 10px / 12px line-height, weight: 400, font: Inter\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Focus rings adaptativos para light y dark mode\n * - Valores exactos de Figma con notación [px]\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n *\n * @example\n * ```tsx\n * <POSTable\n *   tableNumber=\"12\"\n *   status=\"available\"\n *   shape=\"square\"\n *   chairs={4}\n *   onClick={() => console.log('Mesa seleccionada')}\n * />\n * ```\n */\nexport const POSTable: React.FC<POSTableProps> = ({\n  tableNumber,\n  status = 'available',\n  shape = 'square',\n  chairs = 4,\n  showChairs = true,\n  isActive = false,\n  onClick,\n  className = '',\n  disabled = false,\n  children,\n}) => {\n  // ===== COLORES POR ESTADO (VALORES EXACTOS DE FIGMA) =====\n  // ⚠️ NOTA: Estos colores son ESPECÍFICOS del cliente (excepción justificada)\n  // NO son tokens del sistema general de diseño\n  // Light Mode: #0e79fd (azul primario), #af460e (naranja), #7e22ce (púrpura)\n  // Dark Mode:  #93d1fd (azul claro), #f5a927 (naranja/amarillo), #c084fc (púrpura claro)\n  const statusColors = {\n    available: {\n      // Enabled state - Light: #0e79fd (azul primario del sistema), Dark: #93d1fd\n      border: 'border-[#0e79fd]',\n      borderDark: 'dark:border-[#93d1fd]',\n      bgEnabled: 'bg-transparent',\n      bgEnabledDark: 'dark:bg-transparent',\n      // Actived state - Light: Bg #dbeefe + Border #bce4ff según Figma\n      bgActive: 'bg-primary-100',\n      bgActiveDark: 'dark:bg-[#1e3a5f]',\n      borderActive: 'border-[#bce4ff]',\n      borderActiveDark: 'dark:border-[#1e3a5f]',\n      // Table and chairs - Light: #0e79fd, Dark: #93d1fd\n      table: 'bg-[#0e79fd]',\n      tableDark: 'dark:bg-[#93d1fd]',\n      chair: 'bg-[#0e79fd]',\n      chairDark: 'dark:bg-[#93d1fd]',\n      // Text (mismo color del estado - label está FUERA de la mesa según Figma)\n      text: 'text-[#0e79fd]',\n      textDark: 'dark:text-[#93d1fd]',\n      // Focus ring\n      focusRing: 'focus:ring-[#93d1fd]',\n      focusRingDark: 'dark:focus:ring-[#0e79fd]',\n    },\n    busy: {\n      // Enabled state - Light: #af460e, Dark: #f5a927\n      border: 'border-[#af460e]',\n      borderDark: 'dark:border-[#f5a927]',\n      bgEnabled: 'bg-transparent',\n      bgEnabledDark: 'dark:bg-transparent',\n      // Actived state\n      bgActive: 'bg-[#fed7aa]',\n      bgActiveDark: 'dark:bg-[#5c3a1e]',\n      borderActive: 'border-[#fed7aa]',\n      borderActiveDark: 'dark:border-[#5c3a1e]',\n      // Table and chairs - Light: #af460e, Dark: #f5a927\n      table: 'bg-[#af460e]',\n      tableDark: 'dark:bg-[#f5a927]',\n      chair: 'bg-[#af460e]',\n      chairDark: 'dark:bg-[#f5a927]',\n      // Text (mismo color del estado - label está FUERA de la mesa según Figma)\n      text: 'text-[#af460e]',\n      textDark: 'dark:text-[#f5a927]',\n      // Focus ring\n      focusRing: 'focus:ring-[#f5a927]',\n      focusRingDark: 'dark:focus:ring-[#af460e]',\n    },\n    reserved: {\n      // Enabled state - Light: #7e22ce, Dark: #c084fc\n      border: 'border-[#7e22ce]',\n      borderDark: 'dark:border-[#c084fc]',\n      bgEnabled: 'bg-transparent',\n      bgEnabledDark: 'dark:bg-transparent',\n      // Actived state\n      bgActive: 'bg-[#e9d5ff]',\n      bgActiveDark: 'dark:bg-[#3b1f5c]',\n      borderActive: 'border-[#e9d5ff]',\n      borderActiveDark: 'dark:border-[#3b1f5c]',\n      // Table and chairs - Light: #7e22ce, Dark: #c084fc\n      table: 'bg-[#7e22ce]',\n      tableDark: 'dark:bg-[#c084fc]',\n      chair: 'bg-[#7e22ce]',\n      chairDark: 'dark:bg-[#c084fc]',\n      // Text (mismo color del estado - label está FUERA de la mesa según Figma)\n      text: 'text-[#7e22ce]',\n      textDark: 'dark:text-[#c084fc]',\n      // Focus ring\n      focusRing: 'focus:ring-[#c084fc]',\n      focusRingDark: 'dark:focus:ring-[#7e22ce]',\n    },\n  };\n\n  // ===== CLASES DE FORMA (ESPECIFICACIONES EXACTAS DE FIGMA) =====\n  const shapeClasses = {\n    square: {\n      container: 'rounded-[4px]',\n      table: 'w-[64px] h-[64px] rounded-[4px]',\n    },\n    circle: {\n      container: 'rounded-[9999px]',\n      table: 'w-[64px] h-[64px] rounded-[9999px]',\n    },\n    rectangle: {\n      container: 'rounded-[4px]',\n      table: 'w-[80px] h-[64px] rounded-[4px]',\n    },\n    oval: {\n      container: 'rounded-3xl',\n      table: 'w-[80px] h-[64px] rounded-3xl',\n    },\n  };\n\n  // ===== COMPONENTE SILLA (ESPECIFICACIONES EXACTAS DE FIGMA) =====\n  const Chair: React.FC<{ rotation: number }> = ({ rotation }) => (\n    <div\n      className=\"w-[28px] h-[22px]\"\n      style={{ transform: `rotate(${rotation}deg)` }}\n      aria-hidden=\"true\"\n    >\n      {/* Respaldo (parte superior) - 72.73% height */}\n      <div\n        className={`\n          absolute\n          top-0\n          left-0\n          right-0\n          h-[16px]\n          rounded-t-[4px]\n          ${statusColors[status].chair}\n          ${statusColors[status].chairDark}\n        `}\n      />\n      {/* Asiento (parte inferior) - 85.71% width, 63.64% height */}\n      <div\n        className={`\n          absolute\n          bottom-0\n          left-[7.14%]\n          right-[7.14%]\n          h-[14px]\n          rounded-b-[4px]\n          ${statusColors[status].chair}\n          ${statusColors[status].chairDark}\n        `}\n      />\n    </div>\n  );\n\n  // ===== HANDLER DE CLICK =====\n  const handleClick = () => {\n    if (!disabled && onClick) {\n      onClick();\n    }\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {\n    if ((e.key === 'Enter' || e.key === ' ') && !disabled && onClick) {\n      e.preventDefault();\n      onClick();\n    }\n  };\n\n  // ===== CLASES DEL CONTAINER (160x160px según Figma) =====\n  const containerClasses = [\n    // Dimensiones exactas del container\n    'w-[160px]',\n    'h-[160px]',\n    'shrink-0',\n\n    // Estructura\n    'relative',\n    'flex',\n    'flex-col',\n    'items-center',\n    'justify-center',\n    'p-0',\n\n    // Borde (2px según Figma)\n    'border-2',\n    'box-border',\n\n    // Border radius (8px según Figma)\n    'rounded-[8px]',\n\n    // Colores del borde y fondo según estado\n    isActive ? statusColors[status].borderActive : statusColors[status].border,\n    isActive ? statusColors[status].borderActiveDark : statusColors[status].borderDark,\n    isActive ? statusColors[status].bgActive : statusColors[status].bgEnabled,\n    isActive ? statusColors[status].bgActiveDark : statusColors[status].bgEnabledDark,\n\n    // Focus rings adaptativos (siguiendo patrón de Button)\n    'focus:outline-hidden',\n    'focus:ring-2',\n    statusColors[status].focusRing,\n    statusColors[status].focusRingDark,\n    'focus:ring-offset-2',\n    'dark:focus:ring-offset-dark-bg-primary',\n\n    // Transiciones\n    'transition-all',\n    'duration-150',\n\n    // Interactividad\n    onClick && !disabled ? 'cursor-pointer' : '',\n    onClick && !disabled ? 'hover:scale-105' : '',\n    onClick && !disabled ? 'active:scale-95' : '',\n    disabled ? 'opacity-50 cursor-not-allowed' : '',\n\n    // Clases adicionales\n    className,\n  ]\n    .filter(Boolean)\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== RENDER =====\n  return (\n    <button\n      className={containerClasses}\n      onClick={handleClick}\n      onKeyDown={handleKeyDown}\n      disabled={disabled}\n      type=\"button\"\n      aria-label={`Mesa ${tableNumber} - ${\n        status === 'available' ? 'Disponible' : status === 'busy' ? 'Ocupada' : 'Reservada'\n      }`}\n    >\n      {/* INNER CONTAINER (134x134px según Figma) */}\n      <div className=\"flex flex-col gap-[4px] items-center justify-center w-[134px] h-[134px] shrink-0\">\n        {/* FILA DE SILLAS SUPERIORES */}\n        {showChairs && (chairs === 2 || chairs === 4 || chairs === 6 || chairs === 8) && (\n          <div className=\"flex gap-[4px] items-center justify-center shrink-0\">\n            {chairs >= 6 && (\n              <>\n                <Chair rotation={0} />\n                <Chair rotation={0} />\n              </>\n            )}\n            {chairs === 2 && <Chair rotation={0} />}\n            {chairs === 4 && <Chair rotation={0} />}\n          </div>\n        )}\n\n        {/* FILA CENTRAL CON MESA Y SILLAS LATERALES */}\n        <div className=\"flex gap-[4px] items-center justify-center shrink-0\">\n          {/* COLUMNA IZQUIERDA - SILLAS */}\n          {showChairs && (chairs === 4 || chairs === 6 || chairs === 8) && (\n            <div className=\"flex flex-col gap-[4px] items-start justify-center shrink-0\">\n              {chairs >= 8 && (\n                <>\n                  <Chair rotation={270} />\n                  <Chair rotation={270} />\n                </>\n              )}\n              {(chairs === 4 || chairs === 6) && <Chair rotation={270} />}\n            </div>\n          )}\n\n          {/* MESA (sin label - el label va fuera según Figma) */}\n          <div className=\"flex flex-col gap-[4px] items-start justify-center shrink-0\">\n            <div className=\"flex items-center shrink-0\">\n              <div\n                className={`\n                  ${shapeClasses[shape].table}\n                  ${statusColors[status].table}\n                  ${statusColors[status].tableDark}\n                  shrink-0\n                `}\n              />\n            </div>\n          </div>\n\n          {/* COLUMNA DERECHA - SILLAS */}\n          {showChairs && (chairs === 4 || chairs === 6 || chairs === 8) && (\n            <div className=\"flex flex-col gap-[4px] items-start justify-center shrink-0\">\n              {chairs >= 8 && (\n                <>\n                  <Chair rotation={90} />\n                  <Chair rotation={90} />\n                </>\n              )}\n              {(chairs === 4 || chairs === 6) && <Chair rotation={90} />}\n            </div>\n          )}\n        </div>\n\n        {/* FILA DE SILLAS INFERIORES */}\n        {showChairs && (chairs === 2 || chairs === 4 || chairs === 6 || chairs === 8) && (\n          <div className=\"flex gap-[4px] items-center justify-center shrink-0\">\n            {chairs >= 6 && (\n              <>\n                <Chair rotation={180} />\n                <Chair rotation={180} />\n              </>\n            )}\n            {chairs === 2 && <Chair rotation={180} />}\n            {chairs === 4 && <Chair rotation={180} />}\n          </div>\n        )}\n      </div>\n\n      {/* LABEL DE NÚMERO DE MESA - Debajo del conjunto mesa+sillas según Figma */}\n      <div\n        className={`\n          flex\n          flex-col\n          justify-center\n          leading-0\n          not-italic\n          text-ellipsis\n          overflow-hidden\n          min-w-full\n          text-center\n          whitespace-nowrap\n          shrink-0\n          text-[10px]\n          font-normal\n          ${statusColors[status].text}\n          ${statusColors[status].textDark}\n        `}\n      >\n        <p className=\"leading-[12px] text-ellipsis overflow-hidden\">\n          Mesa {tableNumber}\n        </p>\n        {children}\n      </div>\n    </button>\n  );\n};\n","import { useState, useEffect } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport type { AuditHistoryItem, AuditHistoryProps, AuditHistoryResponse } from '../types/audit.types';\n\nexport interface UseAuditHistoryProps {\n  fetchFn: AuditHistoryProps['fetchFn'];\n  entityId: string;\n  pageSize?: number;\n}\n\nexport interface UseAuditHistoryResult {\n  data: AuditHistoryResponse | undefined;\n  isLoading: boolean;\n  isError: boolean;\n  page: number;\n  setPage: (page: number) => void;\n  selectedEntryId: string | null;\n  setSelectedEntryId: (id: string | null) => void;\n  selectedEntry: AuditHistoryItem | undefined;\n}\n\nexport function useAuditHistory({\n  fetchFn,\n  entityId,\n  pageSize = 20,\n}: UseAuditHistoryProps): UseAuditHistoryResult {\n  const [page, setPageState] = useState(1);\n  const [selectedEntryId, setSelectedEntryId] = useState<string | null>(null);\n\n  const { data, isLoading, isError } = useQuery({\n    queryKey: ['audit-history', entityId, page, pageSize],\n    queryFn: () => fetchFn(entityId, { page, pageSize }),\n    enabled: !!entityId,\n    staleTime: 30_000,\n    gcTime: 60_000,\n    refetchOnWindowFocus: false,\n  });\n\n  // Auto-selecciona la primera entrada cuando llegan nuevos datos\n  useEffect(() => {\n    if (data?.items && data.items.length > 0) {\n      setSelectedEntryId(data.items[0].id);\n    } else {\n      setSelectedEntryId(null);\n    }\n  }, [data]);\n\n  const setPage = (newPage: number) => {\n    setSelectedEntryId(null);\n    setPageState(newPage);\n  };\n\n  const selectedEntry = data?.items.find((item) => item.id === selectedEntryId);\n\n  return {\n    data,\n    isLoading,\n    isError,\n    page,\n    setPage,\n    selectedEntryId,\n    setSelectedEntryId,\n    selectedEntry,\n  };\n}\n","'use client';\nimport React from 'react';\n\n/**\n * @internal\n */\nconst SkeletonThemeContext = React.createContext({});\n\n/* eslint-disable react/no-array-index-key */\nconst defaultEnableAnimation = true;\n// For performance & cleanliness, don't add any inline styles unless we have to\nfunction styleOptionsToCssProperties({ baseColor, highlightColor, width, height, borderRadius, circle, direction, duration, enableAnimation = defaultEnableAnimation, customHighlightBackground, }) {\n    const style = {};\n    if (direction === 'rtl')\n        style['--animation-direction'] = 'reverse';\n    if (typeof duration === 'number')\n        style['--animation-duration'] = `${duration}s`;\n    if (!enableAnimation)\n        style['--pseudo-element-display'] = 'none';\n    if (typeof width === 'string' || typeof width === 'number')\n        style.width = width;\n    if (typeof height === 'string' || typeof height === 'number')\n        style.height = height;\n    if (typeof borderRadius === 'string' || typeof borderRadius === 'number')\n        style.borderRadius = borderRadius;\n    if (circle)\n        style.borderRadius = '50%';\n    if (typeof baseColor !== 'undefined')\n        style['--base-color'] = baseColor;\n    if (typeof highlightColor !== 'undefined')\n        style['--highlight-color'] = highlightColor;\n    if (typeof customHighlightBackground === 'string')\n        style['--custom-highlight-background'] = customHighlightBackground;\n    return style;\n}\nfunction Skeleton({ count = 1, wrapper: Wrapper, className: customClassName, containerClassName, containerTestId, circle = false, style: styleProp, ...originalPropsStyleOptions }) {\n    var _a, _b, _c;\n    const contextStyleOptions = React.useContext(SkeletonThemeContext);\n    const propsStyleOptions = { ...originalPropsStyleOptions };\n    // DO NOT overwrite style options from the context if `propsStyleOptions`\n    // has properties explicity set to undefined\n    for (const [key, value] of Object.entries(originalPropsStyleOptions)) {\n        if (typeof value === 'undefined') {\n            delete propsStyleOptions[key];\n        }\n    }\n    // Props take priority over context\n    const styleOptions = {\n        ...contextStyleOptions,\n        ...propsStyleOptions,\n        circle,\n    };\n    // `styleProp` has the least priority out of everything\n    const style = {\n        ...styleProp,\n        ...styleOptionsToCssProperties(styleOptions),\n    };\n    let className = 'react-loading-skeleton';\n    if (customClassName)\n        className += ` ${customClassName}`;\n    const inline = (_a = styleOptions.inline) !== null && _a !== void 0 ? _a : false;\n    const elements = [];\n    const countCeil = Math.ceil(count);\n    for (let i = 0; i < countCeil; i++) {\n        let thisStyle = style;\n        if (countCeil > count && i === countCeil - 1) {\n            // count is not an integer and we've reached the last iteration of\n            // the loop, so add a \"fractional\" skeleton.\n            //\n            // For example, if count is 3.5, we've already added 3 full\n            // skeletons, so now we add one more skeleton that is 0.5 times the\n            // original width.\n            const width = (_b = thisStyle.width) !== null && _b !== void 0 ? _b : '100%'; // 100% is the default since that's what's in the CSS\n            const fractionalPart = count % 1;\n            const fractionalWidth = typeof width === 'number'\n                ? width * fractionalPart\n                : `calc(${width} * ${fractionalPart})`;\n            thisStyle = { ...thisStyle, width: fractionalWidth };\n        }\n        const skeletonSpan = (React.createElement(\"span\", { className: className, style: thisStyle, key: i }, \"\\u200C\"));\n        if (inline) {\n            elements.push(skeletonSpan);\n        }\n        else {\n            // Without the <br />, the skeleton lines will all run together if\n            // `width` is specified\n            elements.push(React.createElement(React.Fragment, { key: i },\n                skeletonSpan,\n                React.createElement(\"br\", null)));\n        }\n    }\n    return (React.createElement(\"span\", { className: containerClassName, \"data-testid\": containerTestId, \"aria-live\": \"polite\", \"aria-busy\": (_c = styleOptions.enableAnimation) !== null && _c !== void 0 ? _c : defaultEnableAnimation }, Wrapper\n        ? elements.map((el, i) => React.createElement(Wrapper, { key: i }, el))\n        : elements));\n}\n\nfunction SkeletonTheme({ children, ...styleOptions }) {\n    return (React.createElement(SkeletonThemeContext.Provider, { value: styleOptions }, children));\n}\n\nexport { SkeletonTheme, Skeleton as default };\n","/**\n * @module constants\n * @summary Useful constants\n * @description\n * Collection of useful date constants.\n *\n * The constants could be imported from `date-fns/constants`:\n *\n * ```ts\n * import { maxTime, minTime } from \"./constants/date-fns/constants\";\n *\n * function isAllowedTime(time) {\n *   return time <= maxTime && time >= minTime;\n * }\n * ```\n */\n\n/**\n * @constant\n * @name daysInWeek\n * @summary Days in 1 week.\n */\nexport const daysInWeek = 7;\n\n/**\n * @constant\n * @name daysInYear\n * @summary Days in 1 year.\n *\n * @description\n * How many days in a year.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n */\nexport const daysInYear = 365.2425;\n\n/**\n * @constant\n * @name maxTime\n * @summary Maximum allowed time.\n *\n * @example\n * import { maxTime } from \"./constants/date-fns/constants\";\n *\n * const isValid = 8640000000000001 <= maxTime;\n * //=> false\n *\n * new Date(8640000000000001);\n * //=> Invalid Date\n */\nexport const maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000;\n\n/**\n * @constant\n * @name minTime\n * @summary Minimum allowed time.\n *\n * @example\n * import { minTime } from \"./constants/date-fns/constants\";\n *\n * const isValid = -8640000000000001 >= minTime;\n * //=> false\n *\n * new Date(-8640000000000001)\n * //=> Invalid Date\n */\nexport const minTime = -maxTime;\n\n/**\n * @constant\n * @name millisecondsInWeek\n * @summary Milliseconds in 1 week.\n */\nexport const millisecondsInWeek = 604800000;\n\n/**\n * @constant\n * @name millisecondsInDay\n * @summary Milliseconds in 1 day.\n */\nexport const millisecondsInDay = 86400000;\n\n/**\n * @constant\n * @name millisecondsInMinute\n * @summary Milliseconds in 1 minute\n */\nexport const millisecondsInMinute = 60000;\n\n/**\n * @constant\n * @name millisecondsInHour\n * @summary Milliseconds in 1 hour\n */\nexport const millisecondsInHour = 3600000;\n\n/**\n * @constant\n * @name millisecondsInSecond\n * @summary Milliseconds in 1 second\n */\nexport const millisecondsInSecond = 1000;\n\n/**\n * @constant\n * @name minutesInYear\n * @summary Minutes in 1 year.\n */\nexport const minutesInYear = 525600;\n\n/**\n * @constant\n * @name minutesInMonth\n * @summary Minutes in 1 month.\n */\nexport const minutesInMonth = 43200;\n\n/**\n * @constant\n * @name minutesInDay\n * @summary Minutes in 1 day.\n */\nexport const minutesInDay = 1440;\n\n/**\n * @constant\n * @name minutesInHour\n * @summary Minutes in 1 hour.\n */\nexport const minutesInHour = 60;\n\n/**\n * @constant\n * @name monthsInQuarter\n * @summary Months in 1 quarter.\n */\nexport const monthsInQuarter = 3;\n\n/**\n * @constant\n * @name monthsInYear\n * @summary Months in 1 year.\n */\nexport const monthsInYear = 12;\n\n/**\n * @constant\n * @name quartersInYear\n * @summary Quarters in 1 year\n */\nexport const quartersInYear = 4;\n\n/**\n * @constant\n * @name secondsInHour\n * @summary Seconds in 1 hour.\n */\nexport const secondsInHour = 3600;\n\n/**\n * @constant\n * @name secondsInMinute\n * @summary Seconds in 1 minute.\n */\nexport const secondsInMinute = 60;\n\n/**\n * @constant\n * @name secondsInDay\n * @summary Seconds in 1 day.\n */\nexport const secondsInDay = secondsInHour * 24;\n\n/**\n * @constant\n * @name secondsInWeek\n * @summary Seconds in 1 week.\n */\nexport const secondsInWeek = secondsInDay * 7;\n\n/**\n * @constant\n * @name secondsInYear\n * @summary Seconds in 1 year.\n */\nexport const secondsInYear = secondsInDay * daysInYear;\n\n/**\n * @constant\n * @name secondsInMonth\n * @summary Seconds in 1 month\n */\nexport const secondsInMonth = secondsInYear / 12;\n\n/**\n * @constant\n * @name secondsInQuarter\n * @summary Seconds in 1 quarter.\n */\nexport const secondsInQuarter = secondsInMonth * 3;\n\n/**\n * @constant\n * @name constructFromSymbol\n * @summary Symbol enabling Date extensions to inherit properties from the reference date.\n *\n * The symbol is used to enable the `constructFrom` function to construct a date\n * using a reference date and a value. It allows to transfer extra properties\n * from the reference date to the new date. It's useful for extensions like\n * [`TZDate`](https://github.com/date-fns/tz) that accept a time zone as\n * a constructor argument.\n */\nexport const constructFromSymbol = Symbol.for(\"constructDateFrom\");\n","import { constructFromSymbol } from \"./constants.js\";\n\n/**\n * @name constructFrom\n * @category Generic Helpers\n * @summary Constructs a date using the reference date and the value\n *\n * @description\n * The function constructs a new date using the constructor from the reference\n * date and the given value. It helps to build generic functions that accept\n * date extensions.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * Starting from v3.7.0, it allows to construct a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The reference date to take constructor from\n * @param value - The value to create the date\n *\n * @returns Date initialized using the given date and value\n *\n * @example\n * import { constructFrom } from \"./constructFrom/date-fns\";\n *\n * // A function that clones a date preserving the original type\n * function cloneDate<DateType extends Date>(date: DateType): DateType {\n *   return constructFrom(\n *     date, // Use constructor from the given date\n *     date.getTime() // Use the date value to create a new date\n *   );\n * }\n */\nexport function constructFrom(date, value) {\n  if (typeof date === \"function\") return date(value);\n\n  if (date && typeof date === \"object\" && constructFromSymbol in date)\n    return date[constructFromSymbol](value);\n\n  if (date instanceof Date) return new date.constructor(value);\n\n  return new Date(value);\n}\n\n// Fallback for modularized imports:\nexport default constructFrom;\n","import { constructFrom } from \"./constructFrom.js\";\n\n/**\n * @name toDate\n * @category Common Helpers\n * @summary Convert the given argument to an instance of Date.\n *\n * @description\n * Convert the given argument to an instance of Date.\n *\n * If the argument is an instance of Date, the function returns its clone.\n *\n * If the argument is a number, it is treated as a timestamp.\n *\n * If the argument is none of the above, the function returns Invalid Date.\n *\n * Starting from v3.7.0, it clones a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Clone the date:\n * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert the timestamp to date:\n * const result = toDate(1392098430000)\n * //=> Tue Feb 11 2014 11:30:30\n */\nexport function toDate(argument, context) {\n  // [TODO] Get rid of `toDate` or `constructFrom`?\n  return constructFrom(context || argument, argument);\n}\n\n// Fallback for modularized imports:\nexport default toDate;\n","let defaultOptions = {};\n\nexport function getDefaultOptions() {\n  return defaultOptions;\n}\n\nexport function setDefaultOptions(newOptions) {\n  defaultOptions = newOptions;\n}\n","import { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link startOfWeek} function options.\n */\n\n/**\n * @name startOfWeek\n * @category Week Helpers\n * @summary Return the start of a week for the given date.\n *\n * @description\n * Return the start of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week\n *\n * @example\n * // The start of a week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport function startOfWeek(date, options) {\n  const defaultOptions = getDefaultOptions();\n  const weekStartsOn =\n    options?.weekStartsOn ??\n    options?.locale?.options?.weekStartsOn ??\n    defaultOptions.weekStartsOn ??\n    defaultOptions.locale?.options?.weekStartsOn ??\n    0;\n\n  const _date = toDate(date, options?.in);\n  const day = _date.getDay();\n  const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n\n  _date.setDate(_date.getDate() - diff);\n  _date.setHours(0, 0, 0, 0);\n  return _date;\n}\n\n// Fallback for modularized imports:\nexport default startOfWeek;\n","import { startOfWeek } from \"./startOfWeek.js\";\n\n/**\n * The {@link startOfISOWeek} function options.\n */\n\n/**\n * @name startOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the start of an ISO week for the given date.\n *\n * @description\n * Return the start of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week\n *\n * @example\n * // The start of an ISO week for 2 September 2014 11:55:00:\n * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport function startOfISOWeek(date, options) {\n  return startOfWeek(date, { ...options, weekStartsOn: 1 });\n}\n\n// Fallback for modularized imports:\nexport default startOfISOWeek;\n","import { constructFrom } from \"./constructFrom.js\";\nimport { startOfISOWeek } from \"./startOfISOWeek.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getISOWeekYear} function options.\n */\n\n/**\n * @name getISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the ISO week-numbering year of the given date.\n *\n * @description\n * Get the ISO week-numbering year of the given date,\n * which always starts 3 days before the year's first Thursday.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n *\n * @returns The ISO week-numbering year\n *\n * @example\n * // Which ISO-week numbering year is 2 January 2005?\n * const result = getISOWeekYear(new Date(2005, 0, 2))\n * //=> 2004\n */\nexport function getISOWeekYear(date, options) {\n  const _date = toDate(date, options?.in);\n  const year = _date.getFullYear();\n\n  const fourthOfJanuaryOfNextYear = constructFrom(_date, 0);\n  fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n  fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n  const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);\n\n  const fourthOfJanuaryOfThisYear = constructFrom(_date, 0);\n  fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);\n  fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);\n  const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);\n\n  if (_date.getTime() >= startOfNextYear.getTime()) {\n    return year + 1;\n  } else if (_date.getTime() >= startOfThisYear.getTime()) {\n    return year;\n  } else {\n    return year - 1;\n  }\n}\n\n// Fallback for modularized imports:\nexport default getISOWeekYear;\n","import { toDate } from \"../toDate.js\";\n\n/**\n * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.\n * They usually appear for dates that denote time before the timezones were introduced\n * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891\n * and GMT+01:00:00 after that date)\n *\n * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,\n * which would lead to incorrect calculations.\n *\n * This function returns the timezone offset in milliseconds that takes seconds in account.\n */\nexport function getTimezoneOffsetInMilliseconds(date) {\n  const _date = toDate(date);\n  const utcDate = new Date(\n    Date.UTC(\n      _date.getFullYear(),\n      _date.getMonth(),\n      _date.getDate(),\n      _date.getHours(),\n      _date.getMinutes(),\n      _date.getSeconds(),\n      _date.getMilliseconds(),\n    ),\n  );\n  utcDate.setUTCFullYear(_date.getFullYear());\n  return +date - +utcDate;\n}\n","import { constructFrom } from \"../constructFrom.js\";\n\nexport function normalizeDates(context, ...dates) {\n  const normalize = constructFrom.bind(\n    null,\n    context || dates.find((date) => typeof date === \"object\"),\n  );\n  return dates.map(normalize);\n}\n","import { toDate } from \"./toDate.js\";\n\n/**\n * The {@link startOfDay} function options.\n */\n\n/**\n * @name startOfDay\n * @category Day Helpers\n * @summary Return the start of a day for the given date.\n *\n * @description\n * Return the start of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a day\n *\n * @example\n * // The start of a day for 2 September 2014 11:55:00:\n * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 00:00:00\n */\nexport function startOfDay(date, options) {\n  const _date = toDate(date, options?.in);\n  _date.setHours(0, 0, 0, 0);\n  return _date;\n}\n\n// Fallback for modularized imports:\nexport default startOfDay;\n","import { getTimezoneOffsetInMilliseconds } from \"./_lib/getTimezoneOffsetInMilliseconds.js\";\nimport { normalizeDates } from \"./_lib/normalizeDates.js\";\nimport { millisecondsInDay } from \"./constants.js\";\nimport { startOfDay } from \"./startOfDay.js\";\n\n/**\n * The {@link differenceInCalendarDays} function options.\n */\n\n/**\n * @name differenceInCalendarDays\n * @category Day Helpers\n * @summary Get the number of calendar days between the given dates.\n *\n * @description\n * Get the number of calendar days between the given dates. This means that the times are removed\n * from the dates and then the difference in days is calculated.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options object\n *\n * @returns The number of calendar days\n *\n * @example\n * // How many calendar days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInCalendarDays(\n *   new Date(2012, 6, 2, 0, 0),\n *   new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 366\n * // How many calendar days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInCalendarDays(\n *   new Date(2011, 6, 3, 0, 1),\n *   new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 1\n */\nexport function differenceInCalendarDays(laterDate, earlierDate, options) {\n  const [laterDate_, earlierDate_] = normalizeDates(\n    options?.in,\n    laterDate,\n    earlierDate,\n  );\n\n  const laterStartOfDay = startOfDay(laterDate_);\n  const earlierStartOfDay = startOfDay(earlierDate_);\n\n  const laterTimestamp =\n    +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);\n  const earlierTimestamp =\n    +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);\n\n  // Round the number of days to the nearest integer because the number of\n  // milliseconds in a day is not constant (e.g. it's different in the week of\n  // the daylight saving time clock shift).\n  return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);\n}\n\n// Fallback for modularized imports:\nexport default differenceInCalendarDays;\n","import { constructFrom } from \"./constructFrom.js\";\nimport { getISOWeekYear } from \"./getISOWeekYear.js\";\nimport { startOfISOWeek } from \"./startOfISOWeek.js\";\n\n/**\n * The {@link startOfISOWeekYear} function options.\n */\n\n/**\n * @name startOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the start of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the start of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week-numbering year\n *\n * @example\n * // The start of an ISO week-numbering year for 2 July 2005:\n * const result = startOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Mon Jan 03 2005 00:00:00\n */\nexport function startOfISOWeekYear(date, options) {\n  const year = getISOWeekYear(date, options);\n  const fourthOfJanuary = constructFrom(options?.in || date, 0);\n  fourthOfJanuary.setFullYear(year, 0, 4);\n  fourthOfJanuary.setHours(0, 0, 0, 0);\n  return startOfISOWeek(fourthOfJanuary);\n}\n\n// Fallback for modularized imports:\nexport default startOfISOWeekYear;\n","/**\n * @name isDate\n * @category Common Helpers\n * @summary Is the given value a date?\n *\n * @description\n * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.\n *\n * @param value - The value to check\n *\n * @returns True if the given value is a date\n *\n * @example\n * // For a valid date:\n * const result = isDate(new Date())\n * //=> true\n *\n * @example\n * // For an invalid date:\n * const result = isDate(new Date(NaN))\n * //=> true\n *\n * @example\n * // For some value:\n * const result = isDate('2014-02-31')\n * //=> false\n *\n * @example\n * // For an object:\n * const result = isDate({})\n * //=> false\n */\nexport function isDate(value) {\n  return (\n    value instanceof Date ||\n    (typeof value === \"object\" &&\n      Object.prototype.toString.call(value) === \"[object Date]\")\n  );\n}\n\n// Fallback for modularized imports:\nexport default isDate;\n","import { isDate } from \"./isDate.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * @name isValid\n * @category Common Helpers\n * @summary Is the given date valid?\n *\n * @description\n * Returns false if argument is Invalid Date and true otherwise.\n * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)\n * Invalid Date is a Date, whose time value is NaN.\n *\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @param date - The date to check\n *\n * @returns The date is valid\n *\n * @example\n * // For the valid date:\n * const result = isValid(new Date(2014, 1, 31))\n * //=> true\n *\n * @example\n * // For the value, convertible into a date:\n * const result = isValid(1393804800000)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isValid(new Date(''))\n * //=> false\n */\nexport function isValid(date) {\n  return !((!isDate(date) && typeof date !== \"number\") || isNaN(+toDate(date)));\n}\n\n// Fallback for modularized imports:\nexport default isValid;\n","import { toDate } from \"./toDate.js\";\n\n/**\n * The {@link startOfYear} function options.\n */\n\n/**\n * @name startOfYear\n * @category Year Helpers\n * @summary Return the start of a year for the given date.\n *\n * @description\n * Return the start of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a year\n *\n * @example\n * // The start of a year for 2 September 2014 11:55:00:\n * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Jan 01 2014 00:00:00\n */\nexport function startOfYear(date, options) {\n  const date_ = toDate(date, options?.in);\n  date_.setFullYear(date_.getFullYear(), 0, 1);\n  date_.setHours(0, 0, 0, 0);\n  return date_;\n}\n\n// Fallback for modularized imports:\nexport default startOfYear;\n","const formatDistanceLocale = {\n  lessThanXSeconds: {\n    one: \"less than a second\",\n    other: \"less than {{count}} seconds\",\n  },\n\n  xSeconds: {\n    one: \"1 second\",\n    other: \"{{count}} seconds\",\n  },\n\n  halfAMinute: \"half a minute\",\n\n  lessThanXMinutes: {\n    one: \"less than a minute\",\n    other: \"less than {{count}} minutes\",\n  },\n\n  xMinutes: {\n    one: \"1 minute\",\n    other: \"{{count}} minutes\",\n  },\n\n  aboutXHours: {\n    one: \"about 1 hour\",\n    other: \"about {{count}} hours\",\n  },\n\n  xHours: {\n    one: \"1 hour\",\n    other: \"{{count}} hours\",\n  },\n\n  xDays: {\n    one: \"1 day\",\n    other: \"{{count}} days\",\n  },\n\n  aboutXWeeks: {\n    one: \"about 1 week\",\n    other: \"about {{count}} weeks\",\n  },\n\n  xWeeks: {\n    one: \"1 week\",\n    other: \"{{count}} weeks\",\n  },\n\n  aboutXMonths: {\n    one: \"about 1 month\",\n    other: \"about {{count}} months\",\n  },\n\n  xMonths: {\n    one: \"1 month\",\n    other: \"{{count}} months\",\n  },\n\n  aboutXYears: {\n    one: \"about 1 year\",\n    other: \"about {{count}} years\",\n  },\n\n  xYears: {\n    one: \"1 year\",\n    other: \"{{count}} years\",\n  },\n\n  overXYears: {\n    one: \"over 1 year\",\n    other: \"over {{count}} years\",\n  },\n\n  almostXYears: {\n    one: \"almost 1 year\",\n    other: \"almost {{count}} years\",\n  },\n};\n\nexport const formatDistance = (token, count, options) => {\n  let result;\n\n  const tokenValue = formatDistanceLocale[token];\n  if (typeof tokenValue === \"string\") {\n    result = tokenValue;\n  } else if (count === 1) {\n    result = tokenValue.one;\n  } else {\n    result = tokenValue.other.replace(\"{{count}}\", count.toString());\n  }\n\n  if (options?.addSuffix) {\n    if (options.comparison && options.comparison > 0) {\n      return \"in \" + result;\n    } else {\n      return result + \" ago\";\n    }\n  }\n\n  return result;\n};\n","export function buildFormatLongFn(args) {\n  return (options = {}) => {\n    // TODO: Remove String()\n    const width = options.width ? String(options.width) : args.defaultWidth;\n    const format = args.formats[width] || args.formats[args.defaultWidth];\n    return format;\n  };\n}\n","import { buildFormatLongFn } from \"../../_lib/buildFormatLongFn.js\";\n\nconst dateFormats = {\n  full: \"EEEE, MMMM do, y\",\n  long: \"MMMM do, y\",\n  medium: \"MMM d, y\",\n  short: \"MM/dd/yyyy\",\n};\n\nconst timeFormats = {\n  full: \"h:mm:ss a zzzz\",\n  long: \"h:mm:ss a z\",\n  medium: \"h:mm:ss a\",\n  short: \"h:mm a\",\n};\n\nconst dateTimeFormats = {\n  full: \"{{date}} 'at' {{time}}\",\n  long: \"{{date}} 'at' {{time}}\",\n  medium: \"{{date}}, {{time}}\",\n  short: \"{{date}}, {{time}}\",\n};\n\nexport const formatLong = {\n  date: buildFormatLongFn({\n    formats: dateFormats,\n    defaultWidth: \"full\",\n  }),\n\n  time: buildFormatLongFn({\n    formats: timeFormats,\n    defaultWidth: \"full\",\n  }),\n\n  dateTime: buildFormatLongFn({\n    formats: dateTimeFormats,\n    defaultWidth: \"full\",\n  }),\n};\n","const formatRelativeLocale = {\n  lastWeek: \"'last' eeee 'at' p\",\n  yesterday: \"'yesterday at' p\",\n  today: \"'today at' p\",\n  tomorrow: \"'tomorrow at' p\",\n  nextWeek: \"eeee 'at' p\",\n  other: \"P\",\n};\n\nexport const formatRelative = (token, _date, _baseDate, _options) =>\n  formatRelativeLocale[token];\n","/**\n * The localize function argument callback which allows to convert raw value to\n * the actual type.\n *\n * @param value - The value to convert\n *\n * @returns The converted value\n */\n\n/**\n * The map of localized values for each width.\n */\n\n/**\n * The index type of the locale unit value. It types conversion of units of\n * values that don't start at 0 (i.e. quarters).\n */\n\n/**\n * Converts the unit value to the tuple of values.\n */\n\n/**\n * The tuple of localized era values. The first element represents BC,\n * the second element represents AD.\n */\n\n/**\n * The tuple of localized quarter values. The first element represents Q1.\n */\n\n/**\n * The tuple of localized day values. The first element represents Sunday.\n */\n\n/**\n * The tuple of localized month values. The first element represents January.\n */\n\nexport function buildLocalizeFn(args) {\n  return (value, options) => {\n    const context = options?.context ? String(options.context) : \"standalone\";\n\n    let valuesArray;\n    if (context === \"formatting\" && args.formattingValues) {\n      const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;\n      const width = options?.width ? String(options.width) : defaultWidth;\n\n      valuesArray =\n        args.formattingValues[width] || args.formattingValues[defaultWidth];\n    } else {\n      const defaultWidth = args.defaultWidth;\n      const width = options?.width ? String(options.width) : args.defaultWidth;\n\n      valuesArray = args.values[width] || args.values[defaultWidth];\n    }\n    const index = args.argumentCallback ? args.argumentCallback(value) : value;\n\n    // @ts-expect-error - For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!\n    return valuesArray[index];\n  };\n}\n","import { buildLocalizeFn } from \"../../_lib/buildLocalizeFn.js\";\n\nconst eraValues = {\n  narrow: [\"B\", \"A\"],\n  abbreviated: [\"BC\", \"AD\"],\n  wide: [\"Before Christ\", \"Anno Domini\"],\n};\n\nconst quarterValues = {\n  narrow: [\"1\", \"2\", \"3\", \"4\"],\n  abbreviated: [\"Q1\", \"Q2\", \"Q3\", \"Q4\"],\n  wide: [\"1st quarter\", \"2nd quarter\", \"3rd quarter\", \"4th quarter\"],\n};\n\n// Note: in English, the names of days of the week and months are capitalized.\n// If you are making a new locale based on this one, check if the same is true for the language you're working on.\n// Generally, formatted dates should look like they are in the middle of a sentence,\n// e.g. in Spanish language the weekdays and months should be in the lowercase.\nconst monthValues = {\n  narrow: [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"],\n  abbreviated: [\n    \"Jan\",\n    \"Feb\",\n    \"Mar\",\n    \"Apr\",\n    \"May\",\n    \"Jun\",\n    \"Jul\",\n    \"Aug\",\n    \"Sep\",\n    \"Oct\",\n    \"Nov\",\n    \"Dec\",\n  ],\n\n  wide: [\n    \"January\",\n    \"February\",\n    \"March\",\n    \"April\",\n    \"May\",\n    \"June\",\n    \"July\",\n    \"August\",\n    \"September\",\n    \"October\",\n    \"November\",\n    \"December\",\n  ],\n};\n\nconst dayValues = {\n  narrow: [\"S\", \"M\", \"T\", \"W\", \"T\", \"F\", \"S\"],\n  short: [\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\"],\n  abbreviated: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n  wide: [\n    \"Sunday\",\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n  ],\n};\n\nconst dayPeriodValues = {\n  narrow: {\n    am: \"a\",\n    pm: \"p\",\n    midnight: \"mi\",\n    noon: \"n\",\n    morning: \"morning\",\n    afternoon: \"afternoon\",\n    evening: \"evening\",\n    night: \"night\",\n  },\n  abbreviated: {\n    am: \"AM\",\n    pm: \"PM\",\n    midnight: \"midnight\",\n    noon: \"noon\",\n    morning: \"morning\",\n    afternoon: \"afternoon\",\n    evening: \"evening\",\n    night: \"night\",\n  },\n  wide: {\n    am: \"a.m.\",\n    pm: \"p.m.\",\n    midnight: \"midnight\",\n    noon: \"noon\",\n    morning: \"morning\",\n    afternoon: \"afternoon\",\n    evening: \"evening\",\n    night: \"night\",\n  },\n};\n\nconst formattingDayPeriodValues = {\n  narrow: {\n    am: \"a\",\n    pm: \"p\",\n    midnight: \"mi\",\n    noon: \"n\",\n    morning: \"in the morning\",\n    afternoon: \"in the afternoon\",\n    evening: \"in the evening\",\n    night: \"at night\",\n  },\n  abbreviated: {\n    am: \"AM\",\n    pm: \"PM\",\n    midnight: \"midnight\",\n    noon: \"noon\",\n    morning: \"in the morning\",\n    afternoon: \"in the afternoon\",\n    evening: \"in the evening\",\n    night: \"at night\",\n  },\n  wide: {\n    am: \"a.m.\",\n    pm: \"p.m.\",\n    midnight: \"midnight\",\n    noon: \"noon\",\n    morning: \"in the morning\",\n    afternoon: \"in the afternoon\",\n    evening: \"in the evening\",\n    night: \"at night\",\n  },\n};\n\nconst ordinalNumber = (dirtyNumber, _options) => {\n  const number = Number(dirtyNumber);\n\n  // If ordinal numbers depend on context, for example,\n  // if they are different for different grammatical genders,\n  // use `options.unit`.\n  //\n  // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',\n  // 'day', 'hour', 'minute', 'second'.\n\n  const rem100 = number % 100;\n  if (rem100 > 20 || rem100 < 10) {\n    switch (rem100 % 10) {\n      case 1:\n        return number + \"st\";\n      case 2:\n        return number + \"nd\";\n      case 3:\n        return number + \"rd\";\n    }\n  }\n  return number + \"th\";\n};\n\nexport const localize = {\n  ordinalNumber,\n\n  era: buildLocalizeFn({\n    values: eraValues,\n    defaultWidth: \"wide\",\n  }),\n\n  quarter: buildLocalizeFn({\n    values: quarterValues,\n    defaultWidth: \"wide\",\n    argumentCallback: (quarter) => quarter - 1,\n  }),\n\n  month: buildLocalizeFn({\n    values: monthValues,\n    defaultWidth: \"wide\",\n  }),\n\n  day: buildLocalizeFn({\n    values: dayValues,\n    defaultWidth: \"wide\",\n  }),\n\n  dayPeriod: buildLocalizeFn({\n    values: dayPeriodValues,\n    defaultWidth: \"wide\",\n    formattingValues: formattingDayPeriodValues,\n    defaultFormattingWidth: \"wide\",\n  }),\n};\n","export function buildMatchFn(args) {\n  return (string, options = {}) => {\n    const width = options.width;\n\n    const matchPattern =\n      (width && args.matchPatterns[width]) ||\n      args.matchPatterns[args.defaultMatchWidth];\n    const matchResult = string.match(matchPattern);\n\n    if (!matchResult) {\n      return null;\n    }\n    const matchedString = matchResult[0];\n\n    const parsePatterns =\n      (width && args.parsePatterns[width]) ||\n      args.parsePatterns[args.defaultParseWidth];\n\n    const key = Array.isArray(parsePatterns)\n      ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))\n      : // [TODO] -- I challenge you to fix the type\n        findKey(parsePatterns, (pattern) => pattern.test(matchedString));\n\n    let value;\n\n    value = args.valueCallback ? args.valueCallback(key) : key;\n    value = options.valueCallback\n      ? // [TODO] -- I challenge you to fix the type\n        options.valueCallback(value)\n      : value;\n\n    const rest = string.slice(matchedString.length);\n\n    return { value, rest };\n  };\n}\n\nfunction findKey(object, predicate) {\n  for (const key in object) {\n    if (\n      Object.prototype.hasOwnProperty.call(object, key) &&\n      predicate(object[key])\n    ) {\n      return key;\n    }\n  }\n  return undefined;\n}\n\nfunction findIndex(array, predicate) {\n  for (let key = 0; key < array.length; key++) {\n    if (predicate(array[key])) {\n      return key;\n    }\n  }\n  return undefined;\n}\n","export function buildMatchPatternFn(args) {\n  return (string, options = {}) => {\n    const matchResult = string.match(args.matchPattern);\n    if (!matchResult) return null;\n    const matchedString = matchResult[0];\n\n    const parseResult = string.match(args.parsePattern);\n    if (!parseResult) return null;\n    let value = args.valueCallback\n      ? args.valueCallback(parseResult[0])\n      : parseResult[0];\n\n    // [TODO] I challenge you to fix the type\n    value = options.valueCallback ? options.valueCallback(value) : value;\n\n    const rest = string.slice(matchedString.length);\n\n    return { value, rest };\n  };\n}\n","import { buildMatchFn } from \"../../_lib/buildMatchFn.js\";\nimport { buildMatchPatternFn } from \"../../_lib/buildMatchPatternFn.js\";\n\nconst matchOrdinalNumberPattern = /^(\\d+)(th|st|nd|rd)?/i;\nconst parseOrdinalNumberPattern = /\\d+/i;\n\nconst matchEraPatterns = {\n  narrow: /^(b|a)/i,\n  abbreviated: /^(b\\.?\\s?c\\.?|b\\.?\\s?c\\.?\\s?e\\.?|a\\.?\\s?d\\.?|c\\.?\\s?e\\.?)/i,\n  wide: /^(before christ|before common era|anno domini|common era)/i,\n};\nconst parseEraPatterns = {\n  any: [/^b/i, /^(a|c)/i],\n};\n\nconst matchQuarterPatterns = {\n  narrow: /^[1234]/i,\n  abbreviated: /^q[1234]/i,\n  wide: /^[1234](th|st|nd|rd)? quarter/i,\n};\nconst parseQuarterPatterns = {\n  any: [/1/i, /2/i, /3/i, /4/i],\n};\n\nconst matchMonthPatterns = {\n  narrow: /^[jfmasond]/i,\n  abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,\n  wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i,\n};\nconst parseMonthPatterns = {\n  narrow: [\n    /^j/i,\n    /^f/i,\n    /^m/i,\n    /^a/i,\n    /^m/i,\n    /^j/i,\n    /^j/i,\n    /^a/i,\n    /^s/i,\n    /^o/i,\n    /^n/i,\n    /^d/i,\n  ],\n\n  any: [\n    /^ja/i,\n    /^f/i,\n    /^mar/i,\n    /^ap/i,\n    /^may/i,\n    /^jun/i,\n    /^jul/i,\n    /^au/i,\n    /^s/i,\n    /^o/i,\n    /^n/i,\n    /^d/i,\n  ],\n};\n\nconst matchDayPatterns = {\n  narrow: /^[smtwf]/i,\n  short: /^(su|mo|tu|we|th|fr|sa)/i,\n  abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,\n  wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i,\n};\nconst parseDayPatterns = {\n  narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],\n  any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],\n};\n\nconst matchDayPeriodPatterns = {\n  narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,\n  any: /^([ap]\\.?\\s?m\\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i,\n};\nconst parseDayPeriodPatterns = {\n  any: {\n    am: /^a/i,\n    pm: /^p/i,\n    midnight: /^mi/i,\n    noon: /^no/i,\n    morning: /morning/i,\n    afternoon: /afternoon/i,\n    evening: /evening/i,\n    night: /night/i,\n  },\n};\n\nexport const match = {\n  ordinalNumber: buildMatchPatternFn({\n    matchPattern: matchOrdinalNumberPattern,\n    parsePattern: parseOrdinalNumberPattern,\n    valueCallback: (value) => parseInt(value, 10),\n  }),\n\n  era: buildMatchFn({\n    matchPatterns: matchEraPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseEraPatterns,\n    defaultParseWidth: \"any\",\n  }),\n\n  quarter: buildMatchFn({\n    matchPatterns: matchQuarterPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseQuarterPatterns,\n    defaultParseWidth: \"any\",\n    valueCallback: (index) => index + 1,\n  }),\n\n  month: buildMatchFn({\n    matchPatterns: matchMonthPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseMonthPatterns,\n    defaultParseWidth: \"any\",\n  }),\n\n  day: buildMatchFn({\n    matchPatterns: matchDayPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseDayPatterns,\n    defaultParseWidth: \"any\",\n  }),\n\n  dayPeriod: buildMatchFn({\n    matchPatterns: matchDayPeriodPatterns,\n    defaultMatchWidth: \"any\",\n    parsePatterns: parseDayPeriodPatterns,\n    defaultParseWidth: \"any\",\n  }),\n};\n","import { formatDistance } from \"./en-US/_lib/formatDistance.js\";\nimport { formatLong } from \"./en-US/_lib/formatLong.js\";\nimport { formatRelative } from \"./en-US/_lib/formatRelative.js\";\nimport { localize } from \"./en-US/_lib/localize.js\";\nimport { match } from \"./en-US/_lib/match.js\";\n\n/**\n * @category Locales\n * @summary English locale (United States).\n * @language English\n * @iso-639-2 eng\n * @author Sasha Koss [@kossnocorp](https://github.com/kossnocorp)\n * @author Lesha Koss [@leshakoss](https://github.com/leshakoss)\n */\nexport const enUS = {\n  code: \"en-US\",\n  formatDistance: formatDistance,\n  formatLong: formatLong,\n  formatRelative: formatRelative,\n  localize: localize,\n  match: match,\n  options: {\n    weekStartsOn: 0 /* Sunday */,\n    firstWeekContainsDate: 1,\n  },\n};\n\n// Fallback for modularized imports:\nexport default enUS;\n","import { differenceInCalendarDays } from \"./differenceInCalendarDays.js\";\nimport { startOfYear } from \"./startOfYear.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getDayOfYear} function options.\n */\n\n/**\n * @name getDayOfYear\n * @category Day Helpers\n * @summary Get the day of the year of the given date.\n *\n * @description\n * Get the day of the year of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of year\n *\n * @example\n * // Which day of the year is 2 July 2014?\n * const result = getDayOfYear(new Date(2014, 6, 2))\n * //=> 183\n */\nexport function getDayOfYear(date, options) {\n  const _date = toDate(date, options?.in);\n  const diff = differenceInCalendarDays(_date, startOfYear(_date));\n  const dayOfYear = diff + 1;\n  return dayOfYear;\n}\n\n// Fallback for modularized imports:\nexport default getDayOfYear;\n","import { millisecondsInWeek } from \"./constants.js\";\nimport { startOfISOWeek } from \"./startOfISOWeek.js\";\nimport { startOfISOWeekYear } from \"./startOfISOWeekYear.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getISOWeek} function options.\n */\n\n/**\n * @name getISOWeek\n * @category ISO Week Helpers\n * @summary Get the ISO week of the given date.\n *\n * @description\n * Get the ISO week of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The ISO week\n *\n * @example\n * // Which week of the ISO-week numbering year is 2 January 2005?\n * const result = getISOWeek(new Date(2005, 0, 2))\n * //=> 53\n */\nexport function getISOWeek(date, options) {\n  const _date = toDate(date, options?.in);\n  const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);\n\n  // Round the number of weeks to the nearest integer because the number of\n  // milliseconds in a week is not constant (e.g. it's different in the week of\n  // the daylight saving time clock shift).\n  return Math.round(diff / millisecondsInWeek) + 1;\n}\n\n// Fallback for modularized imports:\nexport default getISOWeek;\n","import { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { constructFrom } from \"./constructFrom.js\";\nimport { startOfWeek } from \"./startOfWeek.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getWeekYear} function options.\n */\n\n/**\n * @name getWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Get the local week-numbering year of the given date.\n *\n * @description\n * Get the local week-numbering year of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The local week-numbering year\n *\n * @example\n * // Which week numbering year is 26 December 2004 with the default settings?\n * const result = getWeekYear(new Date(2004, 11, 26))\n * //=> 2005\n *\n * @example\n * // Which week numbering year is 26 December 2004 if week starts on Saturday?\n * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })\n * //=> 2004\n *\n * @example\n * // Which week numbering year is 26 December 2004 if the first week contains 4 January?\n * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })\n * //=> 2004\n */\nexport function getWeekYear(date, options) {\n  const _date = toDate(date, options?.in);\n  const year = _date.getFullYear();\n\n  const defaultOptions = getDefaultOptions();\n  const firstWeekContainsDate =\n    options?.firstWeekContainsDate ??\n    options?.locale?.options?.firstWeekContainsDate ??\n    defaultOptions.firstWeekContainsDate ??\n    defaultOptions.locale?.options?.firstWeekContainsDate ??\n    1;\n\n  const firstWeekOfNextYear = constructFrom(options?.in || date, 0);\n  firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);\n  firstWeekOfNextYear.setHours(0, 0, 0, 0);\n  const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);\n\n  const firstWeekOfThisYear = constructFrom(options?.in || date, 0);\n  firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);\n  firstWeekOfThisYear.setHours(0, 0, 0, 0);\n  const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);\n\n  if (+_date >= +startOfNextYear) {\n    return year + 1;\n  } else if (+_date >= +startOfThisYear) {\n    return year;\n  } else {\n    return year - 1;\n  }\n}\n\n// Fallback for modularized imports:\nexport default getWeekYear;\n","import { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { constructFrom } from \"./constructFrom.js\";\nimport { getWeekYear } from \"./getWeekYear.js\";\nimport { startOfWeek } from \"./startOfWeek.js\";\n\n/**\n * The {@link startOfWeekYear} function options.\n */\n\n/**\n * @name startOfWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Return the start of a local week-numbering year for the given date.\n *\n * @description\n * Return the start of a local week-numbering year.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week-numbering year\n *\n * @example\n * // The start of an a week-numbering year for 2 July 2005 with default settings:\n * const result = startOfWeekYear(new Date(2005, 6, 2))\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // The start of a week-numbering year for 2 July 2005\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = startOfWeekYear(new Date(2005, 6, 2), {\n *   weekStartsOn: 1,\n *   firstWeekContainsDate: 4\n * })\n * //=> Mon Jan 03 2005 00:00:00\n */\nexport function startOfWeekYear(date, options) {\n  const defaultOptions = getDefaultOptions();\n  const firstWeekContainsDate =\n    options?.firstWeekContainsDate ??\n    options?.locale?.options?.firstWeekContainsDate ??\n    defaultOptions.firstWeekContainsDate ??\n    defaultOptions.locale?.options?.firstWeekContainsDate ??\n    1;\n\n  const year = getWeekYear(date, options);\n  const firstWeek = constructFrom(options?.in || date, 0);\n  firstWeek.setFullYear(year, 0, firstWeekContainsDate);\n  firstWeek.setHours(0, 0, 0, 0);\n  const _date = startOfWeek(firstWeek, options);\n  return _date;\n}\n\n// Fallback for modularized imports:\nexport default startOfWeekYear;\n","import { millisecondsInWeek } from \"./constants.js\";\nimport { startOfWeek } from \"./startOfWeek.js\";\nimport { startOfWeekYear } from \"./startOfWeekYear.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getWeek} function options.\n */\n\n/**\n * @name getWeek\n * @category Week Helpers\n * @summary Get the local week index of the given date.\n *\n * @description\n * Get the local week index of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The week\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005 with default options?\n * const result = getWeek(new Date(2005, 0, 2))\n * //=> 2\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January?\n * const result = getWeek(new Date(2005, 0, 2), {\n *   weekStartsOn: 1,\n *   firstWeekContainsDate: 4\n * })\n * //=> 53\n */\nexport function getWeek(date, options) {\n  const _date = toDate(date, options?.in);\n  const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);\n\n  // Round the number of weeks to the nearest integer because the number of\n  // milliseconds in a week is not constant (e.g. it's different in the week of\n  // the daylight saving time clock shift).\n  return Math.round(diff / millisecondsInWeek) + 1;\n}\n\n// Fallback for modularized imports:\nexport default getWeek;\n","export function addLeadingZeros(number, targetLength) {\n  const sign = number < 0 ? \"-\" : \"\";\n  const output = Math.abs(number).toString().padStart(targetLength, \"0\");\n  return sign + output;\n}\n","import { addLeadingZeros } from \"../addLeadingZeros.js\";\n\n/*\n * |     | Unit                           |     | Unit                           |\n * |-----|--------------------------------|-----|--------------------------------|\n * |  a  | AM, PM                         |  A* |                                |\n * |  d  | Day of month                   |  D  |                                |\n * |  h  | Hour [1-12]                    |  H  | Hour [0-23]                    |\n * |  m  | Minute                         |  M  | Month                          |\n * |  s  | Second                         |  S  | Fraction of second             |\n * |  y  | Year (abs)                     |  Y  |                                |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n */\n\nexport const lightFormatters = {\n  // Year\n  y(date, token) {\n    // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens\n    // | Year     |     y | yy |   yyy |  yyyy | yyyyy |\n    // |----------|-------|----|-------|-------|-------|\n    // | AD 1     |     1 | 01 |   001 |  0001 | 00001 |\n    // | AD 12    |    12 | 12 |   012 |  0012 | 00012 |\n    // | AD 123   |   123 | 23 |   123 |  0123 | 00123 |\n    // | AD 1234  |  1234 | 34 |  1234 |  1234 | 01234 |\n    // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\n\n    const signedYear = date.getFullYear();\n    // Returns 1 for 1 BC (which is year 0 in JavaScript)\n    const year = signedYear > 0 ? signedYear : 1 - signedYear;\n    return addLeadingZeros(token === \"yy\" ? year % 100 : year, token.length);\n  },\n\n  // Month\n  M(date, token) {\n    const month = date.getMonth();\n    return token === \"M\" ? String(month + 1) : addLeadingZeros(month + 1, 2);\n  },\n\n  // Day of the month\n  d(date, token) {\n    return addLeadingZeros(date.getDate(), token.length);\n  },\n\n  // AM or PM\n  a(date, token) {\n    const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? \"pm\" : \"am\";\n\n    switch (token) {\n      case \"a\":\n      case \"aa\":\n        return dayPeriodEnumValue.toUpperCase();\n      case \"aaa\":\n        return dayPeriodEnumValue;\n      case \"aaaaa\":\n        return dayPeriodEnumValue[0];\n      case \"aaaa\":\n      default:\n        return dayPeriodEnumValue === \"am\" ? \"a.m.\" : \"p.m.\";\n    }\n  },\n\n  // Hour [1-12]\n  h(date, token) {\n    return addLeadingZeros(date.getHours() % 12 || 12, token.length);\n  },\n\n  // Hour [0-23]\n  H(date, token) {\n    return addLeadingZeros(date.getHours(), token.length);\n  },\n\n  // Minute\n  m(date, token) {\n    return addLeadingZeros(date.getMinutes(), token.length);\n  },\n\n  // Second\n  s(date, token) {\n    return addLeadingZeros(date.getSeconds(), token.length);\n  },\n\n  // Fraction of second\n  S(date, token) {\n    const numberOfDigits = token.length;\n    const milliseconds = date.getMilliseconds();\n    const fractionalSeconds = Math.trunc(\n      milliseconds * Math.pow(10, numberOfDigits - 3),\n    );\n    return addLeadingZeros(fractionalSeconds, token.length);\n  },\n};\n","import { getDayOfYear } from \"../../getDayOfYear.js\";\nimport { getISOWeek } from \"../../getISOWeek.js\";\nimport { getISOWeekYear } from \"../../getISOWeekYear.js\";\nimport { getWeek } from \"../../getWeek.js\";\nimport { getWeekYear } from \"../../getWeekYear.js\";\n\nimport { addLeadingZeros } from \"../addLeadingZeros.js\";\nimport { lightFormatters } from \"./lightFormatters.js\";\n\nconst dayPeriodEnum = {\n  am: \"am\",\n  pm: \"pm\",\n  midnight: \"midnight\",\n  noon: \"noon\",\n  morning: \"morning\",\n  afternoon: \"afternoon\",\n  evening: \"evening\",\n  night: \"night\",\n};\n\n/*\n * |     | Unit                           |     | Unit                           |\n * |-----|--------------------------------|-----|--------------------------------|\n * |  a  | AM, PM                         |  A* | Milliseconds in day            |\n * |  b  | AM, PM, noon, midnight         |  B  | Flexible day period            |\n * |  c  | Stand-alone local day of week  |  C* | Localized hour w/ day period   |\n * |  d  | Day of month                   |  D  | Day of year                    |\n * |  e  | Local day of week              |  E  | Day of week                    |\n * |  f  |                                |  F* | Day of week in month           |\n * |  g* | Modified Julian day            |  G  | Era                            |\n * |  h  | Hour [1-12]                    |  H  | Hour [0-23]                    |\n * |  i! | ISO day of week                |  I! | ISO week of year               |\n * |  j* | Localized hour w/ day period   |  J* | Localized hour w/o day period  |\n * |  k  | Hour [1-24]                    |  K  | Hour [0-11]                    |\n * |  l* | (deprecated)                   |  L  | Stand-alone month              |\n * |  m  | Minute                         |  M  | Month                          |\n * |  n  |                                |  N  |                                |\n * |  o! | Ordinal number modifier        |  O  | Timezone (GMT)                 |\n * |  p! | Long localized time            |  P! | Long localized date            |\n * |  q  | Stand-alone quarter            |  Q  | Quarter                        |\n * |  r* | Related Gregorian year         |  R! | ISO week-numbering year        |\n * |  s  | Second                         |  S  | Fraction of second             |\n * |  t! | Seconds timestamp              |  T! | Milliseconds timestamp         |\n * |  u  | Extended year                  |  U* | Cyclic year                    |\n * |  v* | Timezone (generic non-locat.)  |  V* | Timezone (location)            |\n * |  w  | Local week of year             |  W* | Week of month                  |\n * |  x  | Timezone (ISO-8601 w/o Z)      |  X  | Timezone (ISO-8601)            |\n * |  y  | Year (abs)                     |  Y  | Local week-numbering year      |\n * |  z  | Timezone (specific non-locat.) |  Z* | Timezone (aliases)             |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n *   i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n *   `R` is supposed to be used in conjunction with `I` and `i`\n *   for universal ISO week-numbering date, whereas\n *   `Y` is supposed to be used in conjunction with `w` and `e`\n *   for week-numbering date specific to the locale.\n * - `P` is long localized date format\n * - `p` is long localized time format\n */\n\nexport const formatters = {\n  // Era\n  G: function (date, token, localize) {\n    const era = date.getFullYear() > 0 ? 1 : 0;\n    switch (token) {\n      // AD, BC\n      case \"G\":\n      case \"GG\":\n      case \"GGG\":\n        return localize.era(era, { width: \"abbreviated\" });\n      // A, B\n      case \"GGGGG\":\n        return localize.era(era, { width: \"narrow\" });\n      // Anno Domini, Before Christ\n      case \"GGGG\":\n      default:\n        return localize.era(era, { width: \"wide\" });\n    }\n  },\n\n  // Year\n  y: function (date, token, localize) {\n    // Ordinal number\n    if (token === \"yo\") {\n      const signedYear = date.getFullYear();\n      // Returns 1 for 1 BC (which is year 0 in JavaScript)\n      const year = signedYear > 0 ? signedYear : 1 - signedYear;\n      return localize.ordinalNumber(year, { unit: \"year\" });\n    }\n\n    return lightFormatters.y(date, token);\n  },\n\n  // Local week-numbering year\n  Y: function (date, token, localize, options) {\n    const signedWeekYear = getWeekYear(date, options);\n    // Returns 1 for 1 BC (which is year 0 in JavaScript)\n    const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;\n\n    // Two digit year\n    if (token === \"YY\") {\n      const twoDigitYear = weekYear % 100;\n      return addLeadingZeros(twoDigitYear, 2);\n    }\n\n    // Ordinal number\n    if (token === \"Yo\") {\n      return localize.ordinalNumber(weekYear, { unit: \"year\" });\n    }\n\n    // Padding\n    return addLeadingZeros(weekYear, token.length);\n  },\n\n  // ISO week-numbering year\n  R: function (date, token) {\n    const isoWeekYear = getISOWeekYear(date);\n\n    // Padding\n    return addLeadingZeros(isoWeekYear, token.length);\n  },\n\n  // Extended year. This is a single number designating the year of this calendar system.\n  // The main difference between `y` and `u` localizers are B.C. years:\n  // | Year | `y` | `u` |\n  // |------|-----|-----|\n  // | AC 1 |   1 |   1 |\n  // | BC 1 |   1 |   0 |\n  // | BC 2 |   2 |  -1 |\n  // Also `yy` always returns the last two digits of a year,\n  // while `uu` pads single digit years to 2 characters and returns other years unchanged.\n  u: function (date, token) {\n    const year = date.getFullYear();\n    return addLeadingZeros(year, token.length);\n  },\n\n  // Quarter\n  Q: function (date, token, localize) {\n    const quarter = Math.ceil((date.getMonth() + 1) / 3);\n    switch (token) {\n      // 1, 2, 3, 4\n      case \"Q\":\n        return String(quarter);\n      // 01, 02, 03, 04\n      case \"QQ\":\n        return addLeadingZeros(quarter, 2);\n      // 1st, 2nd, 3rd, 4th\n      case \"Qo\":\n        return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n      // Q1, Q2, Q3, Q4\n      case \"QQQ\":\n        return localize.quarter(quarter, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n      case \"QQQQQ\":\n        return localize.quarter(quarter, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      // 1st quarter, 2nd quarter, ...\n      case \"QQQQ\":\n      default:\n        return localize.quarter(quarter, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // Stand-alone quarter\n  q: function (date, token, localize) {\n    const quarter = Math.ceil((date.getMonth() + 1) / 3);\n    switch (token) {\n      // 1, 2, 3, 4\n      case \"q\":\n        return String(quarter);\n      // 01, 02, 03, 04\n      case \"qq\":\n        return addLeadingZeros(quarter, 2);\n      // 1st, 2nd, 3rd, 4th\n      case \"qo\":\n        return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n      // Q1, Q2, Q3, Q4\n      case \"qqq\":\n        return localize.quarter(quarter, {\n          width: \"abbreviated\",\n          context: \"standalone\",\n        });\n      // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n      case \"qqqqq\":\n        return localize.quarter(quarter, {\n          width: \"narrow\",\n          context: \"standalone\",\n        });\n      // 1st quarter, 2nd quarter, ...\n      case \"qqqq\":\n      default:\n        return localize.quarter(quarter, {\n          width: \"wide\",\n          context: \"standalone\",\n        });\n    }\n  },\n\n  // Month\n  M: function (date, token, localize) {\n    const month = date.getMonth();\n    switch (token) {\n      case \"M\":\n      case \"MM\":\n        return lightFormatters.M(date, token);\n      // 1st, 2nd, ..., 12th\n      case \"Mo\":\n        return localize.ordinalNumber(month + 1, { unit: \"month\" });\n      // Jan, Feb, ..., Dec\n      case \"MMM\":\n        return localize.month(month, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      // J, F, ..., D\n      case \"MMMMM\":\n        return localize.month(month, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      // January, February, ..., December\n      case \"MMMM\":\n      default:\n        return localize.month(month, { width: \"wide\", context: \"formatting\" });\n    }\n  },\n\n  // Stand-alone month\n  L: function (date, token, localize) {\n    const month = date.getMonth();\n    switch (token) {\n      // 1, 2, ..., 12\n      case \"L\":\n        return String(month + 1);\n      // 01, 02, ..., 12\n      case \"LL\":\n        return addLeadingZeros(month + 1, 2);\n      // 1st, 2nd, ..., 12th\n      case \"Lo\":\n        return localize.ordinalNumber(month + 1, { unit: \"month\" });\n      // Jan, Feb, ..., Dec\n      case \"LLL\":\n        return localize.month(month, {\n          width: \"abbreviated\",\n          context: \"standalone\",\n        });\n      // J, F, ..., D\n      case \"LLLLL\":\n        return localize.month(month, {\n          width: \"narrow\",\n          context: \"standalone\",\n        });\n      // January, February, ..., December\n      case \"LLLL\":\n      default:\n        return localize.month(month, { width: \"wide\", context: \"standalone\" });\n    }\n  },\n\n  // Local week of year\n  w: function (date, token, localize, options) {\n    const week = getWeek(date, options);\n\n    if (token === \"wo\") {\n      return localize.ordinalNumber(week, { unit: \"week\" });\n    }\n\n    return addLeadingZeros(week, token.length);\n  },\n\n  // ISO week of year\n  I: function (date, token, localize) {\n    const isoWeek = getISOWeek(date);\n\n    if (token === \"Io\") {\n      return localize.ordinalNumber(isoWeek, { unit: \"week\" });\n    }\n\n    return addLeadingZeros(isoWeek, token.length);\n  },\n\n  // Day of the month\n  d: function (date, token, localize) {\n    if (token === \"do\") {\n      return localize.ordinalNumber(date.getDate(), { unit: \"date\" });\n    }\n\n    return lightFormatters.d(date, token);\n  },\n\n  // Day of year\n  D: function (date, token, localize) {\n    const dayOfYear = getDayOfYear(date);\n\n    if (token === \"Do\") {\n      return localize.ordinalNumber(dayOfYear, { unit: \"dayOfYear\" });\n    }\n\n    return addLeadingZeros(dayOfYear, token.length);\n  },\n\n  // Day of week\n  E: function (date, token, localize) {\n    const dayOfWeek = date.getDay();\n    switch (token) {\n      // Tue\n      case \"E\":\n      case \"EE\":\n      case \"EEE\":\n        return localize.day(dayOfWeek, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      // T\n      case \"EEEEE\":\n        return localize.day(dayOfWeek, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      // Tu\n      case \"EEEEEE\":\n        return localize.day(dayOfWeek, {\n          width: \"short\",\n          context: \"formatting\",\n        });\n      // Tuesday\n      case \"EEEE\":\n      default:\n        return localize.day(dayOfWeek, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // Local day of week\n  e: function (date, token, localize, options) {\n    const dayOfWeek = date.getDay();\n    const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n    switch (token) {\n      // Numerical value (Nth day of week with current locale or weekStartsOn)\n      case \"e\":\n        return String(localDayOfWeek);\n      // Padded numerical value\n      case \"ee\":\n        return addLeadingZeros(localDayOfWeek, 2);\n      // 1st, 2nd, ..., 7th\n      case \"eo\":\n        return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n      case \"eee\":\n        return localize.day(dayOfWeek, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      // T\n      case \"eeeee\":\n        return localize.day(dayOfWeek, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      // Tu\n      case \"eeeeee\":\n        return localize.day(dayOfWeek, {\n          width: \"short\",\n          context: \"formatting\",\n        });\n      // Tuesday\n      case \"eeee\":\n      default:\n        return localize.day(dayOfWeek, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // Stand-alone local day of week\n  c: function (date, token, localize, options) {\n    const dayOfWeek = date.getDay();\n    const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n    switch (token) {\n      // Numerical value (same as in `e`)\n      case \"c\":\n        return String(localDayOfWeek);\n      // Padded numerical value\n      case \"cc\":\n        return addLeadingZeros(localDayOfWeek, token.length);\n      // 1st, 2nd, ..., 7th\n      case \"co\":\n        return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n      case \"ccc\":\n        return localize.day(dayOfWeek, {\n          width: \"abbreviated\",\n          context: \"standalone\",\n        });\n      // T\n      case \"ccccc\":\n        return localize.day(dayOfWeek, {\n          width: \"narrow\",\n          context: \"standalone\",\n        });\n      // Tu\n      case \"cccccc\":\n        return localize.day(dayOfWeek, {\n          width: \"short\",\n          context: \"standalone\",\n        });\n      // Tuesday\n      case \"cccc\":\n      default:\n        return localize.day(dayOfWeek, {\n          width: \"wide\",\n          context: \"standalone\",\n        });\n    }\n  },\n\n  // ISO day of week\n  i: function (date, token, localize) {\n    const dayOfWeek = date.getDay();\n    const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;\n    switch (token) {\n      // 2\n      case \"i\":\n        return String(isoDayOfWeek);\n      // 02\n      case \"ii\":\n        return addLeadingZeros(isoDayOfWeek, token.length);\n      // 2nd\n      case \"io\":\n        return localize.ordinalNumber(isoDayOfWeek, { unit: \"day\" });\n      // Tue\n      case \"iii\":\n        return localize.day(dayOfWeek, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      // T\n      case \"iiiii\":\n        return localize.day(dayOfWeek, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      // Tu\n      case \"iiiiii\":\n        return localize.day(dayOfWeek, {\n          width: \"short\",\n          context: \"formatting\",\n        });\n      // Tuesday\n      case \"iiii\":\n      default:\n        return localize.day(dayOfWeek, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // AM or PM\n  a: function (date, token, localize) {\n    const hours = date.getHours();\n    const dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n\n    switch (token) {\n      case \"a\":\n      case \"aa\":\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      case \"aaa\":\n        return localize\n          .dayPeriod(dayPeriodEnumValue, {\n            width: \"abbreviated\",\n            context: \"formatting\",\n          })\n          .toLowerCase();\n      case \"aaaaa\":\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      case \"aaaa\":\n      default:\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // AM, PM, midnight, noon\n  b: function (date, token, localize) {\n    const hours = date.getHours();\n    let dayPeriodEnumValue;\n    if (hours === 12) {\n      dayPeriodEnumValue = dayPeriodEnum.noon;\n    } else if (hours === 0) {\n      dayPeriodEnumValue = dayPeriodEnum.midnight;\n    } else {\n      dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n    }\n\n    switch (token) {\n      case \"b\":\n      case \"bb\":\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      case \"bbb\":\n        return localize\n          .dayPeriod(dayPeriodEnumValue, {\n            width: \"abbreviated\",\n            context: \"formatting\",\n          })\n          .toLowerCase();\n      case \"bbbbb\":\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      case \"bbbb\":\n      default:\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // in the morning, in the afternoon, in the evening, at night\n  B: function (date, token, localize) {\n    const hours = date.getHours();\n    let dayPeriodEnumValue;\n    if (hours >= 17) {\n      dayPeriodEnumValue = dayPeriodEnum.evening;\n    } else if (hours >= 12) {\n      dayPeriodEnumValue = dayPeriodEnum.afternoon;\n    } else if (hours >= 4) {\n      dayPeriodEnumValue = dayPeriodEnum.morning;\n    } else {\n      dayPeriodEnumValue = dayPeriodEnum.night;\n    }\n\n    switch (token) {\n      case \"B\":\n      case \"BB\":\n      case \"BBB\":\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"abbreviated\",\n          context: \"formatting\",\n        });\n      case \"BBBBB\":\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"narrow\",\n          context: \"formatting\",\n        });\n      case \"BBBB\":\n      default:\n        return localize.dayPeriod(dayPeriodEnumValue, {\n          width: \"wide\",\n          context: \"formatting\",\n        });\n    }\n  },\n\n  // Hour [1-12]\n  h: function (date, token, localize) {\n    if (token === \"ho\") {\n      let hours = date.getHours() % 12;\n      if (hours === 0) hours = 12;\n      return localize.ordinalNumber(hours, { unit: \"hour\" });\n    }\n\n    return lightFormatters.h(date, token);\n  },\n\n  // Hour [0-23]\n  H: function (date, token, localize) {\n    if (token === \"Ho\") {\n      return localize.ordinalNumber(date.getHours(), { unit: \"hour\" });\n    }\n\n    return lightFormatters.H(date, token);\n  },\n\n  // Hour [0-11]\n  K: function (date, token, localize) {\n    const hours = date.getHours() % 12;\n\n    if (token === \"Ko\") {\n      return localize.ordinalNumber(hours, { unit: \"hour\" });\n    }\n\n    return addLeadingZeros(hours, token.length);\n  },\n\n  // Hour [1-24]\n  k: function (date, token, localize) {\n    let hours = date.getHours();\n    if (hours === 0) hours = 24;\n\n    if (token === \"ko\") {\n      return localize.ordinalNumber(hours, { unit: \"hour\" });\n    }\n\n    return addLeadingZeros(hours, token.length);\n  },\n\n  // Minute\n  m: function (date, token, localize) {\n    if (token === \"mo\") {\n      return localize.ordinalNumber(date.getMinutes(), { unit: \"minute\" });\n    }\n\n    return lightFormatters.m(date, token);\n  },\n\n  // Second\n  s: function (date, token, localize) {\n    if (token === \"so\") {\n      return localize.ordinalNumber(date.getSeconds(), { unit: \"second\" });\n    }\n\n    return lightFormatters.s(date, token);\n  },\n\n  // Fraction of second\n  S: function (date, token) {\n    return lightFormatters.S(date, token);\n  },\n\n  // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)\n  X: function (date, token, _localize) {\n    const timezoneOffset = date.getTimezoneOffset();\n\n    if (timezoneOffset === 0) {\n      return \"Z\";\n    }\n\n    switch (token) {\n      // Hours and optional minutes\n      case \"X\":\n        return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n      // Hours, minutes and optional seconds without `:` delimiter\n      // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n      // so this token always has the same output as `XX`\n      case \"XXXX\":\n      case \"XX\": // Hours and minutes without `:` delimiter\n        return formatTimezone(timezoneOffset);\n\n      // Hours, minutes and optional seconds with `:` delimiter\n      // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n      // so this token always has the same output as `XXX`\n      case \"XXXXX\":\n      case \"XXX\": // Hours and minutes with `:` delimiter\n      default:\n        return formatTimezone(timezoneOffset, \":\");\n    }\n  },\n\n  // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)\n  x: function (date, token, _localize) {\n    const timezoneOffset = date.getTimezoneOffset();\n\n    switch (token) {\n      // Hours and optional minutes\n      case \"x\":\n        return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n      // Hours, minutes and optional seconds without `:` delimiter\n      // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n      // so this token always has the same output as `xx`\n      case \"xxxx\":\n      case \"xx\": // Hours and minutes without `:` delimiter\n        return formatTimezone(timezoneOffset);\n\n      // Hours, minutes and optional seconds with `:` delimiter\n      // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n      // so this token always has the same output as `xxx`\n      case \"xxxxx\":\n      case \"xxx\": // Hours and minutes with `:` delimiter\n      default:\n        return formatTimezone(timezoneOffset, \":\");\n    }\n  },\n\n  // Timezone (GMT)\n  O: function (date, token, _localize) {\n    const timezoneOffset = date.getTimezoneOffset();\n\n    switch (token) {\n      // Short\n      case \"O\":\n      case \"OO\":\n      case \"OOO\":\n        return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n      // Long\n      case \"OOOO\":\n      default:\n        return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n    }\n  },\n\n  // Timezone (specific non-location)\n  z: function (date, token, _localize) {\n    const timezoneOffset = date.getTimezoneOffset();\n\n    switch (token) {\n      // Short\n      case \"z\":\n      case \"zz\":\n      case \"zzz\":\n        return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n      // Long\n      case \"zzzz\":\n      default:\n        return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n    }\n  },\n\n  // Seconds timestamp\n  t: function (date, token, _localize) {\n    const timestamp = Math.trunc(+date / 1000);\n    return addLeadingZeros(timestamp, token.length);\n  },\n\n  // Milliseconds timestamp\n  T: function (date, token, _localize) {\n    return addLeadingZeros(+date, token.length);\n  },\n};\n\nfunction formatTimezoneShort(offset, delimiter = \"\") {\n  const sign = offset > 0 ? \"-\" : \"+\";\n  const absOffset = Math.abs(offset);\n  const hours = Math.trunc(absOffset / 60);\n  const minutes = absOffset % 60;\n  if (minutes === 0) {\n    return sign + String(hours);\n  }\n  return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);\n}\n\nfunction formatTimezoneWithOptionalMinutes(offset, delimiter) {\n  if (offset % 60 === 0) {\n    const sign = offset > 0 ? \"-\" : \"+\";\n    return sign + addLeadingZeros(Math.abs(offset) / 60, 2);\n  }\n  return formatTimezone(offset, delimiter);\n}\n\nfunction formatTimezone(offset, delimiter = \"\") {\n  const sign = offset > 0 ? \"-\" : \"+\";\n  const absOffset = Math.abs(offset);\n  const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);\n  const minutes = addLeadingZeros(absOffset % 60, 2);\n  return sign + hours + delimiter + minutes;\n}\n","const dateLongFormatter = (pattern, formatLong) => {\n  switch (pattern) {\n    case \"P\":\n      return formatLong.date({ width: \"short\" });\n    case \"PP\":\n      return formatLong.date({ width: \"medium\" });\n    case \"PPP\":\n      return formatLong.date({ width: \"long\" });\n    case \"PPPP\":\n    default:\n      return formatLong.date({ width: \"full\" });\n  }\n};\n\nconst timeLongFormatter = (pattern, formatLong) => {\n  switch (pattern) {\n    case \"p\":\n      return formatLong.time({ width: \"short\" });\n    case \"pp\":\n      return formatLong.time({ width: \"medium\" });\n    case \"ppp\":\n      return formatLong.time({ width: \"long\" });\n    case \"pppp\":\n    default:\n      return formatLong.time({ width: \"full\" });\n  }\n};\n\nconst dateTimeLongFormatter = (pattern, formatLong) => {\n  const matchResult = pattern.match(/(P+)(p+)?/) || [];\n  const datePattern = matchResult[1];\n  const timePattern = matchResult[2];\n\n  if (!timePattern) {\n    return dateLongFormatter(pattern, formatLong);\n  }\n\n  let dateTimeFormat;\n\n  switch (datePattern) {\n    case \"P\":\n      dateTimeFormat = formatLong.dateTime({ width: \"short\" });\n      break;\n    case \"PP\":\n      dateTimeFormat = formatLong.dateTime({ width: \"medium\" });\n      break;\n    case \"PPP\":\n      dateTimeFormat = formatLong.dateTime({ width: \"long\" });\n      break;\n    case \"PPPP\":\n    default:\n      dateTimeFormat = formatLong.dateTime({ width: \"full\" });\n      break;\n  }\n\n  return dateTimeFormat\n    .replace(\"{{date}}\", dateLongFormatter(datePattern, formatLong))\n    .replace(\"{{time}}\", timeLongFormatter(timePattern, formatLong));\n};\n\nexport const longFormatters = {\n  p: timeLongFormatter,\n  P: dateTimeLongFormatter,\n};\n","const dayOfYearTokenRE = /^D+$/;\nconst weekYearTokenRE = /^Y+$/;\n\nconst throwTokens = [\"D\", \"DD\", \"YY\", \"YYYY\"];\n\nexport function isProtectedDayOfYearToken(token) {\n  return dayOfYearTokenRE.test(token);\n}\n\nexport function isProtectedWeekYearToken(token) {\n  return weekYearTokenRE.test(token);\n}\n\nexport function warnOrThrowProtectedError(token, format, input) {\n  const _message = message(token, format, input);\n  console.warn(_message);\n  if (throwTokens.includes(token)) throw new RangeError(_message);\n}\n\nfunction message(token, format, input) {\n  const subject = token[0] === \"Y\" ? \"years\" : \"days of the month\";\n  return `Use \\`${token.toLowerCase()}\\` instead of \\`${token}\\` (in \\`${format}\\`) for formatting ${subject} to the input \\`${input}\\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;\n}\n","import { defaultLocale } from \"./_lib/defaultLocale.js\";\nimport { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { formatters } from \"./_lib/format/formatters.js\";\nimport { longFormatters } from \"./_lib/format/longFormatters.js\";\nimport {\n  isProtectedDayOfYearToken,\n  isProtectedWeekYearToken,\n  warnOrThrowProtectedError,\n} from \"./_lib/protectedTokens.js\";\nimport { isValid } from \"./isValid.js\";\nimport { toDate } from \"./toDate.js\";\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\nexport { formatters, longFormatters };\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n//   (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n//   except a single quote symbol, which ends the sequence.\n//   Two quote characters do not end the sequence.\n//   If there is no matching single quote\n//   then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n  /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\nexport { format as formatDate };\n\n/**\n * The {@link format} function options.\n */\n\n/**\n * @name format\n * @alias formatDate\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. The result may vary by locale.\n *\n * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n * (see the last example)\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 7 below the table).\n *\n * Accepted patterns:\n * | Unit                            | Pattern | Result examples                   | Notes |\n * |---------------------------------|---------|-----------------------------------|-------|\n * | Era                             | G..GGG  | AD, BC                            |       |\n * |                                 | GGGG    | Anno Domini, Before Christ        | 2     |\n * |                                 | GGGGG   | A, B                              |       |\n * | Calendar year                   | y       | 44, 1, 1900, 2017                 | 5     |\n * |                                 | yo      | 44th, 1st, 0th, 17th              | 5,7   |\n * |                                 | yy      | 44, 01, 00, 17                    | 5     |\n * |                                 | yyy     | 044, 001, 1900, 2017              | 5     |\n * |                                 | yyyy    | 0044, 0001, 1900, 2017            | 5     |\n * |                                 | yyyyy   | ...                               | 3,5   |\n * | Local week-numbering year       | Y       | 44, 1, 1900, 2017                 | 5     |\n * |                                 | Yo      | 44th, 1st, 1900th, 2017th         | 5,7   |\n * |                                 | YY      | 44, 01, 00, 17                    | 5,8   |\n * |                                 | YYY     | 044, 001, 1900, 2017              | 5     |\n * |                                 | YYYY    | 0044, 0001, 1900, 2017            | 5,8   |\n * |                                 | YYYYY   | ...                               | 3,5   |\n * | ISO week-numbering year         | R       | -43, 0, 1, 1900, 2017             | 5,7   |\n * |                                 | RR      | -43, 00, 01, 1900, 2017           | 5,7   |\n * |                                 | RRR     | -043, 000, 001, 1900, 2017        | 5,7   |\n * |                                 | RRRR    | -0043, 0000, 0001, 1900, 2017     | 5,7   |\n * |                                 | RRRRR   | ...                               | 3,5,7 |\n * | Extended year                   | u       | -43, 0, 1, 1900, 2017             | 5     |\n * |                                 | uu      | -43, 01, 1900, 2017               | 5     |\n * |                                 | uuu     | -043, 001, 1900, 2017             | 5     |\n * |                                 | uuuu    | -0043, 0001, 1900, 2017           | 5     |\n * |                                 | uuuuu   | ...                               | 3,5   |\n * | Quarter (formatting)            | Q       | 1, 2, 3, 4                        |       |\n * |                                 | Qo      | 1st, 2nd, 3rd, 4th                | 7     |\n * |                                 | QQ      | 01, 02, 03, 04                    |       |\n * |                                 | QQQ     | Q1, Q2, Q3, Q4                    |       |\n * |                                 | QQQQ    | 1st quarter, 2nd quarter, ...     | 2     |\n * |                                 | QQQQQ   | 1, 2, 3, 4                        | 4     |\n * | Quarter (stand-alone)           | q       | 1, 2, 3, 4                        |       |\n * |                                 | qo      | 1st, 2nd, 3rd, 4th                | 7     |\n * |                                 | qq      | 01, 02, 03, 04                    |       |\n * |                                 | qqq     | Q1, Q2, Q3, Q4                    |       |\n * |                                 | qqqq    | 1st quarter, 2nd quarter, ...     | 2     |\n * |                                 | qqqqq   | 1, 2, 3, 4                        | 4     |\n * | Month (formatting)              | M       | 1, 2, ..., 12                     |       |\n * |                                 | Mo      | 1st, 2nd, ..., 12th               | 7     |\n * |                                 | MM      | 01, 02, ..., 12                   |       |\n * |                                 | MMM     | Jan, Feb, ..., Dec                |       |\n * |                                 | MMMM    | January, February, ..., December  | 2     |\n * |                                 | MMMMM   | J, F, ..., D                      |       |\n * | Month (stand-alone)             | L       | 1, 2, ..., 12                     |       |\n * |                                 | Lo      | 1st, 2nd, ..., 12th               | 7     |\n * |                                 | LL      | 01, 02, ..., 12                   |       |\n * |                                 | LLL     | Jan, Feb, ..., Dec                |       |\n * |                                 | LLLL    | January, February, ..., December  | 2     |\n * |                                 | LLLLL   | J, F, ..., D                      |       |\n * | Local week of year              | w       | 1, 2, ..., 53                     |       |\n * |                                 | wo      | 1st, 2nd, ..., 53th               | 7     |\n * |                                 | ww      | 01, 02, ..., 53                   |       |\n * | ISO week of year                | I       | 1, 2, ..., 53                     | 7     |\n * |                                 | Io      | 1st, 2nd, ..., 53th               | 7     |\n * |                                 | II      | 01, 02, ..., 53                   | 7     |\n * | Day of month                    | d       | 1, 2, ..., 31                     |       |\n * |                                 | do      | 1st, 2nd, ..., 31st               | 7     |\n * |                                 | dd      | 01, 02, ..., 31                   |       |\n * | Day of year                     | D       | 1, 2, ..., 365, 366               | 9     |\n * |                                 | Do      | 1st, 2nd, ..., 365th, 366th       | 7     |\n * |                                 | DD      | 01, 02, ..., 365, 366             | 9     |\n * |                                 | DDD     | 001, 002, ..., 365, 366           |       |\n * |                                 | DDDD    | ...                               | 3     |\n * | Day of week (formatting)        | E..EEE  | Mon, Tue, Wed, ..., Sun           |       |\n * |                                 | EEEE    | Monday, Tuesday, ..., Sunday      | 2     |\n * |                                 | EEEEE   | M, T, W, T, F, S, S               |       |\n * |                                 | EEEEEE  | Mo, Tu, We, Th, Fr, Sa, Su        |       |\n * | ISO day of week (formatting)    | i       | 1, 2, 3, ..., 7                   | 7     |\n * |                                 | io      | 1st, 2nd, ..., 7th                | 7     |\n * |                                 | ii      | 01, 02, ..., 07                   | 7     |\n * |                                 | iii     | Mon, Tue, Wed, ..., Sun           | 7     |\n * |                                 | iiii    | Monday, Tuesday, ..., Sunday      | 2,7   |\n * |                                 | iiiii   | M, T, W, T, F, S, S               | 7     |\n * |                                 | iiiiii  | Mo, Tu, We, Th, Fr, Sa, Su        | 7     |\n * | Local day of week (formatting)  | e       | 2, 3, 4, ..., 1                   |       |\n * |                                 | eo      | 2nd, 3rd, ..., 1st                | 7     |\n * |                                 | ee      | 02, 03, ..., 01                   |       |\n * |                                 | eee     | Mon, Tue, Wed, ..., Sun           |       |\n * |                                 | eeee    | Monday, Tuesday, ..., Sunday      | 2     |\n * |                                 | eeeee   | M, T, W, T, F, S, S               |       |\n * |                                 | eeeeee  | Mo, Tu, We, Th, Fr, Sa, Su        |       |\n * | Local day of week (stand-alone) | c       | 2, 3, 4, ..., 1                   |       |\n * |                                 | co      | 2nd, 3rd, ..., 1st                | 7     |\n * |                                 | cc      | 02, 03, ..., 01                   |       |\n * |                                 | ccc     | Mon, Tue, Wed, ..., Sun           |       |\n * |                                 | cccc    | Monday, Tuesday, ..., Sunday      | 2     |\n * |                                 | ccccc   | M, T, W, T, F, S, S               |       |\n * |                                 | cccccc  | Mo, Tu, We, Th, Fr, Sa, Su        |       |\n * | AM, PM                          | a..aa   | AM, PM                            |       |\n * |                                 | aaa     | am, pm                            |       |\n * |                                 | aaaa    | a.m., p.m.                        | 2     |\n * |                                 | aaaaa   | a, p                              |       |\n * | AM, PM, noon, midnight          | b..bb   | AM, PM, noon, midnight            |       |\n * |                                 | bbb     | am, pm, noon, midnight            |       |\n * |                                 | bbbb    | a.m., p.m., noon, midnight        | 2     |\n * |                                 | bbbbb   | a, p, n, mi                       |       |\n * | Flexible day period             | B..BBB  | at night, in the morning, ...     |       |\n * |                                 | BBBB    | at night, in the morning, ...     | 2     |\n * |                                 | BBBBB   | at night, in the morning, ...     |       |\n * | Hour [1-12]                     | h       | 1, 2, ..., 11, 12                 |       |\n * |                                 | ho      | 1st, 2nd, ..., 11th, 12th         | 7     |\n * |                                 | hh      | 01, 02, ..., 11, 12               |       |\n * | Hour [0-23]                     | H       | 0, 1, 2, ..., 23                  |       |\n * |                                 | Ho      | 0th, 1st, 2nd, ..., 23rd          | 7     |\n * |                                 | HH      | 00, 01, 02, ..., 23               |       |\n * | Hour [0-11]                     | K       | 1, 2, ..., 11, 0                  |       |\n * |                                 | Ko      | 1st, 2nd, ..., 11th, 0th          | 7     |\n * |                                 | KK      | 01, 02, ..., 11, 00               |       |\n * | Hour [1-24]                     | k       | 24, 1, 2, ..., 23                 |       |\n * |                                 | ko      | 24th, 1st, 2nd, ..., 23rd         | 7     |\n * |                                 | kk      | 24, 01, 02, ..., 23               |       |\n * | Minute                          | m       | 0, 1, ..., 59                     |       |\n * |                                 | mo      | 0th, 1st, ..., 59th               | 7     |\n * |                                 | mm      | 00, 01, ..., 59                   |       |\n * | Second                          | s       | 0, 1, ..., 59                     |       |\n * |                                 | so      | 0th, 1st, ..., 59th               | 7     |\n * |                                 | ss      | 00, 01, ..., 59                   |       |\n * | Fraction of second              | S       | 0, 1, ..., 9                      |       |\n * |                                 | SS      | 00, 01, ..., 99                   |       |\n * |                                 | SSS     | 000, 001, ..., 999                |       |\n * |                                 | SSSS    | ...                               | 3     |\n * | Timezone (ISO-8601 w/ Z)        | X       | -08, +0530, Z                     |       |\n * |                                 | XX      | -0800, +0530, Z                   |       |\n * |                                 | XXX     | -08:00, +05:30, Z                 |       |\n * |                                 | XXXX    | -0800, +0530, Z, +123456          | 2     |\n * |                                 | XXXXX   | -08:00, +05:30, Z, +12:34:56      |       |\n * | Timezone (ISO-8601 w/o Z)       | x       | -08, +0530, +00                   |       |\n * |                                 | xx      | -0800, +0530, +0000               |       |\n * |                                 | xxx     | -08:00, +05:30, +00:00            | 2     |\n * |                                 | xxxx    | -0800, +0530, +0000, +123456      |       |\n * |                                 | xxxxx   | -08:00, +05:30, +00:00, +12:34:56 |       |\n * | Timezone (GMT)                  | O...OOO | GMT-8, GMT+5:30, GMT+0            |       |\n * |                                 | OOOO    | GMT-08:00, GMT+05:30, GMT+00:00   | 2     |\n * | Timezone (specific non-locat.)  | z...zzz | GMT-8, GMT+5:30, GMT+0            | 6     |\n * |                                 | zzzz    | GMT-08:00, GMT+05:30, GMT+00:00   | 2,6   |\n * | Seconds timestamp               | t       | 512969520                         | 7     |\n * |                                 | tt      | ...                               | 3,7   |\n * | Milliseconds timestamp          | T       | 512969520900                      | 7     |\n * |                                 | TT      | ...                               | 3,7   |\n * | Long localized date             | P       | 04/29/1453                        | 7     |\n * |                                 | PP      | Apr 29, 1453                      | 7     |\n * |                                 | PPP     | April 29th, 1453                  | 7     |\n * |                                 | PPPP    | Friday, April 29th, 1453          | 2,7   |\n * | Long localized time             | p       | 12:00 AM                          | 7     |\n * |                                 | pp      | 12:00:00 AM                       | 7     |\n * |                                 | ppp     | 12:00:00 AM GMT+2                 | 7     |\n * |                                 | pppp    | 12:00:00 AM GMT+02:00             | 2,7   |\n * | Combination of date and time    | Pp      | 04/29/1453, 12:00 AM              | 7     |\n * |                                 | PPpp    | Apr 29, 1453, 12:00:00 AM         | 7     |\n * |                                 | PPPppp  | April 29th, 1453 at ...           | 7     |\n * |                                 | PPPPpppp| Friday, April 29th, 1453 at ...   | 2,7   |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n *    are the same as \"stand-alone\" units, but are different in some languages.\n *    \"Formatting\" units are declined according to the rules of the language\n *    in the context of a date. \"Stand-alone\" units are always nominative singular:\n *\n *    `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n *    `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n *    the single quote characters (see below).\n *    If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)\n *    the output will be the same as default pattern for this unit, usually\n *    the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units\n *    are marked with \"2\" in the last column of the table.\n *\n *    `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`\n *\n *    `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`\n *\n *    `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`\n *\n *    `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`\n *\n *    `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`\n *\n * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).\n *    The output will be padded with zeros to match the length of the pattern.\n *\n *    `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`\n *\n * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n *    These tokens represent the shortest form of the quarter.\n *\n * 5. The main difference between `y` and `u` patterns are B.C. years:\n *\n *    | Year | `y` | `u` |\n *    |------|-----|-----|\n *    | AC 1 |   1 |   1 |\n *    | BC 1 |   1 |   0 |\n *    | BC 2 |   2 |  -1 |\n *\n *    Also `yy` always returns the last two digits of a year,\n *    while `uu` pads single digit years to 2 characters and returns other years unchanged:\n *\n *    | Year | `yy` | `uu` |\n *    |------|------|------|\n *    | 1    |   01 |   01 |\n *    | 14   |   14 |   14 |\n *    | 376  |   76 |  376 |\n *    | 1453 |   53 | 1453 |\n *\n *    The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n *    except local week-numbering years are dependent on `options.weekStartsOn`\n *    and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)\n *    and [getWeekYear](https://date-fns.org/docs/getWeekYear)).\n *\n * 6. Specific non-location timezones are currently unavailable in `date-fns`,\n *    so right now these tokens fall back to GMT timezones.\n *\n * 7. These patterns are not in the Unicode Technical Standard #35:\n *    - `i`: ISO day of week\n *    - `I`: ISO week of year\n *    - `R`: ISO week-numbering year\n *    - `t`: seconds timestamp\n *    - `T`: milliseconds timestamp\n *    - `o`: ordinal number modifier\n *    - `P`: long localized date\n *    - `p`: long localized time\n *\n * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n *    You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n *    You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @param date - The original date\n * @param format - The string of tokens\n * @param options - An object with options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Represent 11 February 2014 in middle-endian format:\n * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')\n * //=> '02/11/2014'\n *\n * @example\n * // Represent 2 July 2014 in Esperanto:\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = format(new Date(2014, 6, 2), \"do 'de' MMMM yyyy\", {\n *   locale: eoLocale\n * })\n * //=> '2-a de julio 2014'\n *\n * @example\n * // Escape string by single quote characters:\n * const result = format(new Date(2014, 6, 2, 15), \"h 'o''clock'\")\n * //=> \"3 o'clock\"\n */\nexport function format(date, formatStr, options) {\n  const defaultOptions = getDefaultOptions();\n  const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;\n\n  const firstWeekContainsDate =\n    options?.firstWeekContainsDate ??\n    options?.locale?.options?.firstWeekContainsDate ??\n    defaultOptions.firstWeekContainsDate ??\n    defaultOptions.locale?.options?.firstWeekContainsDate ??\n    1;\n\n  const weekStartsOn =\n    options?.weekStartsOn ??\n    options?.locale?.options?.weekStartsOn ??\n    defaultOptions.weekStartsOn ??\n    defaultOptions.locale?.options?.weekStartsOn ??\n    0;\n\n  const originalDate = toDate(date, options?.in);\n\n  if (!isValid(originalDate)) {\n    throw new RangeError(\"Invalid time value\");\n  }\n\n  let parts = formatStr\n    .match(longFormattingTokensRegExp)\n    .map((substring) => {\n      const firstCharacter = substring[0];\n      if (firstCharacter === \"p\" || firstCharacter === \"P\") {\n        const longFormatter = longFormatters[firstCharacter];\n        return longFormatter(substring, locale.formatLong);\n      }\n      return substring;\n    })\n    .join(\"\")\n    .match(formattingTokensRegExp)\n    .map((substring) => {\n      // Replace two single quote characters with one single quote character\n      if (substring === \"''\") {\n        return { isToken: false, value: \"'\" };\n      }\n\n      const firstCharacter = substring[0];\n      if (firstCharacter === \"'\") {\n        return { isToken: false, value: cleanEscapedString(substring) };\n      }\n\n      if (formatters[firstCharacter]) {\n        return { isToken: true, value: substring };\n      }\n\n      if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n        throw new RangeError(\n          \"Format string contains an unescaped latin alphabet character `\" +\n            firstCharacter +\n            \"`\",\n        );\n      }\n\n      return { isToken: false, value: substring };\n    });\n\n  // invoke localize preprocessor (only for french locales at the moment)\n  if (locale.localize.preprocessor) {\n    parts = locale.localize.preprocessor(originalDate, parts);\n  }\n\n  const formatterOptions = {\n    firstWeekContainsDate,\n    weekStartsOn,\n    locale,\n  };\n\n  return parts\n    .map((part) => {\n      if (!part.isToken) return part.value;\n\n      const token = part.value;\n\n      if (\n        (!options?.useAdditionalWeekYearTokens &&\n          isProtectedWeekYearToken(token)) ||\n        (!options?.useAdditionalDayOfYearTokens &&\n          isProtectedDayOfYearToken(token))\n      ) {\n        warnOrThrowProtectedError(token, formatStr, String(date));\n      }\n\n      const formatter = formatters[token[0]];\n      return formatter(originalDate, token, locale.localize, formatterOptions);\n    })\n    .join(\"\");\n}\n\nfunction cleanEscapedString(input) {\n  const matched = input.match(escapedStringRegExp);\n\n  if (!matched) {\n    return input;\n  }\n\n  return matched[1].replace(doubleQuoteRegExp, \"'\");\n}\n\n// Fallback for modularized imports:\nexport default format;\n","const formatDistanceLocale = {\n  lessThanXSeconds: {\n    one: \"menos de un segundo\",\n    other: \"menos de {{count}} segundos\",\n  },\n\n  xSeconds: {\n    one: \"1 segundo\",\n    other: \"{{count}} segundos\",\n  },\n\n  halfAMinute: \"medio minuto\",\n\n  lessThanXMinutes: {\n    one: \"menos de un minuto\",\n    other: \"menos de {{count}} minutos\",\n  },\n\n  xMinutes: {\n    one: \"1 minuto\",\n    other: \"{{count}} minutos\",\n  },\n\n  aboutXHours: {\n    one: \"alrededor de 1 hora\",\n    other: \"alrededor de {{count}} horas\",\n  },\n\n  xHours: {\n    one: \"1 hora\",\n    other: \"{{count}} horas\",\n  },\n\n  xDays: {\n    one: \"1 día\",\n    other: \"{{count}} días\",\n  },\n\n  aboutXWeeks: {\n    one: \"alrededor de 1 semana\",\n    other: \"alrededor de {{count}} semanas\",\n  },\n\n  xWeeks: {\n    one: \"1 semana\",\n    other: \"{{count}} semanas\",\n  },\n\n  aboutXMonths: {\n    one: \"alrededor de 1 mes\",\n    other: \"alrededor de {{count}} meses\",\n  },\n\n  xMonths: {\n    one: \"1 mes\",\n    other: \"{{count}} meses\",\n  },\n\n  aboutXYears: {\n    one: \"alrededor de 1 año\",\n    other: \"alrededor de {{count}} años\",\n  },\n\n  xYears: {\n    one: \"1 año\",\n    other: \"{{count}} años\",\n  },\n\n  overXYears: {\n    one: \"más de 1 año\",\n    other: \"más de {{count}} años\",\n  },\n\n  almostXYears: {\n    one: \"casi 1 año\",\n    other: \"casi {{count}} años\",\n  },\n};\n\nexport const formatDistance = (token, count, options) => {\n  let result;\n\n  const tokenValue = formatDistanceLocale[token];\n  if (typeof tokenValue === \"string\") {\n    result = tokenValue;\n  } else if (count === 1) {\n    result = tokenValue.one;\n  } else {\n    result = tokenValue.other.replace(\"{{count}}\", count.toString());\n  }\n\n  if (options?.addSuffix) {\n    if (options.comparison && options.comparison > 0) {\n      return \"en \" + result;\n    } else {\n      return \"hace \" + result;\n    }\n  }\n\n  return result;\n};\n","import { buildFormatLongFn } from \"../../_lib/buildFormatLongFn.js\";\n\nconst dateFormats = {\n  full: \"EEEE, d 'de' MMMM 'de' y\",\n  long: \"d 'de' MMMM 'de' y\",\n  medium: \"d MMM y\",\n  short: \"dd/MM/y\",\n};\n\nconst timeFormats = {\n  full: \"HH:mm:ss zzzz\",\n  long: \"HH:mm:ss z\",\n  medium: \"HH:mm:ss\",\n  short: \"HH:mm\",\n};\n\nconst dateTimeFormats = {\n  full: \"{{date}} 'a las' {{time}}\",\n  long: \"{{date}} 'a las' {{time}}\",\n  medium: \"{{date}}, {{time}}\",\n  short: \"{{date}}, {{time}}\",\n};\n\nexport const formatLong = {\n  date: buildFormatLongFn({\n    formats: dateFormats,\n    defaultWidth: \"full\",\n  }),\n\n  time: buildFormatLongFn({\n    formats: timeFormats,\n    defaultWidth: \"full\",\n  }),\n\n  dateTime: buildFormatLongFn({\n    formats: dateTimeFormats,\n    defaultWidth: \"full\",\n  }),\n};\n","const formatRelativeLocale = {\n  lastWeek: \"'el' eeee 'pasado a la' p\",\n  yesterday: \"'ayer a la' p\",\n  today: \"'hoy a la' p\",\n  tomorrow: \"'mañana a la' p\",\n  nextWeek: \"eeee 'a la' p\",\n  other: \"P\",\n};\n\nconst formatRelativeLocalePlural = {\n  lastWeek: \"'el' eeee 'pasado a las' p\",\n  yesterday: \"'ayer a las' p\",\n  today: \"'hoy a las' p\",\n  tomorrow: \"'mañana a las' p\",\n  nextWeek: \"eeee 'a las' p\",\n  other: \"P\",\n};\n\nexport const formatRelative = (token, date, _baseDate, _options) => {\n  if (date.getHours() !== 1) {\n    return formatRelativeLocalePlural[token];\n  } else {\n    return formatRelativeLocale[token];\n  }\n};\n","import { buildLocalizeFn } from \"../../_lib/buildLocalizeFn.js\";\n\nconst eraValues = {\n  narrow: [\"AC\", \"DC\"],\n  abbreviated: [\"AC\", \"DC\"],\n  wide: [\"antes de cristo\", \"después de cristo\"],\n};\n\nconst quarterValues = {\n  narrow: [\"1\", \"2\", \"3\", \"4\"],\n  abbreviated: [\"T1\", \"T2\", \"T3\", \"T4\"],\n  wide: [\"1º trimestre\", \"2º trimestre\", \"3º trimestre\", \"4º trimestre\"],\n};\n\nconst monthValues = {\n  narrow: [\"e\", \"f\", \"m\", \"a\", \"m\", \"j\", \"j\", \"a\", \"s\", \"o\", \"n\", \"d\"],\n  abbreviated: [\n    \"ene\",\n    \"feb\",\n    \"mar\",\n    \"abr\",\n    \"may\",\n    \"jun\",\n    \"jul\",\n    \"ago\",\n    \"sep\",\n    \"oct\",\n    \"nov\",\n    \"dic\",\n  ],\n\n  wide: [\n    \"enero\",\n    \"febrero\",\n    \"marzo\",\n    \"abril\",\n    \"mayo\",\n    \"junio\",\n    \"julio\",\n    \"agosto\",\n    \"septiembre\",\n    \"octubre\",\n    \"noviembre\",\n    \"diciembre\",\n  ],\n};\n\nconst dayValues = {\n  narrow: [\"d\", \"l\", \"m\", \"m\", \"j\", \"v\", \"s\"],\n  short: [\"do\", \"lu\", \"ma\", \"mi\", \"ju\", \"vi\", \"sá\"],\n  abbreviated: [\"dom\", \"lun\", \"mar\", \"mié\", \"jue\", \"vie\", \"sáb\"],\n  wide: [\n    \"domingo\",\n    \"lunes\",\n    \"martes\",\n    \"miércoles\",\n    \"jueves\",\n    \"viernes\",\n    \"sábado\",\n  ],\n};\n\nconst dayPeriodValues = {\n  narrow: {\n    am: \"a\",\n    pm: \"p\",\n    midnight: \"mn\",\n    noon: \"md\",\n    morning: \"mañana\",\n    afternoon: \"tarde\",\n    evening: \"tarde\",\n    night: \"noche\",\n  },\n  abbreviated: {\n    am: \"AM\",\n    pm: \"PM\",\n    midnight: \"medianoche\",\n    noon: \"mediodia\",\n    morning: \"mañana\",\n    afternoon: \"tarde\",\n    evening: \"tarde\",\n    night: \"noche\",\n  },\n  wide: {\n    am: \"a.m.\",\n    pm: \"p.m.\",\n    midnight: \"medianoche\",\n    noon: \"mediodia\",\n    morning: \"mañana\",\n    afternoon: \"tarde\",\n    evening: \"tarde\",\n    night: \"noche\",\n  },\n};\n\nconst formattingDayPeriodValues = {\n  narrow: {\n    am: \"a\",\n    pm: \"p\",\n    midnight: \"mn\",\n    noon: \"md\",\n    morning: \"de la mañana\",\n    afternoon: \"de la tarde\",\n    evening: \"de la tarde\",\n    night: \"de la noche\",\n  },\n  abbreviated: {\n    am: \"AM\",\n    pm: \"PM\",\n    midnight: \"medianoche\",\n    noon: \"mediodia\",\n    morning: \"de la mañana\",\n    afternoon: \"de la tarde\",\n    evening: \"de la tarde\",\n    night: \"de la noche\",\n  },\n  wide: {\n    am: \"a.m.\",\n    pm: \"p.m.\",\n    midnight: \"medianoche\",\n    noon: \"mediodia\",\n    morning: \"de la mañana\",\n    afternoon: \"de la tarde\",\n    evening: \"de la tarde\",\n    night: \"de la noche\",\n  },\n};\n\nconst ordinalNumber = (dirtyNumber, _options) => {\n  const number = Number(dirtyNumber);\n  return number + \"º\";\n};\n\nexport const localize = {\n  ordinalNumber: ordinalNumber,\n\n  era: buildLocalizeFn({\n    values: eraValues,\n    defaultWidth: \"wide\",\n  }),\n\n  quarter: buildLocalizeFn({\n    values: quarterValues,\n    defaultWidth: \"wide\",\n    argumentCallback: (quarter) => Number(quarter) - 1,\n  }),\n\n  month: buildLocalizeFn({\n    values: monthValues,\n    defaultWidth: \"wide\",\n  }),\n\n  day: buildLocalizeFn({\n    values: dayValues,\n    defaultWidth: \"wide\",\n  }),\n\n  dayPeriod: buildLocalizeFn({\n    values: dayPeriodValues,\n    defaultWidth: \"wide\",\n    formattingValues: formattingDayPeriodValues,\n    defaultFormattingWidth: \"wide\",\n  }),\n};\n","import { buildMatchPatternFn } from \"../../_lib/buildMatchPatternFn.js\";\nimport { buildMatchFn } from \"../../_lib/buildMatchFn.js\";\n\nconst matchOrdinalNumberPattern = /^(\\d+)(º)?/i;\nconst parseOrdinalNumberPattern = /\\d+/i;\n\nconst matchEraPatterns = {\n  narrow: /^(ac|dc|a|d)/i,\n  abbreviated: /^(a\\.?\\s?c\\.?|a\\.?\\s?e\\.?\\s?c\\.?|d\\.?\\s?c\\.?|e\\.?\\s?c\\.?)/i,\n  wide: /^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i,\n};\nconst parseEraPatterns = {\n  any: [/^ac/i, /^dc/i],\n  wide: [\n    /^(antes de cristo|antes de la era com[uú]n)/i,\n    /^(despu[eé]s de cristo|era com[uú]n)/i,\n  ],\n};\n\nconst matchQuarterPatterns = {\n  narrow: /^[1234]/i,\n  abbreviated: /^T[1234]/i,\n  wide: /^[1234](º)? trimestre/i,\n};\nconst parseQuarterPatterns = {\n  any: [/1/i, /2/i, /3/i, /4/i],\n};\n\nconst matchMonthPatterns = {\n  narrow: /^[efmajsond]/i,\n  abbreviated: /^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,\n  wide: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,\n};\nconst parseMonthPatterns = {\n  narrow: [\n    /^e/i,\n    /^f/i,\n    /^m/i,\n    /^a/i,\n    /^m/i,\n    /^j/i,\n    /^j/i,\n    /^a/i,\n    /^s/i,\n    /^o/i,\n    /^n/i,\n    /^d/i,\n  ],\n\n  any: [\n    /^en/i,\n    /^feb/i,\n    /^mar/i,\n    /^abr/i,\n    /^may/i,\n    /^jun/i,\n    /^jul/i,\n    /^ago/i,\n    /^sep/i,\n    /^oct/i,\n    /^nov/i,\n    /^dic/i,\n  ],\n};\n\nconst matchDayPatterns = {\n  narrow: /^[dlmjvs]/i,\n  short: /^(do|lu|ma|mi|ju|vi|s[áa])/i,\n  abbreviated: /^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,\n  wide: /^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i,\n};\nconst parseDayPatterns = {\n  narrow: [/^d/i, /^l/i, /^m/i, /^m/i, /^j/i, /^v/i, /^s/i],\n  any: [/^do/i, /^lu/i, /^ma/i, /^mi/i, /^ju/i, /^vi/i, /^sa/i],\n};\n\nconst matchDayPeriodPatterns = {\n  narrow: /^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,\n  any: /^([ap]\\.?\\s?m\\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i,\n};\nconst parseDayPeriodPatterns = {\n  any: {\n    am: /^a/i,\n    pm: /^p/i,\n    midnight: /^mn/i,\n    noon: /^md/i,\n    morning: /mañana/i,\n    afternoon: /tarde/i,\n    evening: /tarde/i,\n    night: /noche/i,\n  },\n};\n\nexport const match = {\n  ordinalNumber: buildMatchPatternFn({\n    matchPattern: matchOrdinalNumberPattern,\n    parsePattern: parseOrdinalNumberPattern,\n    valueCallback: function (value) {\n      return parseInt(value, 10);\n    },\n  }),\n\n  era: buildMatchFn({\n    matchPatterns: matchEraPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseEraPatterns,\n    defaultParseWidth: \"any\",\n  }),\n\n  quarter: buildMatchFn({\n    matchPatterns: matchQuarterPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseQuarterPatterns,\n    defaultParseWidth: \"any\",\n    valueCallback: (index) => index + 1,\n  }),\n\n  month: buildMatchFn({\n    matchPatterns: matchMonthPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseMonthPatterns,\n    defaultParseWidth: \"any\",\n  }),\n\n  day: buildMatchFn({\n    matchPatterns: matchDayPatterns,\n    defaultMatchWidth: \"wide\",\n    parsePatterns: parseDayPatterns,\n    defaultParseWidth: \"any\",\n  }),\n\n  dayPeriod: buildMatchFn({\n    matchPatterns: matchDayPeriodPatterns,\n    defaultMatchWidth: \"any\",\n    parsePatterns: parseDayPeriodPatterns,\n    defaultParseWidth: \"any\",\n  }),\n};\n","import { formatDistance } from \"./es/_lib/formatDistance.js\";\nimport { formatLong } from \"./es/_lib/formatLong.js\";\nimport { formatRelative } from \"./es/_lib/formatRelative.js\";\nimport { localize } from \"./es/_lib/localize.js\";\nimport { match } from \"./es/_lib/match.js\";\n\n/**\n * @category Locales\n * @summary Spanish locale.\n * @language Spanish\n * @iso-639-2 spa\n * @author Juan Angosto [@juanangosto](https://github.com/juanangosto)\n * @author Guillermo Grau [@guigrpa](https://github.com/guigrpa)\n * @author Fernando Agüero [@fjaguero](https://github.com/fjaguero)\n * @author Gastón Haro [@harogaston](https://github.com/harogaston)\n * @author Yago Carballo [@YagoCarballo](https://github.com/YagoCarballo)\n */\nexport const es = {\n  code: \"es\",\n  formatDistance: formatDistance,\n  formatLong: formatLong,\n  formatRelative: formatRelative,\n  localize: localize,\n  match: match,\n  options: {\n    weekStartsOn: 1 /* Monday */,\n    firstWeekContainsDate: 1,\n  },\n};\n\n// Fallback for modularized imports:\nexport default es;\n","import { format } from 'date-fns';\nimport { es } from 'date-fns/locale';\n\n/**\n * Formato VISIBLE de un timestamp de auditoría: fecha, hora de 12 h con AM/PM y segundos.\n * Ejemplo: \"17/09/2026 10:50:45 AM\".\n *\n * Nunca tiempo relativo (\"hace un minuto\"): dos eventos del mismo minuto deben seguir siendo\n * distinguibles, y para eso bastan los SEGUNDOS. Hasta aquí se pintaban además las centésimas\n * (`15:10:23.45`), que no distinguen nada que los segundos no distingan ya y añaden dos dígitos\n * de ruido a cada tarjeta del historial. La precisión no se pierde: sigue entera en el `title`\n * que devuelve `formatAuditTimestampExact`, que es el sitio natural para el dato forense.\n *\n * `a` con el locale `es` de date-fns rinde «AM»/«PM» en mayúsculas (verificado, no asumido).\n */\nexport function formatAuditTimestamp(isoTimestamp: string): string {\n  return format(new Date(isoTimestamp), 'dd/MM/yyyy hh:mm:ss a', { locale: es });\n}\n\n/**\n * Formato EXACTO para el `title` (tooltip): todo lo anterior más las centésimas.\n * Ejemplo: \"17/09/2026 10:50:45.77 AM\".\n *\n * Aquí sí se conservan las centésimas: el tooltip es donde se va a mirar cuando dos entradas\n * caen en el mismo segundo y hay que desempatarlas.\n */\nexport function formatAuditTimestampExact(isoTimestamp: string): string {\n  return format(new Date(isoTimestamp), 'dd/MM/yyyy hh:mm:ss.SS a', { locale: es });\n}\n","import React from 'react';\nimport { formatAuditTimestamp, formatAuditTimestampExact } from '../utils/formatAuditTimestamp';\nimport type { AuditTimestampProps } from './AuditTimestamp.types';\n\n/**\n * Muestra un timestamp de auditoría con fecha y hora de 12 h: \"17/09/2026 10:50:45 AM\".\n * El hover añade las centésimas vía atributo `title`, para desempatar dos entradas del\n * mismo segundo sin ensuciar la lectura.\n */\nexport const AuditTimestamp: React.FC<AuditTimestampProps> = ({ timestamp, size = 'sm', className = '' }) => {\n  // Tokens del sistema en vez de `slate-500`, que era el único color crudo de todo el panel de\n  // auditoría: el resto ya iba por `content-*` y por eso la fecha desentonaba en oscuro.\n  const classes = [\n    size === 'xs' ? 'text-xs' : 'text-sm',\n    'text-content-secondary dark:text-dark-content-secondary tabular-nums',\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <time dateTime={timestamp} title={formatAuditTimestampExact(timestamp)} className={classes}>\n      {formatAuditTimestamp(timestamp)}\n    </time>\n  );\n};\n\nAuditTimestamp.displayName = 'AuditTimestamp';\n","import React, { useRef, useCallback } from 'react';\nimport Skeleton from 'react-loading-skeleton';\nimport 'react-loading-skeleton/dist/skeleton.css';\nimport { Badge } from '../../components/Badge/Badge';\nimport { Card } from '../../components/Card';\nimport { AuditTimestamp } from './AuditTimestamp';\nimport type { AuditTimelineProps } from './AuditTimeline.types';\nimport type { AuditHistoryItem } from '../types/audit.types';\n\nconst MAX_FIELDS_PREVIEW = 3;\n\n/**\n * `fieldsLabel` rotula la lista de campos de la tarjeta. Sin él, la tercera línea era un\n * «Estado» suelto: el usuario veía un sustantivo sin saber si era el estado de la entrada, un\n * campo, o el nombre del registro. El rótulo va por ACCIÓN porque no significan lo mismo — en un\n * alta los campos son los INICIALES, no unos «modificados».\n */\nconst ACTION_CONFIG: Record<\n  AuditHistoryItem['action'],\n  { color: 'green' | 'amber' | 'red'; label: string; fieldsLabel: string }\n> = {\n  Created: { color: 'green', label: 'Creado', fieldsLabel: 'Campos iniciales' },\n  Modified: { color: 'amber', label: 'Actualizado', fieldsLabel: 'Campos modificados' },\n  Deleted: { color: 'red', label: 'Eliminado', fieldsLabel: 'Campos afectados' },\n};\n\nfunction groupByDate(entries: AuditHistoryItem[]): Array<{ dateLabel: string; entries: AuditHistoryItem[] }> {\n  const groups = new Map<string, AuditHistoryItem[]>();\n  for (const entry of entries) {\n    const date = new Date(entry.timestamp);\n    const today = new Date();\n    const yesterday = new Date(today);\n    yesterday.setDate(today.getDate() - 1);\n\n    let label: string;\n    if (date.toDateString() === today.toDateString()) {\n      label = 'Hoy';\n    } else if (date.toDateString() === yesterday.toDateString()) {\n      label = 'Ayer';\n    } else {\n      label = date.toLocaleDateString('es', { day: '2-digit', month: '2-digit', year: 'numeric' });\n    }\n\n    if (!groups.has(label)) groups.set(label, []);\n    groups.get(label)!.push(entry);\n  }\n  return Array.from(groups.entries()).map(([dateLabel, entries]) => ({ dateLabel, entries }));\n}\n\nconst SkeletonCard: React.FC = () => (\n  <Card className=\"gap-0 rounded-lg px-3 py-3\">\n    <div className=\"flex items-center gap-2 mb-2\">\n      <Skeleton width={64} height={20} borderRadius={4} />\n      <Skeleton width={100} height={14} />\n    </div>\n    <Skeleton width={80} height={12} className=\"mb-1\" />\n    <Skeleton width={140} height={12} />\n  </Card>\n);\n\ninterface TimelineCardProps {\n  entry: AuditHistoryItem;\n  selected: boolean;\n  onSelect: (id: string) => void;\n}\n\nconst TimelineCard: React.FC<TimelineCardProps> = ({ entry, selected, onSelect }) => {\n  const { color, label, fieldsLabel } = ACTION_CONFIG[entry.action];\n  const previewFields = entry.changedFields.slice(0, MAX_FIELDS_PREVIEW);\n  const extraCount = entry.changedFields.length - MAX_FIELDS_PREVIEW;\n\n  const cardClasses = [\n    'gap-0 rounded-lg px-3 py-3 cursor-pointer',\n    'focus:outline-none focus:ring-2 focus:ring-primary-500',\n    'transition-all duration-100',\n    selected\n      ? 'border-primary-500 ring-1 ring-primary-500 bg-[#f7fcff] dark:border-primary-600 dark:bg-primary-900/20'\n      : 'hover:border-primary-300 dark:hover:border-primary-700',\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  const handleKeyDown = (e: React.KeyboardEvent) => {\n    if (e.key === 'Enter' || e.key === ' ') {\n      e.preventDefault();\n      onSelect(entry.id);\n    }\n  };\n\n  const handleClick = () => {\n    // Un click-drag para seleccionar/copiar texto de la tarjeta también dispara este\n    // \"click\" al soltar el mouse. Si el usuario dejó una selección de texto activa,\n    // es que quería copiar, no cambiar la entrada seleccionada del historial.\n    const selection = window.getSelection?.();\n    if (selection && selection.toString().length > 0) return;\n    onSelect(entry.id);\n  };\n\n  return (\n    <Card\n      role=\"listitem\"\n      aria-selected={selected}\n      tabIndex={0}\n      className={cardClasses}\n      onClick={handleClick}\n      onKeyDown={handleKeyDown}\n    >\n      {/* Jerarquía de la tarjeta, de mayor a menor: QUIÉN · CUÁNDO · QUÉ. Las tres líneas\n          comparten el mismo margen inferior (`mb-1`) para que el ritmo vertical sea constante;\n          antes la fecha compartía tamaño (`text-sm`) con el actor y las dos competían. */}\n      <div className=\"flex items-center gap-2 mb-1\">\n        <Badge color={color} label={label} aria-label={`Acción: ${label}`} />\n        <span className=\"min-w-0 flex-1 text-sm font-medium text-content-primary dark:text-dark-content-primary truncate\">\n          {entry.actorFullName}\n        </span>\n      </div>\n      <AuditTimestamp timestamp={entry.timestamp} size=\"xs\" className=\"block mb-1\" />\n      {previewFields.length > 0 && (\n        <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary truncate\">\n          <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">{fieldsLabel}: </span>\n          {previewFields.join(', ')}\n          {extraCount > 0 && (\n            <span className=\"text-content-tertiary dark:text-dark-content-tertiary\"> +{extraCount} más</span>\n          )}\n        </p>\n      )}\n    </Card>\n  );\n};\n\n// ===== Paginador estilo MasterCrud (nav interno de la tabla del kit) =====\n// Iconos (lucide, mismos paths que el paginador de la tabla del kit).\nconst ChevronLeftIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m15 18-6-6 6-6\" /></svg>\n);\nconst ChevronRightIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m9 18 6-6-6-6\" /></svg>\n);\nconst ChevronsLeftIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m11 17-5-5 5-5\" /><path d=\"m18 17-5-5 5-5\" /></svg>\n);\nconst ChevronsRightIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m6 17 5-5-5-5\" /><path d=\"m13 17 5-5-5-5\" /></svg>\n);\n\nconst navIconBtnCls =\n  'inline-flex items-center justify-center w-8 h-8 rounded-md cursor-pointer text-primary-600 dark:text-primary-600 hover:bg-primary-100 dark:hover:bg-primary-900/20 active:scale-95 transition-all duration-150 disabled:opacity-40 disabled:cursor-not-allowed';\nconst navNumBtnCls = (active: boolean) =>\n  [\n    'inline-flex items-center justify-center min-w-8 h-8 px-3 rounded-md cursor-pointer text-sm font-bold transition-all duration-150',\n    active\n      ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-600'\n      : 'text-primary-600 dark:text-primary-600 hover:bg-primary-100 dark:hover:bg-primary-900/20 active:scale-95',\n  ].join(' ');\n\n// Ventana de números idéntica a la del paginador de la tabla: hasta 3 páginas se muestran\n// todas; con más, una ventana de 2 números (primera/última las cubren los chevrones dobles).\nfunction getTimelinePageNumbers(currentPage: number, totalPages: number): number[] {\n  if (totalPages <= 3) return Array.from({ length: totalPages }, (_, i) => i + 1);\n  const start = Math.min(Math.max(currentPage, 1), totalPages - 1);\n  return [start, start + 1];\n}\n\ninterface TimelinePaginationProps {\n  currentPage: number;\n  totalPages: number;\n  onPageChange: (page: number) => void;\n}\n\nconst TimelinePagination: React.FC<TimelinePaginationProps> = ({ currentPage, totalPages, onPageChange }) => (\n  <nav className=\"flex items-center justify-center gap-0.5\" aria-label=\"Navegación de páginas del historial\">\n    <button type=\"button\" aria-label=\"Primera página\" onClick={() => currentPage > 1 && onPageChange(1)} disabled={currentPage === 1} className={navIconBtnCls}>\n      <ChevronsLeftIcon />\n    </button>\n    <button type=\"button\" aria-label=\"Página anterior\" onClick={() => currentPage > 1 && onPageChange(currentPage - 1)} disabled={currentPage === 1} className={navIconBtnCls}>\n      <ChevronLeftIcon />\n    </button>\n    {getTimelinePageNumbers(currentPage, totalPages).map((p) => (\n      <button\n        key={p}\n        type=\"button\"\n        onClick={() => onPageChange(p)}\n        aria-current={p === currentPage ? 'page' : undefined}\n        className={navNumBtnCls(p === currentPage)}\n      >\n        {p}\n      </button>\n    ))}\n    <button type=\"button\" aria-label=\"Página siguiente\" onClick={() => currentPage < totalPages && onPageChange(currentPage + 1)} disabled={currentPage === totalPages} className={navIconBtnCls}>\n      <ChevronRightIcon />\n    </button>\n    <button type=\"button\" aria-label=\"Última página\" onClick={() => currentPage < totalPages && onPageChange(totalPages)} disabled={currentPage === totalPages} className={navIconBtnCls}>\n      <ChevronsRightIcon />\n    </button>\n  </nav>\n);\n\n/**\n * Panel izquierdo del split view: lista cronológica de entradas de auditoría\n * con separadores de fecha, skeleton de carga y paginación.\n */\nexport const AuditTimeline: React.FC<AuditTimelineProps> = ({\n  entries,\n  selectedId,\n  onSelect,\n  isLoading = false,\n  totalCount,\n  page,\n  pageSize,\n  onPageChange,\n  className = '',\n}) => {\n  const listRef = useRef<HTMLDivElement>(null);\n  const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));\n\n  const containerClasses = ['flex flex-col h-full', className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  const handleKeyDown = useCallback(\n    (e: React.KeyboardEvent) => {\n      if (!entries.length) return;\n      const currentIndex = entries.findIndex((en) => en.id === selectedId);\n      if (e.key === 'ArrowDown') {\n        e.preventDefault();\n        const next = entries[Math.min(currentIndex + 1, entries.length - 1)];\n        if (next) onSelect(next.id);\n      } else if (e.key === 'ArrowUp') {\n        e.preventDefault();\n        const prev = entries[Math.max(currentIndex - 1, 0)];\n        if (prev) onSelect(prev.id);\n      }\n    },\n    [entries, selectedId, onSelect]\n  );\n\n  return (\n    <div className={containerClasses}>\n      {/* Lista */}\n      <div\n        ref={listRef}\n        role=\"list\"\n        aria-label=\"Historial de cambios\"\n        // 16px, los MISMOS que el panel derecho (`px-4 pt-4` en su cabecera y `px-4 pb-4` en la\n        // caja de la tabla). Iban a 12 y la diferencia se notaba justo donde más: al final del\n        // scroll la última tarjeta quedaba a 12px del borde del modal mientras la tabla de al\n        // lado respiraba 16. Medido en dev el 2026-09-17 sobre el modal abierto.\n        className=\"flex-1 overflow-y-auto px-4 py-4\"\n        onKeyDown={handleKeyDown}\n      >\n        {isLoading ? (\n          <div className=\"space-y-2\">\n            {Array.from({ length: 5 }).map((_, i) => <SkeletonCard key={i} />)}\n          </div>\n        ) : entries.length === 0 ? (\n          <div\n            role=\"status\"\n            aria-live=\"polite\"\n            className=\"flex items-center justify-center h-32 text-sm text-content-tertiary dark:text-dark-content-tertiary px-4 text-center\"\n          >\n            No hay registros de auditoría para este elemento\n          </div>\n        ) : (\n          groupByDate(entries).map(({ dateLabel, entries: group }) => (\n            <React.Fragment key={dateLabel}>\n              {/* Date separator */}\n              {/* `-mx-4 px-4`: el separador es `sticky`, así que al hacer scroll las tarjetas pasan\n                  POR DEBAJO. Con el fondo acabando donde acaba el contenido, se veían asomar por\n                  los 16px laterales. Se extiende el fondo hasta el borde del scrollport. */}\n              <div className=\"flex items-center gap-2 py-2 mt-2 first:mt-0 sticky top-0 -mx-4 px-4 bg-background-secondary dark:bg-dark-bg-primary z-10\">\n                <span className=\"text-xs font-medium text-content-secondary dark:text-dark-content-secondary uppercase tracking-wide\">\n                  {dateLabel}\n                </span>\n                <div className=\"flex-1 h-px bg-border-primary dark:bg-dark-border-primary\" />\n              </div>\n              <div className=\"space-y-2\">\n                {group.map((entry) => (\n                  <TimelineCard\n                    key={entry.id}\n                    entry={entry}\n                    selected={entry.id === selectedId}\n                    onSelect={onSelect}\n                  />\n                ))}\n              </div>\n            </React.Fragment>\n          ))\n        )}\n      </div>\n\n      {/* Pagination — mismo nav (chevrones + números) que el paginador de la tabla de MasterCrud. */}\n      {!isLoading && totalPages > 1 && (\n        <div className=\"flex-shrink-0 border-t border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-primary px-4 py-2\">\n          <TimelinePagination currentPage={page} totalPages={totalPages} onPageChange={onPageChange} />\n        </div>\n      )}\n    </div>\n  );\n};\n\nAuditTimeline.displayName = 'AuditTimeline';\n","/**\n * Formatea un valor de campo de auditoría para mostrar en la UI.\n *\n * - `null`, `undefined` o string vacío → `\"(vacío)\"`\n * - `\"true\"` o `true` → `\"Sí\"`\n * - `\"false\"` o `false` → `\"No\"`\n * - cualquier otro valor → string tal cual\n */\nexport function formatAuditValue(value: string | null | undefined): string {\n  if (value === null || value === undefined || value === '') return '(vacío)';\n  if (value === 'true' || (value as unknown) === true) return 'Sí';\n  if (value === 'false' || (value as unknown) === false) return 'No';\n  return value;\n}\n\n/**\n * Retorna true si el valor formateado representa un estado vacío.\n * Útil para aplicar estilos de cursiva/muted.\n */\nexport function isEmptyAuditValue(value: string | null | undefined): boolean {\n  return value === null || value === undefined || value === '';\n}\n","import React from 'react';\nimport { Badge } from '../../components/Badge/Badge';\nimport { AuditTimestamp } from './AuditTimestamp';\nimport { formatAuditValue, isEmptyAuditValue } from '../utils/formatAuditValue';\nimport type { AuditEntryDetailProps } from './AuditEntryDetail.types';\nimport type { AuditHistoryItem } from '../types/audit.types';\n\ntype BadgeColor = 'green' | 'amber' | 'red';\n\nconst ACTION_CONFIG: Record<AuditHistoryItem['action'], { color: BadgeColor; label: string }> = {\n  Created: { color: 'green', label: 'Creado' },\n  Modified: { color: 'amber', label: 'Actualizado' },\n  Deleted: { color: 'red', label: 'Eliminado' },\n};\n\nconst Placeholder: React.FC = () => (\n  <div className=\"flex flex-col items-center justify-center h-full min-h-[200px] text-content-tertiary dark:text-dark-content-tertiary gap-3 p-8\">\n    <svg\n      xmlns=\"http://www.w3.org/2000/svg\"\n      fill=\"none\"\n      viewBox=\"0 0 24 24\"\n      strokeWidth={1.5}\n      stroke=\"currentColor\"\n      className=\"w-10 h-10 text-border-primary dark:text-dark-border-primary\"\n      aria-hidden=\"true\"\n    >\n      <path\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        d=\"M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Zm3.75 11.625a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z\"\n      />\n    </svg>\n    <p className=\"text-sm text-center\">Selecciona un registro del historial para ver los detalles</p>\n  </div>\n);\n\n/**\n * Panel derecho del split view: muestra el diff campo por campo de una entrada de auditoría.\n * Si no hay entrada seleccionada, muestra un placeholder.\n */\nexport const AuditEntryDetail: React.FC<AuditEntryDetailProps> = ({ entry, className = '' }) => {\n  const containerClasses = ['flex flex-col h-full bg-background-secondary dark:bg-dark-bg-primary', className]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  if (!entry) {\n    return (\n      <div className={containerClasses}>\n        <Placeholder />\n      </div>\n    );\n  }\n\n  const { color, label } = ACTION_CONFIG[entry.action];\n\n  return (\n    <div className={containerClasses}>\n      {/* Header — badge de acción + actor + fecha, sobre el fondo gris de la sección. */}\n      <div className=\"flex items-center gap-3 px-4 pt-4 pb-3 flex-shrink-0\">\n        <Badge color={color} label={label} aria-label={`Acción: ${label}`} />\n        {/* `min-w-0 flex-1`: dentro de un flex, un hijo no baja de su ancho de contenido, así que\n            `truncate` por sí solo no recorta — empuja a los hermanos. Con un nombre largo la fecha\n            se salía de la caja en vez de quedarse pegada a la derecha. */}\n        <span className=\"min-w-0 flex-1 text-sm font-medium text-content-primary dark:text-dark-content-primary truncate\">\n          {entry.actorFullName}\n        </span>\n        <AuditTimestamp timestamp={entry.timestamp} className=\"flex-shrink-0\" />\n      </div>\n\n      {/* Tarjeta blanca redondeada sobre el gris (padding para que se vea la diferencia),\n          con la tabla de cambios dentro. Mismo lenguaje visual que la tabla de MasterCrud:\n          banda de cabecera #f8f9fc, cabeceras semibold, filas divididas y hover azul. */}\n      <div className=\"flex-1 min-h-0 px-4 pb-4\">\n        <div className=\"h-full overflow-y-auto rounded-lg border border-border-primary dark:border-dark-border-primary bg-white dark:bg-dark-bg-primary\">\n        {entry.details.length === 0 ? (\n          <div className=\"flex items-center justify-center h-32 text-sm text-content-tertiary dark:text-dark-content-tertiary\">\n            Sin cambios de campos registrados\n          </div>\n        ) : (\n          <table className=\"w-full text-sm border-collapse\">\n            <caption className=\"sr-only\">Cambios registrados en esta entrada</caption>\n            <thead>\n              <tr className=\"sticky top-0 z-10 bg-[#f8f9fc] dark:bg-dark-bg-secondary border-b border-border-primary dark:border-dark-border-primary\">\n                <th\n                  scope=\"col\"\n                  className=\"px-4 py-2.5 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary w-1/3\"\n                >\n                  Campo\n                </th>\n                <th\n                  scope=\"col\"\n                  className=\"px-4 py-2.5 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary w-1/3\"\n                >\n                  Antes\n                </th>\n                <th\n                  scope=\"col\"\n                  className=\"px-4 py-2.5 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary w-1/3\"\n                >\n                  Después\n                </th>\n              </tr>\n            </thead>\n            <tbody>\n              {entry.details.map((detail, index) => {\n                const oldEmpty = isEmptyAuditValue(detail.oldValue);\n                const newEmpty = isEmptyAuditValue(detail.newValue);\n                const oldFormatted = formatAuditValue(detail.oldValue);\n                const newFormatted = formatAuditValue(detail.newValue);\n\n                return (\n                  <tr\n                    key={`${detail.fieldName}-${index}`}\n                    className=\"border-b border-border-secondary dark:border-dark-border-primary last:border-0 hover:bg-[#f0f7ff] dark:hover:bg-primary-900/10 transition-colors duration-150\"\n                  >\n                    <td className=\"px-4 py-2.5 font-medium text-content-primary dark:text-dark-content-primary align-top\">\n                      {detail.fieldName}\n                    </td>\n                    <td className=\"px-4 py-2.5 align-top text-red-600 dark:text-red-400\">\n                      {oldEmpty ? (\n                        <span className=\"italic text-content-tertiary dark:text-dark-content-tertiary\">{oldFormatted}</span>\n                      ) : (\n                        oldFormatted\n                      )}\n                    </td>\n                    <td className=\"px-4 py-2.5 align-top text-emerald-600 dark:text-emerald-400\">\n                      {newEmpty ? (\n                        <span className=\"italic text-content-tertiary dark:text-dark-content-tertiary\">{newFormatted}</span>\n                      ) : (\n                        newFormatted\n                      )}\n                    </td>\n                  </tr>\n                );\n              })}\n            </tbody>\n          </table>\n        )}\n        </div>\n      </div>\n    </div>\n  );\n};\n\nAuditEntryDetail.displayName = 'AuditEntryDetail';\n","import React, { useState } from 'react';\nimport { useAuditHistory } from '../hooks/useAuditHistory';\nimport { AuditTimeline } from './AuditTimeline';\nimport { AuditEntryDetail } from './AuditEntryDetail';\nimport type { AuditHistoryPanelProps } from './AuditHistoryPanel.types';\n\n/**\n * Panel de historial de auditoría con split view (B+C):\n * - Panel izquierdo: AuditTimeline con cards y paginación\n * - Panel derecho: AuditEntryDetail con diff campo por campo\n *\n * Gestiona internamente el estado via useAuditHistory.\n * Mobile (<768px): muestra un panel a la vez con botón \"Volver\".\n */\nexport const AuditHistoryPanel: React.FC<AuditHistoryPanelProps> = ({\n  fetchFn,\n  entityId,\n  pageSize = 20,\n  className = '',\n}) => {\n  const [mobileShowDetail, setMobileShowDetail] = useState(false);\n  const { data, isLoading, isError, page, setPage, selectedEntryId, setSelectedEntryId, selectedEntry } =\n    useAuditHistory({ fetchFn, entityId, pageSize });\n\n  const handleSelect = (id: string) => {\n    setSelectedEntryId(id);\n    setMobileShowDetail(true);\n  };\n\n  const containerClasses = [\n    'flex h-full max-h-[70vh] overflow-hidden',\n    'bg-background-secondary dark:bg-dark-bg-primary',\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  if (isError) {\n    return (\n      <div\n        role=\"alert\"\n        aria-live=\"assertive\"\n        className=\"flex flex-col items-center justify-center h-48 gap-2 text-content-secondary dark:text-dark-content-secondary\"\n      >\n        <svg\n          xmlns=\"http://www.w3.org/2000/svg\"\n          fill=\"none\"\n          viewBox=\"0 0 24 24\"\n          strokeWidth={1.5}\n          stroke=\"currentColor\"\n          className=\"w-8 h-8 text-red-400\"\n          aria-hidden=\"true\"\n        >\n          <path\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            d=\"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z\"\n          />\n        </svg>\n        <p className=\"text-sm\">Error al cargar el historial. Intenta de nuevo.</p>\n      </div>\n    );\n  }\n\n  return (\n    <div className={containerClasses}>\n      {/* Panel izquierdo — Timeline (oculto en mobile cuando se ve detalle) */}\n      <div\n        className={[\n          'w-80 flex-shrink-0 border-r border-border-primary dark:border-dark-border-primary',\n          mobileShowDetail ? 'hidden md:flex md:flex-col' : 'flex flex-col',\n        ].join(' ')}\n      >\n        <AuditTimeline\n          entries={data?.items ?? []}\n          selectedId={selectedEntryId}\n          onSelect={handleSelect}\n          isLoading={isLoading}\n          totalCount={data?.totalCount ?? 0}\n          page={page}\n          pageSize={pageSize}\n          onPageChange={setPage}\n          className=\"flex-1\"\n        />\n      </div>\n\n      {/* Panel derecho — Detail (oculto en mobile cuando se ve timeline) */}\n      <div\n        className={[\n          'flex-1 flex flex-col overflow-hidden',\n          !mobileShowDetail ? 'hidden md:flex' : 'flex',\n        ].join(' ')}\n      >\n        {/* Mobile back button */}\n        {mobileShowDetail && (\n          <button\n            className=\"flex items-center gap-1 px-4 py-2 text-sm text-primary-600 dark:text-primary-500 border-b border-border-primary dark:border-dark-border-primary md:hidden hover:bg-background-secondary dark:hover:bg-dark-bg-secondary\"\n            onClick={() => setMobileShowDetail(false)}\n            type=\"button\"\n          >\n            <svg\n              xmlns=\"http://www.w3.org/2000/svg\"\n              fill=\"none\"\n              viewBox=\"0 0 24 24\"\n              strokeWidth={2}\n              stroke=\"currentColor\"\n              className=\"w-4 h-4\"\n              aria-hidden=\"true\"\n            >\n              <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M15.75 19.5 8.25 12l7.5-7.5\" />\n            </svg>\n            Volver al historial\n          </button>\n        )}\n\n        <div className=\"flex-1 overflow-y-auto\">\n          <AuditEntryDetail entry={selectedEntry} />\n        </div>\n      </div>\n    </div>\n  );\n};\n\nAuditHistoryPanel.displayName = 'AuditHistoryPanel';\n","const createStoreImpl = (createState) => {\n  let state;\n  const listeners = /* @__PURE__ */ new Set();\n  const setState = (partial, replace) => {\n    const nextState = typeof partial === \"function\" ? partial(state) : partial;\n    if (!Object.is(nextState, state)) {\n      const previousState = state;\n      state = (replace != null ? replace : typeof nextState !== \"object\" || nextState === null) ? nextState : Object.assign({}, state, nextState);\n      listeners.forEach((listener) => listener(state, previousState));\n    }\n  };\n  const getState = () => state;\n  const getInitialState = () => initialState;\n  const subscribe = (listener) => {\n    listeners.add(listener);\n    return () => listeners.delete(listener);\n  };\n  const api = { setState, getState, getInitialState, subscribe };\n  const initialState = state = createState(setState, getState, api);\n  return api;\n};\nconst createStore = ((createState) => createState ? createStoreImpl(createState) : createStoreImpl);\n\nexport { createStore };\n","/**\n * List slice for the MasterView store.\n *\n * Manages search params, data, loading state, and selection.\n *\n * @internal\n * @module store/slices/listSlice\n */\nimport type { StateCreator } from 'zustand';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterViewState, ListState, SearchParams, ActiveFilter } from '../types';\n\nexport const DEFAULT_SEARCH_PARAMS: SearchParams = {\n  page: 1,\n  pageSize: 20,\n  search: '',\n  sortBy: '',\n  sortOrder: 'asc',\n  filters: [],\n};\n\nexport const createListSlice = <T extends MasterPatternViewEntity>(\n  initialPageSize?: number,\n): StateCreator<\n  MasterViewState<T>,\n  [],\n  [],\n  ListState<T>\n> => (set) => ({\n  searchParams: { ...DEFAULT_SEARCH_PARAMS, ...(initialPageSize ? { pageSize: initialPageSize } : {}) },\n  columnFilters: [],\n  quickFilterValues: {},\n  data: [],\n  total: 0,\n  isLoading: false,\n  selectedIds: [],\n  hasSearched: false,\n\n  setSearchParams: (params: Partial<SearchParams>) =>\n    set((state) => ({\n      searchParams: { ...state.searchParams, ...params },\n    })),\n\n  setColumnFilters: (filters: ActiveFilter[]) =>\n    set({ columnFilters: filters }),\n\n  clearColumnFilters: () =>\n    set({ columnFilters: [] }),\n\n  setQuickFilterValues: (values: Record<string, string>) =>\n    set({ quickFilterValues: values }),\n\n  clearQuickFilters: () =>\n    set({ quickFilterValues: {} }),\n\n  setData: (data: T[], total: number) =>\n    set({ data, total }),\n\n  setIsLoading: (isLoading: boolean) =>\n    set({ isLoading }),\n\n  toggleSelection: (id: string) =>\n    set((state) => ({\n      selectedIds: state.selectedIds.includes(id)\n        ? state.selectedIds.filter((selectedId) => selectedId !== id)\n        : [...state.selectedIds, id],\n    })),\n\n  clearSelection: () =>\n    set({ selectedIds: [] }),\n\n  setHasSearched: (hasSearched: boolean) =>\n    set({ hasSearched }),\n});\n","/**\n * Field Engine — Pure functions for deriving UI descriptors from field definitions.\n *\n * All functions are pure (no React hooks, no side effects).\n * `code` and `name` fields are ALWAYS sortable regardless of the `sortable` flag.\n *\n * @module fieldEngine\n * @see FMPV-MVWC-E001-S004\n */\n\nimport type {\n  MasterPatternViewDefinition,\n  MasterPatternViewFieldDefinition,\n  MasterPatternViewInputType,\n  MasterPatternViewLookupConfig,\n  FilterOperator,\n  SelectOption,\n} from '../types';\n\n/**\n * Returns the flat list of all field definitions from a definition object.\n *\n * Handles both shapes:\n *  - `sections` present → flattens all section fields into one array\n *  - `fields` present   → returns it directly (backward compat)\n *\n * Use this everywhere instead of `definition.fields` directly.\n */\nexport function getAllFields(\n  definition: MasterPatternViewDefinition,\n): MasterPatternViewFieldDefinition[] {\n  if (definition.sections) {\n    return definition.sections.flatMap((s) => s.fields);\n  }\n  return definition.fields ?? [];\n}\n\n// ----- Descriptor Types -----\n\nexport interface ListColumnDescriptor {\n  fieldName: string;\n  label: string;\n  dataType: string;\n  sortable: boolean;\n  inputType: MasterPatternViewInputType;\n}\n\nexport interface FormInputDescriptor {\n  fieldName: string;\n  label: string;\n  inputType: MasterPatternViewInputType;\n  isRequired: boolean;\n  maxLength?: number;\n  colSize?: number | { sm?: number; md?: number; lg?: number };\n  options?: SelectOption[];\n  lookupConfig?: MasterPatternViewLookupConfig;\n}\n\nexport interface FilterControlDescriptor {\n  fieldName: string;\n  label: string;\n  dataType: string;\n  inputType: MasterPatternViewInputType;\n  filterOperator: FilterOperator;\n}\n\nexport interface QuickFilterDescriptor {\n  fieldName: string;\n  label: string;\n  inputType: MasterPatternViewInputType;\n}\n\nexport interface SortableFieldDescriptor {\n  fieldName: string;\n  label: string;\n}\n\n// ----- Input Type Inference -----\n\nconst DATA_TYPE_TO_INPUT: Record<string, MasterPatternViewInputType> = {\n  string: 'text',\n  number: 'number',\n  decimal: 'decimal',\n  boolean: 'boolean',\n  date: 'date',\n  guid: 'text',\n  file: 'file',\n};\n\n/** Always-sortable field names (code and name per project invariant). */\nconst ALWAYS_SORTABLE = new Set(['code', 'name']);\n\n/** Maximum number of quick filters. */\nconst MAX_QUICK_FILTERS = 3;\n\nconst COL_SPAN_MAP: Record<number, string> = {\n  1: 'col-span-1', 2: 'col-span-2', 3: 'col-span-3', 4: 'col-span-4',\n  5: 'col-span-5', 6: 'col-span-6', 7: 'col-span-7', 8: 'col-span-8',\n  9: 'col-span-9', 10: 'col-span-10', 11: 'col-span-11', 12: 'col-span-12',\n};\n\n/**\n * Resolves the Tailwind col-span class for a field based on its colSize definition.\n * Respects responsive colSize objects (uses md breakpoint, then lg, then sm).\n * Defaults to col-span-12 for textarea, col-span-6 for everything else.\n */\nexport function computeColSpanClass(\n  field: Pick<MasterPatternViewFieldDefinition, 'colSize' | 'inputType' | 'dataType'>\n): string {\n  const inputType = field.inputType ?? inferInputType(field);\n  const rawColSize = field.colSize;\n  const colSizeNum: number =\n    typeof rawColSize === 'object' && rawColSize !== null\n      ? (rawColSize.md ?? rawColSize.lg ?? rawColSize.sm ?? (inputType === 'textarea' ? 12 : 6))\n      : ((rawColSize as number | undefined) ?? (inputType === 'textarea' ? 12 : 6));\n  return COL_SPAN_MAP[colSizeNum] ?? 'col-span-6';\n}\n\n/**\n * Resolves the input type for a field.\n * If `inputType` is explicitly set, returns it. Otherwise infers from `dataType`.\n */\nexport function inferInputType(\n  field: Pick<MasterPatternViewFieldDefinition, 'dataType' | 'inputType'>\n): MasterPatternViewInputType {\n  if (field.inputType) {\n    return field.inputType;\n  }\n  return DATA_TYPE_TO_INPUT[field.dataType] ?? 'text';\n}\n\n/**\n * Validates field definitions for mutual exclusivity violations.\n * Warns when `isOverridable` and `isCompanyOnly` are both `true` on the same field.\n * Per PRD §4.3 these flags are mutually exclusive.\n */\nexport function validateFieldDefinitions(\n  fields: MasterPatternViewFieldDefinition[]\n): void {\n  for (const field of fields) {\n    if (field.isOverridable === true && field.isCompanyOnly === true) {\n      console.warn(\n        `[MasterPatternView] Field \"${field.fieldName}\" has both isOverridable and isCompanyOnly set to true. ` +\n          `These are mutually exclusive (PRD §4.3). isCompanyOnly will take precedence.`\n      );\n    }\n  }\n}\n\n/**\n * Derives list column descriptors from field definitions.\n * Only includes fields with `showInList: true`.\n * Column order: explicit `listOrder` if any field defines it; otherwise preserves array declaration order.\n * `code` and `name` are always sortable.\n */\nexport function deriveListColumns(\n  fields: MasterPatternViewFieldDefinition[]\n): ListColumnDescriptor[] {\n  const listFields = fields.filter((f) => f.showInList === true);\n  const hasExplicitOrder = listFields.some((f) => f.listOrder !== undefined);\n  if (hasExplicitOrder) {\n    listFields.sort((a, b) => (a.listOrder ?? Infinity) - (b.listOrder ?? Infinity));\n  }\n  return listFields\n    .map((f) => ({\n      fieldName: f.fieldName,\n      label: f.label,\n      dataType: f.dataType,\n      sortable: ALWAYS_SORTABLE.has(f.fieldName) || f.sortable === true,\n      inputType: inferInputType(f),\n    }));\n}\n\n/**\n * Derives form input descriptors from field definitions.\n * Only includes fields with `showInForm: true`, optionally filtered by tab.\n * Field order within each section is controlled by `formOrder` (independent of `listOrder`).\n */\nexport function deriveFormInputs(\n  fields: MasterPatternViewFieldDefinition[],\n  tab?: string\n): FormInputDescriptor[] {\n  return fields\n    .filter((f) => {\n      if (f.showInForm !== true) return false;\n      if (tab !== undefined && f.formTab !== tab) return false;\n      return true;\n    })\n    .sort((a, b) => (a.formOrder ?? Infinity) - (b.formOrder ?? Infinity))\n    .map((f) => ({\n      fieldName: f.fieldName,\n      label: f.label,\n      inputType: inferInputType(f),\n      isRequired: f.isRequired === true,\n      maxLength: f.maxLength,\n      colSize: f.colSize,\n      options: f.options,\n      lookupConfig: f.lookupConfig,\n    }));\n}\n\n/**\n * Derives filter control descriptors from field definitions.\n * Only includes fields with `filterable: true`.\n */\nexport function deriveFilterControls(\n  fields: MasterPatternViewFieldDefinition[]\n): FilterControlDescriptor[] {\n  return fields\n    .filter((f) => f.filterable === true)\n    .map((f) => ({\n      fieldName: f.fieldName,\n      label: f.label,\n      dataType: f.dataType,\n      inputType: inferInputType(f),\n      filterOperator: getDefaultFilterOperator(f.dataType),\n    }));\n}\n\n/**\n * Derives quick filter descriptors (max 3) from field definitions.\n * Only includes fields with `quickFilter: true`.\n */\nexport function deriveQuickFilters(\n  fields: MasterPatternViewFieldDefinition[]\n): QuickFilterDescriptor[] {\n  return fields\n    .filter((f) => f.quickFilter === true)\n    .slice(0, MAX_QUICK_FILTERS)\n    .map((f) => ({\n      fieldName: f.fieldName,\n      label: f.label,\n      inputType: inferInputType(f),\n    }));\n}\n\n/**\n * Derives all sortable fields, always including `code` and `name`.\n * Used by the SortDropdown component.\n */\nexport function deriveSortableFields(\n  fields: MasterPatternViewFieldDefinition[]\n): SortableFieldDescriptor[] {\n  const seen = new Set<string>();\n  const result: SortableFieldDescriptor[] = [];\n\n  // First add code and name unconditionally (if they exist in fields)\n  for (const fieldName of ALWAYS_SORTABLE) {\n    const field = fields.find((f) => f.fieldName === fieldName);\n    if (field && !seen.has(fieldName)) {\n      seen.add(fieldName);\n      result.push({ fieldName: field.fieldName, label: field.label });\n    }\n  }\n\n  // Then add other sortable fields\n  for (const field of fields) {\n    if (field.sortable === true && !seen.has(field.fieldName)) {\n      seen.add(field.fieldName);\n      result.push({ fieldName: field.fieldName, label: field.label });\n    }\n  }\n\n  return result;\n}\n\n// ----- Internal Helpers -----\n\nfunction getDefaultFilterOperator(dataType: string): FilterOperator {\n  switch (dataType) {\n    case 'string':\n    case 'guid':\n      return 'contains';\n    default:\n      return 'equals';\n  }\n}\n","/**\n * Form slice for the MasterView store.\n *\n * Manages form mode, active record, values, errors, and saving state.\n *\n * @internal\n * @module store/slices/formSlice\n */\nimport type { StateCreator } from 'zustand';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterPatternViewDefinition } from '../../types/definition.types';\nimport type { MasterViewState, FormState } from '../types';\nimport { getAllFields } from '../../engine/fieldEngine';\n\n/** Seed initial form values: boolean fields default to true (Activo). */\nfunction computeInitialValues(definition: MasterPatternViewDefinition): Record<string, unknown> {\n  const values: Record<string, unknown> = {};\n  for (const field of getAllFields(definition)) {\n    if (field.dataType === 'boolean' || field.inputType === 'boolean') {\n      values[field.fieldName] = true;\n    }\n  }\n  return values;\n}\n\nexport const createFormSlice = <T extends MasterPatternViewEntity>(\n  definition: MasterPatternViewDefinition,\n  defaultCreateValues?: Record<string, unknown>,\n): StateCreator<\n  MasterViewState<T>,\n  [],\n  [],\n  FormState<T>\n> => (set) => {\n  const initialValues = { ...computeInitialValues(definition), ...defaultCreateValues };\n\n  return {\n  mode: 'closed',\n  activeRecord: null,\n  values: {},\n  errors: {},\n  isDirty: false,\n  isSaving: false,\n  activeTabKey: '',\n  isLoadingRecord: false,\n  recordLoadFailed: false,\n  initialCreateValues: {},\n\n  openCreate: () =>\n    set({\n      mode: 'creating',\n      activeRecord: null,\n      values: { ...initialValues },\n      initialCreateValues: { ...initialValues },\n      overrides: {},\n      revertedFields: [],\n      errors: {},\n      isDirty: false,\n      isSaving: false,\n      activeTabKey: '',\n      isLoadingRecord: false,\n      recordLoadFailed: false,\n    }),\n\n  openEdit: (record: T) =>\n    set({\n      mode: 'editing',\n      activeRecord: record,\n      values: { ...record },\n      // Snapshot the record values as the baseline global values.\n      // In company context the consumer applies overrides on top via setValues;\n      // globalValues stays as the unmodified global record so the hint can show \"Valor global: X\".\n      globalValues: { ...(record as Record<string, unknown>) },\n      overrides: { ...((record as Record<string, unknown>)._overrides as Record<string, unknown> ?? {}) },\n      revertedFields: [],\n      errors: {},\n      isDirty: false,\n      isSaving: false,\n      activeTabKey: '',\n      isLoadingRecord: false,\n      recordLoadFailed: false,\n    }),\n\n  openView: (record: T) =>\n    set({\n      mode: 'viewing',\n      activeRecord: record,\n      values: { ...record },\n      errors: {},\n      isDirty: false,\n      isSaving: false,\n      activeTabKey: '',\n      isLoadingRecord: false,\n      recordLoadFailed: false,\n    }),\n\n  closeForm: () =>\n    set({\n      mode: 'closed',\n      activeRecord: null,\n      values: {},\n      errors: {},\n      isDirty: false,\n      isSaving: false,\n      isLoadingRecord: false,\n      recordLoadFailed: false,\n    }),\n\n  updateActiveRecord: (record: T) =>\n    set({ activeRecord: record }),\n\n  setValues: (values: Record<string, unknown> | ((prev: Record<string, unknown>) => Record<string, unknown>)) =>\n    typeof values === 'function' ? set((state) => ({ values: values(state.values) })) : set({ values }),\n\n  setInitialCreateValues: (values: Record<string, unknown>) =>\n    set((state) => ({ initialCreateValues: { ...state.initialCreateValues, ...values } })),\n\n  setErrors: (errors: Record<string, string>) =>\n    set({ errors }),\n\n  setIsDirty: (isDirty: boolean) =>\n    set({ isDirty }),\n\n  setIsSaving: (isSaving: boolean) =>\n    set({ isSaving }),\n\n  setActiveTabKey: (key: string) =>\n    set({ activeTabKey: key }),\n\n  setIsLoadingRecord: (isLoadingRecord: boolean) =>\n    set({ isLoadingRecord }),\n\n  setRecordLoadFailed: (recordLoadFailed: boolean) =>\n    set({ recordLoadFailed }),\n  };\n};\n","/**\n * Filter slice for the MasterView store.\n *\n * Manages filter panel visibility, active filters, and derived filter count.\n *\n * @internal\n * @module store/slices/filterSlice\n */\nimport type { StateCreator } from 'zustand';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterViewState, FilterState, ActiveFilter } from '../types';\n\nexport const createFilterSlice = <T extends MasterPatternViewEntity>(): StateCreator<\n  MasterViewState<T>,\n  [],\n  [],\n  FilterState\n> => (set) => ({\n  isFilterPanelOpen: false,\n  activeFilters: [],\n  activeFilterCount: 0,\n\n  toggleFilterPanel: () =>\n    set((state) => ({ isFilterPanelOpen: !state.isFilterPanelOpen })),\n\n  setFilterPanelOpen: (open: boolean) =>\n    set({ isFilterPanelOpen: open }),\n\n  setActiveFilters: (filters: ActiveFilter[]) =>\n    set({ activeFilters: filters, activeFilterCount: filters.length }),\n\n  clearFilters: () =>\n    set({ activeFilters: [], activeFilterCount: 0, columnFilters: [], quickFilterValues: {} }),\n});\n","/**\n * UI slice for the MasterView store.\n *\n * Manages modal open/close states and pending action for confirmation dialogs.\n *\n * @internal\n * @module store/slices/uiSlice\n */\nimport type { StateCreator } from 'zustand';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { PendingAction } from '../../types/internal.types';\nimport type { MasterViewState, UIState } from '../types';\n\nexport const createUISlice = <T extends MasterPatternViewEntity>(): StateCreator<\n  MasterViewState<T>,\n  [],\n  [],\n  UIState\n> => (set) => ({\n  isChangeStatusModalOpen: false,\n  isCompanyEnableModalOpen: false,\n  isNotEnabledModalOpen: false,\n  isDirtyStateDialogOpen: false,\n  isImportModalOpen: false,\n  isConflictDialogOpen: false,\n  pendingAction: null,\n\n  openChangeStatusModal: () => set({ isChangeStatusModalOpen: true }),\n  closeChangeStatusModal: () => set({ isChangeStatusModalOpen: false }),\n\n  openCompanyEnableModal: () => set({ isCompanyEnableModalOpen: true }),\n  closeCompanyEnableModal: () => set({ isCompanyEnableModalOpen: false }),\n\n  openNotEnabledModal: () => set({ isNotEnabledModalOpen: true }),\n  closeNotEnabledModal: () => set({ isNotEnabledModalOpen: false }),\n\n  openDirtyStateDialog: () => set({ isDirtyStateDialogOpen: true }),\n  closeDirtyStateDialog: () => set({ isDirtyStateDialogOpen: false }),\n\n  openImportModal: () => set({ isImportModalOpen: true }),\n  closeImportModal: () => set({ isImportModalOpen: false }),\n\n  openConflictDialog: () => set({ isConflictDialogOpen: true }),\n  closeConflictDialog: () => set({ isConflictDialogOpen: false }),\n\n  setPendingAction: (action: PendingAction) => set({ pendingAction: action }),\n  clearPendingAction: () => set({ pendingAction: null }),\n\n  viewMode: 'table' as const,\n  setViewMode: (mode) => set({ viewMode: mode }),\n});\n","/**\n * Override slice for the MasterView store.\n *\n * Manages company context, field overrides, global values,\n * and the \"show global values\" toggle for GLOBAL master types.\n *\n * @internal\n * @module store/slices/overrideSlice\n */\nimport type { StateCreator } from 'zustand';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterPatternViewDefinition } from '../../types/definition.types';\nimport type { MasterViewState, OverrideState } from '../types';\n\nexport const createOverrideSlice = <T extends MasterPatternViewEntity>(\n  definition: MasterPatternViewDefinition,\n): StateCreator<MasterViewState<T>, [], [], OverrideState> =>\n  (set) => ({\n    activeCompanyContext: (\n      definition.type === 'GLOBAL' ||\n      ((definition.type === 'CONFIG_TABLE' || definition.type === 'CUSTOM') && definition.companyBehavior === 'GLOBAL')\n    ) ? 'global' : undefined,\n    overrides: {},\n    globalValues: {},\n    isShowGlobalValuesEnabled: false,\n    revertedFields: [],\n\n    setActiveCompanyContext: (context: string | undefined) =>\n      set({ activeCompanyContext: context }),\n\n    setOverrides: (overrides: Record<string, unknown>) =>\n      set({ overrides }),\n\n    setGlobalValues: (values: Record<string, unknown>) =>\n      set({ globalValues: values }),\n\n    toggleShowGlobalValues: () =>\n      set((state) => ({ isShowGlobalValuesEnabled: !state.isShowGlobalValuesEnabled })),\n\n    setRevertedFields: (fields: string[]) =>\n      set({ revertedFields: fields }),\n  });\n","/// <reference types=\"vite/client\" />\n/**\n * Factory function for creating isolated Zustand stores.\n *\n * Each call produces a new, independent store instance — NEVER a singleton.\n * Uses `createStore` from zustand/vanilla (Zustand 5 pattern).\n * In development, wraps with devtools middleware for Redux DevTools visibility.\n *\n * @internal\n * @module store/createMasterViewStore\n * @see FMPV-MVWC-E001-S003 — Store isolation requirement\n */\nimport { createStore } from 'zustand/vanilla';\nimport { devtools } from 'zustand/middleware';\nimport type { StateCreator } from 'zustand';\nimport type { MasterPatternViewEntity } from '../types/service.types';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport type { MasterViewState, MasterViewStore } from './types';\nimport { createListSlice } from './slices/listSlice';\nimport { createFormSlice } from './slices/formSlice';\nimport { createFilterSlice } from './slices/filterSlice';\nimport { createUISlice } from './slices/uiSlice';\nimport { createOverrideSlice } from './slices/overrideSlice';\n\nfunction buildStateCreator<T extends MasterPatternViewEntity>(\n  definition: MasterPatternViewDefinition,\n  defaultCreateValues?: Record<string, unknown>,\n  initialPageSize?: number,\n): StateCreator<MasterViewState<T>> {\n  return (...args) => ({\n    ...createListSlice<T>(initialPageSize)(...args),\n    ...createFormSlice<T>(definition, defaultCreateValues)(...args),\n    ...createFilterSlice<T>()(...args),\n    ...createUISlice<T>()(...args),\n    ...createOverrideSlice<T>(definition)(...args),\n  });\n}\n\n/**\n * Creates a new isolated Zustand store instance for a MasterPatternView component.\n * In DEV mode, devtools middleware is applied for Redux DevTools visibility,\n * with each instance named after the definition name for easy identification.\n *\n * @param definition - The master view definition that configures initial state\n * @returns A new StoreApi instance with all slices combined\n */\nexport function createMasterViewStore<T extends MasterPatternViewEntity>(\n  definition: MasterPatternViewDefinition,\n  defaultCreateValues?: Record<string, unknown>,\n  initialPageSize?: number,\n): MasterViewStore<T> {\n  const creator = buildStateCreator<T>(definition, defaultCreateValues, initialPageSize);\n\n  if (import.meta.env.DEV) {\n    return createStore<MasterViewState<T>>()(\n      devtools(creator, { name: `MasterView-${definition.name}` }),\n    );\n  }\n\n  return createStore<MasterViewState<T>>()(creator);\n}\n","/**\n * React context and provider for the MasterView Zustand store.\n *\n * Each MasterViewProvider instance creates an isolated store scoped to its\n * subtree. The useMasterViewStore hook reads from the nearest provider.\n *\n * @internal\n * @module store/MasterViewContext\n * @see FMPV-MVWC-E001-S003 — Context isolation requirement\n */\nimport React, { createContext, useContext, useRef, type ReactNode } from 'react';\nimport { useStore } from 'zustand';\nimport type { StoreApi } from 'zustand';\nimport type { MasterPatternViewEntity } from '../types/service.types';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport type { MasterViewState } from './types';\nimport { createMasterViewStore } from './createMasterViewStore';\n\nconst MasterViewContext = createContext<StoreApi<MasterViewState<any>> | null>(null);\n\nexport interface MasterViewProviderProps<T extends MasterPatternViewEntity> {\n  children: ReactNode;\n  definition: MasterPatternViewDefinition;\n  defaultCreateValues?: Record<string, unknown>;\n  /** Initial `searchParams.pageSize` — mirrors the host's own `pagination.defaultPageSize`. */\n  initialPageSize?: number;\n}\n\n/**\n * Provider that creates and holds an isolated store instance.\n * The store is created once on first render (via useRef) and remains stable.\n */\nexport function MasterViewProvider<T extends MasterPatternViewEntity>({\n  children,\n  definition,\n  defaultCreateValues,\n  initialPageSize,\n}: MasterViewProviderProps<T>) {\n  const storeRef = useRef<StoreApi<MasterViewState<T>> | undefined>(undefined);\n  if (!storeRef.current) {\n    storeRef.current = createMasterViewStore<T>(definition, defaultCreateValues, initialPageSize);\n  }\n\n  return (\n    <MasterViewContext.Provider value={storeRef.current}>\n      {children}\n    </MasterViewContext.Provider>\n  );\n}\n\n/**\n * Hook to access the nearest MasterView store via context.\n * Throws if used outside a MasterViewProvider.\n *\n * @param selector - Selector function to pick state from the store\n * @returns The selected state value\n */\nexport function useMasterViewStore<U>(\n  selector: (state: MasterViewState<any>) => U,\n): U {\n  const store = useContext(MasterViewContext);\n  if (!store) {\n    throw new Error('useMasterViewStore must be used within MasterViewProvider');\n  }\n  return useStore(store, selector);\n}\n","import React, { useState, useEffect } from 'react';\nimport type { ToastProps, ToastPosition, ToastColor } from './Toast.types';\n\nconst positionClasses: Record<ToastPosition, string> = {\n  'top-left': 'top-4 left-4',\n  'top-center': 'top-4 left-1/2 -translate-x-1/2',\n  'top-right': 'top-4 right-4',\n  'bottom-left': 'bottom-4 left-4',\n  'bottom-center': 'bottom-4 left-1/2 -translate-x-1/2',\n  'bottom-right': 'bottom-4 right-4',\n};\n\nconst animationClasses: Record<ToastPosition, { in: string; out: string }> = {\n  'top-left': { in: 'translate-y-0 opacity-100', out: '-translate-y-8 opacity-0' },\n  'top-center': { in: '-translate-x-1/2 translate-y-0 opacity-100', out: '-translate-x-1/2 -translate-y-8 opacity-0' },\n  'top-right': { in: 'translate-y-0 opacity-100', out: '-translate-y-8 opacity-0' },\n  'bottom-left': { in: 'translate-y-0 opacity-100', out: 'translate-y-8 opacity-0' },\n  'bottom-center': { in: '-translate-x-1/2 translate-y-0 opacity-100', out: '-translate-x-1/2 translate-y-8 opacity-0' },\n  'bottom-right': { in: 'translate-y-0 opacity-100', out: 'translate-y-8 opacity-0' },\n};\n\nconst containerColorClasses: Record<ToastColor, string> = {\n  'default': 'text-gray-500 bg-white border border--gray-100 dark:text-gray-400 dark:bg-gray-950 dark:border-gray-950',\n  'zinc': 'text-zinc-700 bg-zinc-100 border border-zinc-100 dark:text-zinc-400 dark:bg-zinc-950 dark:border-zinc-950',\n  'red': 'text-red-700 bg-red-100 border border-red-100 dark:text-red-400 dark:bg-red-950 dark:border-red-950',\n  'orange': 'text-orange-700 bg-orange-100 border border-orange-100 dark:text-orange-400 dark:bg-orange-950 dark:border-orange-950',\n  'amber': 'text-amber-700 bg-amber-100 border border-amber-100 dark:text-amber-400 dark:bg-amber-950 dark:border-amber-950',\n  'yellow': 'text-yellow-700 bg-yellow-100 border border-yellow-100 dark:text-yellow-400 dark:bg-yellow-950 dark:border-yellow-950',\n  'lime': 'text-lime-700 bg-lime-100 border border-lime-100 dark:text-lime-400 dark:bg-lime-950 dark:border-lime-950',\n  'green': 'text-green-700 bg-green-100 border border-green-100 dark:text-green-400 dark:bg-green-950 dark:border-green-950',\n  'emerald': 'text-emerald-700 bg-emerald-100 border border-emerald-100 dark:text-emerald-400 dark:bg-emerald-950 dark:border-emerald-950',\n  'teal': 'text-teal-700 bg-teal-100 border border-teal-100 dark:text-teal-400 dark:bg-teal-950 dark:border-teal-950',\n  'cyan': 'text-cyan-700 bg-cyan-100 border border-cyan-100 dark:text-cyan-400 dark:bg-cyan-950 dark:border-cyan-950',\n  'sky': 'text-sky-700 bg-sky-100 border border-sky-100 dark:text-sky-400 dark:bg-sky-950 dark:border-sky-950',\n  'blue': 'text-blue-700 bg-blue-100 border border-blue-100 dark:text-blue-400 dark:bg-blue-950 dark:border-blue-950',\n  'indigo': 'text-indigo-700 bg-indigo-100 border border-indigo-100 dark:text-indigo-400 dark:bg-indigo-950 dark:border-indigo-950',\n  'violet': 'text-violet-700 bg-violet-100 border border-violet-100 dark:text-violet-400 dark:bg-violet-950 dark:border-violet-950',\n  'purple': 'text-purple-700 bg-purple-100 border border-purple-100 dark:text-purple-400 dark:bg-purple-950 dark:border-purple-950',\n  'fuchsia': 'text-fuchsia-700 bg-fuchsia-100 border border-fuchsia-100 dark:text-fuchsia-400 dark:bg-fuchsia-950 dark:border-fuchsia-950',\n  'pink': 'text-pink-700 bg-pink-100 border border-pink-100 dark:text-pink-400 dark:bg-pink-950 dark:border-pink-950',\n  'rose': 'text-rose-700 bg-rose-100 border border-rose-100 dark:text-rose-400 dark:bg-rose-950 dark:border-rose-950',\n  'primary': 'text-primary-700 bg-primary-100 border border-primary-100 dark:text-primary-400 dark:bg-primary-950 dark:border-primary-950',\n  'secondary': 'text-secondary-700 bg-secondary-100 border border-secondary-100 dark:text-secondary-400 dark:bg-secondary-950 dark:border-secondary-950',\n  'tertiary': 'text-tertiary-700 bg-tertiary-100 border border-tertiary-100 dark:text-tertiary-400 dark:bg-tertiary-950 dark:border-tertiary-950',\n};\n\nexport const Toast: React.FC<ToastProps> = ({\n  position = 'bottom-right',\n  color = 'default',\n  icon: Icon,\n  duration = 5000,\n  autoClose = true,\n  isVisible = false,\n  onClose,\n  title,\n  message,\n  className = '',\n  closeLabel = 'Close',\n}) => {\n  const [shouldRender, setShouldRender] = useState(false);\n  const [isAnimating, setIsAnimating] = useState(false);\n\n  useEffect(() => {\n    if (isVisible) {\n      setShouldRender(true);\n      // Trigger animation after render\n      const animTimer = setTimeout(() => setIsAnimating(true), 10);\n\n      let timer: NodeJS.Timeout;\n      if (autoClose) {\n        timer = setTimeout(() => {\n          if (onClose) onClose(); // Envia señal de cierre al padre\n        }, duration);\n      }\n\n      return () => {\n        clearTimeout(animTimer);\n        if (timer) clearTimeout(timer);\n      };\n    } else {\n      setIsAnimating(false);\n      // Retrasar la eliminación del DOM para permitir la animación de salida\n      const timer = setTimeout(() => {\n        setShouldRender(false);\n      }, 300); // 300ms coincide con duration-300 de Tailwind\n      return () => clearTimeout(timer);\n    }\n  }, [isVisible, autoClose, duration, onClose]);\n\n  const positionClass = positionClasses[position];\n  const animationClass = isAnimating ? animationClasses[position].in : animationClasses[position].out;\n  const containerColorClass = containerColorClasses[color];\n\n  if (!shouldRender) return null;\n\n  return (\n    <div\n      className={`fixed flex items-center w-full max-w-xs p-4 gap-3 rounded-lg shadow-sm transition-all duration-300 ease-in-out ${positionClass} ${animationClass} ${containerColorClass} ${className}`}\n      role=\"alert\"\n    >\n      {Icon && (\n        <div className=\"inline-flex items-center justify-center shrink-0 w-5 h-5 text-current\">\n          <Icon className=\"w-full h-full\" aria-hidden=\"true\" />\n        </div>\n      )}\n      <div className=\"flex flex-col gap-1\">\n        {title && <div className=\"text-sm font-bold\">{title}</div>}\n        <div className=\"text-xs font-normal\">{message}</div>\n      </div>\n      <button\n        type=\"button\"\n        className=\"ms-auto -mx-1.5 -my-1.5 bg-transparent opacity-70 hover:opacity-100 rounded-lg focus:ring-2 focus:ring-current p-1.5 inline-flex items-center justify-center h-8 w-8 transition-opacity\"\n        data-dismiss-target=\"#toast-default\"\n        aria-label={closeLabel}\n        onClick={onClose}\n      >\n        <span className=\"sr-only\">{closeLabel}</span>\n        <svg className=\"w-3 h-3\" aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 14 14\">\n          <path stroke=\"currentColor\" strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth=\"2\" d=\"m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6\"/>\n        </svg>\n      </button>\n    </div>\n  );\n};\n\n\n","import React, { useState, useEffect } from 'react';\nimport { Toast } from './Toast';\nimport type { ToastColor, ToastPosition } from './Toast.types';\nimport {\n  CheckCircleIcon,\n  ExclamationTriangleIcon,\n  InformationCircleIcon,\n  XCircleIcon,\n} from '@heroicons/react/24/outline';\n\ninterface ToastData {\n  id: string;\n  title?: string;\n  message: string;\n  description?: string; // IMPORTANTE: Agregar explicitly 'description' para arreglar el error de Typescript en MasterCrud\n  color: ToastColor;\n  icon?: any;\n  position?: ToastPosition;\n  duration?: number;\n}\n\nlet addToastRef: (toast: Omit<ToastData, 'id'>) => void = () => {\n  console.warn('ToastProvider no está montado. No se puede mostrar el toast.');\n};\n\nexport const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n  const [toasts, setToasts] = useState<ToastData[]>([]);\n\n  useEffect(() => {\n    addToastRef = (newToast) => {\n      const id = Math.random().toString(36).substr(2, 9);\n      setToasts((prev) => [...prev, { ...newToast, id }]);\n    };\n  }, []);\n\n  const handleClose = (id: string) => {\n    setToasts((prev) => prev.filter((t) => t.id !== id));\n  };\n\n  return (\n    <>\n      {children}\n      <div className=\"fixed inset-0 pointer-events-none z-[100] flex flex-col gap-2 p-4 justify-end items-end h-screen w-screen\" style={{ top: 0, left: 0, right: 0, bottom: 0}}>\n         {/* Renderizamos de forma individual, pero como Toast ya trae clases de fix y posiciones, modificamos un poco como se renderiza en viewport para no sobreponerlos ciegamente si hay 2.*/}\n         {toasts.map((t) => (\n            <Toast\n              key={t.id}\n              title={t.title}\n              message={t.message}\n              color={t.color}\n              icon={t.icon}\n              position={t.position || 'bottom-right'}\n              duration={t.duration || 5000}\n              autoClose={true}\n              isVisible={true}\n              onClose={() => handleClose(t.id)}\n            />\n         ))}\n      </div>\n    </>\n  );\n};\n\nexport const toast = Object.assign(\n  (message: string, options?: Partial<Omit<ToastData, 'id' | 'message'>>) => {\n    // Si viene la palabra description por compatibilidad, la unificamos al mensaje\n    const finalMessage = options?.description ? `${message}: ${options.description}` : message;\n    addToastRef({ message: finalMessage, color: 'default', ...options });\n  },\n  {\n    success: (message: string, options?: Partial<Omit<ToastData, 'id' | 'message'>>) => {\n      const finalMessage = options?.description ? `${message}: ${options.description}` : message;\n      addToastRef({ message: finalMessage, color: 'green', icon: CheckCircleIcon, ...options });\n    },\n    error: (message: string, options?: Partial<Omit<ToastData, 'id' | 'message'>>) => {\n      const finalMessage = options?.description ? `${message}: ${options.description}` : message;\n      addToastRef({ message: finalMessage, color: 'red', icon: XCircleIcon, ...options });\n    },\n    warning: (message: string, options?: Partial<Omit<ToastData, 'id' | 'message'>>) => {\n      const finalMessage = options?.description ? `${message}: ${options.description}` : message;\n      addToastRef({ message: finalMessage, color: 'yellow', icon: ExclamationTriangleIcon, ...options });\n    },\n    info: (message: string, options?: Partial<Omit<ToastData, 'id' | 'message'>>) => {\n       const finalMessage = options?.description ? `${message}: ${options.description}` : message;\n      addToastRef({ message: finalMessage, color: 'blue', icon: InformationCircleIcon, ...options });\n    }\n  }\n);\n","/**\n * InternalToastContainer — self-contained toast system for master-pattern-view.\n *\n * Uses a DOM CustomEvent bus so `useToast` can fire toasts without requiring\n * the consumer to provide a `toast` prop or mount a ToastManager.\n *\n * Usage:\n *   - `fireInternalToast(type, message)` — fire from anywhere in the package\n *   - `<InternalToastContainer />` — mount once inside MasterPatternView\n *\n * @module components/InternalToastContainer\n */\nimport React, { useEffect } from 'react';\nimport { toast } from '../../Toast/ToastProvider';\nimport type { ToastType } from '../hooks/useToast';\n\nconst TOAST_EVENT = 'mpv:toast';\n\ninterface ToastEntry {\n  id: string;\n  type: ToastType;\n  message: string;\n}\n\nexport function fireInternalToast(type: ToastType, message: string): void {\n  const id = (typeof crypto !== 'undefined' && crypto.randomUUID)\n    ? crypto.randomUUID()\n    : String(Date.now() + Math.random());\n  window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { id, type, message } }));\n}\n\nexport function InternalToastContainer(): React.ReactElement | null {\n  useEffect(() => {\n    const handler = (e: Event) => {\n      const entry = (e as CustomEvent<ToastEntry>).detail;\n      const t = toast[entry.type === 'error' ? 'error' : entry.type === 'success' ? 'success' : entry.type === 'warning' ? 'warning' : 'info'];\n      if(t){\n          t(entry.message);\n      } else {\n          toast(entry.message);\n      }\n    };\n    window.addEventListener(TOAST_EVENT, handler);\n    return () => window.removeEventListener(TOAST_EVENT, handler);\n  }, []);\n\n  return null;\n}\n","/**\n * useToast — internal toast abstraction.\n *\n * If the consumer provides a `toast` callback prop, delegates to it.\n * Otherwise falls back to `fireInternalToast` which dispatches a DOM event\n * picked up by `InternalToastContainer` (always mounted inside MasterPatternView).\n *\n * @module hooks/useToast\n * @see FMPV-MVWC-E002-S002 I-005\n */\nimport { fireInternalToast } from '../components/InternalToastContainer';\n\nexport type ToastType = 'success' | 'error' | 'warning' | 'info';\nexport type ToastCallback = (type: ToastType, message: string) => void;\n\nexport interface ToastAPI {\n  showSuccess: (message: string) => void;\n  showError: (message: string) => void;\n  showWarning: (message: string) => void;\n  showInfo: (message: string) => void;\n}\n\n/**\n * Returns toast notification methods.\n * Delegates to the consumer-provided `toast` callback when available;\n * otherwise fires the internal event bus handled by InternalToastContainer.\n *\n * `fireInternalToast` dispatches on `window` with no notion of which\n * MasterPatternView instance sent it, and `InternalToastContainer` listens on\n * `window` too — so any mounted container (a sibling master, a different\n * lookup's nested popup) picks up the event whether it's \"theirs\" or not. A\n * consumer with `showInternalToasts={false}` and no `toast` callback was\n * relying on nobody being subscribed, which only holds by accident. Gating\n * the dispatch here — not just the container's mount — means \"don't show\n * internal toasts\" is honored regardless of what else happens to be mounted\n * on the page.\n *\n * @param externalToast - Optional toast callback from MasterPatternViewProps\n * @param showInternalToasts - Whether the owning MasterPatternView renders its\n *   own InternalToastContainer. `false` with no `externalToast` means this\n *   toast has nowhere of its own to go — drop it instead of firing globally.\n */\nexport function useToast(externalToast?: ToastCallback, showInternalToasts: boolean = true): ToastAPI {\n  const dispatch = (type: ToastType, message: string) => {\n    if (externalToast) {\n      externalToast(type, message);\n    } else if (showInternalToasts) {\n      fireInternalToast(type, message);\n    }\n  };\n\n  return {\n    showSuccess: (message) => dispatch('success', message),\n    showError: (message) => dispatch('error', message),\n    showWarning: (message) => dispatch('warning', message),\n    showInfo: (message) => dispatch('info', message),\n  };\n}\n","/**\n * CompanySelector — toolbar company context switcher.\n *\n * For GLOBAL type (showGlobalOption=true): shows \"Global\" first + companies.\n * For COMPANY type: shows companies only.\n *\n * States:\n * - 0 companies (no showGlobalOption): static \"Global\" chip, click shows toast\n * - 0 companies + showGlobalOption: static \"Global\" chip (no dropdown needed)\n * - 1 company (no showGlobalOption): static chip with company name\n * - 1+ companies + showGlobalOption: clickable chip with Global + companies dropdown\n * - 2+ companies (no showGlobalOption): clickable chip with companies dropdown\n *\n * Chip shows Globe icon when activeCompanyId is 'global'/undefined, Building2 otherwise.\n *\n * @module components/toolbar/CompanySelector\n * @see FMPV-MVWC-E004-S002 I-001\n */\nimport React, { useState, useRef, useEffect } from 'react';\nimport { GlobeAltIcon, ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline';\nimport { Building2 } from 'lucide-react';\nimport type { MasterPatternViewCompany } from '../../types/service.types';\nimport type { ToastCallback } from '../../hooks/useToast';\nimport { useToast } from '../../hooks/useToast';\n\nexport interface CompanySelectorProps {\n  companies: MasterPatternViewCompany[];\n  activeCompanyId?: string;\n  onCompanyChange: (company: MasterPatternViewCompany) => void;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** When true, prepends a \"Global\" option to the dropdown (for GLOBAL master types). */\n  showGlobalOption?: boolean;\n  /**\n   * Company ids the CURRENT record is enabled for (GLOBAL type only). When provided, each\n   * company row shows a \"Habilitado\" / \"No habilitado\" indicator alongside its name/code —\n   * same enable/disable data as the \"Habilitar por compañía\" modal, so switching context\n   * from here tells you upfront whether the record actually has anything to show for that\n   * company. Omit to leave the dropdown as it is today (no indicator).\n   */\n  assignedCompanyIds?: string[];\n  /** When true, renders the chip as non-interactive (grayed out, no dropdown). */\n  disabled?: boolean;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nconst GLOBAL_SENTINEL: MasterPatternViewCompany = { id: 'global', name: 'Global', code: '' };\n\nexport function CompanySelector({\n  companies,\n  activeCompanyId,\n  onCompanyChange,\n  toast: toastProp,\n  showInternalToasts = true,\n  showGlobalOption = false,\n  assignedCompanyIds,\n  disabled = false,\n  t,\n}: CompanySelectorProps) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const [dropdownOpen, setDropdownOpen] = useState(false);\n  const dropdownRef = useRef<HTMLDivElement>(null);\n  const { showWarning } = useToast(toastProp, showInternalToasts);\n\n  // Close dropdown on outside click\n  useEffect(() => {\n    if (!dropdownOpen) return;\n    const handler = (e: MouseEvent) => {\n      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {\n        setDropdownOpen(false);\n      }\n    };\n    document.addEventListener('mousedown', handler);\n    return () => document.removeEventListener('mousedown', handler);\n  }, [dropdownOpen]);\n\n  const isGlobalActive = !activeCompanyId || activeCompanyId === 'global';\n  // Trigger azul de marca — mismos tokens que MasterCrud/CompanySelector.tsx (incluyendo dark:).\n  const chipClass =\n    'inline-flex items-center gap-1.5 bg-[#eff8ff] dark:bg-primary-900/20 border border-[#93d1fd] dark:border-primary-800 rounded-md px-3 py-1.5 text-xs font-semibold text-[#1355b7] dark:text-primary-300 leading-none cursor-pointer hover:bg-[#dbeefe] dark:hover:bg-primary-900/40 hover:border-[#3c9bf6] transition-colors select-none';\n  const chipDisabledClass =\n    'inline-flex items-center gap-1.5 bg-background-secondary dark:bg-dark-bg-secondary border border-border-primary dark:border-dark-border-primary rounded-md px-3 py-1.5 text-xs font-semibold text-content-tertiary dark:text-dark-content-tertiary leading-none cursor-not-allowed select-none opacity-60';\n\n  // No companies and no global option — static chip with toast\n  if ((!companies || companies.length === 0) && !showGlobalOption) {\n    return (\n      <button\n        type=\"button\"\n        data-testid=\"company-chip-global\"\n        className={disabled ? chipDisabledClass : chipClass}\n        onClick={disabled ? undefined : () => showWarning(tt('noCompaniesConfigured', 'No hay compañías configuradas para este maestro.'))}\n        disabled={disabled}\n      >\n        <GlobeAltIcon className=\"w-3.5 h-3.5 flex-shrink-0\" />\n        <span>{tt('global', 'Global')}</span>\n        <ChevronDownIcon className=\"w-3 h-3 flex-shrink-0\" />\n      </button>\n    );\n  }\n\n  // Single company, no global option — static non-interactive chip\n  if (companies.length === 1 && !showGlobalOption) {\n    return (\n      <div\n        data-testid=\"company-chip\"\n        className={`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold leading-none select-none ${\n          disabled\n            ? 'bg-background-secondary dark:bg-dark-bg-secondary border border-border-primary dark:border-dark-border-primary text-content-tertiary dark:text-dark-content-tertiary opacity-60'\n            : 'bg-[#eff8ff] dark:bg-primary-900/20 border border-[#93d1fd] dark:border-primary-800 text-[#1355b7] dark:text-primary-300'\n        }`}\n      >\n        <Building2 className=\"w-3.5 h-3.5 flex-shrink-0\" />\n        <span className=\"max-w-[160px] truncate\">{companies[0].name}</span>\n      </div>\n    );\n  }\n\n  // Dropdown: Global + companies (showGlobalOption) OR companies only\n  const activeCompany = companies.find((c) => c.id === activeCompanyId);\n  const activeLabel = isGlobalActive ? tt('global', 'Global') : (activeCompany?.name ?? companies[0]?.name ?? tt('global', 'Global'));\n  const ActiveIcon = isGlobalActive ? GlobeAltIcon : Building2;\n\n  return (\n    <div className=\"relative\" ref={dropdownRef}>\n      <button\n        type=\"button\"\n        data-testid=\"company-dropdown-trigger\"\n        className={disabled ? chipDisabledClass : chipClass}\n        onClick={disabled ? undefined : () => setDropdownOpen((v) => !v)}\n        disabled={disabled}\n      >\n        <ActiveIcon className=\"w-3.5 h-3.5 flex-shrink-0\" />\n        <span className=\"max-w-[160px] truncate\">{activeLabel}</span>\n        <ChevronDownIcon className={`w-3 h-3 flex-shrink-0 transition-transform ${dropdownOpen ? 'rotate-180' : ''}`} />\n      </button>\n\n      {dropdownOpen && (\n        <div\n          data-testid=\"company-dropdown\"\n          // Wider when the enabled/disabled indicator is shown (assignedCompanyIds provided)\n          // — same breakpoint MasterCrud's own CompanySelector uses for its companyEnabledMap\n          // case, so the extra text doesn't cramp against the name/code.\n          className={`absolute left-0 top-full mt-1 z-50 ${\n            assignedCompanyIds !== undefined ? 'min-w-[360px] max-w-[440px]' : 'min-w-[200px]'\n          } bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-lg shadow-md py-1`}\n        >\n          {/* Global option — first, for GLOBAL master types */}\n          {showGlobalOption && (\n            <>\n              <button\n                type=\"button\"\n                data-testid=\"company-option-global\"\n                className=\"w-full flex items-center gap-2 px-3 py-2 text-xs text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                onClick={() => {\n                  onCompanyChange(GLOBAL_SENTINEL);\n                  setDropdownOpen(false);\n                }}\n              >\n                {isGlobalActive\n                  ? <CheckIcon className=\"w-3 h-3 text-[#0e79fd] flex-shrink-0\" />\n                  : <span className=\"w-3 flex-shrink-0\" />}\n                <GlobeAltIcon className=\"w-3 h-3 flex-shrink-0 text-[#1355b7] dark:text-primary-300\" />\n                <span className=\"font-medium\">{tt('global', 'Global')}</span>\n              </button>\n              {companies.length > 0 && (\n                <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n              )}\n            </>\n          )}\n\n          {/* Companies */}\n          {companies.map((company) => {\n            const isActive = company.id === activeCompanyId;\n            const isAssigned = assignedCompanyIds?.includes(company.id);\n            return (\n              <button\n                key={company.id}\n                type=\"button\"\n                data-testid={`company-option-${company.id}`}\n                className=\"w-full flex items-center gap-2 px-3 py-2 text-xs text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                onClick={() => {\n                  onCompanyChange(company);\n                  setDropdownOpen(false);\n                }}\n              >\n                {isActive\n                  ? <CheckIcon className=\"w-3 h-3 text-[#0e79fd] flex-shrink-0\" />\n                  : <span className=\"w-3 flex-shrink-0\" />}\n                <Building2 className=\"w-3 h-3 flex-shrink-0 text-[#1355b7] dark:text-primary-300\" />\n                <span className=\"font-medium truncate\">{company.name}</span>\n                <span className=\"flex items-center gap-2 ml-auto flex-shrink-0\">\n                  <span className=\"text-content-secondary dark:text-dark-content-secondary\">{company.code}</span>\n                  {/* Plain icon + text, no badge background — matches MasterCrud's own\n                      CompanySelector.tsx (companyEnabledMap) exactly, not a colored pill. */}\n                  {assignedCompanyIds !== undefined && (\n                    isAssigned ? (\n                      <span className=\"inline-flex items-center gap-1 text-[11px] font-semibold text-[#4d7c0f] dark:text-lime-400\">\n                        <CheckIcon className=\"w-3 h-3\" />\n                        {tt('enabled', 'Habilitado')}\n                      </span>\n                    ) : (\n                      <span className=\"inline-flex items-center gap-1 text-[11px] font-medium text-content-secondary dark:text-dark-content-secondary\">\n                        <span className=\"inline-block w-3 h-3 rounded-full border border-current\" />\n                        {tt('notEnabled', 'No habilitado')}\n                      </span>\n                    )\n                  )}\n                </span>\n              </button>\n            );\n          })}\n        </div>\n      )}\n    </div>\n  );\n}\n","/**\n * CompanyEnableModal — manage which companies a GLOBAL record is enabled for.\n *\n * Accumulates enable/disable changes locally (pendingChanges Map) and only calls\n * onConfirm when the user explicitly clicks \"Confirmar cambios\". Visually matches\n * MasterCrud's LinkModal.tsx (icon badge, item layout, footer) — the two differ\n * only in this accumulate-then-confirm flow vs LinkModal's immediate local toggle.\n *\n * @module components/modals/CompanyEnableModal\n * @see FMPV-MVWC-E004-S005\n */\nimport React, { useState, useMemo, useEffect } from 'react';\nimport { Building2 } from 'lucide-react';\nimport { XMarkIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';\nimport { Button } from '../../../Button/Button';\nimport type { MasterPatternViewCompany } from '../../types/service.types';\n\nexport interface CompanyEnableChange {\n  companyId: string;\n  action: 'enable' | 'disable';\n}\n\nexport interface CompanyEnableModalProps {\n  isOpen: boolean;\n  recordId: string;\n  /** Human-readable code/name of the record being enabled — shown in the header so it's clear which record this is for when several are open in sequence. Omit to hide. */\n  recordLabel?: string;\n  companies: MasterPatternViewCompany[];\n  assignedCompanyIds: string[];\n  onClose: () => void;\n  onConfirm: (changes: CompanyEnableChange[]) => void;\n  isLoading: boolean;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function CompanyEnableModal({\n  isOpen,\n  recordLabel,\n  companies,\n  assignedCompanyIds,\n  onClose,\n  onConfirm,\n  isLoading,\n  t,\n}: CompanyEnableModalProps): React.ReactElement | null {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const [searchQuery, setSearchQuery] = useState('');\n  const [pendingChanges, setPendingChanges] = useState<Map<string, 'enable' | 'disable'>>(\n    new Map(),\n  );\n\n  // Reset pending changes and search every time the modal opens\n  useEffect(() => {\n    if (isOpen) {\n      setPendingChanges(new Map());\n      setSearchQuery('');\n    }\n  }, [isOpen]);\n\n  const assignedSet = useMemo(() => new Set(assignedCompanyIds), [assignedCompanyIds]);\n\n  const filteredCompanies = useMemo(\n    () =>\n      companies.filter(\n        (c) =>\n          c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||\n          c.code.toLowerCase().includes(searchQuery.toLowerCase()),\n      ),\n    [companies, searchQuery],\n  );\n\n  // Altura del cuerpo SIEMPRE fija en 25rem, sin importar cuántas compañías haya (1, 3, 20...) —\n  // así el modal nunca cambia de tamaño ni al escribir en el buscador (antes usaba max-h-[400px],\n  // que encogía el modal al filtrar a pocos resultados) ni según cuántas compañías tenga el maestro.\n  // En rem (no px) para que escale con el zoom/tamaño de fuente del usuario, y con un tope en vh\n  // para no cortarse en pantallas bajas (laptops, ventanas chicas) — nunca más del 45% del alto visible.\n  const bodyHeight = companies.length === 0 ? '0' : 'min(25rem, 45vh)';\n\n  if (!isOpen) return null;\n\n  function isEffectivelyAssigned(companyId: string): boolean {\n    const pending = pendingChanges.get(companyId);\n    if (pending === 'enable') return true;\n    if (pending === 'disable') return false;\n    return assignedSet.has(companyId);\n  }\n\n  function handleToggle(companyId: string, action: 'enable' | 'disable') {\n    setPendingChanges((prev) => {\n      const next = new Map(prev);\n      const originallyAssigned = assignedSet.has(companyId);\n      const wouldBeOriginal =\n        (action === 'enable' && originallyAssigned) ||\n        (action === 'disable' && !originallyAssigned);\n      if (wouldBeOriginal) {\n        next.delete(companyId);\n      } else {\n        next.set(companyId, action);\n      }\n      return next;\n    });\n  }\n\n  function handleEnableAll() {\n    setPendingChanges((prev) => {\n      const next = new Map(prev);\n      companies.forEach((c) => {\n        if (!assignedSet.has(c.id) && next.get(c.id) !== 'enable') {\n          next.set(c.id, 'enable');\n        }\n      });\n      return next;\n    });\n  }\n\n  function handleConfirm() {\n    const changes: CompanyEnableChange[] = Array.from(pendingChanges.entries()).map(\n      ([companyId, action]) => ({ companyId, action }),\n    );\n    onConfirm(changes);\n  }\n\n  const pendingCount = pendingChanges.size;\n\n  // Botones por compañía — mismas clases que LinkModal.tsx (h-8 px-3 rounded-md text-xs font-semibold border).\n  const btnAssign = 'inline-flex items-center h-8 px-3 rounded-md text-xs font-semibold border transition-all bg-white dark:bg-dark-bg-primary text-primary-600 border-[#93d1fd] hover:bg-[#eff8ff] dark:hover:bg-primary-900/20';\n  const btnUnassign = 'inline-flex items-center h-8 px-3 rounded-md text-xs font-semibold border transition-all bg-error/10 text-error-content border-error-border hover:brightness-95 dark:bg-error/20';\n\n  return (\n    <div\n      role=\"dialog\"\n      aria-modal=\"true\"\n      className=\"fixed inset-0 z-[9000] flex items-center justify-center p-4\"\n      style={{ background: 'rgba(15,23,42,0.45)', backdropFilter: 'blur(2px)' }}\n    >\n      <div className=\"bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-2xl flex flex-col w-full max-w-2xl overflow-hidden relative\">\n\n        {/* Botón Cerrar (X) — absolute, como LinkModal.tsx */}\n        <div className=\"absolute right-4 top-4 z-10\">\n          <Button\n            type=\"outline\"\n            size=\"xs\"\n            iconOnly\n            leftIcon={<XMarkIcon className=\"w-4 h-4\" />}\n            onClick={onClose}\n            ariaLabel={tt('close', 'Cerrar')}\n            className=\"!bg-white dark:!bg-dark-bg-primary\"\n          />\n        </div>\n\n        {/* Header — icono de edificio (lucide Building2), como en el diseño original */}\n        <div className=\"p-[20px] flex gap-5 items-center\">\n          <div className=\"bg-[#dbeefe] dark:bg-primary-900/20 flex items-center justify-center rounded-full shrink-0 size-[40px]\">\n            <Building2 size={24} className=\"text-primary-600 dark:text-primary-400\" />\n          </div>\n          <div className=\"flex flex-col justify-center\">\n            {/* Suffix format (\" · {label}\") and uniform styling match MasterCrud's\n                LinkModal.tsx getDynamicTitle() exactly — a middle dot, not a dash, and\n                no secondary color/weight split between the two parts. */}\n            <h3 className=\"text-[20px] font-bold leading-[28px] tracking-tight text-content-primary dark:text-dark-content-primary\">\n              {tt('companyEnableTitle', 'Habilitar por compañía')}\n              {recordLabel && ` · ${recordLabel}`}\n            </h3>\n            <p className=\"text-[14px] font-normal italic leading-[20px] text-content-tertiary dark:text-dark-content-tertiary\">\n              {tt('companyEnableDesc', 'Gestiona en qué compañías está habilitado este registro.')}\n            </p>\n          </div>\n        </div>\n\n        {/* Buscador (fijo, no scrollea con la lista) */}\n        <div className=\"px-[20px] pb-[12px]\">\n          <div className=\"relative\">\n            <MagnifyingGlassIcon className=\"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n            <input\n              type=\"text\"\n              value={searchQuery}\n              onChange={(e) => setSearchQuery(e.target.value)}\n              placeholder={tt('companySearchPlaceholder', 'Buscar compañía…')}\n              aria-label={tt('companySearchPlaceholder', 'Buscar compañía…')}\n              autoComplete=\"off\"\n              data-testid=\"company-search-input\"\n              className=\"w-full h-10 pl-9 pr-9 rounded-lg border border-border-primary dark:border-dark-border-primary bg-white dark:bg-dark-bg-primary text-sm text-content-primary dark:text-dark-content-primary placeholder:text-content-tertiary focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors\"\n            />\n            {searchQuery && (\n              <button\n                type=\"button\"\n                onClick={() => setSearchQuery('')}\n                aria-label={tt('clear', 'Limpiar')}\n                className=\"absolute right-2 top-1/2 -translate-y-1/2 inline-flex items-center justify-center w-6 h-6 rounded-md text-content-tertiary hover:text-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n              >\n                <XMarkIcon className=\"w-3.5 h-3.5\" />\n              </button>\n            )}\n          </div>\n        </div>\n\n        {/* Body — lista de compañías, cada una en su propia tarjeta con borde (igual a LinkModal.tsx).\n            Altura fija (bodyHeight, calculada arriba) en vez de max-h-[400px]: con max-h el\n            contenedor se encogía al tamaño del resultado filtrado — al buscar y quedar pocas\n            compañías, el modal entero \"saltaba\" más chico y el buscador terminaba pegado a las\n            tarjetas. Con altura fija — igual a como se veía con la lista completa sin filtrar —\n            el modal mantiene siempre el mismo tamaño. */}\n        <div\n          className=\"px-[20px] pb-[20px] flex flex-col gap-[20px] overflow-y-auto\"\n          style={{ height: bodyHeight }}\n        >\n          <div className=\"flex flex-col items-start w-full\">\n            {filteredCompanies.map((company) => {\n              const effective = isEffectivelyAssigned(company.id);\n              return (\n                <div\n                  key={company.id}\n                  className=\"border border-border-primary dark:border-dark-border-primary h-[64px] px-[8px] flex items-center justify-between rounded-[8px] w-full mb-3 last:mb-0 transition-colors hover:border-[#93d1fd] hover:bg-[#eff8ff]/40 dark:hover:bg-primary-900/10\"\n                >\n                  <div className=\"flex items-center gap-[8px]\">\n                    <div className=\"bg-[#dbeefe] dark:bg-primary-900/20 flex items-center justify-center rounded-[16px] shrink-0 size-[32px]\">\n                      <Building2 size={18} className=\"text-primary-600 dark:text-primary-400\" />\n                    </div>\n                    <span className=\"text-[16px] font-medium leading-[24px] text-content-primary dark:text-dark-content-primary truncate max-w-[300px]\">\n                      {company.name}\n                    </span>\n                    <span className=\"text-[11px] text-content-secondary dark:text-dark-content-secondary flex-shrink-0\">{company.code}</span>\n                  </div>\n\n                  {effective ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => handleToggle(company.id, 'disable')}\n                      disabled={isLoading}\n                      className={btnUnassign}\n                      data-testid={`disable-company-${company.id}`}\n                    >\n                      {tt('disable', 'Deshabilitar')}\n                    </button>\n                  ) : (\n                    <button\n                      type=\"button\"\n                      onClick={() => handleToggle(company.id, 'enable')}\n                      disabled={isLoading}\n                      className={btnAssign}\n                      data-testid={`enable-company-${company.id}`}\n                    >\n                      {tt('enable', 'Habilitar')}\n                    </button>\n                  )}\n                </div>\n              );\n            })}\n\n            {/* Estado vacío del buscador */}\n            {filteredCompanies.length === 0 && (\n              <div className=\"w-full flex flex-col items-center justify-center gap-2 py-10 text-center\">\n                <MagnifyingGlassIcon className=\"w-6 h-6 text-content-tertiary dark:text-dark-content-tertiary\" />\n                <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary\">\n                  {tt('noCompaniesFound', 'No se encontraron compañías')}\n                </p>\n                {searchQuery && (\n                  <p className=\"text-xs text-content-tertiary dark:text-dark-content-tertiary\">\n                    <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">&ldquo;{searchQuery}&rdquo;</span>\n                  </p>\n                )}\n              </div>\n            )}\n          </div>\n        </div>\n\n        {/* Footer — Cancelar / Habilitar todas / Confirmar, igual a LinkModal.tsx */}\n        <div className=\"px-[24px] py-[16px] pb-[20px] flex items-center justify-end gap-3 shrink-0 w-full border-t border-border-secondary dark:border-dark-border-primary\">\n          <Button type=\"plain\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium\" onClick={onClose} disabled={isLoading} data-testid=\"company-enable-cancel-button\">\n            {tt('cancel', 'Cancelar')}\n          </Button>\n          <Button type=\"outline\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium\" onClick={handleEnableAll} disabled={isLoading} data-testid=\"enable-all-button\">\n            {tt('enableAllCompanies', 'Habilitar todas')}\n          </Button>\n          <Button\n            type=\"default\"\n            size=\"base\"\n            className=\"!h-9 !px-3 !text-sm font-medium\"\n            onClick={handleConfirm}\n            disabled={pendingCount === 0 || isLoading}\n            data-testid=\"confirm-changes-button\"\n          >\n            {isLoading\n              ? tt('saving', 'Guardando…')\n              : pendingCount > 0\n                ? tt('confirmChangesCount', 'Confirmar cambios ({count})').replace('{count}', String(pendingCount))\n                : tt('confirmChanges', 'Confirmar cambios')}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n","/**\n * ConfigTableContent — body renderer for MasterPatternView when type='CONFIG_TABLE'.\n *\n * Provides: toolbar (title + Acciones), company selector, config data loading,\n * global-values toggle, company-link confirmation dialog, and \"Vincular compañías\" modal.\n * Delegates body rendering to the consumer via `renderConfigBody(ctx)`.\n *\n * @internal\n */\nimport React, { useEffect, useState, useCallback, useRef } from 'react';\nimport { Menu, ChevronDown, Globe, Link2, RotateCcw } from 'lucide-react';\nimport { useMasterViewStore } from '../store/MasterViewContext';\nimport { CompanySelector } from './toolbar/CompanySelector';\nimport { CompanyEnableModal } from './modals/CompanyEnableModal';\nimport type { CompanyEnableChange } from './modals/CompanyEnableModal';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport type { MasterPatternViewCompany, ConfigTableService, ConfigSaveRow } from '../types/service.types';\nimport type { ConfigBodyContext } from '../types/props.types';\n\ninterface ConfigTableContentProps {\n  definition: MasterPatternViewDefinition;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  configService?: ConfigTableService<any>;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  renderConfigBody?: (ctx: ConfigBodyContext<any>) => React.ReactNode;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  renderToolbarActions?: (ctx: ConfigBodyContext<any>) => React.ReactNode;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  renderActionsMenuItems?: (ctx: ConfigBodyContext<any>) => React.ReactNode;\n  title: string;\n  companies?: MasterPatternViewCompany[];\n  defaultCompany?: MasterPatternViewCompany;\n  onCompanyChange?: (company: MasterPatternViewCompany) => void;\n  toast?: (type: 'success' | 'error' | 'warning' | 'info', message: string) => void;\n}\n\nexport function ConfigTableContent({\n  definition,\n  configService,\n  renderConfigBody,\n  renderToolbarActions,\n  renderActionsMenuItems,\n  title,\n  companies = [],\n  defaultCompany,\n  onCompanyChange,\n  toast,\n}: ConfigTableContentProps) {\n  const companyBehavior = definition.companyBehavior ?? 'NONE';\n\n  const activeCompanyContext = useMasterViewStore((s) => s.activeCompanyContext);\n  const setActiveCompanyContext = useMasterViewStore((s) => s.setActiveCompanyContext);\n  const isShowGlobalValuesEnabled = useMasterViewStore((s) => s.isShowGlobalValuesEnabled);\n  const toggleShowGlobalValues = useMasterViewStore((s) => s.toggleShowGlobalValues);\n\n  const [rows, setRows] = useState<unknown[]>([]);\n  const [globalData, setGlobalData] = useState<Map<string, unknown>>(new Map());\n  const [isSaving, setIsSaving] = useState(false);\n  const [isLoading, setIsLoading] = useState(false);\n  const [linkedCompanyIds, setLinkedCompanyIds] = useState<Set<string>>(new Set());\n  const [pendingCompany, setPendingCompany] = useState<MasterPatternViewCompany | null>(null);\n  const [isLinking, setIsLinking] = useState(false);\n  const [linkModalOpen, setLinkModalOpen] = useState(false);\n  const [actionsDropdownOpen, setActionsDropdownOpen] = useState(false);\n  const [isLinkModalSaving, setIsLinkModalSaving] = useState(false);\n\n  const companyId = activeCompanyContext === 'global' ? undefined : (activeCompanyContext ?? undefined);\n  const isCompanyMode = companyBehavior !== 'NONE' && !!activeCompanyContext && activeCompanyContext !== 'global';\n  const showsGlobalOption = companyBehavior === 'GLOBAL';\n\n  // Initialize company context on mount\n  useEffect(() => {\n    if (companyBehavior === 'COMPANY_SPECIFIC' && companies.length > 0) {\n      const initial = defaultCompany ?? companies[0];\n      setActiveCompanyContext(initial.id);\n    } else if (companyBehavior === 'GLOBAL' && defaultCompany && defaultCompany.id !== 'global') {\n      // Pre-select the provided company (e.g. when consumed inside an app that already has a company context)\n      setActiveCompanyContext(defaultCompany.id);\n    }\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // Load linked company IDs on mount (GLOBAL)\n  useEffect(() => {\n    if (companyBehavior === 'GLOBAL' && configService?.getLinkedCompanies) {\n      void configService.getLinkedCompanies().then((ids) => setLinkedCompanyIds(new Set(ids))).catch(() => {});\n    }\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // Load config data when company context changes\n  useEffect(() => {\n    if (!configService) return;\n    setIsLoading(true);\n    void configService.getConfigData(companyId)\n      .then(({ rows: newRows }) => setRows(newRows))\n      .catch(() => {})\n      .finally(() => setIsLoading(false));\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [activeCompanyContext]);\n\n  // Pre-load global data whenever in company+GLOBAL context so it's ready when the toggle is turned on\n  useEffect(() => {\n    if (!configService || !isCompanyMode || companyBehavior !== 'GLOBAL') {\n      setGlobalData(new Map());\n      return;\n    }\n    void configService.getConfigData(undefined)\n      .then(({ rows: globalRows }) => {\n        const map = new Map<string, unknown>();\n        for (const row of globalRows ?? []) {\n          const r = row as { rowId?: string };\n          if (r.rowId) map.set(r.rowId, row);\n        }\n        setGlobalData(map);\n      })\n      .catch(() => setGlobalData(new Map()));\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [activeCompanyContext]);\n\n  const handleCompanyChange = useCallback((company: MasterPatternViewCompany) => {\n    if (company.id === 'global') {\n      setActiveCompanyContext('global');\n      return;\n    }\n    if (companyBehavior === 'GLOBAL' && !linkedCompanyIds.has(company.id)) {\n      setPendingCompany(company);\n    } else {\n      setActiveCompanyContext(company.id);\n      onCompanyChange?.(company);\n    }\n  }, [companyBehavior, linkedCompanyIds, setActiveCompanyContext, onCompanyChange]);\n\n  const handleConfirmLink = useCallback(async () => {\n    if (!pendingCompany || !configService?.linkCompany) return;\n    setIsLinking(true);\n    try {\n      await configService.linkCompany(pendingCompany.id, rows);\n      setActiveCompanyContext(pendingCompany.id);\n      if (configService.getLinkedCompanies) {\n        const updatedIds = await configService.getLinkedCompanies();\n        setLinkedCompanyIds(new Set(updatedIds));\n      }\n      onCompanyChange?.(pendingCompany);\n      setPendingCompany(null);\n    } catch {\n      toast?.('error', 'Error al vincular la compañía');\n      setPendingCompany(null);\n    } finally {\n      setIsLinking(false);\n    }\n  }, [pendingCompany, configService, rows, setActiveCompanyContext, onCompanyChange, toast]);\n\n  const handleSave = useCallback(async (changedRows: ConfigSaveRow<unknown>[]) => {\n    if (!configService) return;\n    setIsSaving(true);\n    try {\n      await configService.saveConfig(changedRows, companyId);\n      const { rows: newRows } = await configService.getConfigData(companyId);\n      setRows(newRows);\n      toast?.('success', 'Guardado exitosamente');\n    } catch {\n      toast?.('error', 'Error al guardar');\n    } finally {\n      setIsSaving(false);\n    }\n  }, [configService, companyId, toast]);\n\n  const handleRestoreRow = useCallback((rowId: string) => {\n    const globalRow = globalData.get(rowId);\n    if (!globalRow) return;\n    setRows((prev) => prev.map((r) => {\n      const row = r as { rowId?: string };\n      return row.rowId === rowId ? globalRow : r;\n    }));\n  }, [globalData]);\n\n  const handleRestoreAll = useCallback(() => {\n    if (!globalData.size) return;\n    setRows((prev) => prev.map((r) => {\n      const row = r as { rowId?: string };\n      if (!row.rowId) return r;\n      return globalData.get(row.rowId) ?? r;\n    }));\n  }, [globalData]);\n\n  const handleLinkModalConfirm = useCallback(async (changes: CompanyEnableChange[]) => {\n    if (!configService?.updateCompanyLinks) return;\n    const toLink = changes.filter((c) => c.action === 'enable').map((c) => c.companyId);\n    const toUnlink = changes.filter((c) => c.action === 'disable').map((c) => c.companyId);\n    setIsLinkModalSaving(true);\n    try {\n      await configService.updateCompanyLinks(toLink, toUnlink, rows);\n      if (configService.getLinkedCompanies) {\n        const updatedIds = await configService.getLinkedCompanies();\n        setLinkedCompanyIds(new Set(updatedIds));\n      }\n      const { rows: newRows } = await configService.getConfigData(companyId);\n      setRows(newRows);\n      setLinkModalOpen(false);\n    } catch {\n      toast?.('error', 'Error al actualizar vínculos');\n    } finally {\n      setIsLinkModalSaving(false);\n    }\n  }, [configService, rows, companyId, toast]);\n\n  const showMostrarDatosGlobales = companyBehavior === 'GLOBAL' && isCompanyMode;\n  const showUsarDatosGlobales = companyBehavior === 'GLOBAL' && isCompanyMode && globalData.size > 0;\n  const showVincularCompanias = companyBehavior === 'GLOBAL';\n  const hasBuiltinActionsItems = showMostrarDatosGlobales || showVincularCompanias;\n  const hasActionsItems = hasBuiltinActionsItems || !!renderActionsMenuItems;\n\n  const ctx: ConfigBodyContext<unknown> = {\n    rows,\n    isCompanyMode,\n    showGlobalValues: isShowGlobalValuesEnabled,\n    globalData,\n    isSaving,\n    onSave: handleSave,\n    onRestoreRow: handleRestoreRow,\n    onRestoreAll: handleRestoreAll,\n  };\n\n  // Close dropdown when clicking outside\n  const dropdownRef = useRef<HTMLDivElement>(null);\n  useEffect(() => {\n    if (!actionsDropdownOpen) return;\n    const handler = (e: MouseEvent) => {\n      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {\n        setActionsDropdownOpen(false);\n      }\n    };\n    document.addEventListener('mousedown', handler);\n    return () => document.removeEventListener('mousedown', handler);\n  }, [actionsDropdownOpen]);\n\n  return (\n    <div data-testid=\"master-pattern-view\" className=\"relative flex flex-col h-screen bg-background-secondary dark:bg-dark-bg-primary overflow-hidden\">\n      {/* Header: Title | Acciones | renderToolbarActions */}\n      <div className=\"flex items-center justify-between px-5 pt-3.5 pb-0\">\n        {title && (\n          <h1 className=\"text-xl font-semibold text-[#1355b7] tracking-tight\" data-testid=\"master-view-title\">\n            {title}\n          </h1>\n        )}\n\n        {(hasActionsItems || renderToolbarActions) && (\n          <div className=\"ml-auto flex items-center gap-2\">\n            {/* Acciones dropdown — left of any custom toolbar actions */}\n            {hasActionsItems && (\n              <div className=\"relative\" ref={dropdownRef}>\n                <button\n                  type=\"button\"\n                  onClick={() => setActionsDropdownOpen((v) => !v)}\n                  data-testid=\"toolbar-actions-dropdown-button\"\n                  className=\"inline-flex items-center gap-2 px-3 h-9 rounded-md border text-sm font-bold cursor-pointer transition-all bg-background-secondary dark:bg-dark-bg-secondary border-border-primary dark:border-dark-border-primary text-content-tertiary dark:text-dark-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary\"\n                >\n                  <Menu size={14} />\n                  Acciones\n                  <ChevronDown size={12} className={`transition-transform ${actionsDropdownOpen ? 'rotate-180' : ''}`} />\n                </button>\n\n                {actionsDropdownOpen && (\n                  <div className=\"absolute right-0 top-full mt-1 bg-bg-primary dark:bg-dark-bg-primary rounded-md border border-border-primary dark:border-dark-border-primary shadow-md z-50 min-w-[250px] py-1\">\n                    {showUsarDatosGlobales && (\n                      <button\n                        type=\"button\"\n                        className=\"w-full flex items-center gap-2 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary cursor-pointer\"\n                        onClick={() => { handleRestoreAll(); setActionsDropdownOpen(false); }}\n                        data-testid=\"toolbar-use-global-data\"\n                      >\n                        <RotateCcw size={13} />\n                        Usar datos globales\n                      </button>\n                    )}\n\n                    {showMostrarDatosGlobales && (\n                      <button\n                        type=\"button\"\n                        className=\"w-full flex items-center justify-between gap-2 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary cursor-pointer\"\n                        onClick={() => { toggleShowGlobalValues(); setActionsDropdownOpen(false); }}\n                        data-testid=\"toolbar-toggle-global-values\"\n                      >\n                        <span className=\"flex items-center gap-2 whitespace-nowrap\">\n                          <Globe size={13} />\n                          Mostrar datos globales\n                        </span>\n                        <span style={{\n                          width: 28, height: 16, borderRadius: 8, flexShrink: 0,\n                          background: isShowGlobalValuesEnabled ? 'var(--text-color-primary-custom-600)' : 'var(--mpv-toggle-inactive)',\n                          position: 'relative', display: 'inline-block',\n                          transition: 'background .2s',\n                        }}>\n                          <span style={{\n                            width: 12, height: 12, borderRadius: '50%', background: 'var(--color-bg-primary)',\n                            position: 'absolute', top: 2,\n                            left: isShowGlobalValuesEnabled ? 14 : 2,\n                            transition: 'left .15s',\n                            boxShadow: '0 1px 2px rgba(0,0,0,.2)',\n                          }} />\n                        </span>\n                      </button>\n                    )}\n\n                    {(showMostrarDatosGlobales || showUsarDatosGlobales) && showVincularCompanias && (\n                      <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n                    )}\n\n                    {showVincularCompanias && (\n                      <button\n                        type=\"button\"\n                        className=\"w-full flex items-center gap-2 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary cursor-pointer\"\n                        onClick={() => { setLinkModalOpen(true); setActionsDropdownOpen(false); }}\n                        data-testid=\"toolbar-link-companies\"\n                      >\n                        <Link2 size={13} />\n                        Habilitar compañías\n                      </button>\n                    )}\n\n                    {/* Custom actions — always available, separated from built-in when both exist */}\n                    {renderActionsMenuItems && (\n                      <>\n                        {hasBuiltinActionsItems && (\n                          <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n                        )}\n                        {renderActionsMenuItems(ctx)}\n                      </>\n                    )}\n                  </div>\n                )}\n              </div>\n            )}\n\n            {/* Custom toolbar actions (e.g. Guardar) — right of Acciones */}\n            {renderToolbarActions && renderToolbarActions(ctx)}\n          </div>\n        )}\n      </div>\n\n      {/* Company selector */}\n      {companyBehavior !== 'NONE' && (\n        <div className=\"px-5 pb-2 pt-2\">\n          <CompanySelector\n            companies={companies}\n            activeCompanyId={activeCompanyContext ?? undefined}\n            showGlobalOption={showsGlobalOption}\n            onCompanyChange={handleCompanyChange}\n            toast={toast}\n          />\n        </div>\n      )}\n\n      {/* Config body */}\n      <div className=\"flex-1 min-h-0 flex flex-col gap-2.5 px-5 pb-5 pt-3\">\n        <div className=\"bg-bg-primary dark:bg-dark-bg-primary rounded-xl border border-border-primary dark:border-dark-border-primary overflow-hidden flex flex-col flex-1 min-h-0\">\n          <div className=\"flex-1 min-h-0 overflow-auto flex flex-col\">\n            {isLoading ? (\n              <div className=\"flex items-center justify-center p-8 text-sm text-content-tertiary dark:text-dark-content-tertiary\">\n                Cargando...\n              </div>\n            ) : (\n              renderConfigBody?.(ctx)\n            )}\n          </div>\n        </div>\n      </div>\n\n      {/* Link-company confirmation dialog */}\n      {pendingCompany && (\n        <div className=\"fixed inset-0 z-[100] flex items-center justify-center bg-black/50\">\n          <div className=\"bg-bg-primary dark:bg-dark-bg-primary rounded-xl border border-border-primary dark:border-dark-border-primary shadow-xl p-6 w-full max-w-sm mx-4\">\n            <h3 className=\"text-base font-semibold text-content-primary dark:text-dark-content-primary mb-2\">\n              Habilitar compañía\n            </h3>\n            <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary mb-6\">\n              {`¿Deseas habilitar \"${pendingCompany.name}\" en esta configuración?`}\n            </p>\n            <div className=\"flex justify-end gap-3\">\n              <button\n                type=\"button\"\n                onClick={() => { if (!isLinking) setPendingCompany(null); }}\n                disabled={isLinking}\n                className=\"px-4 py-2 text-sm font-medium rounded-md border border-border-primary dark:border-dark-border-primary text-content-secondary dark:text-dark-content-secondary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary disabled:opacity-50 cursor-pointer\"\n              >\n                Cancelar\n              </button>\n              <button\n                type=\"button\"\n                onClick={() => void handleConfirmLink()}\n                disabled={isLinking}\n                className=\"px-4 py-2 text-sm font-medium rounded-md bg-[#0e79fd] text-white hover:bg-[#0c6be0] disabled:opacity-50 cursor-pointer\"\n              >\n                {isLinking ? 'Habilitando...' : 'Habilitar'}\n              </button>\n            </div>\n          </div>\n        </div>\n      )}\n\n      {/* Habilitar compañías modal */}\n      <CompanyEnableModal\n        isOpen={linkModalOpen}\n        recordId=\"\"\n        companies={companies}\n        assignedCompanyIds={Array.from(linkedCompanyIds)}\n        onClose={() => setLinkModalOpen(false)}\n        onConfirm={(changes) => void handleLinkModalConfirm(changes)}\n        isLoading={isLinkModalSaving}\n      />\n    </div>\n  );\n}\n\n","/**\n * Permission Engine — Evaluates action permissions.\n *\n * Pure function. Implements the NEVER-HIDE invariant: permissions disable UI\n * elements, never remove them from the DOM.\n *\n * @module permissionEngine\n * @see FMPV-MVWC-E001-S004, FR-FMPV-055\n */\n\nimport type { MasterPatternViewPermissions } from '../types';\n\n/**\n * Operation-to-permission mapping.\n * Maps operation strings to their corresponding permission key.\n */\nconst OPERATION_TO_PERMISSION: Record<string, keyof MasterPatternViewPermissions> = {\n  CREATE: 'canCreate',\n  READ: 'canRead',\n  UPDATE: 'canUpdate',\n  UPDATE_GLOBAL: 'canUpdateGlobal',\n  DELETE: 'canDelete',\n  CHANGE_STATUS: 'canChangeStatus',\n  COMPANY_ENABLE: 'canCompanyEnable',\n};\n\n/**\n * Checks if an action is allowed based on permissions.\n *\n * When `permissions` is `undefined`, all actions default to `true` (per PRD §9).\n * When a specific permission key is `undefined`, it defaults to `true`.\n *\n * @param permissions - Permission configuration (or undefined for all-allowed)\n * @param operation - The operation to check\n * @param masterType - The master type context (for future type-specific logic)\n * @returns true if the action is allowed\n */\nexport function isActionAllowed(\n  permissions: MasterPatternViewPermissions | undefined,\n  operation: string,\n  masterType: string\n): boolean {\n  if (permissions === undefined) {\n    return true;\n  }\n\n  const permissionKey = OPERATION_TO_PERMISSION[operation];\n  if (!permissionKey) {\n    return true;\n  }\n\n  const value = permissions[permissionKey];\n  // Default to true when the specific key is not set\n  return value !== false;\n}\n\n/**\n * Returns the warning message for a disabled action (NEVER-HIDE toast).\n *\n * @param operation - The operation that is disabled\n * @returns A user-friendly message explaining the restriction\n */\nexport function getDisabledToastMessage(operation: string): string {\n  const messages: Record<string, string> = {\n    CREATE: 'No tiene permisos para crear registros.',\n    READ: 'No tiene permisos para ver registros.',\n    UPDATE: 'No tiene permisos para editar registros.',\n    UPDATE_GLOBAL: 'No tiene permisos para editar datos globales.',\n    DELETE: 'No tiene permisos para eliminar registros.',\n    CHANGE_STATUS: 'No tiene permisos para cambiar el estado.',\n    COMPANY_ENABLE: 'No tiene permisos para habilitar compañías.',\n  };\n\n  return messages[operation] ?? 'No tiene permisos para realizar esta acción.';\n}\n","/**\n * FormActionBar — single top action bar for the form panel (title, company/status\n * context, Guardar/Cancelar or Regresar/Editar, and an \"extra actions\" kebab).\n *\n * Verified against MasterCrud's live \"modo página\" header\n * (MasterCrud.tsx:1568-1697 — CompanySelector + Activo/Edición badges left,\n * Cancelar + Guardar + kebab right). Matched pixel-for-pixel:\n * - Title: text-xl font-semibold tracking-tight text-[#1355b7] dark:text-primary-600\n * - Status badge: h-[18px] px-1.5 text-[10px] font-semibold rounded (not rounded-full)\n * - Editing/Creating badge: ONE style (amber, PencilIcon) for both states, text differs\n * - Cancelar/Guardar: size=\"base\" + \"!text-sm font-medium\", w-4 h-4 icons\n * - Extra-actions trigger is an ICON-ONLY kebab (EllipsisVerticalIcon, w-9 h-9)\n *   placed AFTER Guardar — not a labeled \"Acciones\" button before it.\n *\n * Shows dirty indicator (•) in title when isDirty=true.\n *\n * @module components/form/FormActionBar\n * @see FMPV-MVWC-E003-S001 I-003, FMPV-MVWC-E004-S001 I-002\n */\nimport React, { useState, useCallback, useRef, useEffect } from 'react';\nimport { motion } from 'framer-motion';\nimport {\n  XMarkIcon,\n  PencilIcon,\n  EyeIcon,\n  PlusIcon,\n  MinusCircleIcon,\n  CheckCircleIcon,\n  ArrowUturnLeftIcon as RotateCcwIcon,\n  ArrowLeftIcon,\n  GlobeAltIcon,\n  EllipsisVerticalIcon,\n  ClockIcon,\n} from '@heroicons/react/24/outline';\nimport { Building2 } from 'lucide-react';\nimport { Button } from '../../../Button/Button';\nimport type { FormMode } from '../../types/internal.types';\nimport type { MasterPatternViewCompany } from '../../types/service.types';\nimport { CompanySelector } from '../toolbar/CompanySelector';\n\n// Exact custom \"save\" glyph MasterCrud draws inline (Heroicons has no floppy-disk icon).\nconst SaveIcon = ({ className }: { className?: string }) => (\n  <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n    <path d=\"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z\" />\n    <path d=\"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7\" />\n    <path d=\"M7 3v4a1 1 0 0 0 1 1h7\" />\n  </svg>\n);\n\nexport interface FormActionBarProps {\n  mode: FormMode;\n  title: string;\n  isDirty: boolean;\n  onSave: () => void;\n  onCancel: () => void;\n  onEdit: () => void;\n  /** Called when user selects \"Crear nuevo registro\" from the extra-actions kebab (editing mode only) */\n  onHamburgerCreate?: () => void;\n  /** Called when user selects \"Cambiar estado\" from the extra-actions kebab (editing mode only) */\n  onHamburgerChangeStatus?: () => void;\n  /** Called when user selects \"Habilitar compañía\" (non-UNIVERSAL types only) */\n  onHamburgerEnableCompany?: () => void;\n  /** Called when user selects \"Auditoría de Cambios\" — omit to hide the item. */\n  onHamburgerAudit?: () => void;\n  /** Called when user selects \"Usar datos globales\" (company context only) */\n  onHamburgerUseGlobalData?: () => void;\n  /** Called when user toggles \"Mostrar datos globales\" (company context only) */\n  onHamburgerToggleShowGlobal?: () => void;\n  /** Current state of \"Mostrar datos globales\" toggle */\n  showGlobalValues?: boolean;\n  /** Company context — undefined hides the selector (UNIVERSAL) */\n  companies?: MasterPatternViewCompany[];\n  activeCompanyId?: string;\n  onCompanyChange?: (company: MasterPatternViewCompany) => void;\n  /** Company ids this GLOBAL record is enabled for — shown as a per-company indicator in the dropdown. Omit to hide (e.g. record still loading, or non-GLOBAL type). */\n  assignedCompanyIds?: string[];\n  definitionType?: string;\n  /** Current record's active status — shown as badge next to company selector */\n  recordIsActive?: boolean;\n  /** Compact mode: renders action buttons icon-only (no labels) to save horizontal space (sidebar) */\n  compact?: boolean;\n  /** Disables the Guardar button — used when the full record failed to load from the server. */\n  saveDisabled?: boolean;\n  /** Disables the company selector — prevents company switching in certain contexts. */\n  companyDisabled?: boolean;\n  /** Hides the Editar button completely in view mode. */\n  editHidden?: boolean;\n  /** Renders the Editar button as disabled (grayed out, not clickable) in view mode. */\n  editGrayed?: boolean;\n  /** Tooltip text shown on the grayed-out Editar button to explain why editing is unavailable. */\n  editGrayedReason?: string;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nconst BUTTON_TEXT_CLASS = '!text-sm font-medium';\n\nexport function FormActionBar({\n  mode,\n  title,\n  isDirty,\n  onSave,\n  onCancel,\n  onEdit,\n  onHamburgerCreate,\n  onHamburgerChangeStatus,\n  onHamburgerEnableCompany,\n  onHamburgerAudit,\n  onHamburgerUseGlobalData,\n  onHamburgerToggleShowGlobal,\n  showGlobalValues = false,\n  companies,\n  activeCompanyId,\n  onCompanyChange,\n  assignedCompanyIds,\n  definitionType,\n  recordIsActive,\n  compact = false,\n  saveDisabled = false,\n  companyDisabled = false,\n  editHidden = false,\n  editGrayed = false,\n  editGrayedReason,\n  t,\n}: FormActionBarProps) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const displayTitle = isDirty ? `• ${title}` : title;\n  const isViewing = mode === 'viewing';\n  const isEditing = mode === 'editing';\n  const isCreating = mode === 'creating';\n  const showCompany = definitionType !== 'UNIVERSAL';\n\n  // \"company context\" = a specific company is selected (not global / not UNIVERSAL)\n  const isCompanyContext = showCompany && !!activeCompanyId && activeCompanyId !== 'global';\n\n  const [menuOpen, setMenuOpen] = useState(false);\n  const menuRef = useRef<HTMLDivElement>(null);\n\n  const toggleMenu = useCallback(() => setMenuOpen((v) => !v), []);\n\n  const close = useCallback((fn?: () => void) => {\n    setMenuOpen(false);\n    fn?.();\n  }, []);\n\n  useEffect(() => {\n    if (!menuOpen) return;\n    const handler = (e: MouseEvent) => {\n      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {\n        setMenuOpen(false);\n      }\n    };\n    document.addEventListener('mousedown', handler);\n    return () => document.removeEventListener('mousedown', handler);\n  }, [menuOpen]);\n\n  return (\n    <div className=\"flex flex-col md:flex-row md:items-start md:justify-between gap-4 p-5 pb-2\">\n      <div className=\"flex flex-col gap-2 min-w-0\">\n        <span data-testid=\"form-title\" className=\"text-xl font-semibold tracking-tight text-[#1355b7] dark:text-primary-600 truncate\">\n          {displayTitle}\n        </span>\n        {/* Meta row: company context + status badge + creating/editing/readonly badge */}\n        <div className=\"flex items-center gap-2 flex-wrap\">\n          {showCompany && (\n            <CompanySelector\n              companies={companies ?? []}\n              activeCompanyId={activeCompanyId}\n              onCompanyChange={onCompanyChange ?? (() => {})}\n              assignedCompanyIds={assignedCompanyIds}\n              showGlobalOption={definitionType === 'GLOBAL'}\n              disabled={companyDisabled}\n            />\n          )}\n          {recordIsActive !== undefined && (\n            <span\n              data-testid=\"form-status-badge\"\n              className={`inline-flex items-center h-[18px] px-1.5 text-[10px] font-medium leading-none rounded ${\n                recordIsActive\n                  ? 'bg-[#ecfccb] text-[#4d7c0f] dark:bg-lime-900/30 dark:text-lime-400'\n                  : 'bg-background-secondary text-content-tertiary dark:bg-dark-bg-secondary dark:text-dark-content-tertiary'\n              }`}\n            >\n              {recordIsActive ? tt('active', 'Activo') : tt('inactive', 'Inactivo')}\n            </span>\n          )}\n          {(isCreating || isEditing) && (\n            <span\n              data-testid=\"form-mode-badge\"\n              className=\"inline-flex items-center gap-1 h-[18px] px-1.5 text-[10px] font-medium leading-none rounded bg-[#fef9c3] text-[#a16207] dark:bg-yellow-900/20 dark:text-yellow-500 w-fit\"\n            >\n              <PencilIcon className=\"w-3 h-3\" />\n              {isCreating ? tt('creating', 'Creación') : tt('editing', 'Edición')}\n            </span>\n          )}\n          {isViewing && (\n            <span\n              data-testid=\"form-readonly-badge\"\n              className=\"inline-flex items-center gap-1 h-[18px] px-1.5 text-[10px] font-medium leading-none rounded bg-zinc-100 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 w-fit\"\n            >\n              <EyeIcon className=\"w-3 h-3\" />\n              {tt('readOnly', 'Solo lectura')}\n            </span>\n          )}\n        </div>\n      </div>\n\n      <div className=\"flex items-center gap-2 flex-shrink-0\">\n        {isViewing ? (\n          <>\n            <Button type=\"outline\" size=\"base\" className={BUTTON_TEXT_CLASS} leftIcon={<ArrowLeftIcon className=\"w-4 h-4\" />} data-testid=\"form-back-button\" title={tt('back', 'Regresar')} onClick={onCancel}>\n              {!compact && tt('back', 'Regresar')}\n            </Button>\n            {!editHidden && (\n              <Button\n                type=\"default\"\n                size=\"base\"\n                className={BUTTON_TEXT_CLASS}\n                leftIcon={<PencilIcon className=\"w-4 h-4\" />}\n                data-testid=\"form-edit-button\"\n                title={editGrayed ? (editGrayedReason ?? tt('editUnavailable', 'Editar no disponible')) : tt('edit', 'Editar')}\n                disabled={editGrayed}\n                onClick={onEdit}\n              >\n                {!compact && tt('edit', 'Editar')}\n              </Button>\n            )}\n          </>\n        ) : (\n          <>\n            <Button type=\"outline\" size=\"base\" className={BUTTON_TEXT_CLASS} leftIcon={<XMarkIcon className=\"w-4 h-4\" />} data-testid=\"form-cancel-button\" title={tt('discardChanges', 'Cancelar')} onClick={onCancel}>\n              {!compact && tt('discardChanges', 'Cancelar')}\n            </Button>\n            <Button type=\"default\" size=\"base\" className={BUTTON_TEXT_CLASS} leftIcon={<SaveIcon className=\"w-4 h-4\" />} data-testid=\"form-save-button\" title={tt('saveChanges', 'Guardar')} onClick={onSave} disabled={saveDisabled}>\n              {!compact && tt('saveChanges', 'Guardar')}\n            </Button>\n          </>\n        )}\n\n        {/* Extra-actions kebab — icon-only, positioned AFTER Guardar (mirrors MasterCrud.tsx:1630-1641) */}\n        {isEditing && (\n          <div className=\"relative\" ref={menuRef}>\n            <motion.button\n              type=\"button\"\n              data-testid=\"form-hamburger-button\"\n              onClick={toggleMenu}\n              aria-haspopup=\"menu\"\n              aria-expanded={menuOpen}\n              title={tt('moreActions', 'Más acciones')}\n              whileHover={{ scale: 1.1 }}\n              whileTap={{ scale: 0.92 }}\n              transition={{ type: 'spring', bounce: 0.55, duration: 0.4 }}\n              className=\"inline-flex items-center justify-center w-9 h-9 border border-border-primary dark:border-dark-border-primary rounded-md bg-background-secondary dark:bg-dark-bg-secondary hover:bg-[#ebebec] dark:hover:bg-dark-bg-primary text-content-tertiary transition-colors\"\n            >\n              <EllipsisVerticalIcon className=\"w-4 h-4\" />\n            </motion.button>\n\n            {menuOpen && (() => {\n              // Build the item list in display order, then render a SINGLE separator\n              // at the midpoint (mirrors RowActions.tsx's kebab) instead of one per\n              // section. \"Cambiar estado\" always goes last, red/Deshabilitar while\n              // active or green/Habilitar while inactive — same treatment as the\n              // per-row kebab's changeStatus entry.\n              type MenuItem = {\n                key: string;\n                testId: string;\n                icon: React.ReactNode;\n                label: React.ReactNode;\n                onClick: () => void;\n                tone?: 'danger' | 'success';\n                // Semantic group — a separator is rendered whenever this changes from the\n                // previous item, instead of at a data-dependent numeric midpoint.\n                group: 'global' | 'actions' | 'meta';\n              };\n              const items: MenuItem[] = [];\n\n              if (definitionType === 'GLOBAL' && isCompanyContext) {\n                items.push({\n                  key: 'use-global',\n                  testId: 'form-hamburger-use-global',\n                  icon: <RotateCcwIcon className=\"w-4 h-4 text-[#1355b7] dark:text-primary-400 flex-shrink-0\" />,\n                  label: tt('useGlobalData', 'Usar datos globales'),\n                  onClick: () => close(onHamburgerUseGlobalData),\n                  group: 'global',\n                });\n                items.push({\n                  key: 'show-global',\n                  testId: 'form-hamburger-show-global',\n                  icon: <GlobeAltIcon className=\"w-4 h-4 text-[#1355b7] dark:text-primary-400 flex-shrink-0\" />,\n                  label: (\n                    <span className=\"flex items-center justify-between gap-2.5 flex-1\">\n                      <span className=\"whitespace-nowrap\">{tt('showGlobalValuesLabel', 'Mostrar datos globales')}</span>\n                      {/* Toggle — pixel-exact match to mock .dd-toggle-track / .dd-toggle-thumb */}\n                      <span style={{\n                        width: 28, height: 16, borderRadius: 8, flexShrink: 0,\n                        background: showGlobalValues\n                          ? 'var(--text-color-primary-custom-600)'\n                          : 'var(--color-border-primary)',\n                        position: 'relative', display: 'inline-block',\n                        transition: 'background .2s',\n                      }}>\n                        <span style={{\n                          width: 12, height: 12, borderRadius: '50%',\n                          background: 'var(--color-bg-primary)',\n                          position: 'absolute', top: 2,\n                          left: showGlobalValues ? 14 : 2,\n                          transition: 'left .15s',\n                          boxShadow: '0 1px 2px rgba(0,0,0,.2)',\n                        }} />\n                      </span>\n                    </span>\n                  ),\n                  onClick: () => close(onHamburgerToggleShowGlobal),\n                  group: 'global',\n                });\n              }\n\n              if (definitionType === 'GLOBAL') {\n                items.push({\n                  key: 'enable-company',\n                  testId: 'form-hamburger-enable-company',\n                  icon: <Building2 className=\"w-4 h-4 text-content-tertiary flex-shrink-0\" />,\n                  label: tt('enableCompanyAction', 'Habilitar compañía'),\n                  onClick: () => close(onHamburgerEnableCompany),\n                  group: 'actions',\n                });\n              }\n\n              items.push({\n                key: 'create',\n                testId: 'form-hamburger-create',\n                icon: <PlusIcon className=\"w-4 h-4 text-content-tertiary flex-shrink-0\" />,\n                label: tt('createNewRecord', 'Crear nuevo registro'),\n                onClick: () => close(onHamburgerCreate),\n                group: 'actions',\n              });\n\n              if (onHamburgerAudit) {\n                items.push({\n                  key: 'audit',\n                  testId: 'form-hamburger-audit',\n                  icon: <ClockIcon className=\"w-4 h-4 text-content-tertiary flex-shrink-0\" />,\n                  label: tt('auditChanges', 'Auditoría de Cambios'),\n                  onClick: () => close(onHamburgerAudit),\n                  group: 'meta',\n                });\n              }\n\n              // Always last.\n              items.push({\n                key: 'change-status',\n                testId: 'form-hamburger-change-status',\n                icon: recordIsActive\n                  ? <MinusCircleIcon className=\"w-4 h-4 flex-shrink-0\" />\n                  : <CheckCircleIcon className=\"w-4 h-4 flex-shrink-0\" />,\n                label: recordIsActive\n                  ? tt('disableRecordAction', 'Desactivar registro')\n                  : tt('enableRecordAction', 'Activar registro'),\n                onClick: () => close(onHamburgerChangeStatus),\n                tone: recordIsActive ? 'danger' : 'success',\n                group: 'meta',\n              });\n\n              return (\n                <div\n                  data-testid=\"form-hamburger-menu\"\n                  role=\"menu\"\n                  className=\"absolute right-0 top-full mt-1 z-50 min-w-[260px] bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-md shadow-md py-1\"\n                >\n                  {items.map((item, idx) => (\n                    <React.Fragment key={item.key}>\n                      {idx > 0 && item.group !== items[idx - 1].group && (\n                        <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n                      )}\n                      <button\n                        type=\"button\"\n                        role=\"menuitem\"\n                        data-testid={item.testId}\n                        className={`w-full flex items-center gap-2.5 px-3 py-2 text-sm text-left transition-colors ${\n                          item.tone === 'danger'\n                            ? 'text-error-content hover:bg-error/10'\n                            : item.tone === 'success'\n                              ? 'text-emerald-600 dark:text-emerald-400 hover:bg-emerald-50 dark:hover:bg-emerald-950/30'\n                              : 'text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'\n                        }`}\n                        onClick={item.onClick}\n                      >\n                        {item.icon}\n                        {item.label}\n                      </button>\n                    </React.Fragment>\n                  ))}\n                </div>\n              );\n            })()}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n","/**\n * TabBar — tab navigation for the form panel.\n *\n * \"Datos básicos\" with a red \"*\" is always the first tab (key: 'basicData').\n * Additional tabs come from `definition.tabs`.\n * Error count badges are shown per tab from `errors` mapped to tab keys.\n * When navigationType='modal' + more than 1 content tab, logs console.warn and truncates.\n *\n * @module components/form/TabBar\n * @see FMPV-MVWC-E003-S001 I-004\n */\nimport React, { useMemo } from 'react';\nimport { motion } from 'framer-motion';\nimport type { MasterPatternViewDefinition } from '../../types/definition.types';\nimport { getAllFields } from '../../engine/fieldEngine';\nimport type { MasterDetailTabConfig } from '../../types/detail.types';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\n\nexport interface TabBarProps {\n  definition: MasterPatternViewDefinition;\n  activeTabKey: string;\n  errors: Record<string, string>;\n  onTabChange: (key: string) => void;\n  navigationType?: 'sidebar' | 'modal' | 'page' | 'inline';\n  /** Form mode — detail tabs only shown in 'editing' mode */\n  formMode?: 'creating' | 'editing' | 'viewing' | 'closed';\n  /** Structured detail tab configurations (only visible in editing mode) */\n  detailTabConfigs?: MasterDetailTabConfig<MasterPatternViewEntity>[];\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\ninterface ResolvedTab {\n  id: string;\n  label: string;\n  badge?: number;\n}\n\n/** Resolve the tab key for a field: uses formTab if set, otherwise 'basicData'. */\nfunction getFieldTabKey(fieldName: string, formTab?: string): string {\n  return formTab ?? 'basicData';\n}\n\nexport function TabBar({\n  definition,\n  activeTabKey,\n  errors,\n  onTabChange,\n  navigationType,\n  formMode,\n  detailTabConfigs,\n  t,\n}: TabBarProps) {\n  const tt = useMemo(\n    () => t ?? ((key: string, defaultValue?: string) => defaultValue ?? key),\n    [t],\n  );\n  const items = useMemo((): ResolvedTab[] => {\n    const contentTabs = definition.tabs ?? [];\n    const isModal = navigationType === 'modal';\n    const showDetailTabs = (formMode === 'creating' || formMode === 'editing' || formMode === 'viewing') && (detailTabConfigs?.length ?? 0) > 0;\n\n    let visibleContentTabs = contentTabs;\n    if (isModal && contentTabs.length > 1) {\n      console.warn(\n        '[MasterPatternView] navigationType=\"modal\" with more than 1 content tab is not supported. ' +\n          'Only \"Datos básicos *\" and the first content tab will be shown.'\n      );\n      visibleContentTabs = contentTabs.slice(0, 1);\n    }\n\n    // Count errors per tab key\n    const errorCountByTab: Record<string, number> = {};\n    for (const [fieldName] of Object.entries(errors)) {\n      const field = getAllFields(definition).find((f) => f.fieldName === fieldName);\n      const tabKey = getFieldTabKey(fieldName, field?.formTab);\n      errorCountByTab[tabKey] = (errorCountByTab[tabKey] ?? 0) + 1;\n    }\n\n    const basicDataTab: ResolvedTab = {\n      id: 'basicData',\n      label: tt('basicDataTabLabel', 'Datos básicos'),\n      badge: errorCountByTab['basicData'],\n    };\n\n    const additionalTabs: ResolvedTab[] = visibleContentTabs\n      .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))\n      .map((t) => ({\n        id: t.key,\n        label: t.label,\n        badge: errorCountByTab[t.key],\n      }));\n\n    const detailTabs: ResolvedTab[] = showDetailTabs\n      ? (detailTabConfigs ?? []).map((dt) => ({ id: dt.key, label: dt.label }))\n      : [];\n\n    return [basicDataTab, ...additionalTabs, ...detailTabs];\n  }, [definition, errors, navigationType, formMode, detailTabConfigs, tt]);\n\n  // A single tab (just \"Datos básicos\", no content/detail tabs) has nothing to switch\n  // between — showing a one-item tab strip only adds visual noise.\n  if (items.length <= 1) return null;\n\n  return (\n    <div\n      data-testid=\"tabs\"\n      // overflow-x-auto by itself makes the browser also treat overflow-y as\n      // \"auto\" (per the CSS overflow spec — setting one axis forces the other\n      // off \"visible\"), so a 1px content/box-sizing mismatch was enough to pop\n      // a vertical scrollbar (complete with ugly up/down arrow buttons on\n      // Windows) that had nothing real to scroll. overflow-y-hidden pins it.\n      className=\"flex flex-shrink-0 overflow-x-auto overflow-y-hidden gap-1 px-3 pt-2\"\n    >\n      {items.map((item) => {\n        const isActive = item.id === activeTabKey;\n        const isBasicData = item.id === 'basicData';\n\n        return (\n          <motion.button\n            key={item.id}\n            type=\"button\"\n            data-testid={`tab-${item.id}`}\n            data-active={isActive}\n            onClick={() => onTabChange(item.id)}\n            whileTap={{ scaleX: 0.94 }}\n            animate={{ scaleX: isActive ? 1.04 : 1 }}\n            transition={{ type: 'spring', bounce: 0.55, duration: 0.5 }}\n            className={`relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-zinc-900 transition-colors ${\n              isActive\n                ? 'text-blue-600 dark:text-blue-400'\n                : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800'\n            }`}\n          >\n            {isBasicData ? (\n              <>\n                {tt('basicDataTabLabel', 'Datos básicos')}{' '}\n                <span className=\"text-red-500 text-xs\">*</span>\n              </>\n            ) : (\n              item.label\n            )}\n            {item.badge != null && item.badge > 0 && (\n              <span\n                data-testid={`tab-error-badge-${item.id}`}\n                className=\"inline-flex items-center justify-center w-4 h-4 bg-[#dc2626] text-white rounded-full text-[9px] font-bold\"\n              >\n                {item.badge}\n              </span>\n            )}\n            {isActive && (\n              <motion.div\n                layoutId=\"mpv-tab-active-indicator\"\n                className=\"absolute inset-x-0 bottom-0 h-0.5 rounded-full bg-blue-600 dark:bg-blue-400\"\n                transition={{ type: 'spring', bounce: 0.55, duration: 0.5 }}\n              />\n            )}\n          </motion.button>\n        );\n      })}\n    </div>\n  );\n}\n","/**\n * SidebarPanel — absolute-positioned right panel with CSS slide-in animation.\n * Scoped to the MasterPatternView container (position: absolute, not fixed)\n * so it does not cover the application AppShell.\n *\n * @module components/form/SidebarPanel\n * @see FMPV-MVWC-E003-S001 I-002\n */\nimport React, { type ReactNode } from 'react';\n\nexport interface SidebarPanelProps {\n  isOpen: boolean;\n  children: ReactNode;\n  width?: string;\n  onBackdropClick?: () => void;\n}\n\nexport function SidebarPanel({\n  isOpen,\n  children,\n  width = '480px',\n  onBackdropClick,\n}: SidebarPanelProps) {\n  if (!isOpen) return null;\n\n  return (\n    <>\n      {/* Backdrop — covers only the MasterPatternView container */}\n      <div\n        className=\"absolute inset-0 bg-black/20 z-20\"\n        onClick={onBackdropClick}\n        aria-hidden=\"true\"\n      />\n      {/* Panel */}\n      <div\n        data-testid=\"sidebar-panel\"\n        className=\"absolute right-0 top-0 h-full bg-background-secondary dark:bg-dark-bg-secondary shadow-xl z-30 flex flex-col overflow-hidden\"\n        style={{ width, willChange: 'transform', transition: 'transform 200ms ease-out' }}\n        role=\"dialog\"\n        aria-modal=\"true\"\n      >\n        {children}\n      </div>\n    </>\n  );\n}\n","/**\n * ModalPanel — centered overlay modal.\n * siesa-ui-kit does not export a Modal component; custom implementation.\n * Focus trap: Escape key triggers onClose.\n *\n * @module components/form/ModalPanel\n * @see FMPV-MVWC-E003-S001 I-002\n */\nimport React, { type ReactNode, useEffect, useRef } from 'react';\n\nexport interface ModalPanelProps {\n  isOpen: boolean;\n  children: ReactNode;\n  onClose: () => void;\n  /** Custom modal width. Accepts any valid CSS value (e.g. '800px', '70vw'). Default: '640px' */\n  width?: string;\n  /** Custom modal max-height. Accepts any valid CSS value (e.g. '600px', '80vh'). Default: '90vh' */\n  maxHeight?: string;\n}\n\nexport function ModalPanel({ isOpen, children, onClose, width = '640px', maxHeight = '90vh' }: ModalPanelProps) {\n  const panelRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    if (!isOpen) return;\n    const handleKeyDown = (e: KeyboardEvent) => {\n      if (e.key === 'Escape') onClose();\n    };\n    document.addEventListener('keydown', handleKeyDown);\n    return () => document.removeEventListener('keydown', handleKeyDown);\n  }, [isOpen, onClose]);\n\n  if (!isOpen) return null;\n\n  return (\n    <div\n      className=\"absolute inset-0 bg-black/40 z-50 flex items-center justify-center\"\n      onClick={(e) => {\n        if (e.target === e.currentTarget) onClose();\n      }}\n      role=\"dialog\"\n      aria-modal=\"true\"\n    >\n      <div\n        ref={panelRef}\n        data-testid=\"modal-panel\"\n        className=\"bg-background-secondary dark:bg-dark-bg-secondary rounded-lg shadow-2xl flex flex-col overflow-hidden\"\n        style={{ width, maxHeight }}\n      >\n        {children}\n      </div>\n    </div>\n  );\n}\n","/**\n * PagePanel — full-area form replacement (hides the list).\n * Scoped to the MasterPatternView container (position: absolute, not fixed)\n * so it does not cover the application AppShell.\n *\n * @module components/form/PagePanel\n * @see FMPV-MVWC-E003-S001 I-002\n */\nimport React, { type ReactNode } from 'react';\n\nexport interface PagePanelProps {\n  isOpen: boolean;\n  children: ReactNode;\n}\n\nexport function PagePanel({ isOpen, children }: PagePanelProps) {\n  if (!isOpen) return null;\n\n  return (\n    <div\n      data-testid=\"page-panel\"\n      className=\"absolute inset-0 z-30 flex flex-col overflow-y-auto mpv-page-panel-enter\"\n      role=\"main\"\n    >\n      {children}\n    </div>\n  );\n}\n","import { type ClassValue, clsx } from 'clsx'\nimport { twMerge } from 'tailwind-merge'\n\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(clsx(inputs))\n}\n","/**\n * Interpolates a template string with record field values.\n *\n * @example\n * interpolateTemplate(\"{codigo} - {nombre}\", { codigo: \"C001\", nombre: \"Acme\" })\n * // Returns: \"C001 - Acme\"\n *\n * @param template - Template string with {fieldName} placeholders\n * @param record - Record object with field values\n * @returns Interpolated string with placeholders replaced by values\n */\nexport function interpolateTemplate<TRecord extends Record<string, unknown>>(\n  template: string,\n  record: TRecord\n): string {\n  return template.replace(/\\{(\\w+)\\}/g, (_, fieldName) => {\n    const value = record[fieldName]\n    return value !== undefined && value !== null ? String(value) : ''\n  })\n}\n","import type { FilterExpression } from '../types/filter.types'\n\n/**\n * Custom fetcher function type for HTTP requests (FR29, FR31).\n * Receives the entity name and request, returns the search response.\n * Gives full control over URL construction, HTTP client, headers, etc.\n *\n * @example\n * // Using fetch with custom URL and auth. Throwing `ApiError` (not a plain `Error`)\n * // lets LookupField show a message the user can act on — \"no tienes permisos\",\n * // \"tu sesión expiró\", etc. — instead of the raw status code; a plain `Error` still\n * // works, it just falls back to a generic message since there's no status to read.\n * const fetcher: Fetcher = async (entity, request) => {\n *   const response = await fetch(`/api/v2/${entity}/search`, {\n *     method: 'POST',\n *     headers: {\n *       'Content-Type': 'application/json',\n *       'Authorization': `Bearer ${getToken()}`,\n *     },\n *     body: JSON.stringify(request),\n *   })\n *   if (!response.ok) throw new ApiError(`API Error: ${response.status}`, response.status, response.statusText)\n *   return response.json()\n * }\n *\n * @example\n * // Using axios\n * const fetcher: Fetcher = async (entity, request) => {\n *   const { data } = await axios.post(`/api/${entity}/search`, request)\n *   return data\n * }\n *\n * @example\n * // Using the createFetcher helper for simple cases\n * import { createFetcher } from 'siesa-ui-kit'\n * const fetcher = createFetcher('/api')\n */\nexport type Fetcher = <TRecord = Record<string, unknown>>(\n  entity: string,\n  request: SearchRequest\n) => Promise<SearchResponse<TRecord>>\n\n/** Sort configuration for API requests (FR17) */\nexport interface OrderBy {\n  /** Field name to sort by */\n  field: string\n  /** Sort direction */\n  direction: 'asc' | 'desc'\n}\n\n/**\n * How `search` should match against `searchFields`.\n * - `'startsWith'` — matches records whose field begins with the search text (default)\n * - `'contains'` — matches records whose field contains the search text anywhere\n * - `'equals'` — exact match. Not user-facing (no toggle icon for it) — LookupField uses\n *   this internally when the user types a full code and presses Enter without having\n *   navigated to a result, to resolve/verify that exact record instead of guessing from\n *   a prefix/substring match.\n */\nexport type SearchOperator = 'startsWith' | 'contains' | 'equals'\n\n/** Request body for search API calls */\nexport interface SearchRequest {\n  /** Fields to return in the response (always includes 'Id' - PascalCase standard) */\n  fields: string[]\n  /** Search text (empty for initial load) */\n  search?: string\n  /** Fields to search against (defaults to displayFields) */\n  searchFields?: string[]\n  /**\n   * How `search` should be matched. Defaults to `'startsWith'`. `'startsWith'`/`'contains'`\n   * are toggled by the user via the icons inside the search box; `'equals'` is only ever\n   * sent by LookupField itself (Enter-to-resolve-exact-code), never user-toggled. The\n   * fetcher/backend is responsible for actually applying it — LookupField only tracks and\n   * forwards the chosen mode.\n   */\n  searchOperator?: SearchOperator\n  /** Page number (1-indexed) */\n  page: number\n  /** Records per page */\n  pageSize: number\n  /** Filter conditions in expressive format */\n  filters?: FilterExpression\n  /** Sort order for results */\n  orderBy?: OrderBy\n}\n\n/** Response body from search API calls [UPDATED v0.4 - removed total] */\nexport interface SearchResponse<TRecord> {\n  /** Array of matching records */\n  data: TRecord[]\n  /** Current page number */\n  page: number\n  /** Page size used */\n  pageSize: number\n}\n\n/**\n * Error thrown when an API request fails. `createFetcher` throws this automatically;\n * a custom `Fetcher` should throw it too (instead of a plain `Error`) so LookupField\n * can turn `status` into a message the user can actually act on — see\n * `getFriendlyErrorMessage` and the `error.*` translation keys.\n */\nexport class ApiError extends Error {\n  constructor(\n    message: string,\n    public readonly status: number,\n    public readonly statusText: string\n  ) {\n    super(message)\n    this.name = 'ApiError'\n  }\n}\n","import { ApiError } from '../services/api.types'\nimport type { TFunction } from '../hooks/useTranslationSafe'\n\n/**\n * Turns a fetch failure into a message an end user can actually act on, instead of\n * a raw \"API Error: 403 Forbidden\" (or whatever the network layer happened to throw).\n * Only `ApiError` (thrown by the kit's own `createFetcher`) carries a real HTTP status\n * to branch on — a custom `fetcher` can throw anything, so unrecognized shapes still\n * fall back to the original generic `error` message (interpolating `.message`) rather\n * than guessing.\n */\nexport function getFriendlyErrorMessage(error: Error, t: TFunction): string {\n  if (error instanceof ApiError) {\n    switch (error.status) {\n      case 401:\n        return t('error.unauthorized')\n      case 403:\n        return t('error.forbidden')\n      case 404:\n        return t('error.notFound')\n      case 408:\n        return t('error.timeout')\n      case 429:\n        return t('error.rateLimited')\n      default:\n        if (error.status >= 500) return t('error.server')\n        break\n    }\n  }\n\n  // A custom fetcher's own network failure (fetch()/axios rejecting before a response\n  // ever comes back — offline, DNS failure, CORS, connection reset) has no HTTP status\n  // at all; browsers surface it as a TypeError with this wording in both Chromium and\n  // Firefox (axios instead sets `.message === 'Network Error'`).\n  if (error instanceof TypeError && /fetch|network/i.test(error.message)) {\n    return t('error.network')\n  }\n  if (error.message === 'Network Error') {\n    return t('error.network')\n  }\n\n  return t('error', { message: error.message })\n}\n","import type { FilterExpression, SimpleFilter } from '../types/filter.types'\n\n/**\n * Type guard to check if filter is already in expressive format\n * @param filter - Filter to check\n * @returns true if filter is FilterExpression (array of arrays)\n */\nexport function isExpressiveFilter(filter: unknown): filter is FilterExpression {\n  return Array.isArray(filter) && filter.every(Array.isArray)\n}\n\n/**\n * Converts simple filter object to expressive format\n * Each key-value pair becomes a separate AND condition\n *\n * @example\n * buildExpressiveFilter({ activo: true, tipo: \"A\" })\n * // Returns: [[{ activo: true }], [{ tipo: \"A\" }]]\n *\n * @param simpleFilter - Simple filter object\n * @returns Expressive filter format\n */\nexport function buildExpressiveFilter(simpleFilter: SimpleFilter): FilterExpression {\n  return Object.entries(simpleFilter).map(([key, value]) => [{ [key]: value }])\n}\n\n/**\n * Normalizes filter input to expressive format\n * Passes through expressive filters unchanged, converts simple filters\n *\n * @param filters - Simple or expressive filter (or undefined)\n * @returns Expressive filter format or undefined\n */\nexport function normalizeFilters(\n  filters?: SimpleFilter | FilterExpression\n): FilterExpression | undefined {\n  if (!filters) return undefined\n  if (isExpressiveFilter(filters)) return filters\n  return buildExpressiveFilter(filters as SimpleFilter)\n}\n\n/**\n * Merges multiple filter expressions with AND logic\n *\n * @param filters - Array of filter expressions to merge\n * @returns Combined filter expression\n */\nexport function mergeFilters(...filters: (FilterExpression | undefined)[]): FilterExpression {\n  return filters.filter(Boolean).flat() as FilterExpression\n}\n","import { useEffect, useState } from 'react'\n\nconst DEBOUNCE_MS = 300\n\nexport function useDebouncedSearch(value: string, delay: number = DEBOUNCE_MS): string {\n  const [debouncedValue, setDebouncedValue] = useState(value)\n\n  useEffect(() => {\n    const timer = setTimeout(() => {\n      setDebouncedValue(value)\n    }, delay)\n\n    return () => {\n      clearTimeout(timer)\n    }\n  }, [value, delay])\n\n  return debouncedValue\n}\n","import { useCallback, useState } from 'react'\n\nexport interface UseKeyboardNavigationOptions<TRecord> {\n  records: TRecord[]\n  isOpen: boolean\n  onSelect: (record: TRecord) => void\n  onClose: () => void\n  onEscape: () => void\n  onClear: () => void\n  searchQuery: string\n  /**\n   * Fired when Enter is pressed while nothing is highlighted (the user typed and hit\n   * Enter immediately, without arrowing down to a result first) and there's search text\n   * to act on. Lets the host resolve/verify an exact match (e.g. a full code) directly\n   * instead of Enter being a no-op.\n   */\n  onEnterWithoutHighlight?: (searchQuery: string) => void\n}\n\nexport interface UseKeyboardNavigationResult {\n  highlightedIndex: number\n  setHighlightedIndex: (index: number) => void\n  handleKeyDown: (event: React.KeyboardEvent) => void\n}\n\nexport function useKeyboardNavigation<TRecord>(\n  options: UseKeyboardNavigationOptions<TRecord>\n): UseKeyboardNavigationResult {\n  const { records, isOpen, onSelect, onClose, onEscape, onClear, searchQuery, onEnterWithoutHighlight } = options\n  const [highlightedIndex, setHighlightedIndex] = useState(-1)\n\n  const handleKeyDown = useCallback(\n    (event: React.KeyboardEvent) => {\n      if (!isOpen) return\n\n      switch (event.key) {\n        case 'ArrowDown': {\n          event.preventDefault()\n          if (records.length === 0) return\n          setHighlightedIndex((prev) => {\n            // Wrap from last to first, or increment\n            if (prev >= records.length - 1) return 0\n            return prev + 1\n          })\n          break\n        }\n\n        case 'ArrowUp': {\n          event.preventDefault()\n          if (records.length === 0) return\n          setHighlightedIndex((prev) => {\n            // Wrap from first to last, or decrement\n            if (prev <= 0) return records.length - 1\n            return prev - 1\n          })\n          break\n        }\n\n        case 'Home': {\n          event.preventDefault()\n          if (records.length === 0) return\n          setHighlightedIndex(0)\n          break\n        }\n\n        case 'End': {\n          event.preventDefault()\n          if (records.length === 0) return\n          setHighlightedIndex(records.length - 1)\n          break\n        }\n\n        case 'Enter': {\n          event.preventDefault()\n          if (highlightedIndex >= 0 && highlightedIndex < records.length) {\n            onSelect(records[highlightedIndex])\n          } else if (searchQuery.trim().length > 0) {\n            onEnterWithoutHighlight?.(searchQuery)\n          }\n          break\n        }\n\n        case 'Escape': {\n          event.preventDefault()\n          onEscape()\n          break\n        }\n\n        case 'Backspace': {\n          // Only clear selection if search input is empty\n          if (searchQuery === '') {\n            onClear()\n          }\n          // Don't prevent default - allow normal backspace behavior in input\n          break\n        }\n\n        case 'Tab': {\n          // Close dropdown but don't prevent default - allow focus to move to next element\n          onClose()\n          break\n        }\n\n        default:\n          break\n      }\n    },\n    [isOpen, records, highlightedIndex, onSelect, onClose, onEscape, onClear, searchQuery, onEnterWithoutHighlight]\n  )\n\n  return {\n    highlightedIndex,\n    setHighlightedIndex,\n    handleKeyDown,\n  }\n}\n","import { useTranslation } from 'react-i18next'\n\nconst FALLBACK_STRINGS: Record<string, string> = {\n  placeholder: 'Seleccionar...',\n  searchPlaceholder: 'Buscar...',\n  noResults: 'No se encontraron resultados',\n  loading: 'Cargando...',\n  minChars: 'Escribe al menos {{count}} caracteres',\n  error: 'Ocurrió un error: {{message}}',\n  'error.network': 'No se pudo conectar con el servidor. Revisa tu conexión a internet.',\n  'error.unauthorized': 'Tu sesión expiró. Inicia sesión de nuevo.',\n  'error.forbidden': 'No tienes permisos para ver esta información.',\n  'error.notFound': 'No se encontró la información solicitada.',\n  'error.timeout': 'La solicitud tardó demasiado. Intenta de nuevo.',\n  'error.rateLimited': 'Demasiadas solicitudes. Espera un momento e intenta de nuevo.',\n  'error.server': 'Ocurrió un error en el servidor. Intenta más tarde.',\n  notFound: '[Registro no encontrado]',\n  clear: 'Limpiar selección',\n  createNew: 'Crear nuevo',\n  searchOperatorStartsWith: 'Empieza con',\n  searchOperatorContains: 'Contiene',\n  exactMatchNotFound: 'No se encontró ningún registro con el código exacto \"{{value}}\"',\n  open: 'Abrir lista',\n  close: 'Cerrar lista',\n  'announcements.loading': 'Cargando resultados',\n  'announcements.noResults': 'No se encontraron resultados',\n  'announcements.cleared': 'Selección eliminada',\n  'announcements.opened': 'Lista abierta, {{count}} resultados disponibles',\n  'announcements.closed': 'Lista cerrada',\n  'announcements.selected': '{{value}} seleccionado',\n  'announcements.resultsLoaded': '{{count}} resultados cargados',\n  'announcements.exactMatchNotFound': 'No se encontró ningún registro con el código exacto {{value}}',\n  'announcements.exactMatchResolving': 'Buscando código exacto {{value}}',\n  'validation.required': 'Este campo es requerido',\n  'validation.requiredIndicator': '*',\n}\n\nfunction interpolate(template: string, params?: Record<string, unknown>): string {\n  if (!params) return template\n  return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key) => String(params[key] ?? ''))\n}\n\nexport type TFunction = (key: string, params?: Record<string, unknown>) => string\n\ninterface UseTranslationSafeResult {\n  t: TFunction\n  i18n: ReturnType<typeof useTranslation>['i18n'] | null\n}\n\nexport function useTranslationSafe(): UseTranslationSafeResult {\n  try {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    const { t: i18nT, i18n } = useTranslation('lookupField')\n    // If i18n is not initialized, fall back\n    if (!i18n.isInitialized) {\n      throw new Error('i18n not initialized')\n    }\n    return {\n      t: (key: string, params?: Record<string, unknown>) =>\n        params ? i18nT(key, params as Record<string, string | number>) : i18nT(key),\n      i18n,\n    }\n  } catch {\n    // Return fallback t function when i18next is not available\n    const fallbackT: TFunction = (key: string, params?: Record<string, unknown>) => {\n      const template = FALLBACK_STRINGS[key] ?? key\n      return interpolate(template, params)\n    }\n    return { t: fallbackT, i18n: null }\n  }\n}\n","import { type RefObject, useCallback, useEffect } from 'react'\n\n/**\n * Hook to detect clicks outside a referenced element.\n * Uses mousedown for immediate detection.\n *\n * @param ref - Reference to the element to monitor\n * @param handler - Callback when click outside occurs\n * @param enabled - Whether the hook is active (default: true)\n * @param excludeRefs - Additional refs to exclude from outside detection (e.g., portaled elements)\n */\nexport function useClickOutside<T extends HTMLElement>(\n  ref: RefObject<T | null>,\n  handler: (event: MouseEvent) => void,\n  enabled: boolean = true,\n  excludeRefs?: RefObject<HTMLElement | null>[]\n): void {\n  const handleClickOutside = useCallback(\n    (event: MouseEvent) => {\n      const target = event.target as Node\n      if (ref.current && !ref.current.contains(target)) {\n        const isInExcluded = excludeRefs?.some(\n          (excludeRef) => excludeRef.current?.contains(target)\n        )\n        if (!isInExcluded) {\n          handler(event)\n        }\n      }\n    },\n    [ref, handler, excludeRefs]\n  )\n\n  useEffect(() => {\n    if (!enabled) return\n\n    // Use mousedown for immediate detection (before click completes)\n    document.addEventListener('mousedown', handleClickOutside)\n\n    return () => {\n      document.removeEventListener('mousedown', handleClickOutside)\n    }\n  }, [handleClickOutside, enabled])\n}\n","function memo(getDeps, fn, opts) {\n  let deps = opts.initialDeps ?? [];\n  let result;\n  let isInitial = true;\n  function memoizedFunction() {\n    var _a, _b, _c;\n    let depTime;\n    if (opts.key && ((_a = opts.debug) == null ? void 0 : _a.call(opts))) depTime = Date.now();\n    const newDeps = getDeps();\n    const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);\n    if (!depsChanged) {\n      return result;\n    }\n    deps = newDeps;\n    let resultTime;\n    if (opts.key && ((_b = opts.debug) == null ? void 0 : _b.call(opts))) resultTime = Date.now();\n    result = fn(...newDeps);\n    if (opts.key && ((_c = opts.debug) == null ? void 0 : _c.call(opts))) {\n      const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;\n      const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;\n      const resultFpsPercentage = resultEndTime / 16;\n      const pad = (str, num) => {\n        str = String(str);\n        while (str.length < num) {\n          str = \" \" + str;\n        }\n        return str;\n      };\n      console.info(\n        `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n        `\n            font-size: .6rem;\n            font-weight: bold;\n            color: hsl(${Math.max(\n          0,\n          Math.min(120 - 120 * resultFpsPercentage, 120)\n        )}deg 100% 31%);`,\n        opts == null ? void 0 : opts.key\n      );\n    }\n    if ((opts == null ? void 0 : opts.onChange) && !(isInitial && opts.skipInitialOnChange)) {\n      opts.onChange(result);\n    }\n    isInitial = false;\n    return result;\n  }\n  memoizedFunction.updateDeps = (newDeps) => {\n    deps = newDeps;\n  };\n  return memoizedFunction;\n}\nfunction notUndefined(value, msg) {\n  if (value === void 0) {\n    throw new Error(`Unexpected undefined${msg ? `: ${msg}` : \"\"}`);\n  } else {\n    return value;\n  }\n}\nconst approxEqual = (a, b) => Math.abs(a - b) < 1.01;\nconst debounce = (targetWindow, fn, ms) => {\n  let timeoutId;\n  return function(...args) {\n    targetWindow.clearTimeout(timeoutId);\n    timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms);\n  };\n};\nexport {\n  approxEqual,\n  debounce,\n  memo,\n  notUndefined\n};\n//# sourceMappingURL=utils.js.map\n","import { debounce, memo, notUndefined, approxEqual } from \"./utils.js\";\nconst getRect = (element) => {\n  const { offsetWidth, offsetHeight } = element;\n  return { width: offsetWidth, height: offsetHeight };\n};\nconst defaultKeyExtractor = (index) => index;\nconst defaultRangeExtractor = (range) => {\n  const start = Math.max(range.startIndex - range.overscan, 0);\n  const end = Math.min(range.endIndex + range.overscan, range.count - 1);\n  const arr = [];\n  for (let i = start; i <= end; i++) {\n    arr.push(i);\n  }\n  return arr;\n};\nconst observeElementRect = (instance, cb) => {\n  const element = instance.scrollElement;\n  if (!element) {\n    return;\n  }\n  const targetWindow = instance.targetWindow;\n  if (!targetWindow) {\n    return;\n  }\n  const handler = (rect) => {\n    const { width, height } = rect;\n    cb({ width: Math.round(width), height: Math.round(height) });\n  };\n  handler(getRect(element));\n  if (!targetWindow.ResizeObserver) {\n    return () => {\n    };\n  }\n  const observer = new targetWindow.ResizeObserver((entries) => {\n    const run = () => {\n      const entry = entries[0];\n      if (entry == null ? void 0 : entry.borderBoxSize) {\n        const box = entry.borderBoxSize[0];\n        if (box) {\n          handler({ width: box.inlineSize, height: box.blockSize });\n          return;\n        }\n      }\n      handler(getRect(element));\n    };\n    instance.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();\n  });\n  observer.observe(element, { box: \"border-box\" });\n  return () => {\n    observer.unobserve(element);\n  };\n};\nconst addEventListenerOptions = {\n  passive: true\n};\nconst observeWindowRect = (instance, cb) => {\n  const element = instance.scrollElement;\n  if (!element) {\n    return;\n  }\n  const handler = () => {\n    cb({ width: element.innerWidth, height: element.innerHeight });\n  };\n  handler();\n  element.addEventListener(\"resize\", handler, addEventListenerOptions);\n  return () => {\n    element.removeEventListener(\"resize\", handler);\n  };\n};\nconst supportsScrollend = typeof window == \"undefined\" ? true : \"onscrollend\" in window;\nconst observeElementOffset = (instance, cb) => {\n  const element = instance.scrollElement;\n  if (!element) {\n    return;\n  }\n  const targetWindow = instance.targetWindow;\n  if (!targetWindow) {\n    return;\n  }\n  let offset = 0;\n  const fallback = instance.options.useScrollendEvent && supportsScrollend ? () => void 0 : debounce(\n    targetWindow,\n    () => {\n      cb(offset, false);\n    },\n    instance.options.isScrollingResetDelay\n  );\n  const createHandler = (isScrolling) => () => {\n    const { horizontal, isRtl } = instance.options;\n    offset = horizontal ? element[\"scrollLeft\"] * (isRtl && -1 || 1) : element[\"scrollTop\"];\n    fallback();\n    cb(offset, isScrolling);\n  };\n  const handler = createHandler(true);\n  const endHandler = createHandler(false);\n  element.addEventListener(\"scroll\", handler, addEventListenerOptions);\n  const registerScrollendEvent = instance.options.useScrollendEvent && supportsScrollend;\n  if (registerScrollendEvent) {\n    element.addEventListener(\"scrollend\", endHandler, addEventListenerOptions);\n  }\n  return () => {\n    element.removeEventListener(\"scroll\", handler);\n    if (registerScrollendEvent) {\n      element.removeEventListener(\"scrollend\", endHandler);\n    }\n  };\n};\nconst observeWindowOffset = (instance, cb) => {\n  const element = instance.scrollElement;\n  if (!element) {\n    return;\n  }\n  const targetWindow = instance.targetWindow;\n  if (!targetWindow) {\n    return;\n  }\n  let offset = 0;\n  const fallback = instance.options.useScrollendEvent && supportsScrollend ? () => void 0 : debounce(\n    targetWindow,\n    () => {\n      cb(offset, false);\n    },\n    instance.options.isScrollingResetDelay\n  );\n  const createHandler = (isScrolling) => () => {\n    offset = element[instance.options.horizontal ? \"scrollX\" : \"scrollY\"];\n    fallback();\n    cb(offset, isScrolling);\n  };\n  const handler = createHandler(true);\n  const endHandler = createHandler(false);\n  element.addEventListener(\"scroll\", handler, addEventListenerOptions);\n  const registerScrollendEvent = instance.options.useScrollendEvent && supportsScrollend;\n  if (registerScrollendEvent) {\n    element.addEventListener(\"scrollend\", endHandler, addEventListenerOptions);\n  }\n  return () => {\n    element.removeEventListener(\"scroll\", handler);\n    if (registerScrollendEvent) {\n      element.removeEventListener(\"scrollend\", endHandler);\n    }\n  };\n};\nconst measureElement = (element, entry, instance) => {\n  if (entry == null ? void 0 : entry.borderBoxSize) {\n    const box = entry.borderBoxSize[0];\n    if (box) {\n      const size = Math.round(\n        box[instance.options.horizontal ? \"inlineSize\" : \"blockSize\"]\n      );\n      return size;\n    }\n  }\n  return element[instance.options.horizontal ? \"offsetWidth\" : \"offsetHeight\"];\n};\nconst windowScroll = (offset, {\n  adjustments = 0,\n  behavior\n}, instance) => {\n  var _a, _b;\n  const toOffset = offset + adjustments;\n  (_b = (_a = instance.scrollElement) == null ? void 0 : _a.scrollTo) == null ? void 0 : _b.call(_a, {\n    [instance.options.horizontal ? \"left\" : \"top\"]: toOffset,\n    behavior\n  });\n};\nconst elementScroll = (offset, {\n  adjustments = 0,\n  behavior\n}, instance) => {\n  var _a, _b;\n  const toOffset = offset + adjustments;\n  (_b = (_a = instance.scrollElement) == null ? void 0 : _a.scrollTo) == null ? void 0 : _b.call(_a, {\n    [instance.options.horizontal ? \"left\" : \"top\"]: toOffset,\n    behavior\n  });\n};\nclass Virtualizer {\n  constructor(opts) {\n    this.unsubs = [];\n    this.scrollElement = null;\n    this.targetWindow = null;\n    this.isScrolling = false;\n    this.currentScrollToIndex = null;\n    this.measurementsCache = [];\n    this.itemSizeCache = /* @__PURE__ */ new Map();\n    this.laneAssignments = /* @__PURE__ */ new Map();\n    this.pendingMeasuredCacheIndexes = [];\n    this.prevLanes = void 0;\n    this.lanesChangedFlag = false;\n    this.lanesSettling = false;\n    this.scrollRect = null;\n    this.scrollOffset = null;\n    this.scrollDirection = null;\n    this.scrollAdjustments = 0;\n    this.elementsCache = /* @__PURE__ */ new Map();\n    this.observer = /* @__PURE__ */ (() => {\n      let _ro = null;\n      const get = () => {\n        if (_ro) {\n          return _ro;\n        }\n        if (!this.targetWindow || !this.targetWindow.ResizeObserver) {\n          return null;\n        }\n        return _ro = new this.targetWindow.ResizeObserver((entries) => {\n          entries.forEach((entry) => {\n            const run = () => {\n              this._measureElement(entry.target, entry);\n            };\n            this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();\n          });\n        });\n      };\n      return {\n        disconnect: () => {\n          var _a;\n          (_a = get()) == null ? void 0 : _a.disconnect();\n          _ro = null;\n        },\n        observe: (target) => {\n          var _a;\n          return (_a = get()) == null ? void 0 : _a.observe(target, { box: \"border-box\" });\n        },\n        unobserve: (target) => {\n          var _a;\n          return (_a = get()) == null ? void 0 : _a.unobserve(target);\n        }\n      };\n    })();\n    this.range = null;\n    this.setOptions = (opts2) => {\n      Object.entries(opts2).forEach(([key, value]) => {\n        if (typeof value === \"undefined\") delete opts2[key];\n      });\n      this.options = {\n        debug: false,\n        initialOffset: 0,\n        overscan: 1,\n        paddingStart: 0,\n        paddingEnd: 0,\n        scrollPaddingStart: 0,\n        scrollPaddingEnd: 0,\n        horizontal: false,\n        getItemKey: defaultKeyExtractor,\n        rangeExtractor: defaultRangeExtractor,\n        onChange: () => {\n        },\n        measureElement,\n        initialRect: { width: 0, height: 0 },\n        scrollMargin: 0,\n        gap: 0,\n        indexAttribute: \"data-index\",\n        initialMeasurementsCache: [],\n        lanes: 1,\n        isScrollingResetDelay: 150,\n        enabled: true,\n        isRtl: false,\n        useScrollendEvent: false,\n        useAnimationFrameWithResizeObserver: false,\n        ...opts2\n      };\n    };\n    this.notify = (sync) => {\n      var _a, _b;\n      (_b = (_a = this.options).onChange) == null ? void 0 : _b.call(_a, this, sync);\n    };\n    this.maybeNotify = memo(\n      () => {\n        this.calculateRange();\n        return [\n          this.isScrolling,\n          this.range ? this.range.startIndex : null,\n          this.range ? this.range.endIndex : null\n        ];\n      },\n      (isScrolling) => {\n        this.notify(isScrolling);\n      },\n      {\n        key: process.env.NODE_ENV !== \"production\" && \"maybeNotify\",\n        debug: () => this.options.debug,\n        initialDeps: [\n          this.isScrolling,\n          this.range ? this.range.startIndex : null,\n          this.range ? this.range.endIndex : null\n        ]\n      }\n    );\n    this.cleanup = () => {\n      this.unsubs.filter(Boolean).forEach((d) => d());\n      this.unsubs = [];\n      this.observer.disconnect();\n      this.scrollElement = null;\n      this.targetWindow = null;\n    };\n    this._didMount = () => {\n      return () => {\n        this.cleanup();\n      };\n    };\n    this._willUpdate = () => {\n      var _a;\n      const scrollElement = this.options.enabled ? this.options.getScrollElement() : null;\n      if (this.scrollElement !== scrollElement) {\n        this.cleanup();\n        if (!scrollElement) {\n          this.maybeNotify();\n          return;\n        }\n        this.scrollElement = scrollElement;\n        if (this.scrollElement && \"ownerDocument\" in this.scrollElement) {\n          this.targetWindow = this.scrollElement.ownerDocument.defaultView;\n        } else {\n          this.targetWindow = ((_a = this.scrollElement) == null ? void 0 : _a.window) ?? null;\n        }\n        this.elementsCache.forEach((cached) => {\n          this.observer.observe(cached);\n        });\n        this.unsubs.push(\n          this.options.observeElementRect(this, (rect) => {\n            this.scrollRect = rect;\n            this.maybeNotify();\n          })\n        );\n        this.unsubs.push(\n          this.options.observeElementOffset(this, (offset, isScrolling) => {\n            this.scrollAdjustments = 0;\n            this.scrollDirection = isScrolling ? this.getScrollOffset() < offset ? \"forward\" : \"backward\" : null;\n            this.scrollOffset = offset;\n            this.isScrolling = isScrolling;\n            this.maybeNotify();\n          })\n        );\n        this._scrollToOffset(this.getScrollOffset(), {\n          adjustments: void 0,\n          behavior: void 0\n        });\n      }\n    };\n    this.getSize = () => {\n      if (!this.options.enabled) {\n        this.scrollRect = null;\n        return 0;\n      }\n      this.scrollRect = this.scrollRect ?? this.options.initialRect;\n      return this.scrollRect[this.options.horizontal ? \"width\" : \"height\"];\n    };\n    this.getScrollOffset = () => {\n      if (!this.options.enabled) {\n        this.scrollOffset = null;\n        return 0;\n      }\n      this.scrollOffset = this.scrollOffset ?? (typeof this.options.initialOffset === \"function\" ? this.options.initialOffset() : this.options.initialOffset);\n      return this.scrollOffset;\n    };\n    this.getFurthestMeasurement = (measurements, index) => {\n      const furthestMeasurementsFound = /* @__PURE__ */ new Map();\n      const furthestMeasurements = /* @__PURE__ */ new Map();\n      for (let m = index - 1; m >= 0; m--) {\n        const measurement = measurements[m];\n        if (furthestMeasurementsFound.has(measurement.lane)) {\n          continue;\n        }\n        const previousFurthestMeasurement = furthestMeasurements.get(\n          measurement.lane\n        );\n        if (previousFurthestMeasurement == null || measurement.end > previousFurthestMeasurement.end) {\n          furthestMeasurements.set(measurement.lane, measurement);\n        } else if (measurement.end < previousFurthestMeasurement.end) {\n          furthestMeasurementsFound.set(measurement.lane, true);\n        }\n        if (furthestMeasurementsFound.size === this.options.lanes) {\n          break;\n        }\n      }\n      return furthestMeasurements.size === this.options.lanes ? Array.from(furthestMeasurements.values()).sort((a, b) => {\n        if (a.end === b.end) {\n          return a.index - b.index;\n        }\n        return a.end - b.end;\n      })[0] : void 0;\n    };\n    this.getMeasurementOptions = memo(\n      () => [\n        this.options.count,\n        this.options.paddingStart,\n        this.options.scrollMargin,\n        this.options.getItemKey,\n        this.options.enabled,\n        this.options.lanes\n      ],\n      (count, paddingStart, scrollMargin, getItemKey, enabled, lanes) => {\n        const lanesChanged = this.prevLanes !== void 0 && this.prevLanes !== lanes;\n        if (lanesChanged) {\n          this.lanesChangedFlag = true;\n        }\n        this.prevLanes = lanes;\n        this.pendingMeasuredCacheIndexes = [];\n        return {\n          count,\n          paddingStart,\n          scrollMargin,\n          getItemKey,\n          enabled,\n          lanes\n        };\n      },\n      {\n        key: false\n      }\n    );\n    this.getMeasurements = memo(\n      () => [this.getMeasurementOptions(), this.itemSizeCache],\n      ({ count, paddingStart, scrollMargin, getItemKey, enabled, lanes }, itemSizeCache) => {\n        if (!enabled) {\n          this.measurementsCache = [];\n          this.itemSizeCache.clear();\n          this.laneAssignments.clear();\n          return [];\n        }\n        if (this.laneAssignments.size > count) {\n          for (const index of this.laneAssignments.keys()) {\n            if (index >= count) {\n              this.laneAssignments.delete(index);\n            }\n          }\n        }\n        if (this.lanesChangedFlag) {\n          this.lanesChangedFlag = false;\n          this.lanesSettling = true;\n          this.measurementsCache = [];\n          this.itemSizeCache.clear();\n          this.laneAssignments.clear();\n          this.pendingMeasuredCacheIndexes = [];\n        }\n        if (this.measurementsCache.length === 0 && !this.lanesSettling) {\n          this.measurementsCache = this.options.initialMeasurementsCache;\n          this.measurementsCache.forEach((item) => {\n            this.itemSizeCache.set(item.key, item.size);\n          });\n        }\n        const min = this.lanesSettling ? 0 : this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;\n        this.pendingMeasuredCacheIndexes = [];\n        if (this.lanesSettling && this.measurementsCache.length === count) {\n          this.lanesSettling = false;\n        }\n        const measurements = this.measurementsCache.slice(0, min);\n        const laneLastIndex = new Array(lanes).fill(\n          void 0\n        );\n        for (let m = 0; m < min; m++) {\n          const item = measurements[m];\n          if (item) {\n            laneLastIndex[item.lane] = m;\n          }\n        }\n        for (let i = min; i < count; i++) {\n          const key = getItemKey(i);\n          const cachedLane = this.laneAssignments.get(i);\n          let lane;\n          let start;\n          if (cachedLane !== void 0 && this.options.lanes > 1) {\n            lane = cachedLane;\n            const prevIndex = laneLastIndex[lane];\n            const prevInLane = prevIndex !== void 0 ? measurements[prevIndex] : void 0;\n            start = prevInLane ? prevInLane.end + this.options.gap : paddingStart + scrollMargin;\n          } else {\n            const furthestMeasurement = this.options.lanes === 1 ? measurements[i - 1] : this.getFurthestMeasurement(measurements, i);\n            start = furthestMeasurement ? furthestMeasurement.end + this.options.gap : paddingStart + scrollMargin;\n            lane = furthestMeasurement ? furthestMeasurement.lane : i % this.options.lanes;\n            if (this.options.lanes > 1) {\n              this.laneAssignments.set(i, lane);\n            }\n          }\n          const measuredSize = itemSizeCache.get(key);\n          const size = typeof measuredSize === \"number\" ? measuredSize : this.options.estimateSize(i);\n          const end = start + size;\n          measurements[i] = {\n            index: i,\n            start,\n            size,\n            end,\n            key,\n            lane\n          };\n          laneLastIndex[lane] = i;\n        }\n        this.measurementsCache = measurements;\n        return measurements;\n      },\n      {\n        key: process.env.NODE_ENV !== \"production\" && \"getMeasurements\",\n        debug: () => this.options.debug\n      }\n    );\n    this.calculateRange = memo(\n      () => [\n        this.getMeasurements(),\n        this.getSize(),\n        this.getScrollOffset(),\n        this.options.lanes\n      ],\n      (measurements, outerSize, scrollOffset, lanes) => {\n        return this.range = measurements.length > 0 && outerSize > 0 ? calculateRange({\n          measurements,\n          outerSize,\n          scrollOffset,\n          lanes\n        }) : null;\n      },\n      {\n        key: process.env.NODE_ENV !== \"production\" && \"calculateRange\",\n        debug: () => this.options.debug\n      }\n    );\n    this.getVirtualIndexes = memo(\n      () => {\n        let startIndex = null;\n        let endIndex = null;\n        const range = this.calculateRange();\n        if (range) {\n          startIndex = range.startIndex;\n          endIndex = range.endIndex;\n        }\n        this.maybeNotify.updateDeps([this.isScrolling, startIndex, endIndex]);\n        return [\n          this.options.rangeExtractor,\n          this.options.overscan,\n          this.options.count,\n          startIndex,\n          endIndex\n        ];\n      },\n      (rangeExtractor, overscan, count, startIndex, endIndex) => {\n        return startIndex === null || endIndex === null ? [] : rangeExtractor({\n          startIndex,\n          endIndex,\n          overscan,\n          count\n        });\n      },\n      {\n        key: process.env.NODE_ENV !== \"production\" && \"getVirtualIndexes\",\n        debug: () => this.options.debug\n      }\n    );\n    this.indexFromElement = (node) => {\n      const attributeName = this.options.indexAttribute;\n      const indexStr = node.getAttribute(attributeName);\n      if (!indexStr) {\n        console.warn(\n          `Missing attribute name '${attributeName}={index}' on measured element.`\n        );\n        return -1;\n      }\n      return parseInt(indexStr, 10);\n    };\n    this._measureElement = (node, entry) => {\n      const index = this.indexFromElement(node);\n      const item = this.measurementsCache[index];\n      if (!item) {\n        return;\n      }\n      const key = item.key;\n      const prevNode = this.elementsCache.get(key);\n      if (prevNode !== node) {\n        if (prevNode) {\n          this.observer.unobserve(prevNode);\n        }\n        this.observer.observe(node);\n        this.elementsCache.set(key, node);\n      }\n      if (node.isConnected) {\n        this.resizeItem(index, this.options.measureElement(node, entry, this));\n      }\n    };\n    this.resizeItem = (index, size) => {\n      const item = this.measurementsCache[index];\n      if (!item) {\n        return;\n      }\n      const itemSize = this.itemSizeCache.get(item.key) ?? item.size;\n      const delta = size - itemSize;\n      if (delta !== 0) {\n        if (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this) : item.start < this.getScrollOffset() + this.scrollAdjustments) {\n          if (process.env.NODE_ENV !== \"production\" && this.options.debug) {\n            console.info(\"correction\", delta);\n          }\n          this._scrollToOffset(this.getScrollOffset(), {\n            adjustments: this.scrollAdjustments += delta,\n            behavior: void 0\n          });\n        }\n        this.pendingMeasuredCacheIndexes.push(item.index);\n        this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size));\n        this.notify(false);\n      }\n    };\n    this.measureElement = (node) => {\n      if (!node) {\n        this.elementsCache.forEach((cached, key) => {\n          if (!cached.isConnected) {\n            this.observer.unobserve(cached);\n            this.elementsCache.delete(key);\n          }\n        });\n        return;\n      }\n      this._measureElement(node, void 0);\n    };\n    this.getVirtualItems = memo(\n      () => [this.getVirtualIndexes(), this.getMeasurements()],\n      (indexes, measurements) => {\n        const virtualItems = [];\n        for (let k = 0, len = indexes.length; k < len; k++) {\n          const i = indexes[k];\n          const measurement = measurements[i];\n          virtualItems.push(measurement);\n        }\n        return virtualItems;\n      },\n      {\n        key: process.env.NODE_ENV !== \"production\" && \"getVirtualItems\",\n        debug: () => this.options.debug\n      }\n    );\n    this.getVirtualItemForOffset = (offset) => {\n      const measurements = this.getMeasurements();\n      if (measurements.length === 0) {\n        return void 0;\n      }\n      return notUndefined(\n        measurements[findNearestBinarySearch(\n          0,\n          measurements.length - 1,\n          (index) => notUndefined(measurements[index]).start,\n          offset\n        )]\n      );\n    };\n    this.getMaxScrollOffset = () => {\n      if (!this.scrollElement) return 0;\n      if (\"scrollHeight\" in this.scrollElement) {\n        return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;\n      } else {\n        const doc = this.scrollElement.document.documentElement;\n        return this.options.horizontal ? doc.scrollWidth - this.scrollElement.innerWidth : doc.scrollHeight - this.scrollElement.innerHeight;\n      }\n    };\n    this.getOffsetForAlignment = (toOffset, align, itemSize = 0) => {\n      if (!this.scrollElement) return 0;\n      const size = this.getSize();\n      const scrollOffset = this.getScrollOffset();\n      if (align === \"auto\") {\n        align = toOffset >= scrollOffset + size ? \"end\" : \"start\";\n      }\n      if (align === \"center\") {\n        toOffset += (itemSize - size) / 2;\n      } else if (align === \"end\") {\n        toOffset -= size;\n      }\n      const maxOffset = this.getMaxScrollOffset();\n      return Math.max(Math.min(maxOffset, toOffset), 0);\n    };\n    this.getOffsetForIndex = (index, align = \"auto\") => {\n      index = Math.max(0, Math.min(index, this.options.count - 1));\n      const item = this.measurementsCache[index];\n      if (!item) {\n        return void 0;\n      }\n      const size = this.getSize();\n      const scrollOffset = this.getScrollOffset();\n      if (align === \"auto\") {\n        if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {\n          align = \"end\";\n        } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {\n          align = \"start\";\n        } else {\n          return [scrollOffset, align];\n        }\n      }\n      if (align === \"end\" && index === this.options.count - 1) {\n        return [this.getMaxScrollOffset(), align];\n      }\n      const toOffset = align === \"end\" ? item.end + this.options.scrollPaddingEnd : item.start - this.options.scrollPaddingStart;\n      return [\n        this.getOffsetForAlignment(toOffset, align, item.size),\n        align\n      ];\n    };\n    this.isDynamicMode = () => this.elementsCache.size > 0;\n    this.scrollToOffset = (toOffset, { align = \"start\", behavior } = {}) => {\n      if (behavior === \"smooth\" && this.isDynamicMode()) {\n        console.warn(\n          \"The `smooth` scroll behavior is not fully supported with dynamic size.\"\n        );\n      }\n      this._scrollToOffset(this.getOffsetForAlignment(toOffset, align), {\n        adjustments: void 0,\n        behavior\n      });\n    };\n    this.scrollToIndex = (index, { align: initialAlign = \"auto\", behavior } = {}) => {\n      if (behavior === \"smooth\" && this.isDynamicMode()) {\n        console.warn(\n          \"The `smooth` scroll behavior is not fully supported with dynamic size.\"\n        );\n      }\n      index = Math.max(0, Math.min(index, this.options.count - 1));\n      this.currentScrollToIndex = index;\n      let attempts = 0;\n      const maxAttempts = 10;\n      const tryScroll = (currentAlign) => {\n        if (!this.targetWindow) return;\n        const offsetInfo = this.getOffsetForIndex(index, currentAlign);\n        if (!offsetInfo) {\n          console.warn(\"Failed to get offset for index:\", index);\n          return;\n        }\n        const [offset, align] = offsetInfo;\n        this._scrollToOffset(offset, { adjustments: void 0, behavior });\n        this.targetWindow.requestAnimationFrame(() => {\n          const verify = () => {\n            if (this.currentScrollToIndex !== index) return;\n            const currentOffset = this.getScrollOffset();\n            const afterInfo = this.getOffsetForIndex(index, align);\n            if (!afterInfo) {\n              console.warn(\"Failed to get offset for index:\", index);\n              return;\n            }\n            if (!approxEqual(afterInfo[0], currentOffset)) {\n              scheduleRetry(align);\n            }\n          };\n          if (this.isDynamicMode()) {\n            this.targetWindow.requestAnimationFrame(verify);\n          } else {\n            verify();\n          }\n        });\n      };\n      const scheduleRetry = (align) => {\n        if (!this.targetWindow) return;\n        if (this.currentScrollToIndex !== index) return;\n        attempts++;\n        if (attempts < maxAttempts) {\n          if (process.env.NODE_ENV !== \"production\" && this.options.debug) {\n            console.info(\"Schedule retry\", attempts, maxAttempts);\n          }\n          this.targetWindow.requestAnimationFrame(() => tryScroll(align));\n        } else {\n          console.warn(\n            `Failed to scroll to index ${index} after ${maxAttempts} attempts.`\n          );\n        }\n      };\n      tryScroll(initialAlign);\n    };\n    this.scrollBy = (delta, { behavior } = {}) => {\n      if (behavior === \"smooth\" && this.isDynamicMode()) {\n        console.warn(\n          \"The `smooth` scroll behavior is not fully supported with dynamic size.\"\n        );\n      }\n      this._scrollToOffset(this.getScrollOffset() + delta, {\n        adjustments: void 0,\n        behavior\n      });\n    };\n    this.getTotalSize = () => {\n      var _a;\n      const measurements = this.getMeasurements();\n      let end;\n      if (measurements.length === 0) {\n        end = this.options.paddingStart;\n      } else if (this.options.lanes === 1) {\n        end = ((_a = measurements[measurements.length - 1]) == null ? void 0 : _a.end) ?? 0;\n      } else {\n        const endByLane = Array(this.options.lanes).fill(null);\n        let endIndex = measurements.length - 1;\n        while (endIndex >= 0 && endByLane.some((val) => val === null)) {\n          const item = measurements[endIndex];\n          if (endByLane[item.lane] === null) {\n            endByLane[item.lane] = item.end;\n          }\n          endIndex--;\n        }\n        end = Math.max(...endByLane.filter((val) => val !== null));\n      }\n      return Math.max(\n        end - this.options.scrollMargin + this.options.paddingEnd,\n        0\n      );\n    };\n    this._scrollToOffset = (offset, {\n      adjustments,\n      behavior\n    }) => {\n      this.options.scrollToFn(offset, { behavior, adjustments }, this);\n    };\n    this.measure = () => {\n      this.itemSizeCache = /* @__PURE__ */ new Map();\n      this.laneAssignments = /* @__PURE__ */ new Map();\n      this.notify(false);\n    };\n    this.setOptions(opts);\n  }\n}\nconst findNearestBinarySearch = (low, high, getCurrentValue, value) => {\n  while (low <= high) {\n    const middle = (low + high) / 2 | 0;\n    const currentValue = getCurrentValue(middle);\n    if (currentValue < value) {\n      low = middle + 1;\n    } else if (currentValue > value) {\n      high = middle - 1;\n    } else {\n      return middle;\n    }\n  }\n  if (low > 0) {\n    return low - 1;\n  } else {\n    return 0;\n  }\n};\nfunction calculateRange({\n  measurements,\n  outerSize,\n  scrollOffset,\n  lanes\n}) {\n  const lastIndex = measurements.length - 1;\n  const getOffset = (index) => measurements[index].start;\n  if (measurements.length <= lanes) {\n    return {\n      startIndex: 0,\n      endIndex: lastIndex\n    };\n  }\n  let startIndex = findNearestBinarySearch(\n    0,\n    lastIndex,\n    getOffset,\n    scrollOffset\n  );\n  let endIndex = startIndex;\n  if (lanes === 1) {\n    while (endIndex < lastIndex && measurements[endIndex].end < scrollOffset + outerSize) {\n      endIndex++;\n    }\n  } else if (lanes > 1) {\n    const endPerLane = Array(lanes).fill(0);\n    while (endIndex < lastIndex && endPerLane.some((pos) => pos < scrollOffset + outerSize)) {\n      const item = measurements[endIndex];\n      endPerLane[item.lane] = item.end;\n      endIndex++;\n    }\n    const startPerLane = Array(lanes).fill(scrollOffset + outerSize);\n    while (startIndex >= 0 && startPerLane.some((pos) => pos >= scrollOffset)) {\n      const item = measurements[startIndex];\n      startPerLane[item.lane] = item.start;\n      startIndex--;\n    }\n    startIndex = Math.max(0, startIndex - startIndex % lanes);\n    endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - endIndex % lanes));\n  }\n  return { startIndex, endIndex };\n}\nexport {\n  Virtualizer,\n  approxEqual,\n  debounce,\n  defaultKeyExtractor,\n  defaultRangeExtractor,\n  elementScroll,\n  measureElement,\n  memo,\n  notUndefined,\n  observeElementOffset,\n  observeElementRect,\n  observeWindowOffset,\n  observeWindowRect,\n  windowScroll\n};\n//# sourceMappingURL=index.js.map\n","import * as React from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { Virtualizer, elementScroll, observeElementOffset, observeElementRect, windowScroll, observeWindowOffset, observeWindowRect } from \"@tanstack/virtual-core\";\nexport * from \"@tanstack/virtual-core\";\nconst useIsomorphicLayoutEffect = typeof document !== \"undefined\" ? React.useLayoutEffect : React.useEffect;\nfunction useVirtualizerBase({\n  useFlushSync = true,\n  ...options\n}) {\n  const rerender = React.useReducer(() => ({}), {})[1];\n  const resolvedOptions = {\n    ...options,\n    onChange: (instance2, sync) => {\n      var _a;\n      if (useFlushSync && sync) {\n        flushSync(rerender);\n      } else {\n        rerender();\n      }\n      (_a = options.onChange) == null ? void 0 : _a.call(options, instance2, sync);\n    }\n  };\n  const [instance] = React.useState(\n    () => new Virtualizer(resolvedOptions)\n  );\n  instance.setOptions(resolvedOptions);\n  useIsomorphicLayoutEffect(() => {\n    return instance._didMount();\n  }, []);\n  useIsomorphicLayoutEffect(() => {\n    return instance._willUpdate();\n  });\n  return instance;\n}\nfunction useVirtualizer(options) {\n  return useVirtualizerBase({\n    observeElementRect,\n    observeElementOffset,\n    scrollToFn: elementScroll,\n    ...options\n  });\n}\nfunction useWindowVirtualizer(options) {\n  return useVirtualizerBase({\n    getScrollElement: () => typeof document !== \"undefined\" ? window : null,\n    observeElementRect: observeWindowRect,\n    observeElementOffset: observeWindowOffset,\n    scrollToFn: windowScroll,\n    initialOffset: () => typeof document !== \"undefined\" ? window.scrollY : 0,\n    ...options\n  });\n}\nexport {\n  useVirtualizer,\n  useWindowVirtualizer\n};\n//# sourceMappingURL=index.js.map\n","import { useVirtualizer, type VirtualItem } from '@tanstack/react-virtual'\nimport { type RefObject, useCallback } from 'react'\n\n/** Default height for each option item in pixels */\nconst DEFAULT_OPTION_HEIGHT_PX = 36\n\n/** Number of extra items to render above/below viewport for smooth scrolling */\nconst DEFAULT_OVERSCAN = 5\n\nexport interface UseVirtualListOptions {\n  /** Total number of items in the list */\n  count: number\n  /** Reference to the scrollable container element */\n  parentRef: RefObject<HTMLElement | null>\n  /** Height of each item in pixels (default: 36) */\n  estimateSize?: number\n  /** Number of extra items to render above/below viewport (default: 5) */\n  overscan?: number\n  /** Enable/disable virtualization (default: true) */\n  enabled?: boolean\n}\n\nexport interface UseVirtualListResult {\n  /** Array of virtual items currently visible (plus overscan) */\n  virtualItems: VirtualItem[]\n  /** Total height of all items for scrollbar sizing */\n  totalSize: number\n  /** Scroll to a specific item index */\n  scrollToIndex: (index: number, options?: { align?: 'start' | 'center' | 'end' | 'auto' }) => void\n  /** Measure element at index (for dynamic heights if needed) */\n  measureElement: (element: HTMLElement | null) => void\n}\n\n/**\n * Hook for virtualizing a list of items, rendering only visible items in the DOM.\n * Wraps @tanstack/react-virtual with project-specific defaults.\n *\n * @example\n * ```tsx\n * const { virtualItems, totalSize } = useVirtualList({\n *   count: records.length,\n *   parentRef: scrollContainerRef,\n * })\n * ```\n */\nexport function useVirtualList({\n  count,\n  parentRef,\n  estimateSize = DEFAULT_OPTION_HEIGHT_PX,\n  overscan = DEFAULT_OVERSCAN,\n  enabled = true,\n}: UseVirtualListOptions): UseVirtualListResult {\n  const virtualizer = useVirtualizer({\n    count: enabled ? count : 0,\n    getScrollElement: () => parentRef.current,\n    estimateSize: useCallback(() => estimateSize, [estimateSize]),\n    overscan,\n  })\n\n  return {\n    virtualItems: virtualizer.getVirtualItems(),\n    totalSize: virtualizer.getTotalSize(),\n    scrollToIndex: virtualizer.scrollToIndex,\n    measureElement: virtualizer.measureElement,\n  }\n}\n","import { forwardRef, useCallback } from 'react'\nimport { AlignHorizontalSpaceAround, AlignStartVertical, Loader2, Search, X } from 'lucide-react'\nimport { cn } from '../utils/cn'\nimport type { SearchOperator } from '../services/api.types'\n\ninterface SearchInputProps {\n  value: string\n  onChange: (value: string) => void\n  placeholder?: string\n  className?: string\n  listboxId?: string\n  activeDescendantId?: string\n  /** Current match mode for `value` — always exactly one of the two is active. */\n  searchOperator: SearchOperator\n  onSearchOperatorChange: (operator: SearchOperator) => void\n  /** Label shown as the \"starts with\" toggle's tooltip/aria-label. */\n  startsWithLabel: string\n  /** Label shown as the \"contains\" toggle's tooltip/aria-label. */\n  containsLabel: string\n  /**\n   * State of the Enter-to-resolve-exact-code lookup (triggered from outside, via Enter\n   * with nothing highlighted). `'searching'` shows a spinner in place of the operator\n   * toggle. Coming back empty is silent by design — no visible change here at all.\n   */\n  exactMatchStatus?: 'idle' | 'searching'\n}\n\nexport const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(function SearchInput(\n  {\n    value,\n    onChange,\n    placeholder = 'Search...',\n    className,\n    listboxId,\n    activeDescendantId,\n    searchOperator,\n    onSearchOperatorChange,\n    startsWithLabel,\n    containsLabel,\n    exactMatchStatus = 'idle',\n  },\n  ref\n) {\n  const handleClear = useCallback(() => {\n    onChange('')\n  }, [onChange])\n\n  /**\n   * El par de operadores, ahora con pictograma en vez del glifo de texto «Ab…»/«…Ab…»:\n   * `AlignStartVertical` (alinea al inicio) para «empieza por» y\n   * `AlignHorizontalSpaceAround` (distribuye alrededor) para «contiene». Siguen EN FLUJO,\n   * no superpuestos — ver el comentario junto a `{operadores}` más abajo para el porqué\n   * del posicionamiento. El nombre accesible sigue viniendo de `startsWithLabel` /\n   * `containsLabel` vía `aria-label` (el ícono es puramente decorativo, `aria-hidden`),\n   * exactamente como en `title` — nada de eso cambió, solo qué se dibuja.\n   */\n  const operadores =\n    exactMatchStatus === 'searching' ? (\n      <Loader2 className=\"lookup-field__search-resolving h-3.5 w-3.5 animate-spin\" />\n    ) : (\n      <div\n        className=\"lookup-field__search-operator-group\"\n        role=\"radiogroup\"\n        aria-label={`${startsWithLabel} / ${containsLabel}`}\n      >\n        <button\n          type=\"button\"\n          className={cn(\n            'lookup-field__search-operator-btn',\n            searchOperator === 'startsWith' && 'lookup-field__search-operator-btn--active'\n          )}\n          onClick={() => onSearchOperatorChange('startsWith')}\n          role=\"radio\"\n          aria-checked={searchOperator === 'startsWith'}\n          aria-label={startsWithLabel}\n          title={startsWithLabel}\n          tabIndex={-1}\n        >\n          <AlignStartVertical\n            className=\"lookup-field__search-operator-glyph h-3.5 w-3.5\"\n            aria-hidden=\"true\"\n          />\n        </button>\n        <button\n          type=\"button\"\n          className={cn(\n            'lookup-field__search-operator-btn',\n            searchOperator === 'contains' && 'lookup-field__search-operator-btn--active'\n          )}\n          onClick={() => onSearchOperatorChange('contains')}\n          role=\"radio\"\n          aria-checked={searchOperator === 'contains'}\n          aria-label={containsLabel}\n          title={containsLabel}\n          tabIndex={-1}\n        >\n          <AlignHorizontalSpaceAround\n            className=\"lookup-field__search-operator-glyph h-3.5 w-3.5\"\n            aria-hidden=\"true\"\n          />\n        </button>\n      </div>\n    )\n\n  return (\n    <div className={cn('lookup-field__search-container', className)}>\n      <Search className=\"lookup-field__search-icon\" />\n      <input\n        ref={ref}\n        type=\"text\"\n        className=\"lookup-field__search\"\n        value={value}\n        onChange={(e) => onChange(e.target.value)}\n        placeholder={placeholder}\n        aria-label={placeholder}\n        aria-autocomplete=\"list\"\n        aria-controls={listboxId}\n        aria-activedescendant={activeDescendantId}\n      />\n      {value && (\n        <button\n          type=\"button\"\n          className=\"lookup-field__search-clear\"\n          onClick={handleClear}\n          aria-label=\"Clear search\"\n          tabIndex={-1}\n        >\n          <X className=\"h-4 w-4\" />\n        </button>\n      )}\n      {/*\n        A la DERECHA del input y en la misma fila, pero EN FLUJO, no superpuestos.\n        Superpuestos (`position: absolute`) es lo que forzaba la etiqueta de dos\n        caracteres: con la palabra completa taparían lo que el usuario teclea. En flujo,\n        el input cede el ancho que hace falta y nadie se solapa.\n      */}\n      {operadores}\n    </div>\n  )\n})\n","interface LiveRegionProps {\n  message: string\n}\n\nexport function LiveRegion({ message }: LiveRegionProps) {\n  return (\n    <div role=\"status\" aria-live=\"polite\" aria-atomic=\"true\" className=\"lookup-field__live-region\">\n      {message}\n    </div>\n  )\n}\n","import { createPortal } from 'react-dom'\nimport { X } from 'lucide-react'\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react'\n\nexport interface CreatePopupProps {\n  /** Popup shell style — centered modal or a slide-over panel from the right edge. */\n  variant: 'modal' | 'sidebar'\n  title: string\n  onClose: () => void\n  children: React.ReactNode\n  /** Optional decorative icon shown in a circular badge next to the title. */\n  icon?: React.ReactNode\n  /** Custom width override (relative units — vw/%/min(), never px). Omit for the compact default. */\n  width?: string\n  /**\n   * Maximum popup height (relative units — vh/%/min(), never px). Omit for the compact\n   * default. This is always a CAP, never a fixed height — the panel shrinks to fit its\n   * content and only grows up to this value, so a short form doesn't get stretched into\n   * a mostly-empty box.\n   */\n  height?: string\n  /**\n   * Whether to render the built-in title bar (icon + title + close button) and the\n   * body's own padding. Defaults to `false` because `children` is almost always a\n   * form that already renders its own complete header/actions (e.g.\n   * `MasterPatternViewCreateForm`, whose form has a title, Cancelar/Guardar and its\n   * own spacing) — the popup has no way to know whether `children` self-paints a\n   * header, so it assumes it does. Set to `true` only when `children` is genuinely\n   * headerless and should rely on the popup's own title bar instead. Escape-to-close\n   * still works either way; the host's own Cancelar just needs to call the same\n   * `onClose`.\n   * @default false\n   */\n  showHeader?: boolean\n}\n\n/**\n * Popup chrome for LookupField's inline \"create new\" affordance.\n * Owns the overlay, header (title + close button), and Escape-to-close behavior.\n * The host supplies the form content via `children` — this component knows nothing\n * about what's being created.\n */\nexport function CreatePopup({ variant, title, onClose, children, icon, width, height, showHeader = false }: CreatePopupProps) {\n  useEffect(() => {\n    const handleKeyDown = (e: KeyboardEvent) => {\n      if (e.key === 'Escape') onClose()\n    }\n    document.addEventListener('keydown', handleKeyDown)\n    return () => document.removeEventListener('keydown', handleKeyDown)\n  }, [onClose])\n\n  // Lock the host page's own scroll while this popup is open — otherwise the page\n  // behind the dimmed overlay still scrolls under it, which does nothing useful (the\n  // popup itself is fixed) and just reads as broken. Restores whatever value was\n  // there before (not a hardcoded 'visible'), so nested popups (e.g. a lookup's own\n  // create popup opened from inside another lookup's create popup) don't have the\n  // inner one's cleanup accidentally unlock scroll the outer one still needs locked.\n  useEffect(() => {\n    const previousOverflow = document.body.style.overflow\n    document.body.style.overflow = 'hidden'\n    return () => {\n      document.body.style.overflow = previousOverflow\n    }\n  }, [])\n\n  const bodyRef = useRef<HTMLDivElement>(null)\n  // Sticky \"tallest content seen\" height. Without this, a tabbed form (e.g. a\n  // MasterPatternViewCreateForm master) makes the whole popup visibly grow/shrink on\n  // every tab click, since the panel shrinks-to-fit whichever tab happens to be\n  // active — reads as broken, not responsive. Once a taller tab has been shown, the\n  // popup stops shrinking back down for a shorter one; a form with no real height\n  // variance across its own content (no tabs, or same-sized tabs) just keeps\n  // settling at its own natural height, same as before.\n  const [stickyHeight, setStickyHeight] = useState<number>()\n  // Re-measures `scrollHeight` (the content's real extent regardless of any clipping)\n  // on every DOM mutation inside body, via MutationObserver rather than a `children`\n  // dependency: tab-switching lives entirely in `MasterPatternViewForm`'s OWN internal\n  // state, so the `children` element CreatePopup receives never changes reference when\n  // the user clicks a different tab — only the DOM it renders does (content swapped,\n  // or a `hidden` class/attribute toggled). A plain effect keyed on `children` would\n  // only ever measure once, at mount. `characterData`/`attributes` are included\n  // because a tab switch can change nothing but a `hidden` attribute/class on already-\n  // mounted panels, with no nodes added or removed.\n  useLayoutEffect(() => {\n    const el = bodyRef.current\n    if (!el) return\n    const measure = () => {\n      setStickyHeight((prev) => (prev === undefined ? el.scrollHeight : Math.max(prev, el.scrollHeight)))\n    }\n    measure()\n    const observer = new MutationObserver(measure)\n    observer.observe(el, { childList: true, subtree: true, attributes: true, characterData: true })\n    return () => observer.disconnect()\n  }, [])\n\n  const isSidebar = variant === 'sidebar'\n\n  return createPortal(\n    <div\n      className=\"lookup-field-create__overlay\"\n      style={{ justifyContent: isSidebar ? 'flex-end' : 'center' }}\n    >\n      <div\n        className={`lookup-field-create__panel${showHeader ? '' : ' lookup-field-create__panel--flush'}`}\n        data-variant={variant}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={title}\n        onClick={(e) => e.stopPropagation()}\n        // Set as custom properties (consumed by the width/max-width/max-height rules\n        // in the stylesheet) rather than direct inline `maxWidth`/`maxHeight` — an\n        // inline style always wins over ANY stylesheet rule regardless of specificity\n        // or media queries, which would permanently defeat the narrow-viewport\n        // breakpoint below for every consumer that passes its own createWidth/\n        // createHeight (i.e. almost everyone, since MasterPatternView's own default\n        // already sets one). Routing through a custom property lets the responsive\n        // rule override the EFFECTIVE width/height on narrow screens while still\n        // letting the per-instance value win at normal sizes.\n        style={{\n          ...(width ? { '--lf-create-width': width } : {}),\n          ...(height ? { '--lf-create-height': height } : {}),\n          ...(stickyHeight ? { minHeight: `${stickyHeight}px` } : {}),\n        } as React.CSSProperties}\n      >\n        {showHeader && (\n          <div className=\"lookup-field-create__header\">\n            <div className=\"lookup-field-create__heading\">\n              {icon && <span className=\"lookup-field-create__icon\">{icon}</span>}\n              <h3 className=\"lookup-field-create__title\">{title}</h3>\n            </div>\n            <button\n              type=\"button\"\n              className=\"lookup-field-create__close\"\n              onClick={onClose}\n              aria-label=\"Cerrar\"\n            >\n              <X size={16} />\n            </button>\n          </div>\n        )}\n        <div\n          ref={bodyRef}\n          className={showHeader ? 'lookup-field-create__body' : 'lookup-field-create__body lookup-field-create__body--flush'}\n        >\n          {children}\n        </div>\n      </div>\n    </div>,\n    document.body\n  )\n}\n","import {\n  createElement,\n  forwardRef,\n  useCallback,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport { Check, ChevronDown, Loader2, Plus, X } from 'lucide-react'\nimport { Badge } from '../Badge/Badge'\nimport { cn, getFriendlyErrorMessage, interpolateTemplate, normalizeFilters } from './utils'\nimport type { FilterExpression } from './types/filter.types'\nimport {\n  useClickOutside,\n  useDebouncedSearch,\n  useFloatingDropdown,\n  useKeyboardNavigation,\n  useTranslationSafe,\n  useVirtualList,\n} from './hooks'\nimport { SearchInput } from './parts/SearchInput'\nimport { LiveRegion } from './parts/LiveRegion'\nimport { CreatePopup } from './parts/CreatePopup'\nimport type { LookupFieldProps, LookupFieldRef, LookupRecord } from './LookupField.types'\nimport type { SearchOperator } from './services/api.types'\nimport './LookupField.css'\n\nconst DEFAULT_PAGE_SIZE = 10\nconst SCROLL_THRESHOLD_PX = 50\nconst DEFAULT_MIN_CHARS = 1\n// Multi-select trigger: chips beyond this count collapse into a single \"+N\" badge so\n// the trigger doesn't grow without bound as more records get selected.\nconst MAX_VISIBLE_CHIPS = 3\n\nfunction LookupFieldInner<TRecord extends LookupRecord = LookupRecord>(\n  {\n    entity,\n    label,\n    displayFields,\n    value,\n    onChange,\n    fetcher,\n    clearable = true,\n    clearSelectionLabel = 'Clear selection',\n    removeLabel = 'Remove',\n    placeholder,\n    className,\n    pageSize = DEFAULT_PAGE_SIZE,\n    onError,\n    searchFields,\n    minChars = DEFAULT_MIN_CHARS,\n    displayValue,\n    displayTemplate,\n    renderSelected,\n    filters,\n    getFilters,\n    dependencies,\n    orderBy,\n    bindFields,\n    readOnly = false,\n    disabled = false,\n    error = false,\n    onFocus: onFocusProp,\n    onBlur: onBlurProp,\n    onReady,\n    onInvalidValue,\n    noResultsText,\n    searchPlaceholder,\n    required = false,\n    showRequiredIndicator,\n    validateOnBlur = true,\n    onValidationChange,\n    errorText,\n    onCreateNew,\n    createVariant,\n    createTitle,\n    createButtonLabel,\n    createIcon,\n    showCreateButton: showCreateButtonProp,\n    createWidth,\n    createHeight,\n    createShowHeader,\n    isMultiple,\n    maxSelected,\n    onMaxSelectedReached,\n  }: LookupFieldProps<TRecord>,\n  ref: React.Ref<LookupFieldRef<TRecord>>\n) {\n  const { t } = useTranslationSafe()\n\n  // Stable value-based keys for array/object props that hosts routinely pass as fresh\n  // literals every render (e.g. displayFields={['Code', 'Name']}) — comparing by\n  // content (JSON.stringify) instead of by reference in the memoization deps below\n  // means an unrelated parent re-render doesn't recreate fetchRecords/fetchMoreRecords,\n  // which would otherwise re-trigger the fetch-on-open effect and silently refetch page\n  // 1 (discarding scroll position and loaded pages) on every incidental re-render while\n  // the dropdown is open. Same technique already used for the `dependencies` prop above.\n  const displayFieldsKey = JSON.stringify(displayFields)\n  const bindFieldsKey = JSON.stringify(bindFields ?? [])\n  const searchFieldsKey = JSON.stringify(searchFields ?? [])\n  // filtersKey is declared once here and reused both for fetch memoization (below) and\n  // for the cache-invalidation-on-filters-change effect further down.\n  const filtersKey = JSON.stringify(filters ?? [])\n  const orderByKey = JSON.stringify(orderBy ?? null)\n\n  // Compute effective orderBy with default (AC: 2)\n  const effectiveOrderBy = useMemo(\n    () =>\n      orderBy ?? {\n        field: displayFields[0] as string,\n        direction: 'asc' as const,\n      },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [orderByKey, displayFieldsKey]\n  )\n\n  const id = useId()\n  const [isOpen, setIsOpen] = useState(false)\n  const [isCreateOpen, setIsCreateOpen] = useState(false)\n  const [isLoading, setIsLoading] = useState(false)\n  const [apiError, setApiError] = useState<Error | null>(null)\n  const [records, setRecords] = useState<TRecord[]>([])\n  // Source of truth for BOTH modes — single-select never holds more than one entry.\n  // `selectedRecord` below is a derived convenience so the (much larger) single-select\n  // code paths below don't need touching at all.\n  const [selectedRecords, setSelectedRecords] = useState<TRecord[]>([])\n  const selectedRecord = selectedRecords[0] ?? null\n  const [currentPage, setCurrentPage] = useState(1)\n  const [hasMorePages, setHasMorePages] = useState(true)\n  const [isLoadingMore, setIsLoadingMore] = useState(false)\n  const abortControllerRef = useRef<AbortController | null>(null)\n  const previousRecordRef = useRef<TRecord | null>(null)\n  const previousDependenciesRef = useRef(JSON.stringify(dependencies ?? []))\n  const optionsRef = useRef<HTMLDivElement>(null)\n  const searchInputRef = useRef<HTMLInputElement>(null)\n  // A <div role=\"button\"> in multi-select mode (see the trigger render below for why:\n  // it hosts real <button> chip-remove controls, which can't legally nest inside\n  // another <button>), so this ref must accept either element type.\n  const triggerRef = useRef<HTMLButtonElement | HTMLDivElement | null>(null)\n  const [searchQuery, setSearchQuery] = useState('')\n  const debouncedSearchQuery = useDebouncedSearch(searchQuery)\n  // How the typed search text is matched — toggled via the icons inside the search box.\n  // Always starts as 'startsWith'; the user can switch to 'contains' but there's no third\n  // state to cycle back through, so it never defaults to anything else.\n  const [searchOperator, setSearchOperator] = useState<SearchOperator>('startsWith')\n  const [announcement, setAnnouncement] = useState('')\n  // Enter-to-resolve-exact-code: pressing Enter with nothing highlighted (no arrow-key\n  // navigation yet, and no single result auto-highlighted either) tries to resolve the\n  // typed text as an exact code match, bypassing startsWith/contains guessing. 'searching'\n  // shows a spinner in the search box. When it comes back empty, nothing visible happens\n  // (no red banner) — only an aria-live announcement for screen readers.\n  const [exactMatchStatus, setExactMatchStatus] = useState<'idle' | 'searching'>('idle')\n  const isResolvingExactMatchRef = useRef(false)\n\n  // Refs for onReady callback (Task 6) [UPDATED v0.4 - removed totalRecordsRef]\n  const hasCalledOnReadyRef = useRef(false)\n\n  // Ref to track selectedRecord for imperative methods (always up-to-date)\n  const selectedRecordRef = useRef<TRecord | null>(null)\n  // Keep ref in sync with state\n  selectedRecordRef.current = selectedRecord\n  // Multi-select's own ref — mirrors selectedRecords for the toggle/clear/value-sync\n  // logic below that needs the full array, not just the first entry.\n  const selectedRecordsRef = useRef<TRecord[]>([])\n  selectedRecordsRef.current = selectedRecords\n\n  // Refs for focus tracking (Tasks 4, 5)\n  const componentRef = useRef<HTMLDivElement>(null)\n  const isFocusWithinRef = useRef(false)\n  const onInvalidValueRef = useRef(onInvalidValue)\n\n  // Keep onInvalidValue ref in sync\n  useEffect(() => {\n    onInvalidValueRef.current = onInvalidValue\n  }, [onInvalidValue])\n\n  // Floating UI positioning (AC: 8, Story 2.11)\n  const { refs: floatingRefs, floatingStyles } = useFloatingDropdown({\n    enabled: isOpen,\n  })\n\n  // Click outside detection - close dropdown when clicking outside (AC: 4, Story 2.11)\n  // Note: mousedown fires BEFORE focus changes, so we need to manually trigger onBlur\n  // if focus was within the component when clicking outside\n  const handleClickOutside = useCallback(() => {\n    if (isOpen) {\n      // Trigger onBlur if focus was within (mousedown preempts natural blur)\n      if (isFocusWithinRef.current) {\n        isFocusWithinRef.current = false\n        onBlurProp?.(selectedRecordRef.current)\n      }\n      setIsOpen(false)\n      setSearchQuery('')\n    }\n  }, [isOpen, onBlurProp])\n\n  // Exclude the portaled floating dropdown from outside-click detection\n  useClickOutside(componentRef, handleClickOutside, isOpen, [floatingRefs.floating])\n\n  // Multi-select: already-picked records always show first in the dropdown, so the\n  // user can see (and un-pick) their current selection without hunting for it further\n  // down the list. Single-pass stable partition — keeps each group's own relative\n  // order, cheaper than a full sort. This is a RENDER-ONLY reordering: `records`\n  // itself (fetch/pagination order) never changes, only what's displayed does —\n  // keyboard nav and virtualization both key off this same reordered view below so\n  // \"highlighted\" and \"visually at this position\" never disagree.\n  const displayRecords = useMemo(() => {\n    if (!isMultiple || selectedRecords.length === 0) return records\n    const selectedIds = new Set(selectedRecords.map((r) => r.Id))\n    const selected: TRecord[] = []\n    const rest: TRecord[] = []\n    for (const r of records) {\n      if (selectedIds.has(r.Id)) selected.push(r)\n      else rest.push(r)\n    }\n    return [...selected, ...rest]\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [records, isMultiple, selectedRecords])\n\n  // Virtualization for large lists (Story 2.13, AC: 1, 8)\n  const { virtualItems, totalSize } = useVirtualList({\n    count: displayRecords.length,\n    parentRef: optionsRef,\n    enabled: isOpen && displayRecords.length > 0,\n  })\n\n  // State for invalid value detection (Task 7)\n  const [isInvalidValue, setIsInvalidValue] = useState(false)\n\n  // State for required field validation (Story 2.12)\n  const [validationError, setValidationError] = useState(false)\n\n  // Navigation context cache state (Story 2.13, AC: 2, 7)\n  const [cachedRecords, setCachedRecords] = useState<TRecord[]>([])\n  const [cachedScrollPosition, setCachedScrollPosition] = useState<number>(0)\n  const [cachedCurrentPage, setCachedCurrentPage] = useState<number>(1)\n  const [cacheValid, setCacheValid] = useState<boolean>(false)\n  const cachedSearchQueryRef = useRef<string>('')\n  // Ref to prevent fetchMoreRecords during cache restoration (fixes duplicate records bug)\n  const isRestoringCacheRef = useRef<boolean>(false)\n  // Ref to track current page immediately (state updates are async)\n  const currentPageRef = useRef<number>(1)\n\n  // Compute combined error state: external error OR internal validation error\n  const showError = error || validationError\n\n  // The \"+\" button renders only when onCreateNew is provided AND not explicitly\n  // hidden — lets a host keep the create props configured while suppressing the\n  // affordance for a given instance (e.g. permission-gated creation).\n  const showCreateButton = !!onCreateNew && showCreateButtonProp !== false\n\n  // Compute effective showRequiredIndicator (defaults to required prop value)\n  const effectiveShowRequiredIndicator = showRequiredIndicator ?? required\n\n  // Ref for onValidationChange to avoid stale closures\n  const onValidationChangeRef = useRef(onValidationChange)\n  useEffect(() => {\n    onValidationChangeRef.current = onValidationChange\n  }, [onValidationChange])\n\n  // Compute effective filters (getFilters takes precedence over static filters)\n  const getEffectiveFilters = useCallback((): FilterExpression | undefined => {\n    if (getFilters) {\n      return normalizeFilters(getFilters())\n    }\n    return normalizeFilters(filters)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [filtersKey, getFilters])\n\n  const fetchRecords = useCallback(\n    async (search: string = '') => {\n      // Cancel any pending request\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort()\n      }\n\n      const controller = new AbortController()\n      abortControllerRef.current = controller\n\n      try {\n        setIsLoading(true)\n        setApiError(null)\n        setAnnouncement(t('announcements.loading'))\n\n        const effectiveFilters = getEffectiveFilters()\n\n        // Combine fields with deduplication: Id + displayFields + bindFields (PascalCase standard)\n        const allFields = [...new Set(['Id', ...displayFields, ...(bindFields ?? [])])]\n\n        const response = await fetcher<TRecord>(entity, {\n          fields: allFields,\n          search: search.length >= minChars ? search : '',\n          searchFields: searchFields ?? displayFields,\n          searchOperator,\n          page: 1,\n          pageSize,\n          filters: effectiveFilters,\n          orderBy: effectiveOrderBy,\n        })\n\n        // Check if request was aborted\n        if (controller.signal.aborted) return\n\n        setRecords(response.data)\n\n        // Call onReady after first successful data load (AC: 4 - fires only once) [UPDATED v0.4 - removed totalRecords]\n        if (!hasCalledOnReadyRef.current && onReady) {\n          hasCalledOnReadyRef.current = true\n          // Delay slightly to ensure imperativeRef is up to date\n          setTimeout(() => {\n            onReady({ firstPageLoaded: true }, imperativeRef)\n          }, 0)\n        }\n\n        // Announce results loaded or no results (AC: 7)\n        if (response.data.length === 0) {\n          setAnnouncement(t('announcements.noResults'))\n        } else {\n          setAnnouncement(t('announcements.opened', { count: response.data.length }))\n        }\n\n        // Detect end of data on initial load (AC: 5)\n        if (response.data.length < pageSize) {\n          setHasMorePages(false)\n        }\n      } catch (err) {\n        // Don't set error state for aborted requests\n        if (err instanceof Error && err.name === 'AbortError') return\n\n        const fetchError = err instanceof Error ? err : new Error('Unknown error')\n        setApiError(fetchError)\n        onError?.(fetchError)\n      } finally {\n        if (!controller.signal.aborted) {\n          setIsLoading(false)\n        }\n      }\n    },\n    // Note: imperativeRef is accessed via closure, not dependency, to avoid circular dep.\n    // Uses the stable *Key strings (not the raw arrays) so an equivalent-but-new-identity\n    // displayFields/bindFields/searchFields prop doesn't recreate this callback.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [\n      entity,\n      displayFieldsKey,\n      bindFieldsKey,\n      searchFieldsKey,\n      searchOperator,\n      pageSize,\n      minChars,\n      onError,\n      onReady,\n      getEffectiveFilters,\n      effectiveOrderBy,\n      fetcher,\n    ]\n  )\n\n  const fetchMoreRecords = useCallback(\n    async (search: string = '') => {\n      // Skip if currently restoring cache (prevents duplicate records bug)\n      if (isRestoringCacheRef.current) return\n      if (isLoadingMore || !hasMorePages) return\n      // Use ref instead of state to get current page (state updates are async)\n      const actualCurrentPage = currentPageRef.current\n\n      try {\n        setIsLoadingMore(true)\n        setAnnouncement(t('announcements.loadingMore'))\n\n        const effectiveFilters = getEffectiveFilters()\n        const nextPage = actualCurrentPage + 1\n\n        // Combine fields with deduplication: Id + displayFields + bindFields (PascalCase standard)\n        const allFields = [...new Set(['Id', ...displayFields, ...(bindFields ?? [])])]\n\n        const response = await fetcher<TRecord>(entity, {\n          fields: allFields,\n          search: search.length >= minChars ? search : '',\n          searchFields: searchFields ?? displayFields,\n          searchOperator,\n          page: nextPage,\n          pageSize,\n          filters: effectiveFilters,\n          orderBy: effectiveOrderBy,\n        })\n\n        // Append new records to existing list (AC: 4)\n        setRecords((prev) => [...prev, ...response.data])\n        currentPageRef.current = nextPage\n        setCurrentPage(nextPage)\n\n        // Announce loaded count\n        setAnnouncement(t('announcements.resultsLoaded', { count: response.data.length }))\n\n        // Detect end of data (AC: 5)\n        if (response.data.length < pageSize) {\n          setHasMorePages(false)\n        }\n      } catch (err) {\n        if (err instanceof Error && err.name === 'AbortError') return\n        const error = err instanceof Error ? err : new Error('Unknown error')\n        onError?.(error)\n      } finally {\n        setIsLoadingMore(false)\n      }\n    },\n    // Uses the stable *Key strings (not the raw arrays) so an equivalent-but-new-identity\n    // displayFields/bindFields/searchFields prop doesn't recreate this callback.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [\n      entity,\n      displayFieldsKey,\n      bindFieldsKey,\n      searchFieldsKey,\n      searchOperator,\n      pageSize,\n      minChars,\n      // Note: currentPage removed - using currentPageRef instead for immediate updates\n      isLoadingMore,\n      hasMorePages,\n      onError,\n      getEffectiveFilters,\n      effectiveOrderBy,\n      fetcher,\n      t,\n    ]\n  )\n\n  // Helper to fetch a single record by ID (for setValue and invalid value detection)\n  const fetchAndSetRecordById = useCallback(\n    async (recordId: string): Promise<TRecord | null> => {\n      try {\n        const allFields = [...new Set(['Id', ...displayFields, ...(bindFields ?? [])])]\n        const response = await fetcher<TRecord>(entity, {\n          fields: allFields,\n          filters: [[{ Id: recordId }]],\n          page: 1,\n          pageSize: 1,\n        })\n        return response.data[0] ?? null\n      } catch {\n        return null\n      }\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [entity, displayFieldsKey, bindFieldsKey, fetcher]\n  )\n\n  // Multi-select's batched equivalent of fetchAndSetRecordById — one request for the\n  // whole `value` array via an OR filter group, instead of one request per id. Same\n  // \"unresolved id → silently omitted\" contract, and same lack of getEffectiveFilters()\n  // merge, as the single-record fetch above.\n  const fetchRecordsByIds = useCallback(\n    async (recordIds: string[]): Promise<TRecord[]> => {\n      if (recordIds.length === 0) return []\n      try {\n        const allFields = [...new Set(['Id', ...displayFields, ...(bindFields ?? [])])]\n        const response = await fetcher<TRecord>(entity, {\n          fields: allFields,\n          filters: [recordIds.map((id) => ({ Id: id }))],\n          page: 1,\n          pageSize: recordIds.length,\n        })\n        const byId = new Map(response.data.map((r) => [String(r.Id), r]))\n        // Preserve the order of `value`; ids that no longer resolve are simply dropped.\n        return recordIds.map((id) => byId.get(id)).filter((r): r is TRecord => !!r)\n      } catch {\n        return []\n      }\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [entity, displayFieldsKey, bindFieldsKey, fetcher]\n  )\n\n  // Validation function for required field (Story 2.12, AC: 4, 6, 10; Story 2.14, AC: 1)\n  // Used by both blur validation and imperative validate() method\n  const performValidation = useCallback((): boolean => {\n    // Skip validation for disabled or readOnly - can't interact, so always valid\n    if (disabled || readOnly) {\n      setValidationError(false)\n      onValidationChangeRef.current?.(true)\n      return true\n    }\n\n    // Check if required and no selection (works for both modes: single-select never\n    // holds more than one entry in selectedRecordsRef)\n    if (required && selectedRecordsRef.current.length === 0) {\n      setValidationError(true)\n      onValidationChangeRef.current?.(false)\n      return false\n    }\n\n    // Valid - clear any existing validation error\n    setValidationError(false)\n    onValidationChangeRef.current?.(true)\n    return true\n  }, [required, readOnly, disabled])\n\n  const handleScroll = useCallback(() => {\n    const container = optionsRef.current\n    if (!container) return\n\n    // Skip if already loading or no more pages\n    if (isLoadingMore || !hasMorePages) return\n\n    const { scrollTop, scrollHeight, clientHeight } = container\n    const isNearBottom = scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD_PX\n\n    if (isNearBottom) {\n      fetchMoreRecords(debouncedSearchQuery)\n    }\n  }, [isLoadingMore, hasMorePages, fetchMoreRecords, debouncedSearchQuery])\n\n  // Auto-focus search input when dropdown opens\n  useEffect(() => {\n    if (isOpen && searchInputRef.current) {\n      searchInputRef.current.focus({ preventScroll: true })\n    }\n  }, [isOpen])\n\n  // Fetch when debounced search changes or dropdown opens (Story 2.13: cache restore)\n  useEffect(() => {\n    if (isOpen) {\n      // Only fetch if search is empty or has >= minChars\n      if (debouncedSearchQuery.length === 0 || debouncedSearchQuery.length >= minChars) {\n        // Check if we can restore from cache (Story 2.13, AC: 3, 10)\n        const canRestoreFromCache =\n          cacheValid &&\n          cachedSearchQueryRef.current === debouncedSearchQuery &&\n          cachedRecords.length > 0\n\n        if (canRestoreFromCache) {\n          // Restore from cache instead of fetching\n          // Set flag to prevent fetchMoreRecords from being called during scroll restoration\n          isRestoringCacheRef.current = true\n          setRecords(cachedRecords)\n          currentPageRef.current = cachedCurrentPage\n          setCurrentPage(cachedCurrentPage)\n          setHasMorePages(true) // Assume there might be more pages\n          // Restore scroll position after render, then clear the restoring flag\n          requestAnimationFrame(() => {\n            if (optionsRef.current) {\n              optionsRef.current.scrollTop = cachedScrollPosition\n            }\n            // Clear flag after scroll position is restored (use setTimeout to ensure scroll event has been processed)\n            setTimeout(() => {\n              isRestoringCacheRef.current = false\n            }, 0)\n          })\n        } else {\n          // Fresh fetch - reset pagination state\n          currentPageRef.current = 1\n          setCurrentPage(1)\n          setHasMorePages(true)\n          setRecords([])\n          fetchRecords(debouncedSearchQuery)\n        }\n      }\n    }\n  }, [\n    isOpen,\n    debouncedSearchQuery,\n    fetchRecords,\n    minChars,\n    cacheValid,\n    cachedRecords,\n    cachedCurrentPage,\n    cachedScrollPosition,\n  ])\n\n  // Reset search and pagination when dropdown closes\n  useEffect(() => {\n    if (!isOpen) {\n      setSearchQuery('')\n      setSearchOperator('startsWith')\n      currentPageRef.current = 1\n      setCurrentPage(1)\n      setHasMorePages(true)\n      setIsLoadingMore(false)\n    }\n\n    return () => {\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort()\n      }\n    }\n  }, [isOpen])\n\n  // Track previous value to detect value prop changes (initialized to undefined to detect initial value)\n  const previousValueRef = useRef<string | null | undefined>(undefined)\n\n  // Ref for fetchAndSetRecordById to avoid effect re-runs\n  const fetchAndSetRecordByIdRef = useRef(fetchAndSetRecordById)\n  fetchAndSetRecordByIdRef.current = fetchAndSetRecordById\n\n  // Request ID to handle React 18 Strict Mode and race conditions\n  const valueSyncRequestIdRef = useRef(0)\n\n  // Sync external value prop with internal selectedRecord state (controlled mode) —\n  // SINGLE-select only, bails out immediately for isMultiple (see the array-valued\n  // effect right below). Only depends on value - uses refs for callbacks to avoid re-runs\n  useEffect(() => {\n    if (isMultiple) return\n    const singleValue = value as string | null\n\n    // On first run, previousValueRef is undefined, so we should process the initial value\n    const isInitialRun = previousValueRef.current === undefined\n    const valueChanged = isInitialRun || previousValueRef.current !== singleValue\n    previousValueRef.current = singleValue\n\n    // value null/undefined/'' means \"no selection\" in controlled mode — clear the visual state.\n    // LineFormModal resetea los searchers a '' (no null), así que tratamos vacío igual que null\n    // para evitar un fetch por Id: '' que deja el valor anterior pintado.\n    if (singleValue === null || singleValue === undefined || singleValue === '') {\n      // Invalida cualquier fetch(idAnterior) en vuelo: el .then de ese fetch\n      // chequea isStale contra este request-id, así que al incrementarlo aquí\n      // su resultado se descarta y no repinta el registro viejo (race del\n      // remontaje del modal: value pasa a '' mientras el fetch del id anterior\n      // aún no resuelve).\n      ++valueSyncRequestIdRef.current\n      setSelectedRecords([])\n      setIsInvalidValue(false)\n      return\n    }\n\n    // If value didn't change, skip\n    if (!valueChanged) {\n      return\n    }\n\n    // Si el registro ya está en memoria (lo acaba de seleccionar el usuario),\n    // no re-fetchar: evita el parpadeo de \"[record not found]\"\n    const currentRecord = selectedRecordRef.current\n    if (currentRecord) {\n      const recordId = String(currentRecord['Id'] ?? currentRecord['id'] ?? '')\n      if (recordId === singleValue) {\n        setIsInvalidValue(false)\n        return\n      }\n    }\n\n    // Increment request ID to invalidate any pending requests\n    const currentRequestId = ++valueSyncRequestIdRef.current\n\n    fetchAndSetRecordByIdRef.current(singleValue).then((record) => {\n      const isStale = valueSyncRequestIdRef.current !== currentRequestId\n      if (isStale) return\n      if (record) {\n        setSelectedRecords([record])\n        setIsInvalidValue(false)\n      } else {\n        // Record not found - invalid value\n        setIsInvalidValue(true)\n        setSelectedRecords([])\n        onInvalidValueRef.current?.(singleValue)\n      }\n    })\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [isMultiple, value])\n\n  // Ref for fetchRecordsByIds to avoid effect re-runs\n  const fetchRecordsByIdsRef = useRef(fetchRecordsByIds)\n  fetchRecordsByIdsRef.current = fetchRecordsByIds\n\n  // MULTI-select equivalent of the effect above — batches the whole `value` array into\n  // one fetch instead of one fetch per id. Bails out immediately for single-select.\n  const previousMultiValueKeyRef = useRef<string | undefined>(undefined)\n  useEffect(() => {\n    if (!isMultiple) return\n    const ids = (value as string[] | undefined) ?? []\n    const idsKey = JSON.stringify(ids)\n\n    if (previousMultiValueKeyRef.current === idsKey) return\n    previousMultiValueKeyRef.current = idsKey\n\n    if (ids.length === 0) {\n      setSelectedRecords([])\n      setIsInvalidValue(false)\n      return\n    }\n\n    // Skip refetch when every id is already in memory (the user just picked them from\n    // the dropdown) — same \"avoid the not-found flicker\" guard as single-select above.\n    const currentIds = new Set(selectedRecordsRef.current.map((r) => String(r.Id)))\n    if (ids.every((recordId) => currentIds.has(recordId))) return\n\n    const currentRequestId = ++valueSyncRequestIdRef.current\n    fetchRecordsByIdsRef.current(ids).then((resolved) => {\n      const isStale = valueSyncRequestIdRef.current !== currentRequestId\n      if (isStale) return\n      setSelectedRecords(resolved)\n      setIsInvalidValue(false)\n    })\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [isMultiple, JSON.stringify(value)])\n\n  // Dependencies-based reload (AC: 7, 8)\n  const dependenciesKey = JSON.stringify(dependencies ?? [])\n  useEffect(() => {\n    if (previousDependenciesRef.current !== dependenciesKey) {\n      previousDependenciesRef.current = dependenciesKey\n\n      // Abort any pending requests to prevent race conditions\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort()\n      }\n\n      // Invalidate cache on dependencies change (Story 2.13, AC: 6)\n      setCacheValid(false)\n\n      // Reset state on dependency change\n      setRecords([])\n      setSelectedRecords([])\n      currentPageRef.current = 1\n      setCurrentPage(1)\n      setHasMorePages(true)\n      setIsOpen(false)\n      setSearchQuery('')\n      // Note: Don't trigger fetch here - it will happen when dropdown opens\n    }\n  }, [dependenciesKey])\n\n  // Invalidate cache on filters change (Story 2.13, AC: 4)\n  const previousFiltersRef = useRef(filtersKey)\n  useEffect(() => {\n    if (previousFiltersRef.current !== filtersKey) {\n      previousFiltersRef.current = filtersKey\n      setCacheValid(false)\n    }\n  }, [filtersKey])\n\n  // Invalidate cache on search operator change — otherwise toggling startsWith/contains\n  // with the same search text would restore the old (wrong-operator) cached results\n  // instead of doing a fresh fetch.\n  const previousSearchOperatorRef = useRef(searchOperator)\n  useEffect(() => {\n    if (previousSearchOperatorRef.current !== searchOperator) {\n      previousSearchOperatorRef.current = searchOperator\n      setCacheValid(false)\n    }\n  }, [searchOperator])\n\n  /**\n   * Gets display text for the selected value in the trigger.\n   * Implements priority order: renderSelected > displayTemplate > displayValue > all displayFields concatenated\n   */\n  const getSelectedDisplay = useCallback(\n    (record: TRecord): string => {\n      // Priority 1: renderSelected function\n      if (renderSelected) {\n        return renderSelected(record)\n      }\n\n      // Priority 2: displayTemplate with interpolation\n      if (displayTemplate) {\n        return interpolateTemplate(displayTemplate, record)\n      }\n\n      // Priority 3: single displayValue field\n      if (displayValue) {\n        const value = record[displayValue]\n        return value !== undefined && value !== null ? String(value) : ''\n      }\n\n      // Default: concatenate all displayFields separated by \" - \"\n      return displayFields\n        .map((field) => {\n          const value = record[field]\n          return value !== undefined && value !== null ? String(value) : ''\n        })\n        .join(' - ')\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [renderSelected, displayTemplate, displayValue, displayFieldsKey]\n  )\n\n  const handleTriggerClick = () => {\n    if (disabled) return // Check disabled FIRST (Story 2.14, AC: 8)\n    if (readOnly) return\n    setIsOpen((prev) => !prev)\n  }\n\n  // The \"+\" button sits inside componentRef (same as the trigger), so clicking it\n  // doesn't fire useClickOutside's close-on-outside-click logic — without this, the\n  // dropdown (if open) stays open underneath the create popup until the user clicks\n  // away a second time. Close it explicitly before opening the popup.\n  const handleCreateClick = () => {\n    setIsOpen(false)\n    setSearchQuery('')\n    setIsCreateOpen(true)\n  }\n\n  /**\n   * Gets display text for dropdown option items.\n   * Always uses displayFields (separated by \" - \") regardless of display props.\n   */\n  const getOptionDisplay = (record: TRecord): string => {\n    return displayFields.map((field) => String(record[field] ?? '')).join(' - ')\n  }\n\n  const handleSelectRecord = (record: TRecord) => {\n    if (isMultiple) {\n      const prevRecords = selectedRecordsRef.current\n      const alreadySelected = prevRecords.some((r) => r.Id === record.Id)\n      if (!alreadySelected && maxSelected !== undefined && prevRecords.length >= maxSelected) {\n        onMaxSelectedReached?.(maxSelected)\n        return\n      }\n      const nextRecords = alreadySelected\n        ? prevRecords.filter((r) => r.Id !== record.Id)\n        : [...prevRecords, record]\n      setSelectedRecords(nextRecords)\n      selectedRecordsRef.current = nextRecords\n      setIsInvalidValue(false)\n\n      if (validationError) {\n        setValidationError(false)\n        onValidationChangeRef.current?.(true)\n      }\n\n      setCachedRecords(records)\n      setCachedScrollPosition(optionsRef.current?.scrollTop ?? 0)\n      setCachedCurrentPage(currentPage)\n      cachedSearchQueryRef.current = searchQuery\n      setCacheValid(true)\n\n      ;(onChange as (nextRecords: TRecord[], previousRecords: TRecord[]) => void)(nextRecords, prevRecords)\n      setSearchQuery('')\n      // Dropdown stays OPEN in multi-select — the user typically picks several before\n      // closing it themselves (Escape / outside click / the trigger again).\n      const toggleAnnouncementKey = alreadySelected ? 'announcements.cleared' : 'announcements.selected'\n      setAnnouncement(t(toggleAnnouncementKey, { value: getSelectedDisplay(record) }))\n      return\n    }\n\n    previousRecordRef.current = selectedRecord\n    setSelectedRecords([record])\n    selectedRecordRef.current = record // Update ref immediately for blur callbacks\n    setIsInvalidValue(false) // Clear invalid state on valid selection\n\n    // Clear validation error on selection (Story 2.12, AC: 9)\n    if (validationError) {\n      setValidationError(false)\n      onValidationChangeRef.current?.(true)\n    }\n\n    // Save navigation context cache before closing (Story 2.13, AC: 2, 3)\n    setCachedRecords(records)\n    setCachedScrollPosition(optionsRef.current?.scrollTop ?? 0)\n    setCachedCurrentPage(currentPage)\n    cachedSearchQueryRef.current = searchQuery\n    setCacheValid(true)\n\n    ;(onChange as (record: TRecord | null, previousRecord: TRecord | null) => void)(\n      record,\n      previousRecordRef.current\n    )\n    setSearchQuery('')\n    setIsOpen(false)\n    setApiError(null)\n    // Return focus to trigger after selection (fixes Tab behavior)\n    // Set flag to prevent handleTriggerFocus from reopening dropdown\n    justSelectedRef.current = true\n    triggerRef.current?.focus({ preventScroll: true })\n    // Announce selection\n    const displayText = getSelectedDisplay(record)\n    setAnnouncement(t('announcements.selected', { value: displayText }))\n  }\n\n  // Fired by the host's create form (via onCreateNew's `onCreated` helper)\n  // after successfully creating a new record. Always selects it exactly like picking\n  // it from the dropdown (fires onChange) and closes the create popup. Plain function\n  // (not memoized) — same pattern as handleSelectRecord/handleClear above, which it wraps.\n  const handleRecordCreated = (record: TRecord) => {\n    handleSelectRecord(record)\n    setIsCreateOpen(false)\n  }\n\n  // Enter pressed with nothing highlighted: the user typed a full code and wants it\n  // resolved directly, without arrowing down to a startsWith/contains match first (or\n  // one may not even be visible yet — the debounce might not have fired, or the exact\n  // record might not be on the currently loaded page). Runs a dedicated `equals` lookup\n  // — the only place this codebase ever sends `searchOperator: 'equals'` — rather than\n  // trusting the current startsWith/contains results, which could pick the wrong record\n  // (e.g. code \"A1\" also prefix/substring-matches \"A10\").\n  const handleExactMatchEnter = async (query: string) => {\n    const trimmed = query.trim()\n    if (!trimmed || isResolvingExactMatchRef.current) return\n    isResolvingExactMatchRef.current = true\n    setExactMatchStatus('searching')\n    setAnnouncement(t('announcements.exactMatchResolving', { value: trimmed }))\n\n    try {\n      const allFields = [...new Set(['Id', ...displayFields, ...(bindFields ?? [])])]\n      const response = await fetcher<TRecord>(entity, {\n        fields: allFields,\n        search: trimmed,\n        searchFields: searchFields ?? displayFields,\n        searchOperator: 'equals',\n        page: 1,\n        pageSize: 1,\n        filters: getEffectiveFilters(),\n        orderBy: effectiveOrderBy,\n      })\n\n      const match = response.data[0]\n      setExactMatchStatus('idle')\n      if (match) {\n        handleSelectRecord(match)\n      } else {\n        // Nothing visible on purpose — no red banner, just silence. Screen readers\n        // still get the outcome via the announcement.\n        setAnnouncement(t('announcements.exactMatchNotFound', { value: trimmed }))\n      }\n    } catch (err) {\n      setExactMatchStatus('idle')\n      const error = err instanceof Error ? err : new Error('Unknown error')\n      onError?.(error)\n    } finally {\n      isResolvingExactMatchRef.current = false\n    }\n  }\n\n  const handleClear = (event: React.MouseEvent) => {\n    event.stopPropagation()\n    const prevRecords = selectedRecordsRef.current\n    previousRecordRef.current = prevRecords[0] ?? null\n    setSelectedRecords([])\n    selectedRecordRef.current = null // Update ref immediately\n    selectedRecordsRef.current = []\n    setIsInvalidValue(false)\n    if (isMultiple) {\n      ;(onChange as (records: TRecord[], previousRecords: TRecord[]) => void)([], prevRecords)\n    } else {\n      ;(onChange as (record: TRecord | null, previousRecord: TRecord | null) => void)(null, prevRecords[0] ?? null)\n    }\n    setAnnouncement(t('announcements.cleared'))\n  }\n\n  // Keyboard-triggered clear (no event needed)\n  const handleKeyboardClear = useCallback(() => {\n    if (selectedRecordsRef.current.length === 0 && !isInvalidValue) return\n    const prevRecords = selectedRecordsRef.current\n    previousRecordRef.current = prevRecords[0] ?? null\n    setSelectedRecords([])\n    selectedRecordRef.current = null // Update ref immediately\n    selectedRecordsRef.current = []\n    setIsInvalidValue(false)\n    if (isMultiple) {\n      ;(onChange as (records: TRecord[], previousRecords: TRecord[]) => void)([], prevRecords)\n    } else {\n      ;(onChange as (record: TRecord | null, previousRecord: TRecord | null) => void)(null, prevRecords[0] ?? null)\n    }\n    setAnnouncement(t('announcements.cleared'))\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [isInvalidValue, isMultiple, onChange, t])\n\n  // Close handler for keyboard navigation (Tab)\n  // Finds the next tabbable element outside the component and focuses it\n  const handleClose = useCallback(() => {\n    // Set flag to prevent trigger from reopening dropdown when it receives focus during Tab navigation\n    isTabNavigatingRef.current = true\n\n    // Close the dropdown\n    setIsOpen(false)\n    setSearchQuery('')\n    setAnnouncement(t('announcements.closed'))\n\n    // Find and focus the next tabbable element after the component\n    // This ensures Tab navigation works correctly even when the dropdown is unmounted\n    // Use setTimeout to ensure this runs after React's state update and re-render\n    setTimeout(() => {\n      if (!componentRef.current) return\n\n      // Get all tabbable elements in the document (in DOM order)\n      const tabbableSelector =\n        'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n      const allTabbable = Array.from(document.querySelectorAll<HTMLElement>(tabbableSelector))\n\n      // Find the index of our component's trigger button in the tab order\n      const componentIndex = allTabbable.findIndex((el) => componentRef.current?.contains(el))\n\n      // Find the first tabbable element AFTER the component (not inside it)\n      let nextElement: HTMLElement | null = null\n      for (let i = componentIndex + 1; i < allTabbable.length; i++) {\n        if (!componentRef.current?.contains(allTabbable[i])) {\n          nextElement = allTabbable[i]\n          break\n        }\n      }\n\n      if (nextElement) {\n        nextElement.focus({ preventScroll: true })\n      }\n    }, 0)\n  }, [t])\n\n  // Escape handler - close AND return focus to trigger\n  const handleEscapeClose = useCallback(() => {\n    setIsOpen(false)\n    setSearchQuery('')\n    setAnnouncement(t('announcements.closed'))\n    triggerRef.current?.focus({ preventScroll: true })\n  }, [t])\n\n  // Imperative clear (no event needed, for ref.clear())\n  const handleImperativeClear = useCallback(() => {\n    const prevRecords = selectedRecordsRef.current\n    previousRecordRef.current = prevRecords[0] ?? null\n    setSelectedRecords([])\n    selectedRecordsRef.current = []\n    setIsInvalidValue(false)\n    if (isMultiple) {\n      ;(onChange as (records: TRecord[], previousRecords: TRecord[]) => void)([], prevRecords)\n    } else {\n      ;(onChange as (record: TRecord | null, previousRecord: TRecord | null) => void)(null, prevRecords[0] ?? null)\n    }\n    setAnnouncement(t('announcements.cleared'))\n  }, [isMultiple, onChange, t])\n\n  // Create imperative ref object (uses refs to always get latest values). Note: in\n  // multi-select mode getValue()/setValue() only operate on a single record — see the\n  // doc comments on LookupFieldRef for the exact multi-mode semantics.\n  const imperativeRef = useMemo<LookupFieldRef<TRecord>>(\n    () => ({\n      clear: handleImperativeClear,\n      focus: () => triggerRef.current?.focus({ preventScroll: true }),\n      reload: () => fetchRecords(debouncedSearchQuery),\n      getValue: () => selectedRecordRef.current,\n      setValue: async (recordId: string) => {\n        const record = await fetchAndSetRecordById(recordId)\n        if (record) {\n          const prevRecords = selectedRecordsRef.current\n          previousRecordRef.current = prevRecords[0] ?? null\n          setSelectedRecords([record])\n          setIsInvalidValue(false)\n          if (isMultiple) {\n            ;(onChange as (records: TRecord[], previousRecords: TRecord[]) => void)([record], prevRecords)\n          } else {\n            ;(onChange as (r: TRecord | null, prev: TRecord | null) => void)(record, previousRecordRef.current)\n          }\n        } else {\n          // Record not found - set invalid state and notify\n          setIsInvalidValue(true)\n          setSelectedRecords([])\n          onInvalidValue?.(recordId)\n        }\n      },\n      open: () => setIsOpen(true),\n      close: () => setIsOpen(false),\n      validate: performValidation,\n    }),\n    [\n      handleImperativeClear,\n      fetchRecords,\n      debouncedSearchQuery,\n      fetchAndSetRecordById,\n      isMultiple,\n      onChange,\n      onInvalidValue,\n      performValidation,\n    ]\n  )\n\n  // Expose ref to parent\n  useImperativeHandle(ref, () => imperativeRef, [imperativeRef])\n\n  // Keyboard navigation hook\n  const { highlightedIndex, setHighlightedIndex, handleKeyDown } = useKeyboardNavigation({\n    records: displayRecords,\n    isOpen,\n    onSelect: handleSelectRecord,\n    onClose: handleClose,\n    onEscape: handleEscapeClose,\n    onClear: handleKeyboardClear,\n    searchQuery,\n    onEnterWithoutHighlight: handleExactMatchEnter,\n  })\n\n  // Reset highlightedIndex when dropdown opens or records change. When the current\n  // search narrows to exactly one match, highlight it automatically — it reads as\n  // \"already selected\" for the user, and lets Enter confirm it immediately through the\n  // normal highlighted-Enter path instead of falling through to the exact-match lookup.\n  useEffect(() => {\n    if (isOpen) {\n      setHighlightedIndex(displayRecords.length === 1 ? 0 : -1)\n    }\n  }, [isOpen, displayRecords, setHighlightedIndex])\n\n  // Scroll highlighted option into view\n  useEffect(() => {\n    if (highlightedIndex >= 0 && optionsRef.current) {\n      const highlightedOption = optionsRef.current.querySelector(\n        `[data-index=\"${highlightedIndex}\"]`\n      ) as HTMLElement\n      if (highlightedOption?.scrollIntoView) {\n        highlightedOption.scrollIntoView({ block: 'nearest', behavior: 'smooth' })\n      }\n    }\n  }, [highlightedIndex])\n\n  // Track if focus came from mouse click (to distinguish Tab vs Click)\n  const wasClickedRef = useRef(false)\n  // Track if focus is from programmatic selection (to prevent dropdown reopening)\n  const justSelectedRef = useRef(false)\n  // Track if Tab navigation is in progress (to prevent dropdown reopening)\n  const isTabNavigatingRef = useRef(false)\n\n  const handleTriggerMouseDown = () => {\n    wasClickedRef.current = true\n  }\n\n  // Handle keydown on trigger (when dropdown is closed)\n  const handleTriggerKeyDown = (event: React.KeyboardEvent) => {\n    // Block keyboard when disabled (Story 2.14, AC: 6)\n    if (disabled) return\n\n    // The trigger renders as a <div role=\"button\"> (see the render below for why),\n    // which — unlike a native <button> — doesn't get Enter/Space-opens-it for free\n    // from the browser.\n    if (!isOpen && (event.key === 'Enter' || event.key === ' ')) {\n      event.preventDefault()\n      handleTriggerClick()\n      return\n    }\n\n    // Only handle when dropdown is closed\n    if (isOpen) return\n\n    // Backspace clears selection when clearable is enabled, not readOnly, and there's a value\n    if (event.key === 'Backspace' && clearable && !readOnly && (selectedRecord || isInvalidValue)) {\n      event.preventDefault()\n      handleKeyboardClear()\n    }\n  }\n\n  // Handle focus on trigger to open dropdown (Tab key behavior - AC1)\n  const handleTriggerFocus = () => {\n    if (disabled) return // Block focus handling when disabled (Story 2.14)\n    if (readOnly) return\n    // Skip opening if focus came from programmatic selection\n    if (justSelectedRef.current) {\n      justSelectedRef.current = false\n      return\n    }\n    // Skip opening if Tab navigation is closing the dropdown\n    if (isTabNavigatingRef.current) {\n      isTabNavigatingRef.current = false\n      return\n    }\n    // Only open on keyboard focus (Tab), not on click-focus\n    if (wasClickedRef.current) {\n      wasClickedRef.current = false\n      return\n    }\n    if (!isOpen) {\n      setIsOpen(true)\n    }\n  }\n\n  // Handle component-level focus (fires once when focus enters component)\n  const handleComponentFocus = useCallback(() => {\n    // Skip focus callbacks when disabled (Story 2.14, AC: 1)\n    if (disabled) return\n    // Only fire onFocus if focus is entering the component (not moving within)\n    if (!isFocusWithinRef.current) {\n      isFocusWithinRef.current = true\n      // Use ref to get latest selectedRecord (avoids stale closure)\n      onFocusProp?.(selectedRecordRef.current)\n    }\n  }, [onFocusProp, disabled])\n\n  // Handle component-level blur (fires once when focus leaves component entirely)\n  const handleComponentBlur = useCallback(\n    (event: React.FocusEvent) => {\n      // Skip blur callbacks when disabled (Story 2.14, AC: 1)\n      if (disabled) return\n\n      // Check if focus is moving outside the component\n      const relatedTarget = event.relatedTarget as Node | null\n      const isLeavingComponent = !componentRef.current?.contains(relatedTarget)\n\n      if (isLeavingComponent) {\n        isFocusWithinRef.current = false\n\n        // Perform validation on blur if enabled (Story 2.12, AC: 3, 4, 10)\n        if (validateOnBlur && !readOnly) {\n          performValidation()\n        }\n\n        // Use ref to get latest selectedRecord (avoids stale closure)\n        onBlurProp?.(selectedRecordRef.current)\n      }\n    },\n    [onBlurProp, validateOnBlur, readOnly, disabled, performValidation]\n  )\n\n  const renderDropdownContent = () => {\n    // Show min chars message when user has typed but fewer than minChars\n    if (searchQuery.length > 0 && searchQuery.length < minChars) {\n      return <div className=\"lookup-field__empty\">{t('minChars', { count: minChars })}</div>\n    }\n\n    if (isLoading) {\n      return (\n        <div className=\"lookup-field__loading\">\n          <Loader2 className=\"h-4 w-4 animate-spin\" />\n          <span>{t('loading')}</span>\n        </div>\n      )\n    }\n\n    if (apiError) {\n      return <div className=\"lookup-field__error\">{getFriendlyErrorMessage(apiError, t)}</div>\n    }\n\n    if (displayRecords.length === 0) {\n      return <div className=\"lookup-field__empty\">{noResultsText ?? t('noResults')}</div>\n    }\n\n    // Fallback to non-virtualized rendering when virtualizer can't calculate items\n    // (happens in test environments where container has no dimensions)\n    const useVirtualizedRendering = virtualItems.length > 0\n\n    const isOptionSelected = (record: TRecord) =>\n      isMultiple ? selectedRecords.some((r) => r.Id === record.Id) : selectedRecord?.Id === record.Id\n    const isOptionMaxDisabled = (record: TRecord) =>\n      isMultiple && maxSelected !== undefined && selectedRecords.length >= maxSelected && !isOptionSelected(record)\n\n    const renderOptionContent = (record: TRecord) => (\n      <>\n        {isMultiple && (\n          <span\n            className={cn(\n              'lookup-field__option-check',\n              isOptionSelected(record) && 'lookup-field__option-check--checked'\n            )}\n            aria-hidden=\"true\"\n          >\n            {isOptionSelected(record) && <Check className=\"w-3.5 h-3.5\" />}\n          </span>\n        )}\n        {getOptionDisplay(record)}\n      </>\n    )\n\n    return (\n      <div ref={optionsRef} className=\"lookup-field__options\" onScroll={handleScroll}>\n        {useVirtualizedRendering ? (\n          // Virtualized list container (Story 2.13, AC: 1, 8)\n          <div\n            style={{\n              height: `${totalSize}px`,\n              width: '100%',\n              position: 'relative',\n            }}\n          >\n            {virtualItems.map((virtualItem) => {\n              const record = displayRecords[virtualItem.index]\n              const index = virtualItem.index\n              return (\n                <div\n                  key={record.Id}\n                  id={`${id}-option-${record.Id}`}\n                  data-index={index}\n                  className={cn(\n                    'lookup-field__option',\n                    index === highlightedIndex && 'lookup-field__option--highlighted',\n                    isOptionSelected(record) && 'lookup-field__option--selected',\n                    isOptionMaxDisabled(record) && 'lookup-field__option--max-disabled'\n                  )}\n                  role=\"option\"\n                  aria-selected={isOptionSelected(record)}\n                  aria-disabled={isOptionMaxDisabled(record) || undefined}\n                  tabIndex={-1}\n                  onClick={() => handleSelectRecord(record)}\n                  style={{\n                    position: 'absolute',\n                    top: 0,\n                    left: 0,\n                    width: '100%',\n                    height: `${virtualItem.size}px`,\n                    transform: `translateY(${virtualItem.start}px)`,\n                  }}\n                >\n                  {renderOptionContent(record)}\n                </div>\n              )\n            })}\n          </div>\n        ) : (\n          // Non-virtualized fallback for test environments\n          displayRecords.map((record, index) => (\n            <div\n              key={record.Id}\n              id={`${id}-option-${record.Id}`}\n              data-index={index}\n              className={cn(\n                'lookup-field__option',\n                index === highlightedIndex && 'lookup-field__option--highlighted',\n                isOptionSelected(record) && 'lookup-field__option--selected',\n                isOptionMaxDisabled(record) && 'lookup-field__option--max-disabled'\n              )}\n              role=\"option\"\n              aria-selected={isOptionSelected(record)}\n              aria-disabled={isOptionMaxDisabled(record) || undefined}\n              tabIndex={-1}\n              onClick={() => handleSelectRecord(record)}\n            >\n              {renderOptionContent(record)}\n            </div>\n          ))\n        )}\n        {/* Loading more spinner at bottom (AC: 3) */}\n        {isLoadingMore && (\n          <div className=\"lookup-field__loading-more\">\n            <Loader2 className=\"h-4 w-4 animate-spin\" />\n          </div>\n        )}\n        {/* No end indicator per FR30 (AC: 6) */}\n      </div>\n    )\n  }\n\n  const setTriggerRef = useCallback(\n    (node: HTMLButtonElement | HTMLDivElement | null) => {\n      // Combine refs: triggerRef for internal use, floatingRefs.setReference for positioning\n      triggerRef.current = node\n      floatingRefs.setReference(node)\n    },\n    [floatingRefs]\n  )\n\n  return (\n    <div\n      ref={componentRef}\n      className={cn(\n        'lookup-field flex flex-col',\n        disabled && 'lookup-field--disabled',\n        readOnly && 'lookup-field--readonly',\n        showError && 'lookup-field--error',\n        className\n      )}\n      role=\"combobox\"\n      aria-expanded={!disabled && isOpen}\n      aria-haspopup=\"listbox\"\n      aria-labelledby={`${id}-label`}\n      aria-controls={isOpen ? `${id}-listbox` : undefined}\n      aria-disabled={disabled || undefined}\n      aria-readonly={(!disabled && readOnly) || undefined}\n      aria-invalid={showError || undefined}\n      aria-required={required || undefined}\n      onKeyDown={disabled ? undefined : handleKeyDown}\n      onFocus={handleComponentFocus}\n      onBlur={handleComponentBlur}\n    >\n      <LiveRegion message={announcement} />\n      <label id={`${id}-label`} htmlFor={id} className=\"lookup-field__label\">\n        {label}\n        {effectiveShowRequiredIndicator && (\n          <span className=\"lookup-field__required-indicator\">\n            {t('validation.requiredIndicator')}\n          </span>\n        )}\n      </label>\n      <div className={showCreateButton ? 'lookup-field__row' : undefined}>\n        {/* Always a <div role=\"button\"> rather than a native <button> — both modes can\n            end up with a real <button> among its own children (multi-select's chip\n            \"remove\" controls; single-select's own clear \"x\"), and a <button> can't\n            legally contain another <button> in the HTML content model. createElement\n            (rather than a JSX tag) sidesteps the ref-type friction of a prop-polymorphic\n            element; handleTriggerKeyDown adds the Enter/Space-opens-it behavior a native\n            button gets for free but a div role=\"button\" does not. */}\n        {createElement(\n          'div',\n          {\n            ref: setTriggerRef,\n            id,\n            className: cn('lookup-field__trigger', isMultiple && 'lookup-field__trigger--multiple'),\n            onClick: handleTriggerClick,\n            onMouseDown: handleTriggerMouseDown,\n            onKeyDown: handleTriggerKeyDown,\n            onFocus: handleTriggerFocus,\n            tabIndex: disabled ? -1 : 0,\n            role: 'button',\n            'aria-disabled': disabled || undefined,\n          },\n          isMultiple && selectedRecords.length > 0 ? (\n            <span className=\"lookup-field__chips\">\n              {selectedRecords.slice(0, MAX_VISIBLE_CHIPS).map((record) => (\n                <span key={record.Id} className=\"lookup-field__chip\">\n                  <Badge color=\"primary\" label={getSelectedDisplay(record)} />\n                  {!readOnly && !disabled && (\n                    <button\n                      type=\"button\"\n                      className=\"lookup-field__chip-remove\"\n                      aria-label={removeLabel}\n                      onClick={(event) => {\n                        event.stopPropagation()\n                        handleSelectRecord(record)\n                      }}\n                    >\n                      <X className=\"w-2.5 h-2.5\" />\n                    </button>\n                  )}\n                </span>\n              ))}\n              {selectedRecords.length > MAX_VISIBLE_CHIPS && (\n                <Badge color=\"zinc\" label={`+${selectedRecords.length - MAX_VISIBLE_CHIPS}`} />\n              )}\n            </span>\n          ) : (\n            <span className=\"lookup-field__selected-text\">\n              {isInvalidValue\n                ? t('notFound')\n                : selectedRecord\n                  ? getSelectedDisplay(selectedRecord)\n                  : (placeholder ?? t('placeholder'))}\n            </span>\n          ),\n          <span\n            className={cn(\n              'lookup-field__icon-btn lookup-field__chevron',\n              isOpen && 'lookup-field__chevron--open'\n            )}\n          >\n            <ChevronDown className=\"lookup-field__icon-btn-glyph\" aria-hidden=\"true\" />\n          </span>,\n          clearable && (isMultiple ? selectedRecords.length > 0 : selectedRecord) && !readOnly && !disabled && (\n            <button\n              type=\"button\"\n              className=\"lookup-field__icon-btn lookup-field__icon-btn--interactive lookup-field__clear\"\n              onClick={handleClear}\n              aria-label={clearSelectionLabel}\n            >\n              <X className=\"lookup-field__icon-btn-glyph\" aria-hidden=\"true\" />\n            </button>\n          )\n        )}\n        {showCreateButton && (\n          <button\n            type=\"button\"\n            className=\"lookup-field__icon-btn lookup-field__icon-btn--interactive lookup-field__create-btn\"\n            onClick={handleCreateClick}\n            disabled={disabled || readOnly}\n            aria-label={createButtonLabel ?? t('createNew')}\n            title={createButtonLabel ?? t('createNew')}\n          >\n            <Plus className=\"lookup-field__icon-btn-glyph\" aria-hidden=\"true\" />\n          </button>\n        )}\n      </div>\n      {onCreateNew && isCreateOpen && (\n        <CreatePopup\n          variant={createVariant ?? 'modal'}\n          title={createTitle ?? t('createNew')}\n          icon={createIcon}\n          width={createWidth}\n          height={createHeight}\n          showHeader={createShowHeader}\n          onClose={() => setIsCreateOpen(false)}\n        >\n          {onCreateNew({\n            onCreated: handleRecordCreated,\n            onCancel: () => setIsCreateOpen(false),\n          })}\n        </CreatePopup>\n      )}\n      {errorText && (\n        <span className=\"lookup-field__error-text\" role=\"alert\">\n          {errorText}\n        </span>\n      )}\n      {isOpen && createPortal(\n        <div\n          ref={floatingRefs.setFloating}\n          style={{\n            ...floatingStyles,\n            zIndex: 9999, // Ensure it's above modals\n          }}\n          className=\"lookup-field__dropdown\"\n        >\n          <SearchInput\n            ref={searchInputRef}\n            value={searchQuery}\n            onChange={(value) => {\n              setSearchQuery(value)\n              if (exactMatchStatus !== 'idle') setExactMatchStatus('idle')\n            }}\n            placeholder={searchPlaceholder ?? t('searchPlaceholder')}\n            searchOperator={searchOperator}\n            onSearchOperatorChange={setSearchOperator}\n            startsWithLabel={t('searchOperatorStartsWith')}\n            containsLabel={t('searchOperatorContains')}\n            exactMatchStatus={exactMatchStatus}\n            listboxId={`${id}-listbox`}\n            activeDescendantId={\n              highlightedIndex >= 0 && displayRecords[highlightedIndex]\n                ? `${id}-option-${displayRecords[highlightedIndex].Id}`\n                : undefined\n            }\n          />\n          <div id={`${id}-listbox`} role=\"listbox\" aria-label={label}>\n            {renderDropdownContent()}\n          </div>\n        </div>,\n        document.body\n      )}\n    </div>\n  )\n}\n\n// Export with forwardRef for generic component support\nexport const LookupField = forwardRef(LookupFieldInner) as <\n  TRecord extends LookupRecord = LookupRecord,\n>(\n  props: LookupFieldProps<TRecord> & { ref?: React.Ref<LookupFieldRef<TRecord>> }\n) => React.ReactElement\n\n// Set displayName for debugging\n;(LookupField as React.FC).displayName = 'LookupField'\n","/**\n * Validation Engine — Builds Zod schemas from field definitions.\n *\n * Pure function. Uses `t()` for i18n-aware error messages (I18N-RULE-004).\n * Date validation uses z.string().regex() — NEVER z.date() (project-context §3).\n *\n * @module validationEngine\n * @see FMPV-MVWC-E001-S004\n */\n\nimport { z } from 'zod';\nimport type { MasterPatternViewFieldDefinition } from '../types';\n\n/** ISO date-only pattern: YYYY-MM-DD */\nconst DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * Builds a Zod validation schema from an array of field definitions.\n *\n * Only fields with `showInForm: true` are included in the schema.\n * Error messages use the provided `t()` function for i18n.\n *\n * @param fields - Field definitions to build the schema from\n * @param t - Translation function for error messages\n * @returns A Zod object schema keyed by fieldName\n */\nexport function buildZodSchema(\n  fields: MasterPatternViewFieldDefinition[],\n  t: (key: string) => string\n): z.ZodObject<Record<string, z.ZodTypeAny>> {\n  const shape: Record<string, z.ZodTypeAny> = {};\n\n  for (const field of fields) {\n    if (field.showInForm === false) continue;\n\n    shape[field.fieldName] = buildFieldSchema(field, t);\n  }\n\n  return z.object(shape) as z.ZodObject<Record<string, z.ZodTypeAny>>;\n}\n\n/**\n * Builds a Zod schema for a single field.\n * Maps inputType/dataType to the appropriate Zod chain.\n */\nfunction buildFieldSchema(\n  field: MasterPatternViewFieldDefinition,\n  t: (key: string) => string\n): z.ZodTypeAny {\n  const inputType = field.inputType ?? inferInputTypeFromDataType(field.dataType);\n\n  switch (inputType) {\n    case 'number':\n    case 'decimal':\n      return buildNumberSchema(field, t);\n    case 'boolean':\n      return buildBooleanSchema();\n    case 'date':\n      return buildDateSchema(field, t);\n    case 'select':\n      // Select options can hold string OR number values — delegate to dataType.\n      if (field.dataType === 'number' || field.dataType === 'decimal') {\n        return buildNumberSchema(field, t);\n      }\n      return buildStringSchema(field, t);\n    case 'text':\n    case 'textarea':\n    case 'lookup':\n    default:\n      return buildStringSchema(field, t);\n  }\n}\n\nfunction buildStringSchema(\n  field: MasterPatternViewFieldDefinition,\n  t: (key: string) => string\n): z.ZodTypeAny {\n  const requiredMsg = t('validation.required');\n\n  if (field.isRequired) {\n    // z.preprocess coerces undefined/null → '' so min(1) fires the custom\n    // message instead of Zod v4's default \"Invalid input\" type error.\n    let inner = z.string().min(1, { message: requiredMsg });\n    if (field.maxLength !== undefined) {\n      inner = inner.max(field.maxLength, { message: t('validation.maxLength') });\n    }\n    return z.preprocess((val) => (val === undefined || val === null ? '' : val), inner);\n  }\n\n  // Non-required: coerce null/undefined to '' so z.string() accepts them\n  // without Zod v4's default \"Invalid input\" type error on null values from API responses.\n  let inner = z.string();\n  if (field.maxLength !== undefined) {\n    inner = inner.max(field.maxLength, { message: t('validation.maxLength') });\n  }\n  return z.preprocess((val) => (val === undefined || val === null ? '' : val), inner);\n}\n\nfunction buildNumberSchema(\n  field: MasterPatternViewFieldDefinition,\n  t: (key: string) => string\n): z.ZodTypeAny {\n  const schema = z.number({ message: t('validation.number') });\n\n  if (field.isRequired) {\n    return schema;\n  }\n\n  return schema.optional() as unknown as z.ZodTypeAny;\n}\n\nfunction buildBooleanSchema(): z.ZodTypeAny {\n  return z.boolean().optional() as unknown as z.ZodTypeAny;\n}\n\nfunction buildDateSchema(\n  field: MasterPatternViewFieldDefinition,\n  t: (key: string) => string\n): z.ZodTypeAny {\n  let schema = z.string().regex(DATE_REGEX, { message: t('validation.dateFormat') });\n\n  if (field.isRequired) {\n    schema = schema.min(1, { message: t('validation.required') });\n  }\n\n  if (field.isRequired) {\n    return schema;\n  }\n\n  return schema.optional() as unknown as z.ZodTypeAny;\n}\n\nfunction inferInputTypeFromDataType(dataType: string): string {\n  const map: Record<string, string> = {\n    string: 'text',\n    number: 'number',\n    decimal: 'decimal',\n    boolean: 'boolean',\n    date: 'date',\n    guid: 'text',\n  };\n  return map[dataType] ?? 'text';\n}\n","/**\n * useMasterForm — TanStack Query mutations for create/update operations.\n *\n * Validation pipeline:\n * 1. Zod schema validation (buildZodSchema)\n * 2. Custom validate() prop\n * 3. If errors → dispatch setErrors + navigate to basicData → abort\n * 4. Call service.create or service.update\n * 5. On server validation errors → map to formSlice.errors\n * 6. On 409 → open conflict dialog\n *\n * @module hooks/useMasterForm\n * @see FMPV-MVWC-E003-S003 I-001, I-003\n */\nimport { useCallback, useState } from 'react';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useMasterViewStore } from '../store/MasterViewContext';\nimport type { MasterPatternViewEntity } from '../types/service.types';\nimport type { MasterPatternViewService } from '../types/service.types';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport type { MasterPatternViewActionType } from '../types/permissions.types';\nimport { buildZodSchema } from '../engine/validationEngine';\nimport { getAllFields } from '../engine/fieldEngine';\nimport type { ToastCallback } from './useToast';\nimport { useToast } from './useToast';\n\nexport interface UseMasterFormOptions<T extends MasterPatternViewEntity> {\n  definition: MasterPatternViewDefinition;\n  service: MasterPatternViewService<T>;\n  validate?: (values: Partial<T>) => Record<string, string>;\n  onCreateSuccess?: (record: T) => void;\n  onUpdateSuccess?: (record: T) => void;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** Translation function — used for toast messages and validation error messages. */\n  t?: (key: string, defaultValue?: string) => string;\n  onFormSave?: (\n    mode: 'creating' | 'editing',\n    values: Record<string, unknown>,\n    originalRecord?: T,\n  ) => void | Promise<void>;\n  onError?: (error: Error, action: MasterPatternViewActionType) => void;\n}\n\nconst defaultMessages: Record<string, string> = {\n  'validation.required': 'Este campo es requerido',\n  'validation.number': 'Debe ser un número válido',\n  'validation.dateFormat': 'Formato de fecha inválido (YYYY-MM-DD)',\n  'validation.maxLength': 'Excede la longitud máxima permitida',\n};\nconst defaultT = (key: string, defaultValue?: string): string => defaultValue ?? defaultMessages[key] ?? key;\n\n/** Maps buildZodSchema's internal `validation.*` keys to the flat i18n keys used by internalTranslations. */\nconst VALIDATION_KEY_MAP: Record<string, { key: string; defaultValue: string }> = {\n  'validation.required': { key: 'validationRequired', defaultValue: 'Este campo es requerido' },\n  'validation.number': { key: 'validationNumber', defaultValue: 'Debe ser un número válido' },\n  'validation.dateFormat': { key: 'validationDateFormat', defaultValue: 'Formato de fecha inválido (YYYY-MM-DD)' },\n  'validation.maxLength': { key: 'validationMaxLength', defaultValue: 'Excede la longitud máxima permitida' },\n};\n\nexport function useMasterForm<T extends MasterPatternViewEntity>({\n  definition,\n  service,\n  validate,\n  onCreateSuccess,\n  onUpdateSuccess,\n  toast: toastProp,\n  showInternalToasts = true,\n  t = defaultT,\n  onFormSave,\n  onError,\n}: UseMasterFormOptions<T>) {\n  const [isCustomSubmitting, setIsCustomSubmitting] = useState(false);\n\n  const mode = useMasterViewStore((s) => s.mode);\n  const values = useMasterViewStore((s) => s.values);\n  const activeRecord = useMasterViewStore((s) => s.activeRecord);\n  const setErrors = useMasterViewStore((s) => s.setErrors);\n  const setActiveTabKey = useMasterViewStore((s) => s.setActiveTabKey);\n  const closeForm = useMasterViewStore((s) => s.closeForm);\n  const setData = useMasterViewStore((s) => s.setData);\n  const openConflictDialog = useMasterViewStore((s) => s.openConflictDialog);\n  const activeCompanyContext = useMasterViewStore((s) => s.activeCompanyContext);\n  const globalValues = useMasterViewStore((s) => s.globalValues);\n  const overrides = useMasterViewStore((s) => s.overrides);\n  const revertedFields = useMasterViewStore((s) => s.revertedFields);\n  const companyId = activeCompanyContext && activeCompanyContext !== 'global'\n    ? activeCompanyContext\n    : undefined;\n  const { showSuccess, showError } = useToast(toastProp, showInternalToasts);\n\n  const queryClient = useQueryClient();\n\n  // Load record when editing/viewing\n  useQuery({\n    queryKey: ['masterRecord', (activeRecord as T & { id: string })?.id],\n    queryFn: () => service.getById!((activeRecord as T & { id: string }).id),\n    enabled: !!(service.getById && activeRecord && (mode === 'editing' || mode === 'viewing')),\n    staleTime: 0,\n    refetchOnWindowFocus: false,\n  });\n\n  const createMutation = useMutation({\n    mutationFn: (payload: Partial<T>) => service.create(payload, companyId),\n    onSuccess: async (record) => {\n      // OJO: invalidateQueries se dispara DESPUÉS de que companyEnable resuelva (no antes,\n      // como estaba) — si se invalida primero, React Query refetchea la lista mientras el\n      // enable todavía está en vuelo, así que llega con isAssigned=false y el badge de\n      // \"compañía asignada\" no aparece hasta el siguiente reload manual de la página.\n      if (definition.type === 'GLOBAL' && companyId && service.companyEnable) {\n        // Company context: auto-enable + close form immediately\n        try {\n          await service.companyEnable((record as T & { id: string }).id, companyId);\n          showSuccess(t('createEnabledSuccess', 'Registro creado y habilitado para la compañía exitosamente'));\n        } catch {\n          showError(t('createEnabledPartialError', 'Registro creado, pero no se pudo habilitar automáticamente. Habilítelo desde la lista.'));\n        }\n        queryClient.invalidateQueries({ queryKey: ['masterList'] });\n        closeForm();\n      } else if (definition.type === 'GLOBAL' && !companyId) {\n        // Global context: keep form open — CompanyEnableModal opens on top of it.\n        // closeForm() is called by the modal's onClose/onConfirm handlers.\n        queryClient.invalidateQueries({ queryKey: ['masterList'] });\n        showSuccess(t('createSuccess', 'Registro creado exitosamente'));\n      } else {\n        queryClient.invalidateQueries({ queryKey: ['masterList'] });\n        showSuccess(t('createSuccess', 'Registro creado exitosamente'));\n        closeForm();\n      }\n      onCreateSuccess?.(record);\n    },\n    onError: (error: Error) => {\n      showError(error.message || t('createError', 'Error al crear el registro'));\n    },\n  });\n\n  const updateMutation = useMutation({\n    mutationFn: async ({\n      id,\n      payload,\n      initialIsActive,\n    }: {\n      id: string;\n      payload: Partial<T>;\n      initialIsActive?: unknown;\n    }) => {\n      if (companyId && service.getById) {\n        // Company context: PATCH /overrides does not validate version server-side.\n        // Pre-flight check: fetch company-scoped record and compare:\n        //   1. Global version (detects concurrent global edits)\n        //   2. isActive value (detects concurrent company-override edits)\n        const current = await service.getById(id, companyId);\n        const currentVersion = (current as any).version;\n        const payloadVersion = (payload as any).version;\n        if (\n          currentVersion !== undefined &&\n          payloadVersion !== undefined &&\n          currentVersion !== payloadVersion\n        ) {\n          const err = new Error('Conflicto de versión') as any;\n          err.status = 409;\n          throw err;\n        }\n        const currentIsActive = (current as any).isActive;\n        if (\n          initialIsActive !== undefined &&\n          currentIsActive !== undefined &&\n          currentIsActive !== initialIsActive\n        ) {\n          const err = new Error('Conflicto de versión') as any;\n          err.status = 409;\n          throw err;\n        }\n      }\n      // Pass explicitly reverted fields so the service can null them in the backend.\n      // Only meaningful in company context for GLOBAL type — other contexts just ignore it.\n      const rf = companyId && revertedFields.length > 0 ? revertedFields : undefined;\n      return service.update(id, payload, companyId, rf);\n    },\n    onSuccess: (record) => {\n      showSuccess(t('updateSuccess', 'Registro actualizado exitosamente'));\n      queryClient.invalidateQueries({ queryKey: ['masterList'] });\n      closeForm();\n      onUpdateSuccess?.(record);\n    },\n    onError: (error: any) => {\n      if (error?.status === 409 || error?.statusCode === 409) {\n        openConflictDialog();\n        return;\n      }\n      // Map server field errors if present\n      if (error?.errors && Array.isArray(error.errors)) {\n        const fieldErrors: Record<string, string> = {};\n        for (const e of error.errors) {\n          if (e.field) fieldErrors[e.field] = e.message;\n        }\n        if (Object.keys(fieldErrors).length > 0) {\n          setErrors(fieldErrors);\n          setActiveTabKey('basicData');\n          return;\n        }\n      }\n      showError(error?.message || t('updateError', 'Error al actualizar el registro'));\n    },\n  });\n\n  // buildZodSchema calls its `t` argument with a single `validation.*` key (no defaultValue).\n  // This adapter maps those internal keys to the flat i18n keys used by internalTranslations,\n  // supplying the matching Spanish default so behavior is unchanged when i18n isn't configured.\n  const validationT = useCallback(\n    (key: string): string => {\n      const mapped = VALIDATION_KEY_MAP[key];\n      return mapped ? t(mapped.key, mapped.defaultValue) : t(key);\n    },\n    [t],\n  );\n\n  const runValidation = useCallback(\n    (vals: Record<string, unknown>): Record<string, string> => {\n      const errors: Record<string, string> = {};\n\n      // Step 1: Zod schema validation\n      const schema = buildZodSchema(getAllFields(definition), validationT);\n      const result = schema.safeParse(vals);\n      if (!result.success) {\n        for (const issue of result.error.issues) {\n          const field = issue.path[0] as string;\n          if (field && !errors[field]) {\n            errors[field] = issue.message;\n          }\n        }\n      }\n\n      // Step 2: Custom validate() prop (wins over Zod for same field)\n      if (validate) {\n        const customErrors = validate(vals as Partial<T>);\n        for (const [field, message] of Object.entries(customErrors)) {\n          errors[field] = message; // overwrites Zod message for same field\n        }\n      }\n\n      return errors;\n    },\n    [definition, validate, validationT],\n  );\n\n  const submit = useCallback(async () => {\n    const errors = runValidation(values);\n\n    if (Object.keys(errors).length > 0) {\n      setErrors(errors);\n      setActiveTabKey('basicData');\n      return;\n    }\n\n    setErrors({});\n\n    // Offline persistence path — consumer owns the API call and timing.\n    // Exits before createMutation/updateMutation so those paths are untouched.\n    if (onFormSave) {\n      setIsCustomSubmitting(true);\n      try {\n        await onFormSave(\n          mode === 'creating' ? 'creating' : 'editing',\n          values as Record<string, unknown>,\n          activeRecord as T | undefined,\n        );\n        closeForm();\n      } catch (err) {\n        onError?.(err as Error, mode === 'creating' ? 'create' : 'update');\n      } finally {\n        setIsCustomSubmitting(false);\n      }\n      return;\n    }\n\n    if (mode === 'creating') {\n      await createMutation.mutateAsync(values as Partial<T>);\n    } else if (mode === 'editing' && activeRecord) {\n      const id = (activeRecord as T & { id: string }).id;\n      const payload: Partial<T> = { ...values } as Partial<T>;\n      // Include version for optimistic concurrency.\n      // In company context the list row may not carry version — fall back to globalValues.version\n      // (populated by getById without companyId in openEditRecord).\n      const version = activeRecord.version ?? (globalValues as any).version;\n      if (version !== undefined) {\n        (payload as any).version = version;\n      }\n      // Capture isActive at save-click time for company-context conflict detection\n      const initialIsActive = (activeRecord as any).isActive;\n      await updateMutation.mutateAsync({ id, payload, initialIsActive });\n    }\n  }, [\n    runValidation,\n    values,\n    mode,\n    activeRecord,\n    globalValues,\n    overrides,\n    revertedFields,\n    companyId,\n    setErrors,\n    setActiveTabKey,\n    createMutation,\n    updateMutation,\n  ]);\n\n  return {\n    submit,\n    isSubmitting: createMutation.isPending || updateMutation.isPending || isCustomSubmitting,\n  };\n}\n","/**\n * MasterPatternViewCreateForm — standalone creation-only form for a MasterPatternView\n * master: no list, no toolbar, just the tabs/fields/save-cancel of the \"create\" flow.\n *\n * Self-contained (own QueryClient + isolated Zustand store via MasterViewProvider), so\n * it can be embedded anywhere without pulling in the full list+toolbar shell — e.g. as\n * a LookupField `onCreateNew`, letting a lookup field for another MasterPatternView-based\n * master become a full \"entity control\" with a single prop.\n *\n * @module components/MasterPatternViewCreateForm\n */\nimport React, { useEffect, useState } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { MasterViewProvider, useMasterViewStore } from '../store/MasterViewContext';\nimport { MasterPatternViewForm } from './form/MasterPatternViewForm';\nimport { useMasterForm } from '../hooks/useMasterForm';\nimport type { ToastCallback } from '../hooks/useToast';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport type { MasterPatternViewEntity, MasterPatternViewService, MasterPatternViewCompany } from '../types/service.types';\nimport type { MasterPatternViewPermissions } from '../types/permissions.types';\n\nexport interface MasterPatternViewCreateFormProps<T extends MasterPatternViewEntity> {\n  /**\n   * Returns the target master's definition — same shape its own <MasterPatternView>\n   * uses. This is a FUNCTION (not a resolved value) so it can be a parameterless React\n   * hook (e.g. `useAccountDefinition`) without forcing the caller to invoke it outside\n   * of a component render. That matters specifically for a SELF-REFERENCING lookup\n   * (e.g. Account's own \"parent account\" field, which points back at Account itself):\n   * if the caller had to resolve the definition eagerly to build `create.useDefinition`,\n   * building Account's own definition would require calling `useAccountDefinition()`\n   * from inside `useAccountDefinition()` itself — direct, unconditional recursion that\n   * crashes the very first time the form renders, not a rules-of-hooks nuance to work\n   * around. Passing the function instead defers the call until THIS component actually\n   * mounts, which only happens when the user opens the \"+\" popup — a fresh, independent\n   * render, not a call nested inside the definition that's still being constructed.\n   *\n   * For a definition that's already a plain constant (no hook involved), just wrap it:\n   * `useDefinition={() => productosDefinition}`.\n   */\n  useDefinition: () => MasterPatternViewDefinition;\n  /** The target master's service — only `create` (and `getAll`, required by the type) matter here. */\n  service: MasterPatternViewService<T>;\n  /** Human-readable entity name shown in the form header. Falls back to `definition.name`. */\n  entityName?: string;\n  /** Called with the newly created record once `service.create` resolves. */\n  onCreated: (record: T) => void;\n  /** Called when the user cancels out of the form without creating anything. */\n  onCancel: () => void;\n  /** Pre-filled values merged into the fresh create form (same as MasterPatternView's own prop). */\n  defaultCreateValues?: Record<string, unknown>;\n  /** Custom synchronous validation, same contract as MasterPatternView's own `validate` prop. */\n  validate?: (values: Partial<T>) => Record<string, string>;\n  /** Permission configuration — gates the Editar/Guardar affordances same as the full component. */\n  permissions?: MasterPatternViewPermissions;\n  /**\n   * External toast callback. Omit to keep this form silent (no InternalToastContainer is\n   * mounted for this isolated instance, so the default internal toast has nowhere to render).\n   */\n  toast?: ToastCallback;\n  /** Translation function override. */\n  t?: (key: string, defaultValue?: string) => string;\n  /**\n   * Visual chrome wrapped around the form content.\n   * - `'none'` (default) — no wrapper; the host fully controls the surrounding chrome\n   *   (e.g. embedding the form inline inside its own page section).\n   * - `'modal'` | `'sidebar'` — wraps the form in the exact same background/shadow/\n   *   corner-radius classes MasterPatternView's own `ModalPanel`/`SidebarPanel` use, so\n   *   a popup host (e.g. LookupField's `onCreateNew`) can present it looking identical\n   *   to the master's real create modal/sidebar, without inventing its own card chrome\n   *   that would just duplicate this one.\n   * @default 'none'\n   */\n  chrome?: 'none' | 'modal' | 'sidebar';\n  /**\n   * Full company list, for a target master whose own definition is company-scoped\n   * (`companyBehavior !== 'NONE'`). Same shape the target's own `<MasterPatternView>`\n   * would receive. Omit for a company-agnostic master — the form then renders with no\n   * company selector at all, same as before this prop existed.\n   */\n  companies?: MasterPatternViewCompany[];\n  /**\n   * Company this new record should be created under — typically the host's own\n   * currently active/inherited company (e.g. a \"Cuentas\" lookup opened while editing\n   * a record already scoped to \"ACME SAS\" should create its \"Centro de Costo\" under\n   * ACME SAS too, not under \"Global\"). Preseeds the form's own isolated company\n   * context on mount; without it the form falls back to `companies[0]`, same as a\n   * fresh top-level create.\n   */\n  defaultCompany?: MasterPatternViewCompany;\n  /**\n   * Locks the company selector so the user can't change it away from `defaultCompany`.\n   * Plain opt-in, `false` unless the caller says otherwise — this component is used\n   * standalone too (not just behind a lookup's \"+\"), where a suggested default\n   * shouldn't silently become mandatory. The lookup-create wiring in FieldRenderer.tsx\n   * is the one call site that actually wants this on by default; it passes it\n   * explicitly rather than relying on a default here. Has no effect without\n   * `defaultCompany` (nothing to lock to).\n   * @default false\n   */\n  companyLocked?: boolean;\n}\n\n// Same as the public props, minus `defaultCreateValues` (already consumed by\n// MasterViewProvider in the wrapper below) and `useDefinition` (already resolved to a\n// plain `definition` value by the wrapper — this inner component never calls hooks\n// that produce a definition itself).\ntype MasterPatternViewCreateFormInnerProps<T extends MasterPatternViewEntity> = Omit<\n  MasterPatternViewCreateFormProps<T>,\n  'defaultCreateValues' | 'useDefinition'\n> & {\n  definition: MasterPatternViewDefinition;\n};\n\nfunction MasterPatternViewCreateFormInner<T extends MasterPatternViewEntity>({\n  definition,\n  service,\n  entityName,\n  onCreated,\n  onCancel,\n  validate,\n  permissions,\n  toast,\n  t,\n  chrome = 'none',\n  companies,\n  defaultCompany,\n  companyLocked = false,\n}: MasterPatternViewCreateFormInnerProps<T>) {\n  const openCreate = useMasterViewStore((s) => s.openCreate);\n  const setActiveCompanyContext = useMasterViewStore((s) => s.setActiveCompanyContext);\n  useEffect(() => {\n    openCreate();\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n  // Seeds this form's own ISOLATED store with the host's currently active company —\n  // without this it always starts undefined/'global' regardless of what the host was\n  // already scoped to, which is what made the popup default to \"Global\" instead of\n  // the company the record was actually about to be created under.\n  //\n  // Deliberately a SEPARATE effect keyed on `defaultCompany?.id` (not folded into the\n  // mount-once effect above, and not left as `[]`): the host that opens this popup — a\n  // LookupField's \"+\", specifically — commonly keeps this component's subtree mounted\n  // between separate open/close cycles (e.g. for close-transition animations) rather than\n  // fully unmounting it. A `[]`-effect only runs once for the component's entire mounted\n  // lifetime, so it captures whatever company happened to be active the very FIRST time\n  // the popup was ever opened and never re-applies it on a later re-open with a different\n  // company — even though `defaultCompany` itself is a perfectly up-to-date prop on every\n  // one of those renders. Keying on the id (not the object) avoids re-firing on every\n  // parent render if `companies` is rebuilt with fresh-but-equivalent objects each time.\n  useEffect(() => {\n    if (defaultCompany) setActiveCompanyContext(defaultCompany.id);\n  // Keyed on the id on purpose — see comment above.\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [defaultCompany?.id, setActiveCompanyContext]);\n\n  const { submit } = useMasterForm<T>({\n    definition,\n    service,\n    validate,\n    onCreateSuccess: onCreated,\n    toast,\n    t,\n  });\n\n  const form = (\n    <MasterPatternViewForm<T>\n      definition={definition}\n      entityName={entityName ?? definition.name}\n      navigationType=\"inline\"\n      onSave={submit}\n      onCancel={onCancel}\n      onRequestRefresh={() => {}}\n      permissions={permissions}\n      t={t}\n      companies={companies}\n      onCompanyChange={(company) => setActiveCompanyContext(company.id)}\n      companyDisabled={companyLocked && !!defaultCompany}\n      // In 'none' chrome the host owns the surrounding layout (e.g. inline in its own\n      // page section, which usually has other cues that content continues below) —\n      // in 'modal'/'sidebar' this form is confined to a popup where a hidden\n      // scrollbar is the only thing that would tell the user there's more to scroll to.\n      showScrollbar={chrome !== 'none'}\n    />\n  );\n\n  if (chrome === 'modal') {\n    return (\n      <div className=\"bg-background-secondary dark:bg-dark-bg-secondary rounded-lg shadow-2xl flex flex-col h-full overflow-hidden\">\n        {form}\n      </div>\n    );\n  }\n\n  if (chrome === 'sidebar') {\n    return (\n      <div className=\"bg-background-secondary dark:bg-dark-bg-secondary shadow-xl flex flex-col h-full overflow-hidden\">\n        {form}\n      </div>\n    );\n  }\n\n  return form;\n}\n\nexport function MasterPatternViewCreateForm<T extends MasterPatternViewEntity>({\n  useDefinition,\n  defaultCreateValues,\n  ...rest\n}: MasterPatternViewCreateFormProps<T>) {\n  // The one and only place `useDefinition` is invoked — this component's own render,\n  // which only happens on a fresh mount when the popup opens. See the prop's doc\n  // comment for why this must not be resolved any earlier than this.\n  const definition = useDefinition();\n  const [client] = useState(() => new QueryClient());\n  return (\n    <QueryClientProvider client={client}>\n      <MasterViewProvider<T> definition={definition} defaultCreateValues={defaultCreateValues}>\n        <MasterPatternViewCreateFormInner<T> definition={definition} {...rest} />\n      </MasterViewProvider>\n    </QueryClientProvider>\n  );\n}\n","/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","/** @license React v16.13.1\n * react-is.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n\n\nif (process.env.NODE_ENV !== \"production\") {\n  (function() {\n'use strict';\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\n// (unstable) APIs that have been removed. Can we remove the symbols?\n\nvar REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\nvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\nvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\n\nfunction isValidElementType(type) {\n  return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n  type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n}\n\nfunction typeOf(object) {\n  if (typeof object === 'object' && object !== null) {\n    var $$typeof = object.$$typeof;\n\n    switch ($$typeof) {\n      case REACT_ELEMENT_TYPE:\n        var type = object.type;\n\n        switch (type) {\n          case REACT_ASYNC_MODE_TYPE:\n          case REACT_CONCURRENT_MODE_TYPE:\n          case REACT_FRAGMENT_TYPE:\n          case REACT_PROFILER_TYPE:\n          case REACT_STRICT_MODE_TYPE:\n          case REACT_SUSPENSE_TYPE:\n            return type;\n\n          default:\n            var $$typeofType = type && type.$$typeof;\n\n            switch ($$typeofType) {\n              case REACT_CONTEXT_TYPE:\n              case REACT_FORWARD_REF_TYPE:\n              case REACT_LAZY_TYPE:\n              case REACT_MEMO_TYPE:\n              case REACT_PROVIDER_TYPE:\n                return $$typeofType;\n\n              default:\n                return $$typeof;\n            }\n\n        }\n\n      case REACT_PORTAL_TYPE:\n        return $$typeof;\n    }\n  }\n\n  return undefined;\n} // AsyncMode is deprecated along with isAsyncMode\n\nvar AsyncMode = REACT_ASYNC_MODE_TYPE;\nvar ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;\nvar ContextConsumer = REACT_CONTEXT_TYPE;\nvar ContextProvider = REACT_PROVIDER_TYPE;\nvar Element = REACT_ELEMENT_TYPE;\nvar ForwardRef = REACT_FORWARD_REF_TYPE;\nvar Fragment = REACT_FRAGMENT_TYPE;\nvar Lazy = REACT_LAZY_TYPE;\nvar Memo = REACT_MEMO_TYPE;\nvar Portal = REACT_PORTAL_TYPE;\nvar Profiler = REACT_PROFILER_TYPE;\nvar StrictMode = REACT_STRICT_MODE_TYPE;\nvar Suspense = REACT_SUSPENSE_TYPE;\nvar hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated\n\nfunction isAsyncMode(object) {\n  {\n    if (!hasWarnedAboutDeprecatedIsAsyncMode) {\n      hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint\n\n      console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');\n    }\n  }\n\n  return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;\n}\nfunction isConcurrentMode(object) {\n  return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;\n}\nfunction isContextConsumer(object) {\n  return typeOf(object) === REACT_CONTEXT_TYPE;\n}\nfunction isContextProvider(object) {\n  return typeOf(object) === REACT_PROVIDER_TYPE;\n}\nfunction isElement(object) {\n  return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\nfunction isForwardRef(object) {\n  return typeOf(object) === REACT_FORWARD_REF_TYPE;\n}\nfunction isFragment(object) {\n  return typeOf(object) === REACT_FRAGMENT_TYPE;\n}\nfunction isLazy(object) {\n  return typeOf(object) === REACT_LAZY_TYPE;\n}\nfunction isMemo(object) {\n  return typeOf(object) === REACT_MEMO_TYPE;\n}\nfunction isPortal(object) {\n  return typeOf(object) === REACT_PORTAL_TYPE;\n}\nfunction isProfiler(object) {\n  return typeOf(object) === REACT_PROFILER_TYPE;\n}\nfunction isStrictMode(object) {\n  return typeOf(object) === REACT_STRICT_MODE_TYPE;\n}\nfunction isSuspense(object) {\n  return typeOf(object) === REACT_SUSPENSE_TYPE;\n}\n\nexports.AsyncMode = AsyncMode;\nexports.ConcurrentMode = ConcurrentMode;\nexports.ContextConsumer = ContextConsumer;\nexports.ContextProvider = ContextProvider;\nexports.Element = Element;\nexports.ForwardRef = ForwardRef;\nexports.Fragment = Fragment;\nexports.Lazy = Lazy;\nexports.Memo = Memo;\nexports.Portal = Portal;\nexports.Profiler = Profiler;\nexports.StrictMode = StrictMode;\nexports.Suspense = Suspense;\nexports.isAsyncMode = isAsyncMode;\nexports.isConcurrentMode = isConcurrentMode;\nexports.isContextConsumer = isContextConsumer;\nexports.isContextProvider = isContextProvider;\nexports.isElement = isElement;\nexports.isForwardRef = isForwardRef;\nexports.isFragment = isFragment;\nexports.isLazy = isLazy;\nexports.isMemo = isMemo;\nexports.isPortal = isPortal;\nexports.isProfiler = isProfiler;\nexports.isStrictMode = isStrictMode;\nexports.isSuspense = isSuspense;\nexports.isValidElementType = isValidElementType;\nexports.typeOf = typeOf;\n  })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./cjs/react-is.production.min.js');\n} else {\n  module.exports = require('./cjs/react-is.development.js');\n}\n","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc');  // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","module.exports = Function.call.bind(Object.prototype.hasOwnProperty);\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar printWarning = function() {};\n\nif (process.env.NODE_ENV !== 'production') {\n  var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n  var loggedTypeFailures = {};\n  var has = require('./lib/has');\n\n  printWarning = function(text) {\n    var message = 'Warning: ' + text;\n    if (typeof console !== 'undefined') {\n      console.error(message);\n    }\n    try {\n      // --- Welcome to debugging React ---\n      // This error was thrown as a convenience so that you can use this stack\n      // to find the callsite that caused this warning to fire.\n      throw new Error(message);\n    } catch (x) { /**/ }\n  };\n}\n\n/**\n * Assert that the values match with the type specs.\n * Error messages are memorized and will only be shown once.\n *\n * @param {object} typeSpecs Map of name to a ReactPropType\n * @param {object} values Runtime values that need to be type-checked\n * @param {string} location e.g. \"prop\", \"context\", \"child context\"\n * @param {string} componentName Name of the component for error messages.\n * @param {?Function} getStack Returns the component stack.\n * @private\n */\nfunction checkPropTypes(typeSpecs, values, location, componentName, getStack) {\n  if (process.env.NODE_ENV !== 'production') {\n    for (var typeSpecName in typeSpecs) {\n      if (has(typeSpecs, typeSpecName)) {\n        var error;\n        // Prop type validation may throw. In case they do, we don't want to\n        // fail the render phase where it didn't fail before. So we log it.\n        // After these have been cleaned up, we'll let them throw.\n        try {\n          // This is intentionally an invariant that gets caught. It's the same\n          // behavior as without this statement except with a better message.\n          if (typeof typeSpecs[typeSpecName] !== 'function') {\n            var err = Error(\n              (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +\n              'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' +\n              'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'\n            );\n            err.name = 'Invariant Violation';\n            throw err;\n          }\n          error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);\n        } catch (ex) {\n          error = ex;\n        }\n        if (error && !(error instanceof Error)) {\n          printWarning(\n            (componentName || 'React class') + ': type specification of ' +\n            location + ' `' + typeSpecName + '` is invalid; the type checker ' +\n            'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +\n            'You may have forgotten to pass an argument to the type checker ' +\n            'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +\n            'shape all require an argument).'\n          );\n        }\n        if (error instanceof Error && !(error.message in loggedTypeFailures)) {\n          // Only monitor this failure once because there tends to be a lot of the\n          // same error.\n          loggedTypeFailures[error.message] = true;\n\n          var stack = getStack ? getStack() : '';\n\n          printWarning(\n            'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')\n          );\n        }\n      }\n    }\n  }\n}\n\n/**\n * Resets warning cache when testing.\n *\n * @private\n */\ncheckPropTypes.resetWarningCache = function() {\n  if (process.env.NODE_ENV !== 'production') {\n    loggedTypeFailures = {};\n  }\n}\n\nmodule.exports = checkPropTypes;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactIs = require('react-is');\nvar assign = require('object-assign');\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\nvar has = require('./lib/has');\nvar checkPropTypes = require('./checkPropTypes');\n\nvar printWarning = function() {};\n\nif (process.env.NODE_ENV !== 'production') {\n  printWarning = function(text) {\n    var message = 'Warning: ' + text;\n    if (typeof console !== 'undefined') {\n      console.error(message);\n    }\n    try {\n      // --- Welcome to debugging React ---\n      // This error was thrown as a convenience so that you can use this stack\n      // to find the callsite that caused this warning to fire.\n      throw new Error(message);\n    } catch (x) {}\n  };\n}\n\nfunction emptyFunctionThatReturnsNull() {\n  return null;\n}\n\nmodule.exports = function(isValidElement, throwOnDirectAccess) {\n  /* global Symbol */\n  var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\n  var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.\n\n  /**\n   * Returns the iterator method function contained on the iterable object.\n   *\n   * Be sure to invoke the function with the iterable as context:\n   *\n   *     var iteratorFn = getIteratorFn(myIterable);\n   *     if (iteratorFn) {\n   *       var iterator = iteratorFn.call(myIterable);\n   *       ...\n   *     }\n   *\n   * @param {?object} maybeIterable\n   * @return {?function}\n   */\n  function getIteratorFn(maybeIterable) {\n    var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);\n    if (typeof iteratorFn === 'function') {\n      return iteratorFn;\n    }\n  }\n\n  /**\n   * Collection of methods that allow declaration and validation of props that are\n   * supplied to React components. Example usage:\n   *\n   *   var Props = require('ReactPropTypes');\n   *   var MyArticle = React.createClass({\n   *     propTypes: {\n   *       // An optional string prop named \"description\".\n   *       description: Props.string,\n   *\n   *       // A required enum prop named \"category\".\n   *       category: Props.oneOf(['News','Photos']).isRequired,\n   *\n   *       // A prop named \"dialog\" that requires an instance of Dialog.\n   *       dialog: Props.instanceOf(Dialog).isRequired\n   *     },\n   *     render: function() { ... }\n   *   });\n   *\n   * A more formal specification of how these methods are used:\n   *\n   *   type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)\n   *   decl := ReactPropTypes.{type}(.isRequired)?\n   *\n   * Each and every declaration produces a function with the same signature. This\n   * allows the creation of custom validation functions. For example:\n   *\n   *  var MyLink = React.createClass({\n   *    propTypes: {\n   *      // An optional string or URI prop named \"href\".\n   *      href: function(props, propName, componentName) {\n   *        var propValue = props[propName];\n   *        if (propValue != null && typeof propValue !== 'string' &&\n   *            !(propValue instanceof URI)) {\n   *          return new Error(\n   *            'Expected a string or an URI for ' + propName + ' in ' +\n   *            componentName\n   *          );\n   *        }\n   *      }\n   *    },\n   *    render: function() {...}\n   *  });\n   *\n   * @internal\n   */\n\n  var ANONYMOUS = '<<anonymous>>';\n\n  // Important!\n  // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.\n  var ReactPropTypes = {\n    array: createPrimitiveTypeChecker('array'),\n    bigint: createPrimitiveTypeChecker('bigint'),\n    bool: createPrimitiveTypeChecker('boolean'),\n    func: createPrimitiveTypeChecker('function'),\n    number: createPrimitiveTypeChecker('number'),\n    object: createPrimitiveTypeChecker('object'),\n    string: createPrimitiveTypeChecker('string'),\n    symbol: createPrimitiveTypeChecker('symbol'),\n\n    any: createAnyTypeChecker(),\n    arrayOf: createArrayOfTypeChecker,\n    element: createElementTypeChecker(),\n    elementType: createElementTypeTypeChecker(),\n    instanceOf: createInstanceTypeChecker,\n    node: createNodeChecker(),\n    objectOf: createObjectOfTypeChecker,\n    oneOf: createEnumTypeChecker,\n    oneOfType: createUnionTypeChecker,\n    shape: createShapeTypeChecker,\n    exact: createStrictShapeTypeChecker,\n  };\n\n  /**\n   * inlined Object.is polyfill to avoid requiring consumers ship their own\n   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n   */\n  /*eslint-disable no-self-compare*/\n  function is(x, y) {\n    // SameValue algorithm\n    if (x === y) {\n      // Steps 1-5, 7-10\n      // Steps 6.b-6.e: +0 != -0\n      return x !== 0 || 1 / x === 1 / y;\n    } else {\n      // Step 6.a: NaN == NaN\n      return x !== x && y !== y;\n    }\n  }\n  /*eslint-enable no-self-compare*/\n\n  /**\n   * We use an Error-like object for backward compatibility as people may call\n   * PropTypes directly and inspect their output. However, we don't use real\n   * Errors anymore. We don't inspect their stack anyway, and creating them\n   * is prohibitively expensive if they are created too often, such as what\n   * happens in oneOfType() for any type before the one that matched.\n   */\n  function PropTypeError(message, data) {\n    this.message = message;\n    this.data = data && typeof data === 'object' ? data: {};\n    this.stack = '';\n  }\n  // Make `instanceof Error` still work for returned errors.\n  PropTypeError.prototype = Error.prototype;\n\n  function createChainableTypeChecker(validate) {\n    if (process.env.NODE_ENV !== 'production') {\n      var manualPropTypeCallCache = {};\n      var manualPropTypeWarningCount = 0;\n    }\n    function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {\n      componentName = componentName || ANONYMOUS;\n      propFullName = propFullName || propName;\n\n      if (secret !== ReactPropTypesSecret) {\n        if (throwOnDirectAccess) {\n          // New behavior only for users of `prop-types` package\n          var err = new Error(\n            'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n            'Use `PropTypes.checkPropTypes()` to call them. ' +\n            'Read more at http://fb.me/use-check-prop-types'\n          );\n          err.name = 'Invariant Violation';\n          throw err;\n        } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {\n          // Old behavior for people using React.PropTypes\n          var cacheKey = componentName + ':' + propName;\n          if (\n            !manualPropTypeCallCache[cacheKey] &&\n            // Avoid spamming the console because they are often not actionable except for lib authors\n            manualPropTypeWarningCount < 3\n          ) {\n            printWarning(\n              'You are manually calling a React.PropTypes validation ' +\n              'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +\n              'and will throw in the standalone `prop-types` package. ' +\n              'You may be seeing this warning due to a third-party PropTypes ' +\n              'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'\n            );\n            manualPropTypeCallCache[cacheKey] = true;\n            manualPropTypeWarningCount++;\n          }\n        }\n      }\n      if (props[propName] == null) {\n        if (isRequired) {\n          if (props[propName] === null) {\n            return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));\n          }\n          return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));\n        }\n        return null;\n      } else {\n        return validate(props, propName, componentName, location, propFullName);\n      }\n    }\n\n    var chainedCheckType = checkType.bind(null, false);\n    chainedCheckType.isRequired = checkType.bind(null, true);\n\n    return chainedCheckType;\n  }\n\n  function createPrimitiveTypeChecker(expectedType) {\n    function validate(props, propName, componentName, location, propFullName, secret) {\n      var propValue = props[propName];\n      var propType = getPropType(propValue);\n      if (propType !== expectedType) {\n        // `propValue` being instance of, say, date/regexp, pass the 'object'\n        // check, but we can offer a more precise error message here rather than\n        // 'of type `object`'.\n        var preciseType = getPreciseType(propValue);\n\n        return new PropTypeError(\n          'Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'),\n          {expectedType: expectedType}\n        );\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createAnyTypeChecker() {\n    return createChainableTypeChecker(emptyFunctionThatReturnsNull);\n  }\n\n  function createArrayOfTypeChecker(typeChecker) {\n    function validate(props, propName, componentName, location, propFullName) {\n      if (typeof typeChecker !== 'function') {\n        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');\n      }\n      var propValue = props[propName];\n      if (!Array.isArray(propValue)) {\n        var propType = getPropType(propValue);\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));\n      }\n      for (var i = 0; i < propValue.length; i++) {\n        var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);\n        if (error instanceof Error) {\n          return error;\n        }\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createElementTypeChecker() {\n    function validate(props, propName, componentName, location, propFullName) {\n      var propValue = props[propName];\n      if (!isValidElement(propValue)) {\n        var propType = getPropType(propValue);\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createElementTypeTypeChecker() {\n    function validate(props, propName, componentName, location, propFullName) {\n      var propValue = props[propName];\n      if (!ReactIs.isValidElementType(propValue)) {\n        var propType = getPropType(propValue);\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createInstanceTypeChecker(expectedClass) {\n    function validate(props, propName, componentName, location, propFullName) {\n      if (!(props[propName] instanceof expectedClass)) {\n        var expectedClassName = expectedClass.name || ANONYMOUS;\n        var actualClassName = getClassName(props[propName]);\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createEnumTypeChecker(expectedValues) {\n    if (!Array.isArray(expectedValues)) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (arguments.length > 1) {\n          printWarning(\n            'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +\n            'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'\n          );\n        } else {\n          printWarning('Invalid argument supplied to oneOf, expected an array.');\n        }\n      }\n      return emptyFunctionThatReturnsNull;\n    }\n\n    function validate(props, propName, componentName, location, propFullName) {\n      var propValue = props[propName];\n      for (var i = 0; i < expectedValues.length; i++) {\n        if (is(propValue, expectedValues[i])) {\n          return null;\n        }\n      }\n\n      var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {\n        var type = getPreciseType(value);\n        if (type === 'symbol') {\n          return String(value);\n        }\n        return value;\n      });\n      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createObjectOfTypeChecker(typeChecker) {\n    function validate(props, propName, componentName, location, propFullName) {\n      if (typeof typeChecker !== 'function') {\n        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');\n      }\n      var propValue = props[propName];\n      var propType = getPropType(propValue);\n      if (propType !== 'object') {\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));\n      }\n      for (var key in propValue) {\n        if (has(propValue, key)) {\n          var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n          if (error instanceof Error) {\n            return error;\n          }\n        }\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createUnionTypeChecker(arrayOfTypeCheckers) {\n    if (!Array.isArray(arrayOfTypeCheckers)) {\n      process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;\n      return emptyFunctionThatReturnsNull;\n    }\n\n    for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n      var checker = arrayOfTypeCheckers[i];\n      if (typeof checker !== 'function') {\n        printWarning(\n          'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +\n          'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'\n        );\n        return emptyFunctionThatReturnsNull;\n      }\n    }\n\n    function validate(props, propName, componentName, location, propFullName) {\n      var expectedTypes = [];\n      for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n        var checker = arrayOfTypeCheckers[i];\n        var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret);\n        if (checkerResult == null) {\n          return null;\n        }\n        if (checkerResult.data && has(checkerResult.data, 'expectedType')) {\n          expectedTypes.push(checkerResult.data.expectedType);\n        }\n      }\n      var expectedTypesMessage = (expectedTypes.length > 0) ? ', expected one of type [' + expectedTypes.join(', ') + ']': '';\n      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.'));\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createNodeChecker() {\n    function validate(props, propName, componentName, location, propFullName) {\n      if (!isNode(props[propName])) {\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function invalidValidatorError(componentName, location, propFullName, key, type) {\n    return new PropTypeError(\n      (componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' +\n      'it must be a function, usually from the `prop-types` package, but received `' + type + '`.'\n    );\n  }\n\n  function createShapeTypeChecker(shapeTypes) {\n    function validate(props, propName, componentName, location, propFullName) {\n      var propValue = props[propName];\n      var propType = getPropType(propValue);\n      if (propType !== 'object') {\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n      }\n      for (var key in shapeTypes) {\n        var checker = shapeTypes[key];\n        if (typeof checker !== 'function') {\n          return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));\n        }\n        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n        if (error) {\n          return error;\n        }\n      }\n      return null;\n    }\n    return createChainableTypeChecker(validate);\n  }\n\n  function createStrictShapeTypeChecker(shapeTypes) {\n    function validate(props, propName, componentName, location, propFullName) {\n      var propValue = props[propName];\n      var propType = getPropType(propValue);\n      if (propType !== 'object') {\n        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n      }\n      // We need to check all keys in case some are required but missing from props.\n      var allKeys = assign({}, props[propName], shapeTypes);\n      for (var key in allKeys) {\n        var checker = shapeTypes[key];\n        if (has(shapeTypes, key) && typeof checker !== 'function') {\n          return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));\n        }\n        if (!checker) {\n          return new PropTypeError(\n            'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +\n            '\\nBad object: ' + JSON.stringify(props[propName], null, '  ') +\n            '\\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, '  ')\n          );\n        }\n        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n        if (error) {\n          return error;\n        }\n      }\n      return null;\n    }\n\n    return createChainableTypeChecker(validate);\n  }\n\n  function isNode(propValue) {\n    switch (typeof propValue) {\n      case 'number':\n      case 'string':\n      case 'undefined':\n        return true;\n      case 'boolean':\n        return !propValue;\n      case 'object':\n        if (Array.isArray(propValue)) {\n          return propValue.every(isNode);\n        }\n        if (propValue === null || isValidElement(propValue)) {\n          return true;\n        }\n\n        var iteratorFn = getIteratorFn(propValue);\n        if (iteratorFn) {\n          var iterator = iteratorFn.call(propValue);\n          var step;\n          if (iteratorFn !== propValue.entries) {\n            while (!(step = iterator.next()).done) {\n              if (!isNode(step.value)) {\n                return false;\n              }\n            }\n          } else {\n            // Iterator will provide entry [k,v] tuples rather than values.\n            while (!(step = iterator.next()).done) {\n              var entry = step.value;\n              if (entry) {\n                if (!isNode(entry[1])) {\n                  return false;\n                }\n              }\n            }\n          }\n        } else {\n          return false;\n        }\n\n        return true;\n      default:\n        return false;\n    }\n  }\n\n  function isSymbol(propType, propValue) {\n    // Native Symbol.\n    if (propType === 'symbol') {\n      return true;\n    }\n\n    // falsy value can't be a Symbol\n    if (!propValue) {\n      return false;\n    }\n\n    // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'\n    if (propValue['@@toStringTag'] === 'Symbol') {\n      return true;\n    }\n\n    // Fallback for non-spec compliant Symbols which are polyfilled.\n    if (typeof Symbol === 'function' && propValue instanceof Symbol) {\n      return true;\n    }\n\n    return false;\n  }\n\n  // Equivalent of `typeof` but with special handling for array and regexp.\n  function getPropType(propValue) {\n    var propType = typeof propValue;\n    if (Array.isArray(propValue)) {\n      return 'array';\n    }\n    if (propValue instanceof RegExp) {\n      // Old webkits (at least until Android 4.0) return 'function' rather than\n      // 'object' for typeof a RegExp. We'll normalize this here so that /bla/\n      // passes PropTypes.object.\n      return 'object';\n    }\n    if (isSymbol(propType, propValue)) {\n      return 'symbol';\n    }\n    return propType;\n  }\n\n  // This handles more types than `getPropType`. Only used for error messages.\n  // See `createPrimitiveTypeChecker`.\n  function getPreciseType(propValue) {\n    if (typeof propValue === 'undefined' || propValue === null) {\n      return '' + propValue;\n    }\n    var propType = getPropType(propValue);\n    if (propType === 'object') {\n      if (propValue instanceof Date) {\n        return 'date';\n      } else if (propValue instanceof RegExp) {\n        return 'regexp';\n      }\n    }\n    return propType;\n  }\n\n  // Returns a string that is postfixed to a warning about an invalid type.\n  // For example, \"undefined\" or \"of type array\"\n  function getPostfixForTypeWarning(value) {\n    var type = getPreciseType(value);\n    switch (type) {\n      case 'array':\n      case 'object':\n        return 'an ' + type;\n      case 'boolean':\n      case 'date':\n      case 'regexp':\n        return 'a ' + type;\n      default:\n        return type;\n    }\n  }\n\n  // Returns class name of the object, if any.\n  function getClassName(propValue) {\n    if (!propValue.constructor || !propValue.constructor.name) {\n      return ANONYMOUS;\n    }\n    return propValue.constructor.name;\n  }\n\n  ReactPropTypes.checkPropTypes = checkPropTypes;\n  ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;\n  ReactPropTypes.PropTypes = ReactPropTypes;\n\n  return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n  function shim(props, propName, componentName, location, propFullName, secret) {\n    if (secret === ReactPropTypesSecret) {\n      // It is still safe when called from React.\n      return;\n    }\n    var err = new Error(\n      'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n      'Use PropTypes.checkPropTypes() to call them. ' +\n      'Read more at http://fb.me/use-check-prop-types'\n    );\n    err.name = 'Invariant Violation';\n    throw err;\n  };\n  shim.isRequired = shim;\n  function getShim() {\n    return shim;\n  };\n  // Important!\n  // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n  var ReactPropTypes = {\n    array: shim,\n    bigint: shim,\n    bool: shim,\n    func: shim,\n    number: shim,\n    object: shim,\n    string: shim,\n    symbol: shim,\n\n    any: shim,\n    arrayOf: getShim,\n    element: shim,\n    elementType: shim,\n    instanceOf: getShim,\n    node: shim,\n    objectOf: getShim,\n    oneOf: getShim,\n    oneOfType: getShim,\n    shape: getShim,\n    exact: getShim,\n\n    checkPropTypes: emptyFunctionWithReset,\n    resetWarningCache: emptyFunction\n  };\n\n  ReactPropTypes.PropTypes = ReactPropTypes;\n\n  return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n  var ReactIs = require('react-is');\n\n  // By explicitly using `prop-types` you are opting into new development behavior.\n  // http://fb.me/prop-types-in-prod\n  var throwOnDirectAccess = true;\n  module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n  // By explicitly using `prop-types` you are opting into new production behavior.\n  // http://fb.me/prop-types-in-prod\n  module.exports = require('./factoryWithThrowingShims')();\n}\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n  extendStatics = Object.setPrototypeOf ||\n      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n  return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n  if (typeof b !== \"function\" && b !== null)\n      throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n  extendStatics(d, b);\n  function __() { this.constructor = d; }\n  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n  __assign = Object.assign || function __assign(t) {\n      for (var s, i = 1, n = arguments.length; i < n; i++) {\n          s = arguments[i];\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n      }\n      return t;\n  }\n  return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n  var t = {};\n  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n      t[p] = s[p];\n  if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n              t[p[i]] = s[p[i]];\n      }\n  return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n  if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n  return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n  return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n  function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n  var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n  var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n  var _, done = false;\n  for (var i = decorators.length - 1; i >= 0; i--) {\n      var context = {};\n      for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n      for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n      context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n      var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n      if (kind === \"accessor\") {\n          if (result === void 0) continue;\n          if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n          if (_ = accept(result.get)) descriptor.get = _;\n          if (_ = accept(result.set)) descriptor.set = _;\n          if (_ = accept(result.init)) initializers.unshift(_);\n      }\n      else if (_ = accept(result)) {\n          if (kind === \"field\") initializers.unshift(_);\n          else descriptor[key] = _;\n      }\n  }\n  if (target) Object.defineProperty(target, contextIn.name, descriptor);\n  done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n  var useValue = arguments.length > 2;\n  for (var i = 0; i < initializers.length; i++) {\n      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n  }\n  return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n  return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n  if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n  return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n  if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n  return new (P || (P = Promise))(function (resolve, reject) {\n      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n      function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n      step((generator = generator.apply(thisArg, _arguments || [])).next());\n  });\n}\n\nexport function __generator(thisArg, body) {\n  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n  return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n  function verb(n) { return function (v) { return step([n, v]); }; }\n  function step(op) {\n      if (f) throw new TypeError(\"Generator is already executing.\");\n      while (g && (g = 0, op[0] && (_ = 0)), _) try {\n          if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n          if (y = 0, t) op = [op[0] & 2, t.value];\n          switch (op[0]) {\n              case 0: case 1: t = op; break;\n              case 4: _.label++; return { value: op[1], done: false };\n              case 5: _.label++; y = op[1]; op = [0]; continue;\n              case 7: op = _.ops.pop(); _.trys.pop(); continue;\n              default:\n                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                  if (t[2]) _.ops.pop();\n                  _.trys.pop(); continue;\n          }\n          op = body.call(thisArg, _);\n      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n  }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  var desc = Object.getOwnPropertyDescriptor(m, k);\n  if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n  }\n  Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n  for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n  var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n  if (m) return m.call(o);\n  if (o && typeof o.length === \"number\") return {\n      next: function () {\n          if (o && i >= o.length) o = void 0;\n          return { value: o && o[i++], done: !o };\n      }\n  };\n  throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  }\n  catch (error) { e = { error: error }; }\n  finally {\n      try {\n          if (r && !r.done && (m = i[\"return\"])) m.call(i);\n      }\n      finally { if (e) throw e.error; }\n  }\n  return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n      ar = ar.concat(__read(arguments[i]));\n  return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n  for (var r = Array(s), k = 0, i = 0; i < il; i++)\n      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n          r[k] = a[j];\n  return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n      if (ar || !(i in from)) {\n          if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n          ar[i] = from[i];\n      }\n  }\n  return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n  return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n  function fulfill(value) { resume(\"next\", value); }\n  function reject(value) { resume(\"throw\", value); }\n  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n  var i, p;\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator], i;\n  return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n  if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n  return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n  Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n  o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n  ownKeys = Object.getOwnPropertyNames || function (o) {\n    var ar = [];\n    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n    return ar;\n  };\n  return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n  if (mod && mod.__esModule) return mod;\n  var result = {};\n  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n  __setModuleDefault(result, mod);\n  return result;\n}\n\nexport function __importDefault(mod) {\n  return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n  return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n  if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n  return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n  if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n  return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n  if (value !== null && value !== void 0) {\n    if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n    var dispose, inner;\n    if (async) {\n      if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n      dispose = value[Symbol.asyncDispose];\n    }\n    if (dispose === void 0) {\n      if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n      dispose = value[Symbol.dispose];\n      if (async) inner = dispose;\n    }\n    if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n    env.stack.push({ value: value, dispose: dispose, async: async });\n  }\n  else if (async) {\n    env.stack.push({ async: true });\n  }\n  return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n  var e = new Error(message);\n  return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n  function fail(e) {\n    env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n    env.hasError = true;\n  }\n  var r, s = 0;\n  function next() {\n    while (r = env.stack.pop()) {\n      try {\n        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n        if (r.dispose) {\n          var result = r.dispose.call(r.value);\n          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n        }\n        else s |= 1;\n      }\n      catch (e) {\n        fail(e);\n      }\n    }\n    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n    if (env.hasError) throw env.error;\n  }\n  return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n  if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n      return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n          return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n      });\n  }\n  return path;\n}\n\nexport default {\n  __extends,\n  __assign,\n  __rest,\n  __decorate,\n  __param,\n  __esDecorate,\n  __runInitializers,\n  __propKey,\n  __setFunctionName,\n  __metadata,\n  __awaiter,\n  __generator,\n  __createBinding,\n  __exportStar,\n  __values,\n  __read,\n  __spread,\n  __spreadArrays,\n  __spreadArray,\n  __await,\n  __asyncGenerator,\n  __asyncDelegator,\n  __asyncValues,\n  __makeTemplateObject,\n  __importStar,\n  __importDefault,\n  __classPrivateFieldGet,\n  __classPrivateFieldSet,\n  __classPrivateFieldIn,\n  __addDisposableResource,\n  __disposeResources,\n  __rewriteRelativeImportExtension,\n};\n","export const COMMON_MIME_TYPES = new Map([\n    // https://github.com/guzzle/psr7/blob/2d9260799e713f1c475d3c5fdc3d6561ff7441b2/src/MimeType.php\n    ['1km', 'application/vnd.1000minds.decision-model+xml'],\n    ['3dml', 'text/vnd.in3d.3dml'],\n    ['3ds', 'image/x-3ds'],\n    ['3g2', 'video/3gpp2'],\n    ['3gp', 'video/3gp'],\n    ['3gpp', 'video/3gpp'],\n    ['3mf', 'model/3mf'],\n    ['7z', 'application/x-7z-compressed'],\n    ['7zip', 'application/x-7z-compressed'],\n    ['123', 'application/vnd.lotus-1-2-3'],\n    ['aab', 'application/x-authorware-bin'],\n    ['aac', 'audio/x-acc'],\n    ['aam', 'application/x-authorware-map'],\n    ['aas', 'application/x-authorware-seg'],\n    ['abw', 'application/x-abiword'],\n    ['ac', 'application/vnd.nokia.n-gage.ac+xml'],\n    ['ac3', 'audio/ac3'],\n    ['acc', 'application/vnd.americandynamics.acc'],\n    ['ace', 'application/x-ace-compressed'],\n    ['acu', 'application/vnd.acucobol'],\n    ['acutc', 'application/vnd.acucorp'],\n    ['adp', 'audio/adpcm'],\n    ['aep', 'application/vnd.audiograph'],\n    ['afm', 'application/x-font-type1'],\n    ['afp', 'application/vnd.ibm.modcap'],\n    ['ahead', 'application/vnd.ahead.space'],\n    ['ai', 'application/pdf'],\n    ['aif', 'audio/x-aiff'],\n    ['aifc', 'audio/x-aiff'],\n    ['aiff', 'audio/x-aiff'],\n    ['air', 'application/vnd.adobe.air-application-installer-package+zip'],\n    ['ait', 'application/vnd.dvb.ait'],\n    ['ami', 'application/vnd.amiga.ami'],\n    ['amr', 'audio/amr'],\n    ['apk', 'application/vnd.android.package-archive'],\n    ['apng', 'image/apng'],\n    ['appcache', 'text/cache-manifest'],\n    ['application', 'application/x-ms-application'],\n    ['apr', 'application/vnd.lotus-approach'],\n    ['arc', 'application/x-freearc'],\n    ['arj', 'application/x-arj'],\n    ['asc', 'application/pgp-signature'],\n    ['asf', 'video/x-ms-asf'],\n    ['asm', 'text/x-asm'],\n    ['aso', 'application/vnd.accpac.simply.aso'],\n    ['asx', 'video/x-ms-asf'],\n    ['atc', 'application/vnd.acucorp'],\n    ['atom', 'application/atom+xml'],\n    ['atomcat', 'application/atomcat+xml'],\n    ['atomdeleted', 'application/atomdeleted+xml'],\n    ['atomsvc', 'application/atomsvc+xml'],\n    ['atx', 'application/vnd.antix.game-component'],\n    ['au', 'audio/x-au'],\n    ['avi', 'video/x-msvideo'],\n    ['avif', 'image/avif'],\n    ['aw', 'application/applixware'],\n    ['azf', 'application/vnd.airzip.filesecure.azf'],\n    ['azs', 'application/vnd.airzip.filesecure.azs'],\n    ['azv', 'image/vnd.airzip.accelerator.azv'],\n    ['azw', 'application/vnd.amazon.ebook'],\n    ['b16', 'image/vnd.pco.b16'],\n    ['bat', 'application/x-msdownload'],\n    ['bcpio', 'application/x-bcpio'],\n    ['bdf', 'application/x-font-bdf'],\n    ['bdm', 'application/vnd.syncml.dm+wbxml'],\n    ['bdoc', 'application/x-bdoc'],\n    ['bed', 'application/vnd.realvnc.bed'],\n    ['bh2', 'application/vnd.fujitsu.oasysprs'],\n    ['bin', 'application/octet-stream'],\n    ['blb', 'application/x-blorb'],\n    ['blorb', 'application/x-blorb'],\n    ['bmi', 'application/vnd.bmi'],\n    ['bmml', 'application/vnd.balsamiq.bmml+xml'],\n    ['bmp', 'image/bmp'],\n    ['book', 'application/vnd.framemaker'],\n    ['box', 'application/vnd.previewsystems.box'],\n    ['boz', 'application/x-bzip2'],\n    ['bpk', 'application/octet-stream'],\n    ['bpmn', 'application/octet-stream'],\n    ['bsp', 'model/vnd.valve.source.compiled-map'],\n    ['btif', 'image/prs.btif'],\n    ['buffer', 'application/octet-stream'],\n    ['bz', 'application/x-bzip'],\n    ['bz2', 'application/x-bzip2'],\n    ['c', 'text/x-c'],\n    ['c4d', 'application/vnd.clonk.c4group'],\n    ['c4f', 'application/vnd.clonk.c4group'],\n    ['c4g', 'application/vnd.clonk.c4group'],\n    ['c4p', 'application/vnd.clonk.c4group'],\n    ['c4u', 'application/vnd.clonk.c4group'],\n    ['c11amc', 'application/vnd.cluetrust.cartomobile-config'],\n    ['c11amz', 'application/vnd.cluetrust.cartomobile-config-pkg'],\n    ['cab', 'application/vnd.ms-cab-compressed'],\n    ['caf', 'audio/x-caf'],\n    ['cap', 'application/vnd.tcpdump.pcap'],\n    ['car', 'application/vnd.curl.car'],\n    ['cat', 'application/vnd.ms-pki.seccat'],\n    ['cb7', 'application/x-cbr'],\n    ['cba', 'application/x-cbr'],\n    ['cbr', 'application/x-cbr'],\n    ['cbt', 'application/x-cbr'],\n    ['cbz', 'application/x-cbr'],\n    ['cc', 'text/x-c'],\n    ['cco', 'application/x-cocoa'],\n    ['cct', 'application/x-director'],\n    ['ccxml', 'application/ccxml+xml'],\n    ['cdbcmsg', 'application/vnd.contact.cmsg'],\n    ['cda', 'application/x-cdf'],\n    ['cdf', 'application/x-netcdf'],\n    ['cdfx', 'application/cdfx+xml'],\n    ['cdkey', 'application/vnd.mediastation.cdkey'],\n    ['cdmia', 'application/cdmi-capability'],\n    ['cdmic', 'application/cdmi-container'],\n    ['cdmid', 'application/cdmi-domain'],\n    ['cdmio', 'application/cdmi-object'],\n    ['cdmiq', 'application/cdmi-queue'],\n    ['cdr', 'application/cdr'],\n    ['cdx', 'chemical/x-cdx'],\n    ['cdxml', 'application/vnd.chemdraw+xml'],\n    ['cdy', 'application/vnd.cinderella'],\n    ['cer', 'application/pkix-cert'],\n    ['cfs', 'application/x-cfs-compressed'],\n    ['cgm', 'image/cgm'],\n    ['chat', 'application/x-chat'],\n    ['chm', 'application/vnd.ms-htmlhelp'],\n    ['chrt', 'application/vnd.kde.kchart'],\n    ['cif', 'chemical/x-cif'],\n    ['cii', 'application/vnd.anser-web-certificate-issue-initiation'],\n    ['cil', 'application/vnd.ms-artgalry'],\n    ['cjs', 'application/node'],\n    ['cla', 'application/vnd.claymore'],\n    ['class', 'application/octet-stream'],\n    ['clkk', 'application/vnd.crick.clicker.keyboard'],\n    ['clkp', 'application/vnd.crick.clicker.palette'],\n    ['clkt', 'application/vnd.crick.clicker.template'],\n    ['clkw', 'application/vnd.crick.clicker.wordbank'],\n    ['clkx', 'application/vnd.crick.clicker'],\n    ['clp', 'application/x-msclip'],\n    ['cmc', 'application/vnd.cosmocaller'],\n    ['cmdf', 'chemical/x-cmdf'],\n    ['cml', 'chemical/x-cml'],\n    ['cmp', 'application/vnd.yellowriver-custom-menu'],\n    ['cmx', 'image/x-cmx'],\n    ['cod', 'application/vnd.rim.cod'],\n    ['coffee', 'text/coffeescript'],\n    ['com', 'application/x-msdownload'],\n    ['conf', 'text/plain'],\n    ['cpio', 'application/x-cpio'],\n    ['cpp', 'text/x-c'],\n    ['cpt', 'application/mac-compactpro'],\n    ['crd', 'application/x-mscardfile'],\n    ['crl', 'application/pkix-crl'],\n    ['crt', 'application/x-x509-ca-cert'],\n    ['crx', 'application/x-chrome-extension'],\n    ['cryptonote', 'application/vnd.rig.cryptonote'],\n    ['csh', 'application/x-csh'],\n    ['csl', 'application/vnd.citationstyles.style+xml'],\n    ['csml', 'chemical/x-csml'],\n    ['csp', 'application/vnd.commonspace'],\n    ['csr', 'application/octet-stream'],\n    ['css', 'text/css'],\n    ['cst', 'application/x-director'],\n    ['csv', 'text/csv'],\n    ['cu', 'application/cu-seeme'],\n    ['curl', 'text/vnd.curl'],\n    ['cww', 'application/prs.cww'],\n    ['cxt', 'application/x-director'],\n    ['cxx', 'text/x-c'],\n    ['dae', 'model/vnd.collada+xml'],\n    ['daf', 'application/vnd.mobius.daf'],\n    ['dart', 'application/vnd.dart'],\n    ['dataless', 'application/vnd.fdsn.seed'],\n    ['davmount', 'application/davmount+xml'],\n    ['dbf', 'application/vnd.dbf'],\n    ['dbk', 'application/docbook+xml'],\n    ['dcr', 'application/x-director'],\n    ['dcurl', 'text/vnd.curl.dcurl'],\n    ['dd2', 'application/vnd.oma.dd2+xml'],\n    ['ddd', 'application/vnd.fujixerox.ddd'],\n    ['ddf', 'application/vnd.syncml.dmddf+xml'],\n    ['dds', 'image/vnd.ms-dds'],\n    ['deb', 'application/x-debian-package'],\n    ['def', 'text/plain'],\n    ['deploy', 'application/octet-stream'],\n    ['der', 'application/x-x509-ca-cert'],\n    ['dfac', 'application/vnd.dreamfactory'],\n    ['dgc', 'application/x-dgc-compressed'],\n    ['dic', 'text/x-c'],\n    ['dir', 'application/x-director'],\n    ['dis', 'application/vnd.mobius.dis'],\n    ['disposition-notification', 'message/disposition-notification'],\n    ['dist', 'application/octet-stream'],\n    ['distz', 'application/octet-stream'],\n    ['djv', 'image/vnd.djvu'],\n    ['djvu', 'image/vnd.djvu'],\n    ['dll', 'application/octet-stream'],\n    ['dmg', 'application/x-apple-diskimage'],\n    ['dmn', 'application/octet-stream'],\n    ['dmp', 'application/vnd.tcpdump.pcap'],\n    ['dms', 'application/octet-stream'],\n    ['dna', 'application/vnd.dna'],\n    ['doc', 'application/msword'],\n    ['docm', 'application/vnd.ms-word.template.macroEnabled.12'],\n    ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],\n    ['dot', 'application/msword'],\n    ['dotm', 'application/vnd.ms-word.template.macroEnabled.12'],\n    ['dotx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'],\n    ['dp', 'application/vnd.osgi.dp'],\n    ['dpg', 'application/vnd.dpgraph'],\n    ['dra', 'audio/vnd.dra'],\n    ['drle', 'image/dicom-rle'],\n    ['dsc', 'text/prs.lines.tag'],\n    ['dssc', 'application/dssc+der'],\n    ['dtb', 'application/x-dtbook+xml'],\n    ['dtd', 'application/xml-dtd'],\n    ['dts', 'audio/vnd.dts'],\n    ['dtshd', 'audio/vnd.dts.hd'],\n    ['dump', 'application/octet-stream'],\n    ['dvb', 'video/vnd.dvb.file'],\n    ['dvi', 'application/x-dvi'],\n    ['dwd', 'application/atsc-dwd+xml'],\n    ['dwf', 'model/vnd.dwf'],\n    ['dwg', 'image/vnd.dwg'],\n    ['dxf', 'image/vnd.dxf'],\n    ['dxp', 'application/vnd.spotfire.dxp'],\n    ['dxr', 'application/x-director'],\n    ['ear', 'application/java-archive'],\n    ['ecelp4800', 'audio/vnd.nuera.ecelp4800'],\n    ['ecelp7470', 'audio/vnd.nuera.ecelp7470'],\n    ['ecelp9600', 'audio/vnd.nuera.ecelp9600'],\n    ['ecma', 'application/ecmascript'],\n    ['edm', 'application/vnd.novadigm.edm'],\n    ['edx', 'application/vnd.novadigm.edx'],\n    ['efif', 'application/vnd.picsel'],\n    ['ei6', 'application/vnd.pg.osasli'],\n    ['elc', 'application/octet-stream'],\n    ['emf', 'image/emf'],\n    ['eml', 'message/rfc822'],\n    ['emma', 'application/emma+xml'],\n    ['emotionml', 'application/emotionml+xml'],\n    ['emz', 'application/x-msmetafile'],\n    ['eol', 'audio/vnd.digital-winds'],\n    ['eot', 'application/vnd.ms-fontobject'],\n    ['eps', 'application/postscript'],\n    ['epub', 'application/epub+zip'],\n    ['es', 'application/ecmascript'],\n    ['es3', 'application/vnd.eszigno3+xml'],\n    ['esa', 'application/vnd.osgi.subsystem'],\n    ['esf', 'application/vnd.epson.esf'],\n    ['et3', 'application/vnd.eszigno3+xml'],\n    ['etx', 'text/x-setext'],\n    ['eva', 'application/x-eva'],\n    ['evy', 'application/x-envoy'],\n    ['exe', 'application/octet-stream'],\n    ['exi', 'application/exi'],\n    ['exp', 'application/express'],\n    ['exr', 'image/aces'],\n    ['ext', 'application/vnd.novadigm.ext'],\n    ['ez', 'application/andrew-inset'],\n    ['ez2', 'application/vnd.ezpix-album'],\n    ['ez3', 'application/vnd.ezpix-package'],\n    ['f', 'text/x-fortran'],\n    ['f4v', 'video/mp4'],\n    ['f77', 'text/x-fortran'],\n    ['f90', 'text/x-fortran'],\n    ['fbs', 'image/vnd.fastbidsheet'],\n    ['fcdt', 'application/vnd.adobe.formscentral.fcdt'],\n    ['fcs', 'application/vnd.isac.fcs'],\n    ['fdf', 'application/vnd.fdf'],\n    ['fdt', 'application/fdt+xml'],\n    ['fe_launch', 'application/vnd.denovo.fcselayout-link'],\n    ['fg5', 'application/vnd.fujitsu.oasysgp'],\n    ['fgd', 'application/x-director'],\n    ['fh', 'image/x-freehand'],\n    ['fh4', 'image/x-freehand'],\n    ['fh5', 'image/x-freehand'],\n    ['fh7', 'image/x-freehand'],\n    ['fhc', 'image/x-freehand'],\n    ['fig', 'application/x-xfig'],\n    ['fits', 'image/fits'],\n    ['flac', 'audio/x-flac'],\n    ['fli', 'video/x-fli'],\n    ['flo', 'application/vnd.micrografx.flo'],\n    ['flv', 'video/x-flv'],\n    ['flw', 'application/vnd.kde.kivio'],\n    ['flx', 'text/vnd.fmi.flexstor'],\n    ['fly', 'text/vnd.fly'],\n    ['fm', 'application/vnd.framemaker'],\n    ['fnc', 'application/vnd.frogans.fnc'],\n    ['fo', 'application/vnd.software602.filler.form+xml'],\n    ['for', 'text/x-fortran'],\n    ['fpx', 'image/vnd.fpx'],\n    ['frame', 'application/vnd.framemaker'],\n    ['fsc', 'application/vnd.fsc.weblaunch'],\n    ['fst', 'image/vnd.fst'],\n    ['ftc', 'application/vnd.fluxtime.clip'],\n    ['fti', 'application/vnd.anser-web-funds-transfer-initiation'],\n    ['fvt', 'video/vnd.fvt'],\n    ['fxp', 'application/vnd.adobe.fxp'],\n    ['fxpl', 'application/vnd.adobe.fxp'],\n    ['fzs', 'application/vnd.fuzzysheet'],\n    ['g2w', 'application/vnd.geoplan'],\n    ['g3', 'image/g3fax'],\n    ['g3w', 'application/vnd.geospace'],\n    ['gac', 'application/vnd.groove-account'],\n    ['gam', 'application/x-tads'],\n    ['gbr', 'application/rpki-ghostbusters'],\n    ['gca', 'application/x-gca-compressed'],\n    ['gdl', 'model/vnd.gdl'],\n    ['gdoc', 'application/vnd.google-apps.document'],\n    ['geo', 'application/vnd.dynageo'],\n    ['geojson', 'application/geo+json'],\n    ['gex', 'application/vnd.geometry-explorer'],\n    ['ggb', 'application/vnd.geogebra.file'],\n    ['ggt', 'application/vnd.geogebra.tool'],\n    ['ghf', 'application/vnd.groove-help'],\n    ['gif', 'image/gif'],\n    ['gim', 'application/vnd.groove-identity-message'],\n    ['glb', 'model/gltf-binary'],\n    ['gltf', 'model/gltf+json'],\n    ['gml', 'application/gml+xml'],\n    ['gmx', 'application/vnd.gmx'],\n    ['gnumeric', 'application/x-gnumeric'],\n    ['gpg', 'application/gpg-keys'],\n    ['gph', 'application/vnd.flographit'],\n    ['gpx', 'application/gpx+xml'],\n    ['gqf', 'application/vnd.grafeq'],\n    ['gqs', 'application/vnd.grafeq'],\n    ['gram', 'application/srgs'],\n    ['gramps', 'application/x-gramps-xml'],\n    ['gre', 'application/vnd.geometry-explorer'],\n    ['grv', 'application/vnd.groove-injector'],\n    ['grxml', 'application/srgs+xml'],\n    ['gsf', 'application/x-font-ghostscript'],\n    ['gsheet', 'application/vnd.google-apps.spreadsheet'],\n    ['gslides', 'application/vnd.google-apps.presentation'],\n    ['gtar', 'application/x-gtar'],\n    ['gtm', 'application/vnd.groove-tool-message'],\n    ['gtw', 'model/vnd.gtw'],\n    ['gv', 'text/vnd.graphviz'],\n    ['gxf', 'application/gxf'],\n    ['gxt', 'application/vnd.geonext'],\n    ['gz', 'application/gzip'],\n    ['gzip', 'application/gzip'],\n    ['h', 'text/x-c'],\n    ['h261', 'video/h261'],\n    ['h263', 'video/h263'],\n    ['h264', 'video/h264'],\n    ['hal', 'application/vnd.hal+xml'],\n    ['hbci', 'application/vnd.hbci'],\n    ['hbs', 'text/x-handlebars-template'],\n    ['hdd', 'application/x-virtualbox-hdd'],\n    ['hdf', 'application/x-hdf'],\n    ['heic', 'image/heic'],\n    ['heics', 'image/heic-sequence'],\n    ['heif', 'image/heif'],\n    ['heifs', 'image/heif-sequence'],\n    ['hej2', 'image/hej2k'],\n    ['held', 'application/atsc-held+xml'],\n    ['hh', 'text/x-c'],\n    ['hjson', 'application/hjson'],\n    ['hlp', 'application/winhlp'],\n    ['hpgl', 'application/vnd.hp-hpgl'],\n    ['hpid', 'application/vnd.hp-hpid'],\n    ['hps', 'application/vnd.hp-hps'],\n    ['hqx', 'application/mac-binhex40'],\n    ['hsj2', 'image/hsj2'],\n    ['htc', 'text/x-component'],\n    ['htke', 'application/vnd.kenameaapp'],\n    ['htm', 'text/html'],\n    ['html', 'text/html'],\n    ['hvd', 'application/vnd.yamaha.hv-dic'],\n    ['hvp', 'application/vnd.yamaha.hv-voice'],\n    ['hvs', 'application/vnd.yamaha.hv-script'],\n    ['i2g', 'application/vnd.intergeo'],\n    ['icc', 'application/vnd.iccprofile'],\n    ['ice', 'x-conference/x-cooltalk'],\n    ['icm', 'application/vnd.iccprofile'],\n    ['ico', 'image/x-icon'],\n    ['ics', 'text/calendar'],\n    ['ief', 'image/ief'],\n    ['ifb', 'text/calendar'],\n    ['ifm', 'application/vnd.shana.informed.formdata'],\n    ['iges', 'model/iges'],\n    ['igl', 'application/vnd.igloader'],\n    ['igm', 'application/vnd.insors.igm'],\n    ['igs', 'model/iges'],\n    ['igx', 'application/vnd.micrografx.igx'],\n    ['iif', 'application/vnd.shana.informed.interchange'],\n    ['img', 'application/octet-stream'],\n    ['imp', 'application/vnd.accpac.simply.imp'],\n    ['ims', 'application/vnd.ms-ims'],\n    ['in', 'text/plain'],\n    ['ini', 'text/plain'],\n    ['ink', 'application/inkml+xml'],\n    ['inkml', 'application/inkml+xml'],\n    ['install', 'application/x-install-instructions'],\n    ['iota', 'application/vnd.astraea-software.iota'],\n    ['ipfix', 'application/ipfix'],\n    ['ipk', 'application/vnd.shana.informed.package'],\n    ['irm', 'application/vnd.ibm.rights-management'],\n    ['irp', 'application/vnd.irepository.package+xml'],\n    ['iso', 'application/x-iso9660-image'],\n    ['itp', 'application/vnd.shana.informed.formtemplate'],\n    ['its', 'application/its+xml'],\n    ['ivp', 'application/vnd.immervision-ivp'],\n    ['ivu', 'application/vnd.immervision-ivu'],\n    ['jad', 'text/vnd.sun.j2me.app-descriptor'],\n    ['jade', 'text/jade'],\n    ['jam', 'application/vnd.jam'],\n    ['jar', 'application/java-archive'],\n    ['jardiff', 'application/x-java-archive-diff'],\n    ['java', 'text/x-java-source'],\n    ['jhc', 'image/jphc'],\n    ['jisp', 'application/vnd.jisp'],\n    ['jls', 'image/jls'],\n    ['jlt', 'application/vnd.hp-jlyt'],\n    ['jng', 'image/x-jng'],\n    ['jnlp', 'application/x-java-jnlp-file'],\n    ['joda', 'application/vnd.joost.joda-archive'],\n    ['jp2', 'image/jp2'],\n    ['jpe', 'image/jpeg'],\n    ['jpeg', 'image/jpeg'],\n    ['jpf', 'image/jpx'],\n    ['jpg', 'image/jpeg'],\n    ['jpg2', 'image/jp2'],\n    ['jpgm', 'video/jpm'],\n    ['jpgv', 'video/jpeg'],\n    ['jph', 'image/jph'],\n    ['jpm', 'video/jpm'],\n    ['jpx', 'image/jpx'],\n    ['js', 'application/javascript'],\n    ['json', 'application/json'],\n    ['json5', 'application/json5'],\n    ['jsonld', 'application/ld+json'],\n    // https://jsonlines.org/\n    ['jsonl', 'application/jsonl'],\n    ['jsonml', 'application/jsonml+json'],\n    ['jsx', 'text/jsx'],\n    ['jxr', 'image/jxr'],\n    ['jxra', 'image/jxra'],\n    ['jxrs', 'image/jxrs'],\n    ['jxs', 'image/jxs'],\n    ['jxsc', 'image/jxsc'],\n    ['jxsi', 'image/jxsi'],\n    ['jxss', 'image/jxss'],\n    ['kar', 'audio/midi'],\n    ['karbon', 'application/vnd.kde.karbon'],\n    ['kdb', 'application/octet-stream'],\n    ['kdbx', 'application/x-keepass2'],\n    ['key', 'application/x-iwork-keynote-sffkey'],\n    ['kfo', 'application/vnd.kde.kformula'],\n    ['kia', 'application/vnd.kidspiration'],\n    ['kml', 'application/vnd.google-earth.kml+xml'],\n    ['kmz', 'application/vnd.google-earth.kmz'],\n    ['kne', 'application/vnd.kinar'],\n    ['knp', 'application/vnd.kinar'],\n    ['kon', 'application/vnd.kde.kontour'],\n    ['kpr', 'application/vnd.kde.kpresenter'],\n    ['kpt', 'application/vnd.kde.kpresenter'],\n    ['kpxx', 'application/vnd.ds-keypoint'],\n    ['ksp', 'application/vnd.kde.kspread'],\n    ['ktr', 'application/vnd.kahootz'],\n    ['ktx', 'image/ktx'],\n    ['ktx2', 'image/ktx2'],\n    ['ktz', 'application/vnd.kahootz'],\n    ['kwd', 'application/vnd.kde.kword'],\n    ['kwt', 'application/vnd.kde.kword'],\n    ['lasxml', 'application/vnd.las.las+xml'],\n    ['latex', 'application/x-latex'],\n    ['lbd', 'application/vnd.llamagraphics.life-balance.desktop'],\n    ['lbe', 'application/vnd.llamagraphics.life-balance.exchange+xml'],\n    ['les', 'application/vnd.hhe.lesson-player'],\n    ['less', 'text/less'],\n    ['lgr', 'application/lgr+xml'],\n    ['lha', 'application/octet-stream'],\n    ['link66', 'application/vnd.route66.link66+xml'],\n    ['list', 'text/plain'],\n    ['list3820', 'application/vnd.ibm.modcap'],\n    ['listafp', 'application/vnd.ibm.modcap'],\n    ['litcoffee', 'text/coffeescript'],\n    ['lnk', 'application/x-ms-shortcut'],\n    ['log', 'text/plain'],\n    ['lostxml', 'application/lost+xml'],\n    ['lrf', 'application/octet-stream'],\n    ['lrm', 'application/vnd.ms-lrm'],\n    ['ltf', 'application/vnd.frogans.ltf'],\n    ['lua', 'text/x-lua'],\n    ['luac', 'application/x-lua-bytecode'],\n    ['lvp', 'audio/vnd.lucent.voice'],\n    ['lwp', 'application/vnd.lotus-wordpro'],\n    ['lzh', 'application/octet-stream'],\n    ['m1v', 'video/mpeg'],\n    ['m2a', 'audio/mpeg'],\n    ['m2v', 'video/mpeg'],\n    ['m3a', 'audio/mpeg'],\n    ['m3u', 'text/plain'],\n    ['m3u8', 'application/vnd.apple.mpegurl'],\n    ['m4a', 'audio/x-m4a'],\n    ['m4p', 'application/mp4'],\n    ['m4s', 'video/iso.segment'],\n    ['m4u', 'application/vnd.mpegurl'],\n    ['m4v', 'video/x-m4v'],\n    ['m13', 'application/x-msmediaview'],\n    ['m14', 'application/x-msmediaview'],\n    ['m21', 'application/mp21'],\n    ['ma', 'application/mathematica'],\n    ['mads', 'application/mads+xml'],\n    ['maei', 'application/mmt-aei+xml'],\n    ['mag', 'application/vnd.ecowin.chart'],\n    ['maker', 'application/vnd.framemaker'],\n    ['man', 'text/troff'],\n    ['manifest', 'text/cache-manifest'],\n    ['map', 'application/json'],\n    ['mar', 'application/octet-stream'],\n    ['markdown', 'text/markdown'],\n    ['mathml', 'application/mathml+xml'],\n    ['mb', 'application/mathematica'],\n    ['mbk', 'application/vnd.mobius.mbk'],\n    ['mbox', 'application/mbox'],\n    ['mc1', 'application/vnd.medcalcdata'],\n    ['mcd', 'application/vnd.mcd'],\n    ['mcurl', 'text/vnd.curl.mcurl'],\n    ['md', 'text/markdown'],\n    ['mdb', 'application/x-msaccess'],\n    ['mdi', 'image/vnd.ms-modi'],\n    ['mdx', 'text/mdx'],\n    ['me', 'text/troff'],\n    ['mesh', 'model/mesh'],\n    ['meta4', 'application/metalink4+xml'],\n    ['metalink', 'application/metalink+xml'],\n    ['mets', 'application/mets+xml'],\n    ['mfm', 'application/vnd.mfmp'],\n    ['mft', 'application/rpki-manifest'],\n    ['mgp', 'application/vnd.osgeo.mapguide.package'],\n    ['mgz', 'application/vnd.proteus.magazine'],\n    ['mid', 'audio/midi'],\n    ['midi', 'audio/midi'],\n    ['mie', 'application/x-mie'],\n    ['mif', 'application/vnd.mif'],\n    ['mime', 'message/rfc822'],\n    ['mj2', 'video/mj2'],\n    ['mjp2', 'video/mj2'],\n    ['mjs', 'application/javascript'],\n    ['mk3d', 'video/x-matroska'],\n    ['mka', 'audio/x-matroska'],\n    ['mkd', 'text/x-markdown'],\n    ['mks', 'video/x-matroska'],\n    ['mkv', 'video/x-matroska'],\n    ['mlp', 'application/vnd.dolby.mlp'],\n    ['mmd', 'application/vnd.chipnuts.karaoke-mmd'],\n    ['mmf', 'application/vnd.smaf'],\n    ['mml', 'text/mathml'],\n    ['mmr', 'image/vnd.fujixerox.edmics-mmr'],\n    ['mng', 'video/x-mng'],\n    ['mny', 'application/x-msmoney'],\n    ['mobi', 'application/x-mobipocket-ebook'],\n    ['mods', 'application/mods+xml'],\n    ['mov', 'video/quicktime'],\n    ['movie', 'video/x-sgi-movie'],\n    ['mp2', 'audio/mpeg'],\n    ['mp2a', 'audio/mpeg'],\n    ['mp3', 'audio/mpeg'],\n    ['mp4', 'video/mp4'],\n    ['mp4a', 'audio/mp4'],\n    ['mp4s', 'application/mp4'],\n    ['mp4v', 'video/mp4'],\n    ['mp21', 'application/mp21'],\n    ['mpc', 'application/vnd.mophun.certificate'],\n    ['mpd', 'application/dash+xml'],\n    ['mpe', 'video/mpeg'],\n    ['mpeg', 'video/mpeg'],\n    ['mpg', 'video/mpeg'],\n    ['mpg4', 'video/mp4'],\n    ['mpga', 'audio/mpeg'],\n    ['mpkg', 'application/vnd.apple.installer+xml'],\n    ['mpm', 'application/vnd.blueice.multipass'],\n    ['mpn', 'application/vnd.mophun.application'],\n    ['mpp', 'application/vnd.ms-project'],\n    ['mpt', 'application/vnd.ms-project'],\n    ['mpy', 'application/vnd.ibm.minipay'],\n    ['mqy', 'application/vnd.mobius.mqy'],\n    ['mrc', 'application/marc'],\n    ['mrcx', 'application/marcxml+xml'],\n    ['ms', 'text/troff'],\n    ['mscml', 'application/mediaservercontrol+xml'],\n    ['mseed', 'application/vnd.fdsn.mseed'],\n    ['mseq', 'application/vnd.mseq'],\n    ['msf', 'application/vnd.epson.msf'],\n    ['msg', 'application/vnd.ms-outlook'],\n    ['msh', 'model/mesh'],\n    ['msi', 'application/x-msdownload'],\n    ['msl', 'application/vnd.mobius.msl'],\n    ['msm', 'application/octet-stream'],\n    ['msp', 'application/octet-stream'],\n    ['msty', 'application/vnd.muvee.style'],\n    ['mtl', 'model/mtl'],\n    ['mts', 'model/vnd.mts'],\n    ['mus', 'application/vnd.musician'],\n    ['musd', 'application/mmt-usd+xml'],\n    ['musicxml', 'application/vnd.recordare.musicxml+xml'],\n    ['mvb', 'application/x-msmediaview'],\n    ['mvt', 'application/vnd.mapbox-vector-tile'],\n    ['mwf', 'application/vnd.mfer'],\n    ['mxf', 'application/mxf'],\n    ['mxl', 'application/vnd.recordare.musicxml'],\n    ['mxmf', 'audio/mobile-xmf'],\n    ['mxml', 'application/xv+xml'],\n    ['mxs', 'application/vnd.triscape.mxs'],\n    ['mxu', 'video/vnd.mpegurl'],\n    ['n-gage', 'application/vnd.nokia.n-gage.symbian.install'],\n    ['n3', 'text/n3'],\n    ['nb', 'application/mathematica'],\n    ['nbp', 'application/vnd.wolfram.player'],\n    ['nc', 'application/x-netcdf'],\n    ['ncx', 'application/x-dtbncx+xml'],\n    ['nfo', 'text/x-nfo'],\n    ['ngdat', 'application/vnd.nokia.n-gage.data'],\n    ['nitf', 'application/vnd.nitf'],\n    ['nlu', 'application/vnd.neurolanguage.nlu'],\n    ['nml', 'application/vnd.enliven'],\n    ['nnd', 'application/vnd.noblenet-directory'],\n    ['nns', 'application/vnd.noblenet-sealer'],\n    ['nnw', 'application/vnd.noblenet-web'],\n    ['npx', 'image/vnd.net-fpx'],\n    ['nq', 'application/n-quads'],\n    ['nsc', 'application/x-conference'],\n    ['nsf', 'application/vnd.lotus-notes'],\n    ['nt', 'application/n-triples'],\n    ['ntf', 'application/vnd.nitf'],\n    ['numbers', 'application/x-iwork-numbers-sffnumbers'],\n    ['nzb', 'application/x-nzb'],\n    ['oa2', 'application/vnd.fujitsu.oasys2'],\n    ['oa3', 'application/vnd.fujitsu.oasys3'],\n    ['oas', 'application/vnd.fujitsu.oasys'],\n    ['obd', 'application/x-msbinder'],\n    ['obgx', 'application/vnd.openblox.game+xml'],\n    ['obj', 'model/obj'],\n    ['oda', 'application/oda'],\n    ['odb', 'application/vnd.oasis.opendocument.database'],\n    ['odc', 'application/vnd.oasis.opendocument.chart'],\n    ['odf', 'application/vnd.oasis.opendocument.formula'],\n    ['odft', 'application/vnd.oasis.opendocument.formula-template'],\n    ['odg', 'application/vnd.oasis.opendocument.graphics'],\n    ['odi', 'application/vnd.oasis.opendocument.image'],\n    ['odm', 'application/vnd.oasis.opendocument.text-master'],\n    ['odp', 'application/vnd.oasis.opendocument.presentation'],\n    ['ods', 'application/vnd.oasis.opendocument.spreadsheet'],\n    ['odt', 'application/vnd.oasis.opendocument.text'],\n    ['oga', 'audio/ogg'],\n    ['ogex', 'model/vnd.opengex'],\n    ['ogg', 'audio/ogg'],\n    ['ogv', 'video/ogg'],\n    ['ogx', 'application/ogg'],\n    ['omdoc', 'application/omdoc+xml'],\n    ['onepkg', 'application/onenote'],\n    ['onetmp', 'application/onenote'],\n    ['onetoc', 'application/onenote'],\n    ['onetoc2', 'application/onenote'],\n    ['opf', 'application/oebps-package+xml'],\n    ['opml', 'text/x-opml'],\n    ['oprc', 'application/vnd.palm'],\n    ['opus', 'audio/ogg'],\n    ['org', 'text/x-org'],\n    ['osf', 'application/vnd.yamaha.openscoreformat'],\n    ['osfpvg', 'application/vnd.yamaha.openscoreformat.osfpvg+xml'],\n    ['osm', 'application/vnd.openstreetmap.data+xml'],\n    ['otc', 'application/vnd.oasis.opendocument.chart-template'],\n    ['otf', 'font/otf'],\n    ['otg', 'application/vnd.oasis.opendocument.graphics-template'],\n    ['oth', 'application/vnd.oasis.opendocument.text-web'],\n    ['oti', 'application/vnd.oasis.opendocument.image-template'],\n    ['otp', 'application/vnd.oasis.opendocument.presentation-template'],\n    ['ots', 'application/vnd.oasis.opendocument.spreadsheet-template'],\n    ['ott', 'application/vnd.oasis.opendocument.text-template'],\n    ['ova', 'application/x-virtualbox-ova'],\n    ['ovf', 'application/x-virtualbox-ovf'],\n    ['owl', 'application/rdf+xml'],\n    ['oxps', 'application/oxps'],\n    ['oxt', 'application/vnd.openofficeorg.extension'],\n    ['p', 'text/x-pascal'],\n    ['p7a', 'application/x-pkcs7-signature'],\n    ['p7b', 'application/x-pkcs7-certificates'],\n    ['p7c', 'application/pkcs7-mime'],\n    ['p7m', 'application/pkcs7-mime'],\n    ['p7r', 'application/x-pkcs7-certreqresp'],\n    ['p7s', 'application/pkcs7-signature'],\n    ['p8', 'application/pkcs8'],\n    ['p10', 'application/x-pkcs10'],\n    ['p12', 'application/x-pkcs12'],\n    ['pac', 'application/x-ns-proxy-autoconfig'],\n    ['pages', 'application/x-iwork-pages-sffpages'],\n    ['pas', 'text/x-pascal'],\n    ['paw', 'application/vnd.pawaafile'],\n    ['pbd', 'application/vnd.powerbuilder6'],\n    ['pbm', 'image/x-portable-bitmap'],\n    ['pcap', 'application/vnd.tcpdump.pcap'],\n    ['pcf', 'application/x-font-pcf'],\n    ['pcl', 'application/vnd.hp-pcl'],\n    ['pclxl', 'application/vnd.hp-pclxl'],\n    ['pct', 'image/x-pict'],\n    ['pcurl', 'application/vnd.curl.pcurl'],\n    ['pcx', 'image/x-pcx'],\n    ['pdb', 'application/x-pilot'],\n    ['pde', 'text/x-processing'],\n    ['pdf', 'application/pdf'],\n    ['pem', 'application/x-x509-user-cert'],\n    ['pfa', 'application/x-font-type1'],\n    ['pfb', 'application/x-font-type1'],\n    ['pfm', 'application/x-font-type1'],\n    ['pfr', 'application/font-tdpfr'],\n    ['pfx', 'application/x-pkcs12'],\n    ['pgm', 'image/x-portable-graymap'],\n    ['pgn', 'application/x-chess-pgn'],\n    ['pgp', 'application/pgp'],\n    ['php', 'application/x-httpd-php'],\n    ['php3', 'application/x-httpd-php'],\n    ['php4', 'application/x-httpd-php'],\n    ['phps', 'application/x-httpd-php-source'],\n    ['phtml', 'application/x-httpd-php'],\n    ['pic', 'image/x-pict'],\n    ['pkg', 'application/octet-stream'],\n    ['pki', 'application/pkixcmp'],\n    ['pkipath', 'application/pkix-pkipath'],\n    ['pkpass', 'application/vnd.apple.pkpass'],\n    ['pl', 'application/x-perl'],\n    ['plb', 'application/vnd.3gpp.pic-bw-large'],\n    ['plc', 'application/vnd.mobius.plc'],\n    ['plf', 'application/vnd.pocketlearn'],\n    ['pls', 'application/pls+xml'],\n    ['pm', 'application/x-perl'],\n    ['pml', 'application/vnd.ctc-posml'],\n    ['png', 'image/png'],\n    ['pnm', 'image/x-portable-anymap'],\n    ['portpkg', 'application/vnd.macports.portpkg'],\n    ['pot', 'application/vnd.ms-powerpoint'],\n    ['potm', 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'],\n    ['potx', 'application/vnd.openxmlformats-officedocument.presentationml.template'],\n    ['ppa', 'application/vnd.ms-powerpoint'],\n    ['ppam', 'application/vnd.ms-powerpoint.addin.macroEnabled.12'],\n    ['ppd', 'application/vnd.cups-ppd'],\n    ['ppm', 'image/x-portable-pixmap'],\n    ['pps', 'application/vnd.ms-powerpoint'],\n    ['ppsm', 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'],\n    ['ppsx', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'],\n    ['ppt', 'application/powerpoint'],\n    ['pptm', 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'],\n    ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],\n    ['pqa', 'application/vnd.palm'],\n    ['prc', 'application/x-pilot'],\n    ['pre', 'application/vnd.lotus-freelance'],\n    ['prf', 'application/pics-rules'],\n    ['provx', 'application/provenance+xml'],\n    ['ps', 'application/postscript'],\n    ['psb', 'application/vnd.3gpp.pic-bw-small'],\n    ['psd', 'application/x-photoshop'],\n    ['psf', 'application/x-font-linux-psf'],\n    ['pskcxml', 'application/pskc+xml'],\n    ['pti', 'image/prs.pti'],\n    ['ptid', 'application/vnd.pvi.ptid1'],\n    ['pub', 'application/x-mspublisher'],\n    ['pvb', 'application/vnd.3gpp.pic-bw-var'],\n    ['pwn', 'application/vnd.3m.post-it-notes'],\n    ['pya', 'audio/vnd.ms-playready.media.pya'],\n    ['pyv', 'video/vnd.ms-playready.media.pyv'],\n    ['qam', 'application/vnd.epson.quickanime'],\n    ['qbo', 'application/vnd.intu.qbo'],\n    ['qfx', 'application/vnd.intu.qfx'],\n    ['qps', 'application/vnd.publishare-delta-tree'],\n    ['qt', 'video/quicktime'],\n    ['qwd', 'application/vnd.quark.quarkxpress'],\n    ['qwt', 'application/vnd.quark.quarkxpress'],\n    ['qxb', 'application/vnd.quark.quarkxpress'],\n    ['qxd', 'application/vnd.quark.quarkxpress'],\n    ['qxl', 'application/vnd.quark.quarkxpress'],\n    ['qxt', 'application/vnd.quark.quarkxpress'],\n    ['ra', 'audio/x-realaudio'],\n    ['ram', 'audio/x-pn-realaudio'],\n    ['raml', 'application/raml+yaml'],\n    ['rapd', 'application/route-apd+xml'],\n    ['rar', 'application/x-rar'],\n    ['ras', 'image/x-cmu-raster'],\n    ['rcprofile', 'application/vnd.ipunplugged.rcprofile'],\n    ['rdf', 'application/rdf+xml'],\n    ['rdz', 'application/vnd.data-vision.rdz'],\n    ['relo', 'application/p2p-overlay+xml'],\n    ['rep', 'application/vnd.businessobjects'],\n    ['res', 'application/x-dtbresource+xml'],\n    ['rgb', 'image/x-rgb'],\n    ['rif', 'application/reginfo+xml'],\n    ['rip', 'audio/vnd.rip'],\n    ['ris', 'application/x-research-info-systems'],\n    ['rl', 'application/resource-lists+xml'],\n    ['rlc', 'image/vnd.fujixerox.edmics-rlc'],\n    ['rld', 'application/resource-lists-diff+xml'],\n    ['rm', 'audio/x-pn-realaudio'],\n    ['rmi', 'audio/midi'],\n    ['rmp', 'audio/x-pn-realaudio-plugin'],\n    ['rms', 'application/vnd.jcp.javame.midlet-rms'],\n    ['rmvb', 'application/vnd.rn-realmedia-vbr'],\n    ['rnc', 'application/relax-ng-compact-syntax'],\n    ['rng', 'application/xml'],\n    ['roa', 'application/rpki-roa'],\n    ['roff', 'text/troff'],\n    ['rp9', 'application/vnd.cloanto.rp9'],\n    ['rpm', 'audio/x-pn-realaudio-plugin'],\n    ['rpss', 'application/vnd.nokia.radio-presets'],\n    ['rpst', 'application/vnd.nokia.radio-preset'],\n    ['rq', 'application/sparql-query'],\n    ['rs', 'application/rls-services+xml'],\n    ['rsa', 'application/x-pkcs7'],\n    ['rsat', 'application/atsc-rsat+xml'],\n    ['rsd', 'application/rsd+xml'],\n    ['rsheet', 'application/urc-ressheet+xml'],\n    ['rss', 'application/rss+xml'],\n    ['rtf', 'text/rtf'],\n    ['rtx', 'text/richtext'],\n    ['run', 'application/x-makeself'],\n    ['rusd', 'application/route-usd+xml'],\n    ['rv', 'video/vnd.rn-realvideo'],\n    ['s', 'text/x-asm'],\n    ['s3m', 'audio/s3m'],\n    ['saf', 'application/vnd.yamaha.smaf-audio'],\n    ['sass', 'text/x-sass'],\n    ['sbml', 'application/sbml+xml'],\n    ['sc', 'application/vnd.ibm.secure-container'],\n    ['scd', 'application/x-msschedule'],\n    ['scm', 'application/vnd.lotus-screencam'],\n    ['scq', 'application/scvp-cv-request'],\n    ['scs', 'application/scvp-cv-response'],\n    ['scss', 'text/x-scss'],\n    ['scurl', 'text/vnd.curl.scurl'],\n    ['sda', 'application/vnd.stardivision.draw'],\n    ['sdc', 'application/vnd.stardivision.calc'],\n    ['sdd', 'application/vnd.stardivision.impress'],\n    ['sdkd', 'application/vnd.solent.sdkm+xml'],\n    ['sdkm', 'application/vnd.solent.sdkm+xml'],\n    ['sdp', 'application/sdp'],\n    ['sdw', 'application/vnd.stardivision.writer'],\n    ['sea', 'application/octet-stream'],\n    ['see', 'application/vnd.seemail'],\n    ['seed', 'application/vnd.fdsn.seed'],\n    ['sema', 'application/vnd.sema'],\n    ['semd', 'application/vnd.semd'],\n    ['semf', 'application/vnd.semf'],\n    ['senmlx', 'application/senml+xml'],\n    ['sensmlx', 'application/sensml+xml'],\n    ['ser', 'application/java-serialized-object'],\n    ['setpay', 'application/set-payment-initiation'],\n    ['setreg', 'application/set-registration-initiation'],\n    ['sfd-hdstx', 'application/vnd.hydrostatix.sof-data'],\n    ['sfs', 'application/vnd.spotfire.sfs'],\n    ['sfv', 'text/x-sfv'],\n    ['sgi', 'image/sgi'],\n    ['sgl', 'application/vnd.stardivision.writer-global'],\n    ['sgm', 'text/sgml'],\n    ['sgml', 'text/sgml'],\n    ['sh', 'application/x-sh'],\n    ['shar', 'application/x-shar'],\n    ['shex', 'text/shex'],\n    ['shf', 'application/shf+xml'],\n    ['shtml', 'text/html'],\n    ['sid', 'image/x-mrsid-image'],\n    ['sieve', 'application/sieve'],\n    ['sig', 'application/pgp-signature'],\n    ['sil', 'audio/silk'],\n    ['silo', 'model/mesh'],\n    ['sis', 'application/vnd.symbian.install'],\n    ['sisx', 'application/vnd.symbian.install'],\n    ['sit', 'application/x-stuffit'],\n    ['sitx', 'application/x-stuffitx'],\n    ['siv', 'application/sieve'],\n    ['skd', 'application/vnd.koan'],\n    ['skm', 'application/vnd.koan'],\n    ['skp', 'application/vnd.koan'],\n    ['skt', 'application/vnd.koan'],\n    ['sldm', 'application/vnd.ms-powerpoint.slide.macroenabled.12'],\n    ['sldx', 'application/vnd.openxmlformats-officedocument.presentationml.slide'],\n    ['slim', 'text/slim'],\n    ['slm', 'text/slim'],\n    ['sls', 'application/route-s-tsid+xml'],\n    ['slt', 'application/vnd.epson.salt'],\n    ['sm', 'application/vnd.stepmania.stepchart'],\n    ['smf', 'application/vnd.stardivision.math'],\n    ['smi', 'application/smil'],\n    ['smil', 'application/smil'],\n    ['smv', 'video/x-smv'],\n    ['smzip', 'application/vnd.stepmania.package'],\n    ['snd', 'audio/basic'],\n    ['snf', 'application/x-font-snf'],\n    ['so', 'application/octet-stream'],\n    ['spc', 'application/x-pkcs7-certificates'],\n    ['spdx', 'text/spdx'],\n    ['spf', 'application/vnd.yamaha.smaf-phrase'],\n    ['spl', 'application/x-futuresplash'],\n    ['spot', 'text/vnd.in3d.spot'],\n    ['spp', 'application/scvp-vp-response'],\n    ['spq', 'application/scvp-vp-request'],\n    ['spx', 'audio/ogg'],\n    ['sql', 'application/x-sql'],\n    ['src', 'application/x-wais-source'],\n    ['srt', 'application/x-subrip'],\n    ['sru', 'application/sru+xml'],\n    ['srx', 'application/sparql-results+xml'],\n    ['ssdl', 'application/ssdl+xml'],\n    ['sse', 'application/vnd.kodak-descriptor'],\n    ['ssf', 'application/vnd.epson.ssf'],\n    ['ssml', 'application/ssml+xml'],\n    ['sst', 'application/octet-stream'],\n    ['st', 'application/vnd.sailingtracker.track'],\n    ['stc', 'application/vnd.sun.xml.calc.template'],\n    ['std', 'application/vnd.sun.xml.draw.template'],\n    ['stf', 'application/vnd.wt.stf'],\n    ['sti', 'application/vnd.sun.xml.impress.template'],\n    ['stk', 'application/hyperstudio'],\n    ['stl', 'model/stl'],\n    ['stpx', 'model/step+xml'],\n    ['stpxz', 'model/step-xml+zip'],\n    ['stpz', 'model/step+zip'],\n    ['str', 'application/vnd.pg.format'],\n    ['stw', 'application/vnd.sun.xml.writer.template'],\n    ['styl', 'text/stylus'],\n    ['stylus', 'text/stylus'],\n    ['sub', 'text/vnd.dvb.subtitle'],\n    ['sus', 'application/vnd.sus-calendar'],\n    ['susp', 'application/vnd.sus-calendar'],\n    ['sv4cpio', 'application/x-sv4cpio'],\n    ['sv4crc', 'application/x-sv4crc'],\n    ['svc', 'application/vnd.dvb.service'],\n    ['svd', 'application/vnd.svd'],\n    ['svg', 'image/svg+xml'],\n    ['svgz', 'image/svg+xml'],\n    ['swa', 'application/x-director'],\n    ['swf', 'application/x-shockwave-flash'],\n    ['swi', 'application/vnd.aristanetworks.swi'],\n    ['swidtag', 'application/swid+xml'],\n    ['sxc', 'application/vnd.sun.xml.calc'],\n    ['sxd', 'application/vnd.sun.xml.draw'],\n    ['sxg', 'application/vnd.sun.xml.writer.global'],\n    ['sxi', 'application/vnd.sun.xml.impress'],\n    ['sxm', 'application/vnd.sun.xml.math'],\n    ['sxw', 'application/vnd.sun.xml.writer'],\n    ['t', 'text/troff'],\n    ['t3', 'application/x-t3vm-image'],\n    ['t38', 'image/t38'],\n    ['taglet', 'application/vnd.mynfc'],\n    ['tao', 'application/vnd.tao.intent-module-archive'],\n    ['tap', 'image/vnd.tencent.tap'],\n    ['tar', 'application/x-tar'],\n    ['tcap', 'application/vnd.3gpp2.tcap'],\n    ['tcl', 'application/x-tcl'],\n    ['td', 'application/urc-targetdesc+xml'],\n    ['teacher', 'application/vnd.smart.teacher'],\n    ['tei', 'application/tei+xml'],\n    ['teicorpus', 'application/tei+xml'],\n    ['tex', 'application/x-tex'],\n    ['texi', 'application/x-texinfo'],\n    ['texinfo', 'application/x-texinfo'],\n    ['text', 'text/plain'],\n    ['tfi', 'application/thraud+xml'],\n    ['tfm', 'application/x-tex-tfm'],\n    ['tfx', 'image/tiff-fx'],\n    ['tga', 'image/x-tga'],\n    ['tgz', 'application/x-tar'],\n    ['thmx', 'application/vnd.ms-officetheme'],\n    ['tif', 'image/tiff'],\n    ['tiff', 'image/tiff'],\n    ['tk', 'application/x-tcl'],\n    ['tmo', 'application/vnd.tmobile-livetv'],\n    ['toml', 'application/toml'],\n    ['torrent', 'application/x-bittorrent'],\n    ['tpl', 'application/vnd.groove-tool-template'],\n    ['tpt', 'application/vnd.trid.tpt'],\n    ['tr', 'text/troff'],\n    ['tra', 'application/vnd.trueapp'],\n    ['trig', 'application/trig'],\n    ['trm', 'application/x-msterminal'],\n    ['ts', 'video/mp2t'],\n    ['tsd', 'application/timestamped-data'],\n    ['tsv', 'text/tab-separated-values'],\n    ['ttc', 'font/collection'],\n    ['ttf', 'font/ttf'],\n    ['ttl', 'text/turtle'],\n    ['ttml', 'application/ttml+xml'],\n    ['twd', 'application/vnd.simtech-mindmapper'],\n    ['twds', 'application/vnd.simtech-mindmapper'],\n    ['txd', 'application/vnd.genomatix.tuxedo'],\n    ['txf', 'application/vnd.mobius.txf'],\n    ['txt', 'text/plain'],\n    ['u8dsn', 'message/global-delivery-status'],\n    ['u8hdr', 'message/global-headers'],\n    ['u8mdn', 'message/global-disposition-notification'],\n    ['u8msg', 'message/global'],\n    ['u32', 'application/x-authorware-bin'],\n    ['ubj', 'application/ubjson'],\n    ['udeb', 'application/x-debian-package'],\n    ['ufd', 'application/vnd.ufdl'],\n    ['ufdl', 'application/vnd.ufdl'],\n    ['ulx', 'application/x-glulx'],\n    ['umj', 'application/vnd.umajin'],\n    ['unityweb', 'application/vnd.unity'],\n    ['uoml', 'application/vnd.uoml+xml'],\n    ['uri', 'text/uri-list'],\n    ['uris', 'text/uri-list'],\n    ['urls', 'text/uri-list'],\n    ['usdz', 'model/vnd.usdz+zip'],\n    ['ustar', 'application/x-ustar'],\n    ['utz', 'application/vnd.uiq.theme'],\n    ['uu', 'text/x-uuencode'],\n    ['uva', 'audio/vnd.dece.audio'],\n    ['uvd', 'application/vnd.dece.data'],\n    ['uvf', 'application/vnd.dece.data'],\n    ['uvg', 'image/vnd.dece.graphic'],\n    ['uvh', 'video/vnd.dece.hd'],\n    ['uvi', 'image/vnd.dece.graphic'],\n    ['uvm', 'video/vnd.dece.mobile'],\n    ['uvp', 'video/vnd.dece.pd'],\n    ['uvs', 'video/vnd.dece.sd'],\n    ['uvt', 'application/vnd.dece.ttml+xml'],\n    ['uvu', 'video/vnd.uvvu.mp4'],\n    ['uvv', 'video/vnd.dece.video'],\n    ['uvva', 'audio/vnd.dece.audio'],\n    ['uvvd', 'application/vnd.dece.data'],\n    ['uvvf', 'application/vnd.dece.data'],\n    ['uvvg', 'image/vnd.dece.graphic'],\n    ['uvvh', 'video/vnd.dece.hd'],\n    ['uvvi', 'image/vnd.dece.graphic'],\n    ['uvvm', 'video/vnd.dece.mobile'],\n    ['uvvp', 'video/vnd.dece.pd'],\n    ['uvvs', 'video/vnd.dece.sd'],\n    ['uvvt', 'application/vnd.dece.ttml+xml'],\n    ['uvvu', 'video/vnd.uvvu.mp4'],\n    ['uvvv', 'video/vnd.dece.video'],\n    ['uvvx', 'application/vnd.dece.unspecified'],\n    ['uvvz', 'application/vnd.dece.zip'],\n    ['uvx', 'application/vnd.dece.unspecified'],\n    ['uvz', 'application/vnd.dece.zip'],\n    ['vbox', 'application/x-virtualbox-vbox'],\n    ['vbox-extpack', 'application/x-virtualbox-vbox-extpack'],\n    ['vcard', 'text/vcard'],\n    ['vcd', 'application/x-cdlink'],\n    ['vcf', 'text/x-vcard'],\n    ['vcg', 'application/vnd.groove-vcard'],\n    ['vcs', 'text/x-vcalendar'],\n    ['vcx', 'application/vnd.vcx'],\n    ['vdi', 'application/x-virtualbox-vdi'],\n    ['vds', 'model/vnd.sap.vds'],\n    ['vhd', 'application/x-virtualbox-vhd'],\n    ['vis', 'application/vnd.visionary'],\n    ['viv', 'video/vnd.vivo'],\n    ['vlc', 'application/videolan'],\n    ['vmdk', 'application/x-virtualbox-vmdk'],\n    ['vob', 'video/x-ms-vob'],\n    ['vor', 'application/vnd.stardivision.writer'],\n    ['vox', 'application/x-authorware-bin'],\n    ['vrml', 'model/vrml'],\n    ['vsd', 'application/vnd.visio'],\n    ['vsf', 'application/vnd.vsf'],\n    ['vss', 'application/vnd.visio'],\n    ['vst', 'application/vnd.visio'],\n    ['vsw', 'application/vnd.visio'],\n    ['vtf', 'image/vnd.valve.source.texture'],\n    ['vtt', 'text/vtt'],\n    ['vtu', 'model/vnd.vtu'],\n    ['vxml', 'application/voicexml+xml'],\n    ['w3d', 'application/x-director'],\n    ['wad', 'application/x-doom'],\n    ['wadl', 'application/vnd.sun.wadl+xml'],\n    ['war', 'application/java-archive'],\n    ['wasm', 'application/wasm'],\n    ['wav', 'audio/x-wav'],\n    ['wax', 'audio/x-ms-wax'],\n    ['wbmp', 'image/vnd.wap.wbmp'],\n    ['wbs', 'application/vnd.criticaltools.wbs+xml'],\n    ['wbxml', 'application/wbxml'],\n    ['wcm', 'application/vnd.ms-works'],\n    ['wdb', 'application/vnd.ms-works'],\n    ['wdp', 'image/vnd.ms-photo'],\n    ['weba', 'audio/webm'],\n    ['webapp', 'application/x-web-app-manifest+json'],\n    ['webm', 'video/webm'],\n    ['webmanifest', 'application/manifest+json'],\n    ['webp', 'image/webp'],\n    ['wg', 'application/vnd.pmi.widget'],\n    ['wgt', 'application/widget'],\n    ['wks', 'application/vnd.ms-works'],\n    ['wm', 'video/x-ms-wm'],\n    ['wma', 'audio/x-ms-wma'],\n    ['wmd', 'application/x-ms-wmd'],\n    ['wmf', 'image/wmf'],\n    ['wml', 'text/vnd.wap.wml'],\n    ['wmlc', 'application/wmlc'],\n    ['wmls', 'text/vnd.wap.wmlscript'],\n    ['wmlsc', 'application/vnd.wap.wmlscriptc'],\n    ['wmv', 'video/x-ms-wmv'],\n    ['wmx', 'video/x-ms-wmx'],\n    ['wmz', 'application/x-msmetafile'],\n    ['woff', 'font/woff'],\n    ['woff2', 'font/woff2'],\n    ['word', 'application/msword'],\n    ['wpd', 'application/vnd.wordperfect'],\n    ['wpl', 'application/vnd.ms-wpl'],\n    ['wps', 'application/vnd.ms-works'],\n    ['wqd', 'application/vnd.wqd'],\n    ['wri', 'application/x-mswrite'],\n    ['wrl', 'model/vrml'],\n    ['wsc', 'message/vnd.wfa.wsc'],\n    ['wsdl', 'application/wsdl+xml'],\n    ['wspolicy', 'application/wspolicy+xml'],\n    ['wtb', 'application/vnd.webturbo'],\n    ['wvx', 'video/x-ms-wvx'],\n    ['x3d', 'model/x3d+xml'],\n    ['x3db', 'model/x3d+fastinfoset'],\n    ['x3dbz', 'model/x3d+binary'],\n    ['x3dv', 'model/x3d-vrml'],\n    ['x3dvz', 'model/x3d+vrml'],\n    ['x3dz', 'model/x3d+xml'],\n    ['x32', 'application/x-authorware-bin'],\n    ['x_b', 'model/vnd.parasolid.transmit.binary'],\n    ['x_t', 'model/vnd.parasolid.transmit.text'],\n    ['xaml', 'application/xaml+xml'],\n    ['xap', 'application/x-silverlight-app'],\n    ['xar', 'application/vnd.xara'],\n    ['xav', 'application/xcap-att+xml'],\n    ['xbap', 'application/x-ms-xbap'],\n    ['xbd', 'application/vnd.fujixerox.docuworks.binder'],\n    ['xbm', 'image/x-xbitmap'],\n    ['xca', 'application/xcap-caps+xml'],\n    ['xcs', 'application/calendar+xml'],\n    ['xdf', 'application/xcap-diff+xml'],\n    ['xdm', 'application/vnd.syncml.dm+xml'],\n    ['xdp', 'application/vnd.adobe.xdp+xml'],\n    ['xdssc', 'application/dssc+xml'],\n    ['xdw', 'application/vnd.fujixerox.docuworks'],\n    ['xel', 'application/xcap-el+xml'],\n    ['xenc', 'application/xenc+xml'],\n    ['xer', 'application/patch-ops-error+xml'],\n    ['xfdf', 'application/vnd.adobe.xfdf'],\n    ['xfdl', 'application/vnd.xfdl'],\n    ['xht', 'application/xhtml+xml'],\n    ['xhtml', 'application/xhtml+xml'],\n    ['xhvml', 'application/xv+xml'],\n    ['xif', 'image/vnd.xiff'],\n    ['xl', 'application/excel'],\n    ['xla', 'application/vnd.ms-excel'],\n    ['xlam', 'application/vnd.ms-excel.addin.macroEnabled.12'],\n    ['xlc', 'application/vnd.ms-excel'],\n    ['xlf', 'application/xliff+xml'],\n    ['xlm', 'application/vnd.ms-excel'],\n    ['xls', 'application/vnd.ms-excel'],\n    ['xlsb', 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'],\n    ['xlsm', 'application/vnd.ms-excel.sheet.macroEnabled.12'],\n    ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],\n    ['xlt', 'application/vnd.ms-excel'],\n    ['xltm', 'application/vnd.ms-excel.template.macroEnabled.12'],\n    ['xltx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'],\n    ['xlw', 'application/vnd.ms-excel'],\n    ['xm', 'audio/xm'],\n    ['xml', 'application/xml'],\n    ['xns', 'application/xcap-ns+xml'],\n    ['xo', 'application/vnd.olpc-sugar'],\n    ['xop', 'application/xop+xml'],\n    ['xpi', 'application/x-xpinstall'],\n    ['xpl', 'application/xproc+xml'],\n    ['xpm', 'image/x-xpixmap'],\n    ['xpr', 'application/vnd.is-xpr'],\n    ['xps', 'application/vnd.ms-xpsdocument'],\n    ['xpw', 'application/vnd.intercon.formnet'],\n    ['xpx', 'application/vnd.intercon.formnet'],\n    ['xsd', 'application/xml'],\n    ['xsl', 'application/xml'],\n    ['xslt', 'application/xslt+xml'],\n    ['xsm', 'application/vnd.syncml+xml'],\n    ['xspf', 'application/xspf+xml'],\n    ['xul', 'application/vnd.mozilla.xul+xml'],\n    ['xvm', 'application/xv+xml'],\n    ['xvml', 'application/xv+xml'],\n    ['xwd', 'image/x-xwindowdump'],\n    ['xyz', 'chemical/x-xyz'],\n    ['xz', 'application/x-xz'],\n    ['yaml', 'text/yaml'],\n    ['yang', 'application/yang'],\n    ['yin', 'application/yin+xml'],\n    ['yml', 'text/yaml'],\n    ['ymp', 'text/x-suse-ymp'],\n    ['z', 'application/x-compress'],\n    ['z1', 'application/x-zmachine'],\n    ['z2', 'application/x-zmachine'],\n    ['z3', 'application/x-zmachine'],\n    ['z4', 'application/x-zmachine'],\n    ['z5', 'application/x-zmachine'],\n    ['z6', 'application/x-zmachine'],\n    ['z7', 'application/x-zmachine'],\n    ['z8', 'application/x-zmachine'],\n    ['zaz', 'application/vnd.zzazz.deck+xml'],\n    ['zip', 'application/zip'],\n    ['zir', 'application/vnd.zul'],\n    ['zirz', 'application/vnd.zul'],\n    ['zmm', 'application/vnd.handheld-entertainment+xml'],\n    ['zsh', 'text/x-scriptzsh']\n]);\nexport function toFileWithPath(file, path, h) {\n    const f = withMimeType(file);\n    const { webkitRelativePath } = file;\n    const p = typeof path === 'string'\n        ? path\n        // If <input webkitdirectory> is set,\n        // the File will have a {webkitRelativePath} property\n        // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory\n        : typeof webkitRelativePath === 'string' && webkitRelativePath.length > 0\n            ? webkitRelativePath\n            : `./${file.name}`;\n    if (typeof f.path !== 'string') { // on electron, path is already set to the absolute path\n        setObjProp(f, 'path', p);\n    }\n    if (h !== undefined) {\n        Object.defineProperty(f, 'handle', {\n            value: h,\n            writable: false,\n            configurable: false,\n            enumerable: true\n        });\n    }\n    // Always populate a relative path so that even electron apps have access to a relativePath value\n    setObjProp(f, 'relativePath', p);\n    return f;\n}\nfunction withMimeType(file) {\n    const { name } = file;\n    const hasExtension = name && name.lastIndexOf('.') !== -1;\n    if (hasExtension && !file.type) {\n        const ext = name.split('.')\n            .pop().toLowerCase();\n        const type = COMMON_MIME_TYPES.get(ext);\n        if (type) {\n            Object.defineProperty(file, 'type', {\n                value: type,\n                writable: false,\n                configurable: false,\n                enumerable: true\n            });\n        }\n    }\n    return file;\n}\nfunction setObjProp(f, key, value) {\n    Object.defineProperty(f, key, {\n        value,\n        writable: false,\n        configurable: false,\n        enumerable: true\n    });\n}\n//# sourceMappingURL=file.js.map","import { __awaiter } from \"tslib\";\nimport { toFileWithPath } from './file';\nconst FILES_TO_IGNORE = [\n    // Thumbnail cache files for macOS and Windows\n    '.DS_Store', // macOs\n    'Thumbs.db' // Windows\n];\n/**\n * Convert a DragEvent's DataTrasfer object to a list of File objects\n * NOTE: If some of the items are folders,\n * everything will be flattened and placed in the same list but the paths will be kept as a {path} property.\n *\n * EXPERIMENTAL: A list of https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle objects can also be passed as an arg\n * and a list of File objects will be returned.\n *\n * @param evt\n */\nexport function fromEvent(evt) {\n    return __awaiter(this, void 0, void 0, function* () {\n        if (isObject(evt) && isDataTransfer(evt.dataTransfer)) {\n            return getDataTransferFiles(evt.dataTransfer, evt.type);\n        }\n        else if (isChangeEvt(evt)) {\n            return getInputFiles(evt);\n        }\n        else if (Array.isArray(evt) && evt.every(item => 'getFile' in item && typeof item.getFile === 'function')) {\n            return getFsHandleFiles(evt);\n        }\n        return [];\n    });\n}\nfunction isDataTransfer(value) {\n    return isObject(value);\n}\nfunction isChangeEvt(value) {\n    return isObject(value) && isObject(value.target);\n}\nfunction isObject(v) {\n    return typeof v === 'object' && v !== null;\n}\nfunction getInputFiles(evt) {\n    return fromList(evt.target.files).map(file => toFileWithPath(file));\n}\n// Ee expect each handle to be https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle\nfunction getFsHandleFiles(handles) {\n    return __awaiter(this, void 0, void 0, function* () {\n        const files = yield Promise.all(handles.map(h => h.getFile()));\n        return files.map(file => toFileWithPath(file));\n    });\n}\nfunction getDataTransferFiles(dt, type) {\n    return __awaiter(this, void 0, void 0, function* () {\n        // IE11 does not support dataTransfer.items\n        // See https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/items#Browser_compatibility\n        if (dt.items) {\n            const items = fromList(dt.items)\n                .filter(item => item.kind === 'file');\n            // According to https://html.spec.whatwg.org/multipage/dnd.html#dndevents,\n            // only 'dragstart' and 'drop' has access to the data (source node)\n            if (type !== 'drop') {\n                return items;\n            }\n            const files = yield Promise.all(items.map(toFilePromises));\n            return noIgnoredFiles(flatten(files));\n        }\n        return noIgnoredFiles(fromList(dt.files)\n            .map(file => toFileWithPath(file)));\n    });\n}\nfunction noIgnoredFiles(files) {\n    return files.filter(file => FILES_TO_IGNORE.indexOf(file.name) === -1);\n}\n// IE11 does not support Array.from()\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility\n// https://developer.mozilla.org/en-US/docs/Web/API/FileList\n// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList\nfunction fromList(items) {\n    if (items === null) {\n        return [];\n    }\n    const files = [];\n    // tslint:disable: prefer-for-of\n    for (let i = 0; i < items.length; i++) {\n        const file = items[i];\n        files.push(file);\n    }\n    return files;\n}\n// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem\nfunction toFilePromises(item) {\n    if (typeof item.webkitGetAsEntry !== 'function') {\n        return fromDataTransferItem(item);\n    }\n    const entry = item.webkitGetAsEntry();\n    // Safari supports dropping an image node from a different window and can be retrieved using\n    // the DataTransferItem.getAsFile() API\n    // NOTE: FileSystemEntry.file() throws if trying to get the file\n    if (entry && entry.isDirectory) {\n        return fromDirEntry(entry);\n    }\n    return fromDataTransferItem(item, entry);\n}\nfunction flatten(items) {\n    return items.reduce((acc, files) => [\n        ...acc,\n        ...(Array.isArray(files) ? flatten(files) : [files])\n    ], []);\n}\nfunction fromDataTransferItem(item, entry) {\n    return __awaiter(this, void 0, void 0, function* () {\n        var _a;\n        // Check if we're in a secure context; due to a bug in Chrome (as far as we know)\n        // the browser crashes when calling this API (yet to be confirmed as a consistent behaviour).\n        //\n        // See:\n        // - https://issues.chromium.org/issues/40186242\n        // - https://github.com/react-dropzone/react-dropzone/issues/1397\n        if (globalThis.isSecureContext && typeof item.getAsFileSystemHandle === 'function') {\n            const h = yield item.getAsFileSystemHandle();\n            if (h === null) {\n                throw new Error(`${item} is not a File`);\n            }\n            // It seems that the handle can be `undefined` (see https://github.com/react-dropzone/file-selector/issues/120),\n            // so we check if it isn't; if it is, the code path continues to the next API (`getAsFile`).\n            if (h !== undefined) {\n                const file = yield h.getFile();\n                file.handle = h;\n                return toFileWithPath(file);\n            }\n        }\n        const file = item.getAsFile();\n        if (!file) {\n            throw new Error(`${item} is not a File`);\n        }\n        const fwp = toFileWithPath(file, (_a = entry === null || entry === void 0 ? void 0 : entry.fullPath) !== null && _a !== void 0 ? _a : undefined);\n        return fwp;\n    });\n}\n// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry\nfunction fromEntry(entry) {\n    return __awaiter(this, void 0, void 0, function* () {\n        return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);\n    });\n}\n// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry\nfunction fromDirEntry(entry) {\n    const reader = entry.createReader();\n    return new Promise((resolve, reject) => {\n        const entries = [];\n        function readEntries() {\n            // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry/createReader\n            // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries\n            reader.readEntries((batch) => __awaiter(this, void 0, void 0, function* () {\n                if (!batch.length) {\n                    // Done reading directory\n                    try {\n                        const files = yield Promise.all(entries);\n                        resolve(files);\n                    }\n                    catch (err) {\n                        reject(err);\n                    }\n                }\n                else {\n                    const items = Promise.all(batch.map(fromEntry));\n                    entries.push(items);\n                    // Continue reading\n                    readEntries();\n                }\n            }), (err) => {\n                reject(err);\n            });\n        }\n        readEntries();\n    });\n}\n// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry\nfunction fromFileEntry(entry) {\n    return __awaiter(this, void 0, void 0, function* () {\n        return new Promise((resolve, reject) => {\n            entry.file((file) => {\n                const fwp = toFileWithPath(file, entry.fullPath);\n                resolve(fwp);\n            }, (err) => {\n                reject(err);\n            });\n        });\n    });\n}\n//# sourceMappingURL=file-selector.js.map","\"use strict\";\n\nexports.__esModule = true;\n\nexports.default = function (file, acceptedFiles) {\n  if (file && acceptedFiles) {\n    var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(',');\n\n    if (acceptedFilesArray.length === 0) {\n      return true;\n    }\n\n    var fileName = file.name || '';\n    var mimeType = (file.type || '').toLowerCase();\n    var baseMimeType = mimeType.replace(/\\/.*$/, '');\n    return acceptedFilesArray.some(function (type) {\n      var validType = type.trim().toLowerCase();\n\n      if (validType.charAt(0) === '.') {\n        return fileName.toLowerCase().endsWith(validType);\n      } else if (validType.endsWith('/*')) {\n        // This is something like a image/* mime type\n        return baseMimeType === validType.replace(/\\/.*$/, '');\n      }\n\n      return mimeType === validType;\n    });\n  }\n\n  return true;\n};","function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nimport _accepts from \"attr-accept\";\nvar accepts = typeof _accepts === \"function\" ? _accepts : _accepts.default; // Error codes\n\nexport var FILE_INVALID_TYPE = \"file-invalid-type\";\nexport var FILE_TOO_LARGE = \"file-too-large\";\nexport var FILE_TOO_SMALL = \"file-too-small\";\nexport var TOO_MANY_FILES = \"too-many-files\";\nexport var ErrorCode = {\n  FileInvalidType: FILE_INVALID_TYPE,\n  FileTooLarge: FILE_TOO_LARGE,\n  FileTooSmall: FILE_TOO_SMALL,\n  TooManyFiles: TOO_MANY_FILES\n};\n/**\n *\n * @param {string} accept\n */\n\nexport var getInvalidTypeRejectionErr = function getInvalidTypeRejectionErr() {\n  var accept = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : \"\";\n  var acceptArr = accept.split(\",\");\n  var msg = acceptArr.length > 1 ? \"one of \".concat(acceptArr.join(\", \")) : acceptArr[0];\n  return {\n    code: FILE_INVALID_TYPE,\n    message: \"File type must be \".concat(msg)\n  };\n};\nexport var getTooLargeRejectionErr = function getTooLargeRejectionErr(maxSize) {\n  return {\n    code: FILE_TOO_LARGE,\n    message: \"File is larger than \".concat(maxSize, \" \").concat(maxSize === 1 ? \"byte\" : \"bytes\")\n  };\n};\nexport var getTooSmallRejectionErr = function getTooSmallRejectionErr(minSize) {\n  return {\n    code: FILE_TOO_SMALL,\n    message: \"File is smaller than \".concat(minSize, \" \").concat(minSize === 1 ? \"byte\" : \"bytes\")\n  };\n};\nexport var TOO_MANY_FILES_REJECTION = {\n  code: TOO_MANY_FILES,\n  message: \"Too many files\"\n};\n/**\n * Check if the given file is a DataTransferItem with an empty type.\n *\n * During drag events, browsers may return DataTransferItem objects instead of File objects.\n * Some browsers (e.g., Chrome) return an empty MIME type for certain file types (like .md files)\n * on DataTransferItem during drag events, even though the type is correctly set during drop.\n *\n * This function detects such cases by checking for:\n * 1. Empty type string\n * 2. Presence of getAsFile method (indicates it's a DataTransferItem, not a File)\n *\n * We accept these during drag to provide proper UI feedback, while maintaining\n * strict validation during drop when real File objects are available.\n *\n * @param {File | DataTransferItem} file\n * @returns {boolean}\n */\n\nexport function isDataTransferItemWithEmptyType(file) {\n  return file.type === \"\" && typeof file.getAsFile === \"function\";\n}\n/**\n * Check if file is accepted.\n *\n * Firefox versions prior to 53 return a bogus MIME type for every file drag,\n * so dragovers with that MIME type will always be accepted.\n *\n * Chrome/other browsers may return an empty MIME type for files during drag events,\n * so we accept those as well (we'll validate properly on drop).\n *\n * @param {File} file\n * @param {string} accept\n * @returns\n */\n\nexport function fileAccepted(file, accept) {\n  var isAcceptable = file.type === \"application/x-moz-file\" || accepts(file, accept) || isDataTransferItemWithEmptyType(file);\n  return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)];\n}\nexport function fileMatchSize(file, minSize, maxSize) {\n  if (isDefined(file.size)) {\n    if (isDefined(minSize) && isDefined(maxSize)) {\n      if (file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];\n      if (file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];\n    } else if (isDefined(minSize) && file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];else if (isDefined(maxSize) && file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];\n  }\n\n  return [true, null];\n}\n\nfunction isDefined(value) {\n  return value !== undefined && value !== null;\n}\n/**\n *\n * @param {object} options\n * @param {File[]} options.files\n * @param {string} [options.accept]\n * @param {number} [options.minSize]\n * @param {number} [options.maxSize]\n * @param {boolean} [options.multiple]\n * @param {number} [options.maxFiles]\n * @param {(f: File) => FileError|FileError[]|null} [options.validator]\n * @returns\n */\n\n\nexport function allFilesAccepted(_ref) {\n  var files = _ref.files,\n      accept = _ref.accept,\n      minSize = _ref.minSize,\n      maxSize = _ref.maxSize,\n      multiple = _ref.multiple,\n      maxFiles = _ref.maxFiles,\n      validator = _ref.validator;\n\n  if (!multiple && files.length > 1 || multiple && maxFiles >= 1 && files.length > maxFiles) {\n    return false;\n  }\n\n  return files.every(function (file) {\n    var _fileAccepted = fileAccepted(file, accept),\n        _fileAccepted2 = _slicedToArray(_fileAccepted, 1),\n        accepted = _fileAccepted2[0];\n\n    var _fileMatchSize = fileMatchSize(file, minSize, maxSize),\n        _fileMatchSize2 = _slicedToArray(_fileMatchSize, 1),\n        sizeMatch = _fileMatchSize2[0];\n\n    var customErrors = validator ? validator(file) : null;\n    return accepted && sizeMatch && !customErrors;\n  });\n} // React's synthetic events has event.isPropagationStopped,\n// but to remain compatibility with other libs (Preact) fall back\n// to check event.cancelBubble\n\nexport function isPropagationStopped(event) {\n  if (typeof event.isPropagationStopped === \"function\") {\n    return event.isPropagationStopped();\n  } else if (typeof event.cancelBubble !== \"undefined\") {\n    return event.cancelBubble;\n  }\n\n  return false;\n}\nexport function isEvtWithFiles(event) {\n  if (!event.dataTransfer) {\n    return !!event.target && !!event.target.files;\n  } // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types\n  // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file\n\n\n  return Array.prototype.some.call(event.dataTransfer.types, function (type) {\n    return type === \"Files\" || type === \"application/x-moz-file\";\n  });\n}\nexport function isKindFile(item) {\n  return _typeof(item) === \"object\" && item !== null && item.kind === \"file\";\n} // allow the entire document to be a drag target\n\nexport function onDocumentDragOver(event) {\n  event.preventDefault();\n}\n\nfunction isIe(userAgent) {\n  return userAgent.indexOf(\"MSIE\") !== -1 || userAgent.indexOf(\"Trident/\") !== -1;\n}\n\nfunction isEdge(userAgent) {\n  return userAgent.indexOf(\"Edge/\") !== -1;\n}\n\nexport function isIeOrEdge() {\n  var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.navigator.userAgent;\n  return isIe(userAgent) || isEdge(userAgent);\n}\n/**\n * This is intended to be used to compose event handlers\n * They are executed in order until one of them calls `event.isPropagationStopped()`.\n * Note that the check is done on the first invoke too,\n * meaning that if propagation was stopped before invoking the fns,\n * no handlers will be executed.\n *\n * @param {Function} fns the event hanlder functions\n * @return {Function} the event handler to add to an element\n */\n\nexport function composeEventHandlers() {\n  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n    fns[_key] = arguments[_key];\n  }\n\n  return function (event) {\n    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n      args[_key2 - 1] = arguments[_key2];\n    }\n\n    return fns.some(function (fn) {\n      if (!isPropagationStopped(event) && fn) {\n        fn.apply(void 0, [event].concat(args));\n      }\n\n      return isPropagationStopped(event);\n    });\n  };\n}\n/**\n * canUseFileSystemAccessAPI checks if the [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API)\n * is supported by the browser.\n * @returns {boolean}\n */\n\nexport function canUseFileSystemAccessAPI() {\n  return \"showOpenFilePicker\" in window;\n}\n/**\n * Convert the `{accept}` dropzone prop to the\n * `{types}` option for https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker\n *\n * @param {AcceptProp} accept\n * @returns {{accept: string[]}[]}\n */\n\nexport function pickerOptionsFromAccept(accept) {\n  if (isDefined(accept)) {\n    var acceptForPicker = Object.entries(accept).filter(function (_ref2) {\n      var _ref3 = _slicedToArray(_ref2, 2),\n          mimeType = _ref3[0],\n          ext = _ref3[1];\n\n      var ok = true;\n\n      if (!isMIMEType(mimeType)) {\n        console.warn(\"Skipped \\\"\".concat(mimeType, \"\\\" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.\"));\n        ok = false;\n      }\n\n      if (!Array.isArray(ext) || !ext.every(isExt)) {\n        console.warn(\"Skipped \\\"\".concat(mimeType, \"\\\" because an invalid file extension was provided.\"));\n        ok = false;\n      }\n\n      return ok;\n    }).reduce(function (agg, _ref4) {\n      var _ref5 = _slicedToArray(_ref4, 2),\n          mimeType = _ref5[0],\n          ext = _ref5[1];\n\n      return _objectSpread(_objectSpread({}, agg), {}, _defineProperty({}, mimeType, ext));\n    }, {});\n    return [{\n      // description is required due to https://crbug.com/1264708\n      description: \"Files\",\n      accept: acceptForPicker\n    }];\n  }\n\n  return accept;\n}\n/**\n * Convert the `{accept}` dropzone prop to an array of MIME types/extensions.\n * @param {AcceptProp} accept\n * @returns {string}\n */\n\nexport function acceptPropAsAcceptAttr(accept) {\n  if (isDefined(accept)) {\n    return Object.entries(accept).reduce(function (a, _ref6) {\n      var _ref7 = _slicedToArray(_ref6, 2),\n          mimeType = _ref7[0],\n          ext = _ref7[1];\n\n      return [].concat(_toConsumableArray(a), [mimeType], _toConsumableArray(ext));\n    }, []) // Silently discard invalid entries as pickerOptionsFromAccept warns about these\n    .filter(function (v) {\n      return isMIMEType(v) || isExt(v);\n    }).join(\",\");\n  }\n\n  return undefined;\n}\n/**\n * Check if v is an exception caused by aborting a request (e.g window.showOpenFilePicker()).\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/DOMException.\n * @param {any} v\n * @returns {boolean} True if v is an abort exception.\n */\n\nexport function isAbort(v) {\n  return v instanceof DOMException && (v.name === \"AbortError\" || v.code === v.ABORT_ERR);\n}\n/**\n * Check if v is a security error.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/DOMException.\n * @param {any} v\n * @returns {boolean} True if v is a security error.\n */\n\nexport function isSecurityError(v) {\n  return v instanceof DOMException && (v.name === \"SecurityError\" || v.code === v.SECURITY_ERR);\n}\n/**\n * Check if v is a MIME type string.\n *\n * See accepted format: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers.\n *\n * @param {string} v\n */\n\nexport function isMIMEType(v) {\n  return v === \"audio/*\" || v === \"video/*\" || v === \"image/*\" || v === \"text/*\" || v === \"application/*\" || /\\w+\\/[-+.\\w]+/g.test(v);\n}\n/**\n * Check if v is a file extension.\n * @param {string} v\n */\n\nexport function isExt(v) {\n  return /^.*\\.[\\w]+$/.test(v);\n}\n/**\n * @typedef {Object.<string, string[]>} AcceptProp\n */\n\n/**\n * @typedef {object} FileError\n * @property {string} message\n * @property {ErrorCode|string} code\n */\n\n/**\n * @typedef {\"file-invalid-type\"|\"file-too-large\"|\"file-too-small\"|\"too-many-files\"} ErrorCode\n */","var _excluded = [\"children\"],\n    _excluded2 = [\"open\"],\n    _excluded3 = [\"refKey\", \"role\", \"onKeyDown\", \"onFocus\", \"onBlur\", \"onClick\", \"onDragEnter\", \"onDragOver\", \"onDragLeave\", \"onDrop\"],\n    _excluded4 = [\"refKey\", \"onChange\", \"onClick\"];\n\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* eslint prefer-template: 0 */\nimport React, { forwardRef, Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useReducer, useRef } from \"react\";\nimport PropTypes from \"prop-types\";\nimport { fromEvent } from \"file-selector\";\nimport { acceptPropAsAcceptAttr, allFilesAccepted, composeEventHandlers, fileAccepted, fileMatchSize, canUseFileSystemAccessAPI, isAbort, isEvtWithFiles, isIeOrEdge, isPropagationStopped, isSecurityError, onDocumentDragOver, pickerOptionsFromAccept, TOO_MANY_FILES_REJECTION } from \"./utils/index.js\";\n/**\n * Convenience wrapper component for the `useDropzone` hook\n *\n * ```jsx\n * <Dropzone>\n *   {({getRootProps, getInputProps}) => (\n *     <div {...getRootProps()}>\n *       <input {...getInputProps()} />\n *       <p>Drag 'n' drop some files here, or click to select files</p>\n *     </div>\n *   )}\n * </Dropzone>\n * ```\n */\n\nvar Dropzone = /*#__PURE__*/forwardRef(function (_ref, ref) {\n  var children = _ref.children,\n      params = _objectWithoutProperties(_ref, _excluded);\n\n  var _useDropzone = useDropzone(params),\n      open = _useDropzone.open,\n      props = _objectWithoutProperties(_useDropzone, _excluded2);\n\n  useImperativeHandle(ref, function () {\n    return {\n      open: open\n    };\n  }, [open]); // TODO: Figure out why react-styleguidist cannot create docs if we don't return a jsx element\n\n  return /*#__PURE__*/React.createElement(Fragment, null, children(_objectSpread(_objectSpread({}, props), {}, {\n    open: open\n  })));\n});\nDropzone.displayName = \"Dropzone\"; // Add default props for react-docgen\n\nvar defaultProps = {\n  disabled: false,\n  getFilesFromEvent: fromEvent,\n  maxSize: Infinity,\n  minSize: 0,\n  multiple: true,\n  maxFiles: 0,\n  preventDropOnDocument: true,\n  noClick: false,\n  noKeyboard: false,\n  noDrag: false,\n  noDragEventsBubbling: false,\n  validator: null,\n  useFsAccessApi: false,\n  autoFocus: false\n};\nDropzone.defaultProps = defaultProps;\nDropzone.propTypes = {\n  /**\n   * Render function that exposes the dropzone state and prop getter fns\n   *\n   * @param {object} params\n   * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render\n   * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render\n   * @param {Function} params.open Open the native file selection dialog\n   * @param {boolean} params.isFocused Dropzone area is in focus\n   * @param {boolean} params.isFileDialogActive File dialog is opened\n   * @param {boolean} params.isDragActive Active drag is in progress\n   * @param {boolean} params.isDragAccept Dragged files are accepted\n   * @param {boolean} params.isDragReject True only during an active drag when some dragged files would be rejected. After drop, this resets to false. Use fileRejections for post-drop errors.\n   * @param {boolean} params.isDragGlobal Files are being dragged anywhere on the document\n   * @param {File[]} params.acceptedFiles Accepted files\n   * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected. This persists after drop and is the source of truth for post-drop rejections.\n   */\n  children: PropTypes.func,\n\n  /**\n   * Set accepted file types.\n   * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.\n   * Keep in mind that mime type determination is not reliable across platforms. CSV files,\n   * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under\n   * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).\n   */\n  accept: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),\n\n  /**\n   * Allow drag 'n' drop (or selection from the file dialog) of multiple files\n   */\n  multiple: PropTypes.bool,\n\n  /**\n   * If false, allow dropped items to take over the current browser window\n   */\n  preventDropOnDocument: PropTypes.bool,\n\n  /**\n   * If true, disables click to open the native file selection dialog\n   */\n  noClick: PropTypes.bool,\n\n  /**\n   * If true, disables SPACE/ENTER to open the native file selection dialog.\n   * Note that it also stops tracking the focus state.\n   */\n  noKeyboard: PropTypes.bool,\n\n  /**\n   * If true, disables drag 'n' drop\n   */\n  noDrag: PropTypes.bool,\n\n  /**\n   * If true, stops drag event propagation to parents\n   */\n  noDragEventsBubbling: PropTypes.bool,\n\n  /**\n   * Minimum file size (in bytes)\n   */\n  minSize: PropTypes.number,\n\n  /**\n   * Maximum file size (in bytes)\n   */\n  maxSize: PropTypes.number,\n\n  /**\n   * Maximum accepted number of files\n   * The default value is 0 which means there is no limitation to how many files are accepted.\n   */\n  maxFiles: PropTypes.number,\n\n  /**\n   * Enable/disable the dropzone\n   */\n  disabled: PropTypes.bool,\n\n  /**\n   * Use this to provide a custom file aggregator\n   *\n   * @param {(DragEvent|Event|Array<FileSystemFileHandle>)} event A drag event or input change event (if files were selected via the file dialog)\n   */\n  getFilesFromEvent: PropTypes.func,\n\n  /**\n   * Cb for when closing the file dialog with no selection\n   */\n  onFileDialogCancel: PropTypes.func,\n\n  /**\n   * Cb for when opening the file dialog\n   */\n  onFileDialogOpen: PropTypes.func,\n\n  /**\n   * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API\n   * to open the file picker instead of using an `<input type=\"file\">` click event.\n   */\n  useFsAccessApi: PropTypes.bool,\n\n  /**\n   * Set to true to focus the root element on render\n   */\n  autoFocus: PropTypes.bool,\n\n  /**\n   * Cb for when the `dragenter` event occurs.\n   *\n   * @param {DragEvent} event\n   */\n  onDragEnter: PropTypes.func,\n\n  /**\n   * Cb for when the `dragleave` event occurs\n   *\n   * @param {DragEvent} event\n   */\n  onDragLeave: PropTypes.func,\n\n  /**\n   * Cb for when the `dragover` event occurs\n   *\n   * @param {DragEvent} event\n   */\n  onDragOver: PropTypes.func,\n\n  /**\n   * Cb for when the `drop` event occurs.\n   * Note that this callback is invoked after the `getFilesFromEvent` callback is done.\n   *\n   * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.\n   * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension.\n   * If `multiple` is set to false and additional files are dropped,\n   * all files besides the first will be rejected.\n   * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.\n   *\n   * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.\n   * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.\n   *\n   * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.\n   * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:\n   *\n   * ```js\n   * function onDrop(acceptedFiles) {\n   *   const req = request.post('/upload')\n   *   acceptedFiles.forEach(file => {\n   *     req.attach(file.name, file)\n   *   })\n   *   req.end(callback)\n   * }\n   * ```\n   *\n   * @param {File[]} acceptedFiles\n   * @param {FileRejection[]} fileRejections\n   * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)\n   */\n  onDrop: PropTypes.func,\n\n  /**\n   * Cb for when the `drop` event occurs.\n   * Note that if no files are accepted, this callback is not invoked.\n   *\n   * @param {File[]} files\n   * @param {(DragEvent|Event)} event\n   */\n  onDropAccepted: PropTypes.func,\n\n  /**\n   * Cb for when the `drop` event occurs.\n   * Note that if no files are rejected, this callback is not invoked.\n   *\n   * @param {FileRejection[]} fileRejections\n   * @param {(DragEvent|Event)} event\n   */\n  onDropRejected: PropTypes.func,\n\n  /**\n   * Cb for when there's some error from any of the promises.\n   *\n   * @param {Error} error\n   */\n  onError: PropTypes.func,\n\n  /**\n   * Custom validation function. It must return null if there's no errors.\n   * @param {File} file\n   * @returns {FileError|FileError[]|null}\n   */\n  validator: PropTypes.func\n};\nexport default Dropzone;\n/**\n * A function that is invoked for the `dragenter`,\n * `dragover` and `dragleave` events.\n * It is not invoked if the items are not files (such as link, text, etc.).\n *\n * @callback dragCb\n * @param {DragEvent} event\n */\n\n/**\n * A function that is invoked for the `drop` or input change event.\n * It is not invoked if the items are not files (such as link, text, etc.).\n *\n * @callback dropCb\n * @param {File[]} acceptedFiles List of accepted files\n * @param {FileRejection[]} fileRejections List of rejected files and why they were rejected. This is the authoritative source for post-drop file rejections.\n * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)\n */\n\n/**\n * A function that is invoked for the `drop` or input change event.\n * It is not invoked if the items are files (such as link, text, etc.).\n *\n * @callback dropAcceptedCb\n * @param {File[]} files List of accepted files that meet the given criteria\n * (`accept`, `multiple`, `minSize`, `maxSize`)\n * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)\n */\n\n/**\n * A function that is invoked for the `drop` or input change event.\n *\n * @callback dropRejectedCb\n * @param {File[]} files List of rejected files that do not meet the given criteria\n * (`accept`, `multiple`, `minSize`, `maxSize`)\n * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)\n */\n\n/**\n * A function that is used aggregate files,\n * in a asynchronous fashion, from drag or input change events.\n *\n * @callback getFilesFromEvent\n * @param {(DragEvent|Event|Array<FileSystemFileHandle>)} event A drag event or input change event (if files were selected via the file dialog)\n * @returns {(File[]|Promise<File[]>)}\n */\n\n/**\n * An object with the current dropzone state.\n *\n * @typedef {object} DropzoneState\n * @property {boolean} isFocused Dropzone area is in focus\n * @property {boolean} isFileDialogActive File dialog is opened\n * @property {boolean} isDragActive Active drag is in progress\n * @property {boolean} isDragAccept Dragged files are accepted\n * @property {boolean} isDragReject True only during an active drag when some dragged files would be rejected. After drop, this resets to false. Use fileRejections for post-drop errors.\n * @property {boolean} isDragGlobal Files are being dragged anywhere on the document\n * @property {File[]} acceptedFiles Accepted files\n * @property {FileRejection[]} fileRejections Rejected files and why they were rejected. This persists after drop and is the source of truth for post-drop rejections.\n */\n\n/**\n * An object with the dropzone methods.\n *\n * @typedef {object} DropzoneMethods\n * @property {Function} getRootProps Returns the props you should apply to the root drop container you render\n * @property {Function} getInputProps Returns the props you should apply to hidden file input you render\n * @property {Function} open Open the native file selection dialog\n */\n\nvar initialState = {\n  isFocused: false,\n  isFileDialogActive: false,\n  isDragActive: false,\n  isDragAccept: false,\n  isDragReject: false,\n  isDragGlobal: false,\n  acceptedFiles: [],\n  fileRejections: []\n};\n/**\n * A React hook that creates a drag 'n' drop area.\n *\n * ```jsx\n * function MyDropzone(props) {\n *   const {getRootProps, getInputProps} = useDropzone({\n *     onDrop: acceptedFiles => {\n *       // do something with the File objects, e.g. upload to some server\n *     }\n *   });\n *   return (\n *     <div {...getRootProps()}>\n *       <input {...getInputProps()} />\n *       <p>Drag and drop some files here, or click to select files</p>\n *     </div>\n *   )\n * }\n * ```\n *\n * @function useDropzone\n *\n * @param {object} props\n * @param {import(\"./utils\").AcceptProp} [props.accept] Set accepted file types.\n * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.\n * Keep in mind that mime type determination is not reliable across platforms. CSV files,\n * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under\n * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).\n * @param {boolean} [props.multiple=true] Allow drag 'n' drop (or selection from the file dialog) of multiple files\n * @param {boolean} [props.preventDropOnDocument=true] If false, allow dropped items to take over the current browser window\n * @param {boolean} [props.noClick=false] If true, disables click to open the native file selection dialog\n * @param {boolean} [props.noKeyboard=false] If true, disables SPACE/ENTER to open the native file selection dialog.\n * Note that it also stops tracking the focus state.\n * @param {boolean} [props.noDrag=false] If true, disables drag 'n' drop\n * @param {boolean} [props.noDragEventsBubbling=false] If true, stops drag event propagation to parents\n * @param {number} [props.minSize=0] Minimum file size (in bytes)\n * @param {number} [props.maxSize=Infinity] Maximum file size (in bytes)\n * @param {boolean} [props.disabled=false] Enable/disable the dropzone\n * @param {getFilesFromEvent} [props.getFilesFromEvent] Use this to provide a custom file aggregator\n * @param {Function} [props.onFileDialogCancel] Cb for when closing the file dialog with no selection\n * @param {boolean} [props.useFsAccessApi] Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API\n * to open the file picker instead of using an `<input type=\"file\">` click event.\n * @param {boolean} autoFocus Set to true to auto focus the root element.\n * @param {Function} [props.onFileDialogOpen] Cb for when opening the file dialog\n * @param {dragCb} [props.onDragEnter] Cb for when the `dragenter` event occurs.\n * @param {dragCb} [props.onDragLeave] Cb for when the `dragleave` event occurs\n * @param {dragCb} [props.onDragOver] Cb for when the `dragover` event occurs\n * @param {dropCb} [props.onDrop] Cb for when the `drop` event occurs.\n * Note that this callback is invoked after the `getFilesFromEvent` callback is done.\n *\n * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.\n * `accept` must be an object with keys as a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) and the value an array of file extensions (optional).\n * If `multiple` is set to false and additional files are dropped,\n * all files besides the first will be rejected.\n * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.\n *\n * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.\n * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.\n *\n * The second parameter (fileRejections) is the authoritative list of rejected files after a drop.\n * Use this parameter or the fileRejections state property to handle post-drop file rejections,\n * as isDragReject only indicates rejection state during active drag operations.\n *\n * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.\n * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:\n *\n * ```js\n * function onDrop(acceptedFiles) {\n *   const req = request.post('/upload')\n *   acceptedFiles.forEach(file => {\n *     req.attach(file.name, file)\n *   })\n *   req.end(callback)\n * }\n * ```\n * @param {dropAcceptedCb} [props.onDropAccepted]\n * @param {dropRejectedCb} [props.onDropRejected]\n * @param {(error: Error) => void} [props.onError]\n *\n * @returns {DropzoneState & DropzoneMethods}\n */\n\nexport function useDropzone() {\n  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n  var _defaultProps$props = _objectSpread(_objectSpread({}, defaultProps), props),\n      accept = _defaultProps$props.accept,\n      disabled = _defaultProps$props.disabled,\n      getFilesFromEvent = _defaultProps$props.getFilesFromEvent,\n      maxSize = _defaultProps$props.maxSize,\n      minSize = _defaultProps$props.minSize,\n      multiple = _defaultProps$props.multiple,\n      maxFiles = _defaultProps$props.maxFiles,\n      onDragEnter = _defaultProps$props.onDragEnter,\n      onDragLeave = _defaultProps$props.onDragLeave,\n      onDragOver = _defaultProps$props.onDragOver,\n      onDrop = _defaultProps$props.onDrop,\n      onDropAccepted = _defaultProps$props.onDropAccepted,\n      onDropRejected = _defaultProps$props.onDropRejected,\n      onFileDialogCancel = _defaultProps$props.onFileDialogCancel,\n      onFileDialogOpen = _defaultProps$props.onFileDialogOpen,\n      useFsAccessApi = _defaultProps$props.useFsAccessApi,\n      autoFocus = _defaultProps$props.autoFocus,\n      preventDropOnDocument = _defaultProps$props.preventDropOnDocument,\n      noClick = _defaultProps$props.noClick,\n      noKeyboard = _defaultProps$props.noKeyboard,\n      noDrag = _defaultProps$props.noDrag,\n      noDragEventsBubbling = _defaultProps$props.noDragEventsBubbling,\n      onError = _defaultProps$props.onError,\n      validator = _defaultProps$props.validator;\n\n  var acceptAttr = useMemo(function () {\n    return acceptPropAsAcceptAttr(accept);\n  }, [accept]);\n  var pickerTypes = useMemo(function () {\n    return pickerOptionsFromAccept(accept);\n  }, [accept]);\n  var onFileDialogOpenCb = useMemo(function () {\n    return typeof onFileDialogOpen === \"function\" ? onFileDialogOpen : noop;\n  }, [onFileDialogOpen]);\n  var onFileDialogCancelCb = useMemo(function () {\n    return typeof onFileDialogCancel === \"function\" ? onFileDialogCancel : noop;\n  }, [onFileDialogCancel]);\n  /**\n   * @constant\n   * @type {React.MutableRefObject<HTMLElement>}\n   */\n\n  var rootRef = useRef(null);\n  var inputRef = useRef(null);\n\n  var _useReducer = useReducer(reducer, initialState),\n      _useReducer2 = _slicedToArray(_useReducer, 2),\n      state = _useReducer2[0],\n      dispatch = _useReducer2[1];\n\n  var isFocused = state.isFocused,\n      isFileDialogActive = state.isFileDialogActive;\n  var fsAccessApiWorksRef = useRef(typeof window !== \"undefined\" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI()); // Update file dialog active state when the window is focused on\n\n  var onWindowFocus = function onWindowFocus() {\n    // Execute the timeout only if the file dialog is opened in the browser\n    if (!fsAccessApiWorksRef.current && isFileDialogActive) {\n      setTimeout(function () {\n        if (inputRef.current) {\n          var files = inputRef.current.files;\n\n          if (!files.length) {\n            dispatch({\n              type: \"closeDialog\"\n            });\n            onFileDialogCancelCb();\n          }\n        }\n      }, 300);\n    }\n  };\n\n  useEffect(function () {\n    window.addEventListener(\"focus\", onWindowFocus, false);\n    return function () {\n      window.removeEventListener(\"focus\", onWindowFocus, false);\n    };\n  }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]);\n  var dragTargetsRef = useRef([]);\n  var globalDragTargetsRef = useRef([]);\n\n  var onDocumentDrop = function onDocumentDrop(event) {\n    if (rootRef.current && rootRef.current.contains(event.target)) {\n      // If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler\n      return;\n    }\n\n    event.preventDefault();\n    dragTargetsRef.current = [];\n  };\n\n  useEffect(function () {\n    if (preventDropOnDocument) {\n      document.addEventListener(\"dragover\", onDocumentDragOver, false);\n      document.addEventListener(\"drop\", onDocumentDrop, false);\n    }\n\n    return function () {\n      if (preventDropOnDocument) {\n        document.removeEventListener(\"dragover\", onDocumentDragOver);\n        document.removeEventListener(\"drop\", onDocumentDrop);\n      }\n    };\n  }, [rootRef, preventDropOnDocument]); // Track global drag state for document-level drag events\n\n  useEffect(function () {\n    var onDocumentDragEnter = function onDocumentDragEnter(event) {\n      globalDragTargetsRef.current = [].concat(_toConsumableArray(globalDragTargetsRef.current), [event.target]);\n\n      if (isEvtWithFiles(event)) {\n        dispatch({\n          isDragGlobal: true,\n          type: \"setDragGlobal\"\n        });\n      }\n    };\n\n    var onDocumentDragLeave = function onDocumentDragLeave(event) {\n      // Only deactivate once we've left all children\n      globalDragTargetsRef.current = globalDragTargetsRef.current.filter(function (el) {\n        return el !== event.target && el !== null;\n      });\n\n      if (globalDragTargetsRef.current.length > 0) {\n        return;\n      }\n\n      dispatch({\n        isDragGlobal: false,\n        type: \"setDragGlobal\"\n      });\n    };\n\n    var onDocumentDragEnd = function onDocumentDragEnd() {\n      globalDragTargetsRef.current = [];\n      dispatch({\n        isDragGlobal: false,\n        type: \"setDragGlobal\"\n      });\n    };\n\n    var onDocumentDropGlobal = function onDocumentDropGlobal() {\n      globalDragTargetsRef.current = [];\n      dispatch({\n        isDragGlobal: false,\n        type: \"setDragGlobal\"\n      });\n    };\n\n    document.addEventListener(\"dragenter\", onDocumentDragEnter, false);\n    document.addEventListener(\"dragleave\", onDocumentDragLeave, false);\n    document.addEventListener(\"dragend\", onDocumentDragEnd, false);\n    document.addEventListener(\"drop\", onDocumentDropGlobal, false);\n    return function () {\n      document.removeEventListener(\"dragenter\", onDocumentDragEnter);\n      document.removeEventListener(\"dragleave\", onDocumentDragLeave);\n      document.removeEventListener(\"dragend\", onDocumentDragEnd);\n      document.removeEventListener(\"drop\", onDocumentDropGlobal);\n    };\n  }, [rootRef]); // Auto focus the root when autoFocus is true\n\n  useEffect(function () {\n    if (!disabled && autoFocus && rootRef.current) {\n      rootRef.current.focus();\n    }\n\n    return function () {};\n  }, [rootRef, autoFocus, disabled]);\n  var onErrCb = useCallback(function (e) {\n    if (onError) {\n      onError(e);\n    } else {\n      // Let the user know something's gone wrong if they haven't provided the onError cb.\n      console.error(e);\n    }\n  }, [onError]);\n  var onDragEnterCb = useCallback(function (event) {\n    event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done\n\n    event.persist();\n    stopPropagation(event);\n    dragTargetsRef.current = [].concat(_toConsumableArray(dragTargetsRef.current), [event.target]);\n\n    if (isEvtWithFiles(event)) {\n      Promise.resolve(getFilesFromEvent(event)).then(function (files) {\n        if (isPropagationStopped(event) && !noDragEventsBubbling) {\n          return;\n        }\n\n        var fileCount = files.length;\n        var isDragAccept = fileCount > 0 && allFilesAccepted({\n          files: files,\n          accept: acceptAttr,\n          minSize: minSize,\n          maxSize: maxSize,\n          multiple: multiple,\n          maxFiles: maxFiles,\n          validator: validator\n        });\n        var isDragReject = fileCount > 0 && !isDragAccept;\n        dispatch({\n          isDragAccept: isDragAccept,\n          isDragReject: isDragReject,\n          isDragActive: true,\n          type: \"setDraggedFiles\"\n        });\n\n        if (onDragEnter) {\n          onDragEnter(event);\n        }\n      }).catch(function (e) {\n        return onErrCb(e);\n      });\n    }\n  }, [getFilesFromEvent, onDragEnter, onErrCb, noDragEventsBubbling, acceptAttr, minSize, maxSize, multiple, maxFiles, validator]);\n  var onDragOverCb = useCallback(function (event) {\n    event.preventDefault();\n    event.persist();\n    stopPropagation(event);\n    var hasFiles = isEvtWithFiles(event);\n\n    if (hasFiles && event.dataTransfer) {\n      try {\n        event.dataTransfer.dropEffect = \"copy\";\n      } catch (_unused) {}\n      /* eslint-disable-line no-empty */\n\n    }\n\n    if (hasFiles && onDragOver) {\n      onDragOver(event);\n    }\n\n    return false;\n  }, [onDragOver, noDragEventsBubbling]);\n  var onDragLeaveCb = useCallback(function (event) {\n    event.preventDefault();\n    event.persist();\n    stopPropagation(event); // Only deactivate once the dropzone and all children have been left\n\n    var targets = dragTargetsRef.current.filter(function (target) {\n      return rootRef.current && rootRef.current.contains(target);\n    }); // Make sure to remove a target present multiple times only once\n    // (Firefox may fire dragenter/dragleave multiple times on the same element)\n\n    var targetIdx = targets.indexOf(event.target);\n\n    if (targetIdx !== -1) {\n      targets.splice(targetIdx, 1);\n    }\n\n    dragTargetsRef.current = targets;\n\n    if (targets.length > 0) {\n      return;\n    }\n\n    dispatch({\n      type: \"setDraggedFiles\",\n      isDragActive: false,\n      isDragAccept: false,\n      isDragReject: false\n    });\n\n    if (isEvtWithFiles(event) && onDragLeave) {\n      onDragLeave(event);\n    }\n  }, [rootRef, onDragLeave, noDragEventsBubbling]);\n  var setFiles = useCallback(function (files, event) {\n    var acceptedFiles = [];\n    var fileRejections = [];\n    files.forEach(function (file) {\n      var _fileAccepted = fileAccepted(file, acceptAttr),\n          _fileAccepted2 = _slicedToArray(_fileAccepted, 2),\n          accepted = _fileAccepted2[0],\n          acceptError = _fileAccepted2[1];\n\n      var _fileMatchSize = fileMatchSize(file, minSize, maxSize),\n          _fileMatchSize2 = _slicedToArray(_fileMatchSize, 2),\n          sizeMatch = _fileMatchSize2[0],\n          sizeError = _fileMatchSize2[1];\n\n      var customErrors = validator ? validator(file) : null;\n\n      if (accepted && sizeMatch && !customErrors) {\n        acceptedFiles.push(file);\n      } else {\n        var errors = [acceptError, sizeError];\n\n        if (customErrors) {\n          errors = errors.concat(customErrors);\n        }\n\n        fileRejections.push({\n          file: file,\n          errors: errors.filter(function (e) {\n            return e;\n          })\n        });\n      }\n    });\n\n    if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) {\n      // Reject everything and empty accepted files\n      acceptedFiles.forEach(function (file) {\n        fileRejections.push({\n          file: file,\n          errors: [TOO_MANY_FILES_REJECTION]\n        });\n      });\n      acceptedFiles.splice(0);\n    }\n\n    dispatch({\n      acceptedFiles: acceptedFiles,\n      fileRejections: fileRejections,\n      type: \"setFiles\"\n    });\n\n    if (onDrop) {\n      onDrop(acceptedFiles, fileRejections, event);\n    }\n\n    if (fileRejections.length > 0 && onDropRejected) {\n      onDropRejected(fileRejections, event);\n    }\n\n    if (acceptedFiles.length > 0 && onDropAccepted) {\n      onDropAccepted(acceptedFiles, event);\n    }\n  }, [dispatch, multiple, acceptAttr, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator]);\n  var onDropCb = useCallback(function (event) {\n    event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done\n\n    event.persist();\n    stopPropagation(event);\n    dragTargetsRef.current = [];\n\n    if (isEvtWithFiles(event)) {\n      Promise.resolve(getFilesFromEvent(event)).then(function (files) {\n        if (isPropagationStopped(event) && !noDragEventsBubbling) {\n          return;\n        }\n\n        setFiles(files, event);\n      }).catch(function (e) {\n        return onErrCb(e);\n      });\n    }\n\n    dispatch({\n      type: \"reset\"\n    });\n  }, [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]); // Fn for opening the file dialog programmatically\n\n  var openFileDialog = useCallback(function () {\n    // No point to use FS access APIs if context is not secure\n    // https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#feature_detection\n    if (fsAccessApiWorksRef.current) {\n      dispatch({\n        type: \"openDialog\"\n      });\n      onFileDialogOpenCb(); // https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker\n\n      var opts = {\n        multiple: multiple,\n        types: pickerTypes\n      };\n      window.showOpenFilePicker(opts).then(function (handles) {\n        return getFilesFromEvent(handles);\n      }).then(function (files) {\n        setFiles(files, null);\n        dispatch({\n          type: \"closeDialog\"\n        });\n      }).catch(function (e) {\n        // AbortError means the user canceled\n        if (isAbort(e)) {\n          onFileDialogCancelCb(e);\n          dispatch({\n            type: \"closeDialog\"\n          });\n        } else if (isSecurityError(e)) {\n          fsAccessApiWorksRef.current = false; // CORS, so cannot use this API\n          // Try using the input\n\n          if (inputRef.current) {\n            inputRef.current.value = null;\n            inputRef.current.click();\n          } else {\n            onErrCb(new Error(\"Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided.\"));\n          }\n        } else {\n          onErrCb(e);\n        }\n      });\n      return;\n    }\n\n    if (inputRef.current) {\n      dispatch({\n        type: \"openDialog\"\n      });\n      onFileDialogOpenCb();\n      inputRef.current.value = null;\n      inputRef.current.click();\n    }\n  }, [dispatch, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, onErrCb, pickerTypes, multiple]); // Cb to open the file dialog when SPACE/ENTER occurs on the dropzone\n\n  var onKeyDownCb = useCallback(function (event) {\n    // Ignore keyboard events bubbling up the DOM tree\n    if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {\n      return;\n    }\n\n    if (event.key === \" \" || event.key === \"Enter\" || event.keyCode === 32 || event.keyCode === 13) {\n      event.preventDefault();\n      openFileDialog();\n    }\n  }, [rootRef, openFileDialog]); // Update focus state for the dropzone\n\n  var onFocusCb = useCallback(function () {\n    dispatch({\n      type: \"focus\"\n    });\n  }, []);\n  var onBlurCb = useCallback(function () {\n    dispatch({\n      type: \"blur\"\n    });\n  }, []); // Cb to open the file dialog when click occurs on the dropzone\n\n  var onClickCb = useCallback(function () {\n    if (noClick) {\n      return;\n    } // In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout()\n    // to ensure React can handle state changes\n    // See: https://github.com/react-dropzone/react-dropzone/issues/450\n\n\n    if (isIeOrEdge()) {\n      setTimeout(openFileDialog, 0);\n    } else {\n      openFileDialog();\n    }\n  }, [noClick, openFileDialog]);\n\n  var composeHandler = function composeHandler(fn) {\n    return disabled ? null : fn;\n  };\n\n  var composeKeyboardHandler = function composeKeyboardHandler(fn) {\n    return noKeyboard ? null : composeHandler(fn);\n  };\n\n  var composeDragHandler = function composeDragHandler(fn) {\n    return noDrag ? null : composeHandler(fn);\n  };\n\n  var stopPropagation = function stopPropagation(event) {\n    if (noDragEventsBubbling) {\n      event.stopPropagation();\n    }\n  };\n\n  var getRootProps = useMemo(function () {\n    return function () {\n      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n          _ref2$refKey = _ref2.refKey,\n          refKey = _ref2$refKey === void 0 ? \"ref\" : _ref2$refKey,\n          role = _ref2.role,\n          onKeyDown = _ref2.onKeyDown,\n          onFocus = _ref2.onFocus,\n          onBlur = _ref2.onBlur,\n          onClick = _ref2.onClick,\n          onDragEnter = _ref2.onDragEnter,\n          onDragOver = _ref2.onDragOver,\n          onDragLeave = _ref2.onDragLeave,\n          onDrop = _ref2.onDrop,\n          rest = _objectWithoutProperties(_ref2, _excluded3);\n\n      return _objectSpread(_objectSpread(_defineProperty({\n        onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)),\n        onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)),\n        onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),\n        onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),\n        onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter, onDragEnterCb)),\n        onDragOver: composeDragHandler(composeEventHandlers(onDragOver, onDragOverCb)),\n        onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave, onDragLeaveCb)),\n        onDrop: composeDragHandler(composeEventHandlers(onDrop, onDropCb)),\n        role: typeof role === \"string\" && role !== \"\" ? role : \"presentation\"\n      }, refKey, rootRef), !disabled && !noKeyboard ? {\n        tabIndex: 0\n      } : {}), rest);\n    };\n  }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]);\n  var onInputElementClick = useCallback(function (event) {\n    event.stopPropagation();\n  }, []);\n  var getInputProps = useMemo(function () {\n    return function () {\n      var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n          _ref3$refKey = _ref3.refKey,\n          refKey = _ref3$refKey === void 0 ? \"ref\" : _ref3$refKey,\n          onChange = _ref3.onChange,\n          onClick = _ref3.onClick,\n          rest = _objectWithoutProperties(_ref3, _excluded4);\n\n      var inputProps = _defineProperty({\n        accept: acceptAttr,\n        multiple: multiple,\n        type: \"file\",\n        style: {\n          border: 0,\n          clip: \"rect(0, 0, 0, 0)\",\n          clipPath: \"inset(50%)\",\n          height: \"1px\",\n          margin: \"0 -1px -1px 0\",\n          overflow: \"hidden\",\n          padding: 0,\n          position: \"absolute\",\n          width: \"1px\",\n          whiteSpace: \"nowrap\"\n        },\n        onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),\n        onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)),\n        tabIndex: -1\n      }, refKey, inputRef);\n\n      return _objectSpread(_objectSpread({}, inputProps), rest);\n    };\n  }, [inputRef, accept, multiple, onDropCb, disabled]);\n  return _objectSpread(_objectSpread({}, state), {}, {\n    isFocused: isFocused && !disabled,\n    getRootProps: getRootProps,\n    getInputProps: getInputProps,\n    rootRef: rootRef,\n    inputRef: inputRef,\n    open: composeHandler(openFileDialog)\n  });\n}\n/**\n * @param {DropzoneState} state\n * @param {{type: string} & DropzoneState} action\n * @returns {DropzoneState}\n */\n\nfunction reducer(state, action) {\n  /* istanbul ignore next */\n  switch (action.type) {\n    case \"focus\":\n      return _objectSpread(_objectSpread({}, state), {}, {\n        isFocused: true\n      });\n\n    case \"blur\":\n      return _objectSpread(_objectSpread({}, state), {}, {\n        isFocused: false\n      });\n\n    case \"openDialog\":\n      return _objectSpread(_objectSpread({}, initialState), {}, {\n        isFileDialogActive: true\n      });\n\n    case \"closeDialog\":\n      return _objectSpread(_objectSpread({}, state), {}, {\n        isFileDialogActive: false\n      });\n\n    case \"setDraggedFiles\":\n      return _objectSpread(_objectSpread({}, state), {}, {\n        isDragActive: action.isDragActive,\n        isDragAccept: action.isDragAccept,\n        isDragReject: action.isDragReject\n      });\n\n    case \"setFiles\":\n      return _objectSpread(_objectSpread({}, state), {}, {\n        acceptedFiles: action.acceptedFiles,\n        fileRejections: action.fileRejections,\n        isDragReject: false\n      });\n\n    case \"setDragGlobal\":\n      return _objectSpread(_objectSpread({}, state), {}, {\n        isDragGlobal: action.isDragGlobal\n      });\n\n    case \"reset\":\n      return _objectSpread({}, initialState);\n\n    default:\n      return state;\n  }\n}\n\nfunction noop() {}\n\nexport { ErrorCode } from \"./utils/index.js\";","import React from 'react';\nimport type { UploadedFile } from './FileUploader.types';\nimport {\n    XMarkIcon,\n    ArrowPathIcon,\n    DocumentIcon,\n    PhotoIcon,\n    FilmIcon,\n    MusicalNoteIcon\n} from '@heroicons/react/24/outline'; // Start with Heroicons as they are likely available or use Lucide if preferred\n\ninterface FilePreviewProps {\n    file: UploadedFile;\n    onRemove: (id: string) => void;\n    disabled?: boolean;\n    dictionary?: {\n        errorUploading?: string;\n        retryTooltip?: string;\n        uploadingCancel?: string;\n        remove?: string;\n    };\n}\n\nexport const FilePreview: React.FC<FilePreviewProps> = ({\n    file,\n    onRemove,\n    disabled = false,\n    dictionary = {},\n}) => {\n    const isImage = file.type?.startsWith('image/');\n\n    // Helper to get icon based on file type\n    const getFileIcon = () => {\n        if (isImage) return <PhotoIcon className=\"w-8 h-8 text-gray-400\" />;\n        if (file.type?.startsWith('video/')) return <FilmIcon className=\"w-8 h-8 text-gray-400\" />;\n        if (file.type?.startsWith('audio/')) return <MusicalNoteIcon className=\"w-8 h-8 text-gray-400\" />;\n        return <DocumentIcon className=\"w-8 h-8 text-gray-400\" />;\n    };\n\n    return (\n        <div className={`\n            relative flex items-center p-3 rounded-lg border\n            ${file.status === 'error' ? 'border-error-border bg-error-bg' : 'border-border-primary dark:border-dark-border-primary bg-bg-primary dark:bg-dark-bg-secondary'}\n            transition-all duration-200\n        `}>\n            {/* Thumbnail / Icon */}\n            <div className=\"flex-shrink-0 w-12 h-12 rounded-md overflow-hidden bg-gray-100 dark:bg-gray-800 flex items-center justify-center mr-4\">\n                {isImage && file.preview ? (\n                    <img\n                        src={file.preview}\n                        alt={file.name}\n                        className=\"w-full h-full object-cover\"\n                    />\n                ) : (\n                    getFileIcon()\n                )}\n            </div>\n\n            {/* Content */}\n            <div className=\"flex-1 min-w-0 mr-4\">\n                <div className=\"flex justify-between items-start mb-1\">\n                    <p className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary truncate max-w-[80%]\">\n                        {file.name}\n                    </p>\n                    <span className=\"text-xs text-content-tertiary dark:text-dark-content-tertiary whitespace-nowrap ml-2\">\n                        {(file.size ? (file.size / 1024 / 1024).toFixed(2) : 0)} MB\n                    </span>\n                </div>\n\n                {/* Status Bar / Error Message */}\n                {file.status === 'error' ? (\n                    <p className=\"text-xs text-error-content font-medium\">\n                        {file.error || dictionary.errorUploading || 'Error al subir'}\n                    </p>\n                ) : (\n                    <div className=\"w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5 mt-2\">\n                        <div\n                            className={`h-1.5 rounded-full transition-all duration-300 ${file.status === 'completed'\n                                ? 'bg-green-500'\n                                : 'bg-primary-500'\n                                }`}\n                            style={{ width: `${file.progress}%` }}\n                        />\n                    </div>\n                )}\n            </div>\n\n            {/* Actions */}\n            <div className=\"flex items-center space-x-2\">\n                {/* Retry Button (only on error) */}\n                {file.status === 'error' && !disabled && (\n                    <button\n                        onClick={(e) => {\n                            e.stopPropagation();\n                            // Logic for retry could be handled by parent if we expose onRetry\n                            // For now, removing is the default action\n                            onRemove(file.id);\n                        }}\n                        className=\"p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 transition-colors\"\n                        title={dictionary.retryTooltip || \"Reintentar (Eliminar y volver a agregar)\"}\n                    >\n                        <ArrowPathIcon className=\"w-5 h-5\" />\n                    </button>\n                )}\n\n                {/* Cancel / Remove Button */}\n                {!disabled && (\n                    <button\n                        onClick={(e) => {\n                            e.stopPropagation();\n                            onRemove(file.id);\n                        }}\n                        className=\"p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 hover:text-red-500 transition-colors\"\n                        title={file.status === 'uploading' ? (dictionary.uploadingCancel || 'Cancelar subida') : (dictionary.remove || 'Eliminar')}\n                    >\n                        <XMarkIcon className=\"w-5 h-5\" />\n                    </button>\n                )}\n            </div>\n        </div>\n    );\n};\n","import React, { useState, useCallback, useEffect } from 'react';\nimport { useDropzone } from 'react-dropzone';\nimport type { FileRejection, DropEvent } from 'react-dropzone';\nimport type { FileUploaderProps, UploadedFile } from './FileUploader.types';\nimport { FilePreview } from './FilePreview';\nimport { CloudArrowUpIcon } from './icons';\n\nexport const FileUploader: React.FC<FileUploaderProps> = ({\n    accept,\n    maxSize = 5 * 1024 * 1024, // 5MB default\n    multiple = true,\n    uploadFunction,\n    initialFiles = [],\n    variant = 'dropzone', // Sent to style logic if needed later\n    autoUpload = true,\n    errorMessages,\n    label = 'Arrastra y suelta archivos aquí',\n    subLabel = 'o haz clic para explorar',\n    onFilesChange,\n    className = '',\n    disabled = false,\n    dictionary = {},\n    showValidationHints = true,\n    icon,\n    classNames = {},\n}) => {\n    const [files, setFiles] = useState<UploadedFile[]>(\n        initialFiles.map((f) => ({ ...f, status: 'completed', progress: 100 }))\n    );\n\n    // Get hint text from accept and maxSize\n    const getHintsText = () => {\n        const parts: string[] = [];\n        \n        if (accept) {\n            if (typeof accept === 'string') {\n                parts.push(accept.replace(/\\./g, '').toUpperCase());\n            } else {\n                const extensions = Object.values(accept).flat().map(ext => ext.replace('.', '').toUpperCase());\n                parts.push(Array.from(new Set(extensions)).join(', '));\n            }\n        }\n\n        if (maxSize) {\n            const mb = maxSize / (1024 * 1024);\n            parts.push(`hasta ${mb.toFixed(0)}MB`);\n        }\n\n        return parts.join(' ');\n    };\n\n    // Notify parent when files change\n    useEffect(() => {\n        if (onFilesChange) {\n            onFilesChange(files);\n        }\n    }, [files, onFilesChange]);\n\n    const onDrop = useCallback(\n        (acceptedFiles: File[]) => {\n            if (disabled) return;\n\n            const newFiles: UploadedFile[] = acceptedFiles.map((file) => ({\n                id: Math.random().toString(36).substr(2, 9),\n                file,\n                name: file.name,\n                size: file.size,\n                type: file.type,\n                status: 'pending',\n                progress: 0,\n                preview: file.type.startsWith('image/')\n                    ? URL.createObjectURL(file)\n                    : undefined,\n            }));\n\n            setFiles((prev) => [...prev, ...newFiles]);\n\n            if (autoUpload) {\n                // Trigger upload for each new file immediately\n                newFiles.forEach((fileWrapper) => {\n                    uploadFile(fileWrapper);\n                });\n            }\n        },\n        [disabled, uploadFunction, autoUpload]\n    );\n\n    const uploadFile = async (fileWrapper: UploadedFile) => {\n        if (!fileWrapper.file) return;\n\n        setFiles((prev) =>\n            prev.map((f) =>\n                f.id === fileWrapper.id ? { ...f, status: 'uploading' } : f\n            )\n        );\n\n        try {\n            const result = await uploadFunction(fileWrapper.file, (progress) => {\n                setFiles((prev) =>\n                    prev.map((f) =>\n                        f.id === fileWrapper.id ? { ...f, progress } : f\n                    )\n                );\n            });\n\n            const url = typeof result === 'string' ? result : result.url;\n\n            setFiles((prev) =>\n                prev.map((f) =>\n                    f.id === fileWrapper.id\n                        ? { ...f, status: 'completed', progress: 100, url }\n                        : f\n                )\n            );\n        } catch (error) {\n            console.error('Upload failed:', error);\n            setFiles((prev) =>\n                prev.map((f) =>\n                    f.id === fileWrapper.id\n                        ? { ...f, status: 'error', error: dictionary.uploadFailed || 'Error al subir' }\n                        : f\n                )\n            );\n        }\n    };\n\n    const uploadPendingFiles = () => {\n        const pendingFiles = files.filter(f => f.status === 'pending');\n        pendingFiles.forEach(f => uploadFile(f));\n    };\n\n    const removeFile = (id: string) => {\n        const fileToRemove = files.find(f => f.id === id);\n        // If we implemented AbortController, we would call abort() here if status is 'uploading'\n        setFiles((prev) => prev.filter((f) => f.id !== id));\n    };\n\n    const { getRootProps, getInputProps, isDragActive, fileRejections } = useDropzone({\n        onDrop,\n        accept: accept as any, // Type cast for dropzone compatibility\n        maxSize,\n        multiple,\n        disabled,\n    });\n\n    // Validations: fileRejections (from react-dropzone)\n    const fileRejectionItems = fileRejections.map(({ file, errors }) => (\n        <div key={file.name} className=\"mt-2 text-sm text-error-content bg-error-bg p-2 rounded\">\n            <strong>{file.name}</strong> {dictionary.hasErrors || 'tiene errores:'}\n            <ul className=\"list-disc ml-4\">\n                {errors.map((e) => (\n                    <li key={e.code}>\n                        {errorMessages?.[e.code] || e.message}\n                    </li>\n                ))}\n            </ul>\n        </div>\n    ));\n\n    const hasPendingFiles = files.some(f => f.status === 'pending');\n\n    return (\n        <div className={`w-full ${className}`}>\n            {/* Dropzone Area */}\n            <div\n                {...getRootProps()}\n                className={`\n          relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer\n          ${isDragActive\n                        ? (classNames.dropzoneActive || 'border-primary-500 bg-primary-50 dark:bg-primary-900/20')\n                        : (classNames.dropzoneInactive || 'border-border-secondary dark:border-dark-border-secondary hover:border-primary-400 dark:hover:border-primary-400')\n                    }\n          ${disabled ? 'opacity-50 cursor-not-allowed' : ''}\n          bg-bg-primary dark:bg-dark-bg-primary\n        `}\n            >\n                <input {...getInputProps()} />\n\n                <div className=\"flex flex-col items-center justify-center space-y-3\">\n                    <div className=\"p-3 bg-bg-secondary dark:bg-dark-bg-tertiary rounded-full\">\n                        {icon ? (\n                            icon\n                        ) : (\n                            <CloudArrowUpIcon className=\"w-8 h-8 text-primary-600 dark:text-primary-400\" />\n                        )}\n                    </div>\n                    <div>\n                        <p className=\"text-lg font-medium text-content-primary dark:text-dark-content-primary\">\n                            {label}\n                        </p>\n                        <p className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary mt-1\">\n                            {subLabel}\n                        </p>\n                        {showValidationHints && (\n                            <p className=\"text-[11px] font-normal text-content-tertiary dark:text-dark-content-tertiary mt-2 uppercase tracking-wider\">\n                                {getHintsText()}\n                            </p>\n                        )}\n                    </div>\n                </div>\n            </div>\n\n            {/* Error Messages for Rejected Files */}\n            {fileRejectionItems.length > 0 && (\n                <div className=\"mt-4\">\n                    {fileRejectionItems}\n                </div>\n            )}\n\n            {/* File List - Ocultar si autoUpload es true según requerimiento */}\n            {!autoUpload && files.length > 0 && (\n                <div className=\"mt-6 space-y-3\">\n                    {files.map((file) => (\n                        <FilePreview\n                            key={file.id}\n                            file={file}\n                            onRemove={removeFile}\n                            disabled={disabled}\n                            dictionary={dictionary}\n                        />\n                    ))}\n                </div>\n            )}\n\n            {/* Manual Upload Action */}\n            {!autoUpload && hasPendingFiles && (\n                <div className=\"mt-6 flex justify-end\">\n                    <button\n                        onClick={uploadPendingFiles}\n                        className={`px-4 py-2 rounded-md font-medium transition-colors shadow-sm flex items-center ${classNames.submitButton || 'bg-primary-600 hover:bg-primary-700 text-white'}`}\n                    >\n                        {icon ? icon : <CloudArrowUpIcon className=\"w-5 h-5 mr-2\" />}\n                        {dictionary.uploadPendingButton \n                            ? dictionary.uploadPendingButton.replace('{count}', files.filter(f => f.status === 'pending').length.toString()) \n                            : `Subir ${files.filter(f => f.status === 'pending').length} archivos pendientes`\n                        }\n                    </button>\n                </div>\n            )}\n        </div>\n    );\n};\n","/**\n * FieldRenderer — resolves inputType and renders the appropriate field component.\n *\n * Wraps in a responsive grid cell based on colSize.\n * Renders readOnly text span in view mode.\n *\n * @module components/form/fields/FieldRenderer\n * @see FMPV-MVWC-E003-S002 I-001\n */\nimport React from 'react';\nimport { Input } from '../../../../Input/Input';\nimport { Textarea } from '../../../../Textarea/Textarea';\nimport { Select } from '../../../../Select/Select';\nimport { LookupField } from '../../../../LookupField/LookupField';\nimport { interpolateTemplate } from '../../../../LookupField/utils';\nimport { MasterPatternViewCreateForm } from '../../MasterPatternViewCreateForm';\nimport type { MasterPatternViewEntity, MasterPatternViewCompany } from '../../../types/service.types';\nimport { FileUploader } from '../../../../FileUploader/FileUploader';\nimport type { UploadedFile } from '../../../../FileUploader/FileUploader.types';\nimport { Switch } from '../../../../Switch/Switch';\nimport { AlertTriangle } from 'lucide-react';\nimport { inferInputType, computeColSpanClass } from '../../../engine/fieldEngine';\nimport { isActionAllowed } from '../../../engine/permissionEngine';\nimport type { MasterPatternViewFieldDefinition, MasterPatternViewFileConfig } from '../../../types/definition.types';\n\ntype InitialFile = { id: string; url: string; name: string; size?: number; type?: string };\nconst EMPTY_FILES: InitialFile[] = [];\n\n/**\n * Suffix for the shadow form field that mirrors a lookup's resolved label alongside its\n * `Id` — MasterPatternView.tsx's \"Campos modificados\" diff can only show a readable value\n * for a lookup selection made in the current session (rather than the raw guid) by reading\n * this, since a freshly-picked record isn't joined with display columns the way a persisted\n * row from the API is.\n */\nexport const LOOKUP_DISPLAY_FIELD_SUFFIX = '__display';\n\n/** Same priority order as LookupField's own internal `getSelectedDisplay` (renderSelected is\n * not part of `MasterPatternViewLookupConfig`, so it's not in this priority list). */\nfunction getLookupSelectedDisplay(\n  cfg: { displayTemplate?: string; displayValue?: string; displayFields: string[] },\n  record: Record<string, unknown>,\n): string {\n  if (cfg.displayTemplate) return interpolateTemplate(cfg.displayTemplate, record);\n  if (cfg.displayValue) {\n    const v = record[cfg.displayValue];\n    return v !== undefined && v !== null ? String(v) : '';\n  }\n  return cfg.displayFields\n    .map((f) => {\n      const v = record[f];\n      return v !== undefined && v !== null ? String(v) : '';\n    })\n    .join(' - ');\n}\n\n/**\n * Stable wrapper for FileUploader that avoids infinite re-render loops.\n * The initialFiles prop is memoized, and onFilesChange skips no-op updates.\n */\nfunction FileField({ field, value, onChange, isDisabled, cfg }: {\n  field: MasterPatternViewFieldDefinition;\n  value: unknown;\n  onChange: (v: unknown) => void;\n  isDisabled: boolean;\n  cfg: MasterPatternViewFileConfig;\n}) {\n  const initialFiles = React.useMemo((): InitialFile[] => {\n    if (Array.isArray(value) && value.length > 0) {\n      return value as InitialFile[];\n    }\n    return EMPTY_FILES;\n  }, [value]);\n\n  const handleFilesChange = React.useCallback((files: UploadedFile[]) => {\n    // Only propagate when files actually changed (has completed uploads or was cleared)\n    const completed = files.filter(f => f.status === 'completed' || (f as { id?: string }).id);\n    if (completed.length > 0 || (Array.isArray(value) && (value as unknown[]).length > 0 && files.length === 0)) {\n      onChange(files);\n    }\n  }, [onChange, value]);\n\n  // Use compact padding override when field has rowSpan (image beside short inputs)\n  const compactClass = field.rowSpan ? '[&>div]:p-3 [&>div]:space-y-1' : undefined;\n\n  return (\n    <FileUploader\n      data-testid={`field-input-${field.fieldName}`}\n      uploadFunction={cfg.uploadFunction}\n      accept={cfg.accept}\n      maxSize={cfg.maxSize}\n      multiple={cfg.multiple}\n      variant={cfg.variant}\n      autoUpload={cfg.autoUpload}\n      initialFiles={initialFiles}\n      onFilesChange={handleFilesChange}\n      disabled={isDisabled}\n      className={compactClass}\n    />\n  );\n}\n\nexport interface FieldRendererProps {\n  field: MasterPatternViewFieldDefinition;\n  value: unknown;\n  onChange: (value: unknown) => void;\n  error?: string;\n  disabled?: boolean;\n  readOnly?: boolean;\n  /** All current form values — passed to renderFormField for derived/computed fields */\n  allValues?: Record<string, unknown>;\n  /** Current form mode — passed as context to renderFormField */\n  formMode?: 'create' | 'edit' | 'view';\n  /** Multi-field setter forwarded to lookupConfig.onFormSelect for cascade updates */\n  setFormValue?: (field: string, value: unknown) => void;\n  /** This form's own company list — forwarded to a same-repo lookup's inline \"create new\" (`cfg.create`) so the child master's company selector starts seeded instead of always defaulting to Global. */\n  companies?: MasterPatternViewCompany[];\n  /** This form's own currently active company (undefined/'global' when in global context) — same forwarding as `companies`. */\n  activeCompanyId?: string | null;\n}\n\nexport function FieldRenderer({\n  field,\n  value,\n  onChange,\n  error,\n  disabled = false,\n  readOnly = false,\n  allValues = {},\n  formMode,\n  setFormValue,\n  companies,\n  activeCompanyId,\n}: FieldRendererProps) {\n  const inputType = field.inputType ?? inferInputType(field);\n  const colSpanClass = computeColSpanClass(field);\n  const rowSpanClass = field.rowSpan && field.rowSpan > 1 ? `row-span-${field.rowSpan}` : '';\n  const strValue = value !== null && value !== undefined ? String(value) : '';\n\n  // Memoize select options to avoid passing a new array reference on every render,\n  // which would defeat Select's internal stability guarantees.\n  const selectOptions = React.useMemo(\n    () => (field.options ?? []).map((o) => ({ value: o.value, label: o.label })),\n    [field.options]\n  );\n\n  const label = (\n    <label className=\"block text-sm font-bold text-content-primary dark:text-dark-content-primary mb-2 leading-5\" data-testid={`field-label-${field.fieldName}`}>\n      {field.label}\n      {field.isRequired && <span className=\"text-red-500 ml-1\">*</span>}\n    </label>\n  );\n\n  const errorEl = error ? (\n    <p className=\"flex items-center gap-[3px] text-xs text-[#dc2626] mt-1\" data-testid={`field-error-${field.fieldName}`}>\n      <AlertTriangle size={11} className=\"flex-shrink-0\" />\n      {error}\n    </p>\n  ) : null;\n\n  // In readOnly mode fields are rendered as disabled controls (identical layout to edit mode)\n  const isDisabled = disabled || readOnly;\n\n  // renderFormField escape hatch — consumer controls the entire input element\n  if (field.renderFormField) {\n    const resolvedMode = formMode ?? (readOnly ? 'view' : 'edit');\n    return (\n      <div data-testid={`field-wrapper-${field.fieldName}`} className={`${colSpanClass} ${rowSpanClass}`.trim()}>\n        {label}\n        {field.renderFormField(value, onChange, allValues, { readOnly, mode: resolvedMode })}\n        {errorEl}\n      </div>\n    );\n  }\n\n  let inputEl: React.ReactNode;\n\n  switch (inputType) {\n    case 'boolean': {\n      // Single toggle pill below the shared bold label (like every other field), instead of the\n      // old two-button Sí/No segmented control. If field has custom `options`, show the current\n      // state's label next to the switch instead of a second button.\n      const hasCustomLabels = field.options && field.options.length >= 2;\n      const trueLabel = hasCustomLabels ? field.options![0].label : null;\n      const falseLabel = hasCustomLabels ? field.options![1].label : null;\n      inputEl = (\n        <div className=\"flex items-center gap-2 h-10\" data-testid={`field-input-${field.fieldName}`}>\n          <Switch\n            checked={value === true}\n            onCheckedChange={(checked) => !isDisabled && onChange(checked)}\n            disabled={isDisabled}\n            data-testid={`field-bool-switch-${field.fieldName}`}\n          />\n          {hasCustomLabels && (\n            <span className=\"text-sm text-content-primary dark:text-dark-content-primary\">\n              {value === true ? trueLabel : falseLabel}\n            </span>\n          )}\n        </div>\n      );\n      break;\n    }\n\n    case 'select':\n      inputEl = (\n        <Select\n          data-testid={`field-input-${field.fieldName}`}\n          options={selectOptions}\n          value={value as string | number}\n          onChange={onChange as (v: string | number) => void}\n          disabled={isDisabled}\n          selectSize=\"sm\"\n        />\n      );\n      break;\n\n    case 'textarea':\n      inputEl = (\n        <Textarea\n          data-testid={`field-input-${field.fieldName}`}\n          value={strValue}\n          onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => onChange(e.target.value)}\n          disabled={isDisabled}\n          fullWidth\n        />\n      );\n      break;\n\n    case 'date':\n      inputEl = (\n        <input\n          type=\"date\"\n          data-testid={`field-input-${field.fieldName}`}\n          value={strValue}\n          onChange={(e) => onChange(e.target.value)}\n          disabled={isDisabled}\n          className=\"w-full border border-border-primary dark:border-dark-border-primary rounded px-2 py-1 text-sm disabled:bg-background-secondary dark:disabled:bg-dark-bg-secondary disabled:text-content-tertiary dark:disabled:text-dark-content-tertiary disabled:cursor-not-allowed\"\n        />\n      );\n      break;\n\n    case 'number':\n    case 'decimal':\n      inputEl = (\n        <Input\n          type=\"number\"\n          data-testid={`field-input-${field.fieldName}`}\n          value={strValue}\n          step={inputType === 'decimal' ? 'any' : '1'}\n          onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(inputType === 'decimal' ? parseFloat(e.target.value) : parseInt(e.target.value, 10))}\n          disabled={isDisabled}\n        />\n      );\n      break;\n\n    case 'lookup': {\n      const cfg = field.lookupConfig;\n      if (!cfg) {\n        inputEl = (\n          <Input\n            data-testid={`field-input-${field.fieldName}`}\n            value=\"[lookupConfig required]\"\n            disabled\n          />\n        );\n      } else {\n        inputEl = (\n          <LookupField\n            // Hides LookupField's own internal empty label — the label above (rendered by\n            // this form) already shows the field name, and the empty one still takes up\n            // ~20px (display:block by design), pushing the trigger down and misaligning it\n            // against sibling fields in the same row.\n            className=\"lookup-field--label-hidden\"\n            data-testid={`field-input-${field.fieldName}`}\n            entity={cfg.entity}\n            fetcher={cfg.fetcher}\n            displayFields={cfg.displayFields}\n            bindFields={cfg.bindFields}\n            displayTemplate={cfg.displayTemplate}\n            displayValue={cfg.displayValue}\n            filters={cfg.getFilters ? cfg.getFilters(allValues) : cfg.filters}\n            minChars={cfg.minChars}\n            value={strValue || null}\n            onChange={(rec, prevRec) => {\n              onChange(rec?.Id ?? null);\n              setFormValue?.(\n                `${field.fieldName}${LOOKUP_DISPLAY_FIELD_SUFFIX}`,\n                rec ? getLookupSelectedDisplay(cfg, rec) : null,\n              );\n              if (cfg.onFormSelect && setFormValue) {\n                cfg.onFormSelect(rec ?? null, setFormValue, {\n                  previousRecord: prevRec ?? null,\n                  revert: () => {\n                    onChange(prevRec?.Id ?? null);\n                    setFormValue(\n                      `${field.fieldName}${LOOKUP_DISPLAY_FIELD_SUFFIX}`,\n                      prevRec ? getLookupSelectedDisplay(cfg, prevRec) : null,\n                    );\n                  },\n                });\n              }\n            }}\n            readOnly={readOnly}\n            disabled={disabled}\n            // Do NOT pass required — the label above already renders the asterisk.\n            // Passing required here causes LookupField to render a second asterisk.\n            createVariant={cfg.create?.variant}\n            // No `.definition.name` fallback here on purpose: `useDefinition` must never\n            // be called outside of MasterPatternViewCreateForm's own render (see its doc\n            // comment) — calling it here, still inside the outer field's render, would\n            // reintroduce the exact self-referencing-lookup recursion this design avoids.\n            // Omit `title`/`entityName` and LookupField falls back to a generic label.\n            createTitle={cfg.create?.title ?? cfg.create?.entityName}\n            createButtonLabel={cfg.create?.buttonLabel}\n            // Default width is always 80% of the viewport for modal creates — a fixed,\n            // consistent footprint across every master. Height is NOT fixed the same way:\n            // it's a CAP (80vh) that the popup only grows into if the content needs it —\n            // CreatePopup treats `height` as max-height only, so a 3-field master shrinks\n            // to fit while a many-tab master can use the full 80vh. Sidebar keeps its own\n            // compact width default (edge-panel, not meant to span most of the screen).\n            createWidth={cfg.create?.width ?? (cfg.create?.variant === 'sidebar' ? undefined : '80vw')}\n            createHeight={cfg.create?.height ?? (cfg.create?.variant === 'sidebar' ? undefined : '80vh')}\n            createIcon={cfg.create?.icon}\n            // Gated by the CHILD entity's own `cfg.create.permissions` (e.g. Teléfono's\n            // canCreate), never by this field's own master's permissions — see the doc\n            // comment on `create.permissions`. Defaults to allowed when omitted, same as\n            // every other permission check in the kit.\n            showCreateButton={\n              cfg.create?.showCreateButton === false\n                ? false\n                : isActionAllowed(cfg.create?.permissions, 'CREATE', 'UNIVERSAL')\n            }\n            // MasterPatternViewCreateForm renders its own complete header (title,\n            // Cancelar/Guardar, \"Creando\" badge) — the popup's own title bar would just\n            // duplicate it. The cross-repo `onCreateNew` escape hatch below usually owns\n            // none of that itself, so it defaults to the native header (with createTitle)\n            // instead — explicit `true`/`false` here rather than leaning on LookupField's\n            // own default, since that default is about ITS assumption (a same-repo\n            // MasterPatternViewCreateForm-shaped consumer), not this cross-repo one.\n            // `create.showHeader` still lets either path override the default, e.g. for\n            // an onCreateNew render function that DOES bring its own header.\n            createShowHeader={\n              cfg.create?.showHeader !== undefined\n                ? cfg.create.showHeader\n                : cfg.create?.onCreateNew\n                  ? true\n                  : false\n            }\n            onCreateNew={\n              cfg.create?.onCreateNew\n                // Cross-repo / fully custom path — same-repo useDefinition+service can't\n                // reach a target master that lives in a different build, so this passes\n                // straight through to LookupField's own generic onCreateNew contract.\n                ? cfg.create.onCreateNew\n                // Gate the local fallback on `useDefinition` specifically, NOT on `cfg.create`\n                // being truthy — a consumer using the cross-repo `onCreateNew` escape hatch\n                // never sets `useDefinition` (see its doc comment: \"omit useDefinition/service\n                // in that case\"), so when that escape hatch resolves to `undefined` (e.g. a\n                // host-side kill switch temporarily disabling nested creation), `cfg.create`\n                // itself is still a truthy object — falling back to this same-repo form here\n                // would try to mount MasterPatternViewCreateForm with `useDefinition`/`service`\n                // both undefined, and — because the arrow function below is unconditionally\n                // truthy — would keep showing LookupField's \"+\" button even though creation was\n                // just explicitly turned off. Only ever fall back here when the consumer\n                // genuinely opted into the same-repo path.\n                : cfg.create?.useDefinition\n                  ? ({ onCreated, onCancel }) => (\n                      <MasterPatternViewCreateForm<MasterPatternViewEntity>\n                        useDefinition={cfg.create!.useDefinition!}\n                        service={cfg.create!.service!}\n                        entityName={cfg.create!.entityName}\n                        permissions={cfg.create!.permissions}\n                        // Wear the same background/shadow/radius as the master's own\n                        // ModalPanel/SidebarPanel, so the popup shows it exactly like the\n                        // real create modal/sidebar instead of a foreign popup shell.\n                        chrome={cfg.create!.variant ?? 'modal'}\n                        // This IS the one call site that wants the child's company locked\n                        // by default: the record being created here belongs to THIS\n                        // field's parent record's company, not to whatever the child\n                        // master's own create form would otherwise default to (its own\n                        // companies[0], which reads as \"Global\" to the user). Only locks\n                        // when the parent itself is actually scoped to a specific company —\n                        // a parent still in Global context has nothing specific to lock to,\n                        // so the child's selector stays open in that case.\n                        companies={companies}\n                        defaultCompany={companies?.find((c) => c.id === activeCompanyId)}\n                        companyLocked={!!activeCompanyId}\n                        onCancel={onCancel}\n                        onCreated={(record) => {\n                          // Bridge casing conventions: MasterPatternViewService records use\n                          // camelCase `id` (MasterPatternViewEntity), but LookupField's own\n                          // selection contract needs PascalCase `Id` (LookupRecord) to work —\n                          // alias it on without touching any other field.\n                          const asLookupRecord = {\n                            ...(record as unknown as Record<string, unknown>),\n                            Id: String((record as unknown as Record<string, unknown>).id),\n                          };\n                          // service.create()'s response is shaped by this master's own API,\n                          // which can (and often does) differ from what THIS lookup's own\n                          // search `fetcher` returns for the same entity — e.g. a reverse\n                          // cascade `onFormSelect` reading `rec.CountryID`/`rec.StateID`\n                          // (fields the search fetcher injects) would silently get\n                          // `undefined` from the raw create response, so the dependent\n                          // fields it's meant to fill never activate. Re-fetch by Id through\n                          // the same fetcher used for search, so the just-created record\n                          // reaches `onCreated`/`onFormSelect` in the exact same shape as one\n                          // picked from the dropdown — falling back to the bridged create\n                          // response only if that lookup fails (e.g. read-after-write lag).\n                          cfg\n                            .fetcher(cfg.entity, {\n                              fields: [...new Set(['Id', ...cfg.displayFields, ...(cfg.bindFields ?? [])])],\n                              filters: [[{ Id: asLookupRecord.Id as string }]],\n                              page: 1,\n                              pageSize: 1,\n                            })\n                            .then((response) => {\n                              const fetched = response.data[0] as Record<string, unknown> | undefined;\n                              onCreated(fetched ? { ...fetched, Id: asLookupRecord.Id } : asLookupRecord);\n                            })\n                            .catch(() => onCreated(asLookupRecord));\n                        }}\n                      />\n                    )\n                  : undefined\n            }\n          />\n        );\n      }\n      break;\n    }\n\n    case 'email':\n    case 'password':\n      inputEl = (\n        <Input\n          data-testid={`field-input-${field.fieldName}`}\n          type={inputType}\n          value={strValue}\n          onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(e.target.value)}\n          readOnly={readOnly}\n          disabled={disabled}\n          required={field.isRequired}\n          maxLength={field.maxLength}\n        />\n      );\n      break;\n\n    case 'file': {\n      const cfg = field.fileConfig;\n      if (!cfg) {\n        inputEl = (\n          <Input\n            data-testid={`field-input-${field.fieldName}`}\n            value=\"[fileConfig required]\"\n            disabled\n          />\n        );\n      } else {\n        inputEl = (\n          <FileField\n            field={field}\n            value={value}\n            onChange={onChange}\n            isDisabled={isDisabled}\n            cfg={cfg}\n          />\n        );\n      }\n      break;\n    }\n\n    default: // 'text'\n      inputEl = (\n        <Input\n          data-testid={`field-input-${field.fieldName}`}\n          value={strValue}\n          onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(e.target.value)}\n          disabled={isDisabled}\n          maxLength={field.maxLength}\n        />\n      );\n  }\n\n  return (\n    <div data-testid={`field-wrapper-${field.fieldName}`} className={`${colSpanClass} ${rowSpanClass}`.trim()}>\n      {label}\n      {inputEl}\n      {errorEl}\n    </div>\n  );\n}\n\n","/**\n * OverridableFieldWrapper — context-aware wrapper for GLOBAL override fields.\n *\n * Rendering rules:\n * - Global context + isOverridable: renders children normally\n * - Global context + isCompanyOnly: returns null (hidden)\n * - Global context + non-overridable: renders children normally\n * - Company context + non-overridable (not isCompanyOnly): shows disabled overlay\n * - Company context + isOverridable: renders children + ↺ revert button + optional global hint\n * - Company context + isCompanyOnly: renders children normally (no revert)\n *\n * Revert button placement:\n * - Selection types (boolean): button rendered inline, immediately right of the component\n * - Text-entry types (input, select, textarea, …): button rendered inside the input on the right\n *\n * @module components/form/fields/OverridableFieldWrapper\n * @see FMPV-MVWC-E004-S004 I-002\n */\nimport React from 'react';\nimport { RotateCcw, Globe } from 'lucide-react';\nimport type { MasterPatternViewInputType } from '../../../types/definition.types';\n\n/** Field types whose value is chosen, not typed — revert btn goes beside them */\nconst SELECTION_TYPES = new Set<MasterPatternViewInputType>(['boolean']);\n\nexport interface OverridableFieldWrapperProps {\n  fieldName: string;\n  isOverridable: boolean;\n  isCompanyOnly: boolean;\n  context: 'global' | 'company';\n  globalValue: unknown;\n  isShowGlobalValuesEnabled: boolean;\n  onRevert: (fieldName: string, globalValue: unknown) => void;\n  children: React.ReactNode;\n  /** Resolved input type — used to decide revert button placement */\n  fieldType: MasterPatternViewInputType;\n  /** Grid cell class (e.g. col-span-6) — must be set when this wrapper is a direct grid child */\n  className?: string;\n}\n\nexport function OverridableFieldWrapper({\n  fieldName,\n  isOverridable,\n  isCompanyOnly,\n  context,\n  globalValue,\n  isShowGlobalValuesEnabled,\n  onRevert,\n  children,\n  fieldType,\n  className = '',\n}: OverridableFieldWrapperProps): React.ReactElement | null {\n  // isCompanyOnly fields are hidden in global context (no global row)\n  if (isCompanyOnly && context === 'global') {\n    return null;\n  }\n\n  // Company context + non-overridable (and not isCompanyOnly): show disabled\n  if (context === 'company' && !isOverridable && !isCompanyOnly) {\n    return (\n      <div data-testid=\"override-field-disabled\" className={`relative opacity-50 pointer-events-none ${className}`.trim()}>\n        {children}\n      </div>\n    );\n  }\n\n  // Company context + isOverridable: children + ↺ button + optional global hint\n  if (context === 'company' && isOverridable) {\n    const isSelection = SELECTION_TYPES.has(fieldType);\n\n    const revertBtn = (\n      <button\n        data-testid=\"override-revert-button\"\n        type=\"button\"\n        title=\"Revertir al valor global\"\n        className=\"flex-shrink-0 text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary cursor-pointer\"\n        onClick={() => onRevert(fieldName, globalValue)}\n      >\n        <RotateCcw size={14} />\n      </button>\n    );\n\n    const hint = isShowGlobalValuesEnabled && globalValue !== undefined && (\n      <span\n        data-testid=\"override-global-value-hint\"\n        className=\"flex items-center gap-1 text-[12px] text-[#1355b7] italic\"\n        style={{ marginTop: 2 }}\n      >\n        <Globe size={11} className=\"flex-shrink-0 text-[#1355b7]\" />\n        Valor global: <strong className=\"font-bold\">{String(globalValue)}</strong>\n      </span>\n    );\n\n    if (isSelection) {\n      // Button sits immediately to the right of the component, aligned at the bottom\n      // (items-end so the button sits level with the control, not the label)\n      return (\n        <div className={`flex flex-col gap-1 ${className}`.trim()}>\n          <div className=\"flex items-end gap-2\">\n            <div>{children}</div>\n            <div className=\"mb-0.5\">{revertBtn}</div>\n          </div>\n          {hint}\n        </div>\n      );\n    }\n\n    // Text-entry types: button is absolutely positioned inside the input on the right.\n    // [&_input]:pr-8 adds right padding to native <input> so text doesn't slide under the icon.\n    return (\n      <div className={`flex flex-col gap-1 ${className}`.trim()}>\n        <div className=\"relative [&_input]:pr-8\">\n          {children}\n          <div className=\"absolute right-2 top-[46px] -translate-y-1/2\">\n            {revertBtn}\n          </div>\n        </div>\n        {hint}\n      </div>\n    );\n  }\n\n  // Global context + isOverridable: render children normally (no extra hint)\n  if (context === 'global' && isOverridable) {\n    return <>{children}</>;\n  }\n\n  // Default: render children as-is (isCompanyOnly in company context, or normal global field)\n  return <>{children}</>;\n}\n","/**\n * BasicDataTab — renders the \"Datos básicos *\" tab fields.\n *\n * Supports two layouts driven by the definition:\n *  1. Sectioned (`definition.sections` present): renders each section with an optional\n *     titled header (icon + label + divider line) followed by the section's fields grid.\n *  2. Flat (`definition.fields` present): backward-compatible flat grid, no section titles.\n *     `headerFields` (code, name, isActive) are rendered first in both layouts.\n *\n * In GLOBAL type with company context, wraps each field in OverridableFieldWrapper.\n *\n * @module components/form/BasicDataTab\n * @see FMPV-MVWC-E003-S001 I-005\n */\nimport React from 'react';\nimport { Globe } from 'lucide-react';\nimport type { MasterPatternViewDefinition, MasterPatternViewFieldDefinition } from '../../types/definition.types';\nimport type { MasterPatternViewCompany } from '../../types/service.types';\nimport { FieldRenderer } from './fields/FieldRenderer';\nimport { OverridableFieldWrapper } from './fields/OverridableFieldWrapper';\nimport { computeColSpanClass, inferInputType } from '../../engine/fieldEngine';\n\nexport interface BasicDataTabProps {\n  definition: MasterPatternViewDefinition;\n  values: Record<string, unknown>;\n  errors: Record<string, string>;\n  onChange: (field: string, value: unknown) => void;\n  headerFields?: string[];\n  readOnly?: boolean;\n  /** 'company' when a specific company is selected; 'global' otherwise */\n  fieldContext?: 'global' | 'company';\n  isShowGlobalValuesEnabled?: boolean;\n  globalValues?: Record<string, unknown>;\n  onFieldRevert?: (fieldName: string, globalValue: unknown) => void;\n  /** Current form mode — forwarded to renderFormField as context */\n  formMode?: 'create' | 'edit' | 'view';\n  /** This form's own company list — forwarded to a lookup field's inline \"create new\" so it can seed the child master's company selector instead of always defaulting to Global. */\n  companies?: MasterPatternViewCompany[];\n  /** This form's own currently active company (undefined/'global' when in global context) — same forwarding as `companies`. */\n  activeCompanyId?: string | null;\n}\n\nconst DEFAULT_HEADER_FIELDS = ['code', 'name', 'isActive'];\n\n/** Renders a single field — either plain or wrapped in OverridableFieldWrapper. */\nfunction renderField(\n  field: MasterPatternViewFieldDefinition,\n  props: BasicDataTabProps,\n  showOverrides: boolean,\n  values: Record<string, unknown>,\n) {\n  const { onChange, errors, readOnly = false, fieldContext, isShowGlobalValuesEnabled = false, globalValues = {}, onFieldRevert, formMode, companies, activeCompanyId } = props;\n\n  const isDisabled = typeof field.disabled === 'function'\n    ? field.disabled(values)\n    : (field.disabled ?? false);\n\n  const renderer = (\n    <FieldRenderer\n      key={field.fieldName}\n      field={field}\n      value={values[field.fieldName]}\n      onChange={(v) => onChange(field.fieldName, v)}\n      error={errors[field.fieldName]}\n      disabled={isDisabled}\n      readOnly={readOnly}\n      allValues={values}\n      formMode={formMode}\n      setFormValue={onChange}\n      companies={companies}\n      activeCompanyId={activeCompanyId}\n    />\n  );\n\n  if (!showOverrides) return renderer;\n\n  return (\n    <OverridableFieldWrapper\n      key={field.fieldName}\n      fieldName={field.fieldName}\n      isOverridable={field.isOverridable ?? false}\n      isCompanyOnly={field.isCompanyOnly ?? false}\n      context={fieldContext!}\n      globalValue={globalValues[field.fieldName]}\n      isShowGlobalValuesEnabled={isShowGlobalValuesEnabled}\n      onRevert={onFieldRevert ?? (() => {})}\n      fieldType={field.inputType ?? inferInputType(field)}\n      className={computeColSpanClass(field)}\n    >\n      {renderer}\n    </OverridableFieldWrapper>\n  );\n}\n\nexport function BasicDataTab(props: BasicDataTabProps) {\n  const {\n    definition,\n    values,\n    headerFields = DEFAULT_HEADER_FIELDS,\n    fieldContext,\n    isShowGlobalValuesEnabled = false,\n  } = props;\n\n  const isGlobal = definition.type === 'GLOBAL';\n  const showOverrides = isGlobal && !!fieldContext;\n  const showNotice = showOverrides && fieldContext === 'company' && isShowGlobalValuesEnabled;\n\n  const noticeBanner = showNotice ? (\n    <div\n      data-testid=\"global-fields-notice\"\n      className=\"mx-5 mt-3 mb-0 bg-[#eff8ff] border border-[#93d1fd] rounded-lg flex items-start gap-2 flex-shrink-0\"\n      style={{ padding: '9px 14px' }}\n    >\n      <Globe size={15} className=\"flex-shrink-0 text-[#0e79fd] mt-px\" />\n      <p className=\"text-[11px] text-[#1355b7] leading-[1.5]\">\n        Los campos deshabilitados corresponden a <strong>valores globales</strong> y solo pueden\n        editarse desde el contexto Global.\n      </p>\n    </div>\n  ) : null;\n\n  // ── Sectioned layout ────────────────────────────────────────────────────────\n  if (definition.sections) {\n    return (\n      <div data-testid=\"basic-data-tab\">\n        {noticeBanner}\n        {definition.sections.map((section, idx) => {\n          const SectionIcon = section.icon;\n          return (\n            <div key={section.label ?? idx}>\n              {section.label && (\n                <div className=\"flex items-center gap-2 px-5 pt-5\">\n                  {SectionIcon && (\n                    <SectionIcon size={14} className=\"flex-shrink-0 text-[#1355b7]\" />\n                  )}\n                  <span className=\"text-sm font-semibold text-[#1355b7] whitespace-nowrap\">\n                    {section.label}\n                  </span>\n                  <div className=\"flex-1 h-px bg-[#dde5ef] dark:bg-dark-border-primary\" />\n                </div>\n              )}\n              <div className=\"grid grid-cols-12 gap-x-4 gap-y-6 items-start px-5 pt-4 pb-2\">\n                {section.fields\n                  .filter((f) => f.showInForm !== false)\n                  .map((field) => renderField(field, props, showOverrides, values))}\n              </div>\n            </div>\n          );\n        })}\n        {/* bottom padding to balance last section */}\n        <div className=\"pb-4\" />\n      </div>\n    );\n  }\n\n  // ── Flat layout (backward compat) ───────────────────────────────────────────\n  const basicFields = (definition.fields ?? []).filter(\n    (f) => f.showInForm === true && (f.formTab === undefined || f.formTab === 'basicData'),\n  );\n\n  // headerFields come first, then remaining basic fields\n  const orderedFields = [\n    ...headerFields\n      .map((name) => basicFields.find((f) => f.fieldName === name))\n      .filter(Boolean),\n    ...basicFields.filter((f) => !headerFields.includes(f.fieldName)),\n  ] as typeof basicFields;\n\n  return (\n    <div data-testid=\"basic-data-tab\">\n      {noticeBanner}\n      <div className=\"grid grid-cols-12 gap-x-4 gap-y-6 items-start px-5 pt-4 pb-6\">\n        {orderedFields.map((field) => renderField(field, props, showOverrides, values))}\n      </div>\n    </div>\n  );\n}\n","/**\n * TabSection — renders section title and fields in a 12-column grid.\n *\n * @module components/form/TabSection\n * @see FMPV-MVWC-E003-S001 I-007\n */\nimport React, { type ReactNode } from 'react';\n\nexport interface TabSectionProps {\n  sectionKey: string;\n  label?: string;\n  children: ReactNode;\n}\n\nexport function TabSection({ sectionKey, label, children }: TabSectionProps) {\n  return (\n    <div data-testid={`tab-section-${sectionKey}`} className=\"mb-6\">\n      {label && (\n        <div className=\"flex items-center gap-2.5 pt-4 pb-2 px-0 mb-0\">\n          <h3 className=\"text-xs font-bold text-[#a1a1aa] uppercase tracking-[0.4px] whitespace-nowrap\">\n            {label}\n          </h3>\n          <div className=\"flex-1 h-px bg-[#f4f4f5]\" />\n        </div>\n      )}\n      <div className=\"grid grid-cols-12 gap-x-4 gap-y-5 px-5 pt-4\">\n        {children}\n      </div>\n    </div>\n  );\n}\n","/**\n * ContentTab — renders fields for a specific formTab key, grouped by formSection.\n *\n * @module components/form/ContentTab\n * @see FMPV-MVWC-E003-S001 I-006\n */\nimport React from 'react';\nimport type { MasterPatternViewDefinition, MasterPatternViewTabConfig } from '../../types/definition.types';\nimport type { MasterPatternViewCompany } from '../../types/service.types';\nimport { TabSection } from './TabSection';\nimport { FieldRenderer } from './fields/FieldRenderer';\nimport { OverridableFieldWrapper } from './fields/OverridableFieldWrapper';\nimport { computeColSpanClass, inferInputType, getAllFields } from '../../engine/fieldEngine';\n\nexport interface ContentTabProps {\n  definition: MasterPatternViewDefinition;\n  tabConfig: MasterPatternViewTabConfig;\n  values: Record<string, unknown>;\n  errors: Record<string, string>;\n  onChange: (field: string, value: unknown) => void;\n  readOnly?: boolean;\n  fieldContext?: 'global' | 'company';\n  isShowGlobalValuesEnabled?: boolean;\n  globalValues?: Record<string, unknown>;\n  onFieldRevert?: (fieldName: string, globalValue: unknown) => void;\n  /** Current form mode — forwarded to renderFormField as context */\n  formMode?: 'create' | 'edit' | 'view';\n  /** This form's own company list — forwarded to a lookup field's inline \"create new\" so it can seed the child master's company selector instead of always defaulting to Global. */\n  companies?: MasterPatternViewCompany[];\n  /** This form's own currently active company (undefined/'global' when in global context) — same forwarding as `companies`. */\n  activeCompanyId?: string | null;\n}\n\nexport function ContentTab({\n  definition,\n  tabConfig,\n  values,\n  errors,\n  onChange,\n  readOnly = false,\n  fieldContext,\n  isShowGlobalValuesEnabled = false,\n  globalValues = {},\n  onFieldRevert,\n  formMode,\n  companies,\n  activeCompanyId,\n}: ContentTabProps) {\n  const tabFields = getAllFields(definition)\n    .filter((f) => f.showInForm === true && f.formTab === tabConfig.key)\n    .sort((a, b) => (a.formOrder ?? Infinity) - (b.formOrder ?? Infinity));\n\n  // Group by formSection\n  const sections = tabConfig.sections ?? [];\n  const sectionMap = new Map(sections.map((s) => [s.key, s]));\n  const fieldsBySection = new Map<string, typeof tabFields>();\n\n  for (const field of tabFields) {\n    const sectionKey = field.formSection ?? '_default';\n    const existing = fieldsBySection.get(sectionKey) ?? [];\n    fieldsBySection.set(sectionKey, [...existing, field]);\n  }\n\n  const sectionKeys = sections.length > 0\n    ? [...sections.map((s) => s.key), ...Array.from(fieldsBySection.keys()).filter((k) => !sections.find((s) => s.key === k))]\n    : Array.from(fieldsBySection.keys());\n\n  const isGlobal = definition.type === 'GLOBAL';\n  const showOverrides = isGlobal && !!fieldContext;\n\n  return (\n    <div data-testid={`content-tab-${tabConfig.key}`}>\n      {sectionKeys.map((sectionKey) => {\n        const sectionFields = fieldsBySection.get(sectionKey) ?? [];\n        if (sectionFields.length === 0) return null;\n        const sectionConfig = sectionMap.get(sectionKey);\n        return (\n          <TabSection key={sectionKey} sectionKey={sectionKey} label={sectionConfig?.label}>\n            {sectionFields.map((field) => {\n              const isDisabled = typeof field.disabled === 'function'\n                ? field.disabled(values)\n                : (field.disabled ?? false);\n              const renderer = (\n                <FieldRenderer\n                  key={field.fieldName}\n                  field={field}\n                  value={values[field.fieldName]}\n                  onChange={(v) => onChange(field.fieldName, v)}\n                  error={errors[field.fieldName]}\n                  disabled={isDisabled}\n                  readOnly={readOnly}\n                  allValues={values}\n                  formMode={formMode}\n                  setFormValue={onChange}\n                  companies={companies}\n                  activeCompanyId={activeCompanyId}\n                />\n              );\n\n              if (!showOverrides) return renderer;\n\n              return (\n                <OverridableFieldWrapper\n                  key={field.fieldName}\n                  fieldName={field.fieldName}\n                  isOverridable={field.isOverridable ?? false}\n                  isCompanyOnly={field.isCompanyOnly ?? false}\n                  context={fieldContext!}\n                  globalValue={globalValues[field.fieldName]}\n                  isShowGlobalValuesEnabled={isShowGlobalValuesEnabled}\n                  onRevert={onFieldRevert ?? (() => {})}\n                  fieldType={field.inputType ?? inferInputType(field)}\n                  className={computeColSpanClass(field)}\n                >\n                  {renderer}\n                </OverridableFieldWrapper>\n              );\n            })}\n          </TabSection>\n        );\n      })}\n    </div>\n  );\n}\n","/**\n * MasterPatternViewForm — root form component.\n *\n * Orchestrates the form panel: navigation container (sidebar/modal/page),\n * FormActionBar, TabBar, and tab content rendering.\n * Uses forwardRef to expose MasterPatternViewRef to consumers.\n *\n * @module components/form/MasterPatternViewForm\n * @see FMPV-MVWC-E003-S001 I-001\n */\nimport React, { forwardRef, useCallback, useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { AlertTriangle, RefreshCw } from 'lucide-react';\nimport { ArrowLeftIcon } from '@heroicons/react/24/outline';\nimport type { MasterPatternViewEntity, MasterPatternViewCompany } from '../../types/service.types';\nimport type { MasterPatternViewProps, MasterPatternViewRef, MasterPatternViewDetailTabConfig, MasterPatternViewFormProps as ExternalFormProps } from '../../types/props.types';\nimport type { MasterPatternViewPermissions } from '../../types/permissions.types';\nimport { isActionAllowed } from '../../engine/permissionEngine';\nimport { useMasterViewStore } from '../../store/MasterViewContext';\nimport { useToast } from '../../hooks/useToast';\nimport type { ToastCallback } from '../../hooks/useToast';\nimport { FormActionBar } from './FormActionBar';\nimport { TabBar } from './TabBar';\nimport type { TabBarProps } from './TabBar';\nimport { SidebarPanel } from './SidebarPanel';\nimport { ModalPanel } from './ModalPanel';\nimport { PagePanel } from './PagePanel';\nimport { BasicDataTab } from './BasicDataTab';\nimport { ContentTab } from './ContentTab';\n\nexport interface MasterPatternViewFormProps<T extends MasterPatternViewEntity> {\n  definition: MasterPatternViewProps<T>['definition'];\n  entityName: string;\n  /**\n   * `'inline'` renders just the card (action bar + tabs + fields) with no panel\n   * chrome — no overlay, no backdrop, no fixed positioning. For embedding the form\n   * inside a host-owned container (e.g. `MasterPatternViewCreateForm`, used inside a\n   * `LookupField` `onCreateNew` popup) instead of managing its own modal/sidebar.\n   */\n  navigationType?: 'sidebar' | 'modal' | 'page' | 'inline';\n  /**\n   * Whether the `navigationType='page'` form shows its own internal \"Volver\" back-nav\n   * link. No effect on sidebar/modal/inline. Set to `false` when there's genuinely\n   * nothing to \"go back\" to — e.g. this page-mode form is itself embedded inside a\n   * host's own popup/route.\n   * @default true\n   */\n  showBackButton?: boolean;\n  /** Custom panel width. For sidebar: panel width (default '480px'). For modal: modal width (default '640px'). No effect on page/inline. */\n  formWidth?: string;\n  /** Custom modal max-height (default '90vh'). Only affects navigationType='modal'. */\n  formHeight?: string;\n  tabs?: MasterPatternViewProps<T>['tabs'];\n  headerFields?: string[];\n  onSave: () => void;\n  onCancel: () => void;\n  onRequestRefresh: () => void;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** Company context for the form action bar */\n  companies?: MasterPatternViewCompany[];\n  onCompanyChange?: (company: MasterPatternViewCompany) => void;\n  /** Company ids the currently open record is enabled for — see FormActionBar's own doc. */\n  assignedCompanyIds?: string[];\n  /** Fully custom form renderer — replaces auto-generated form when provided. FR-007. */\n  renderForm?: (props: ExternalFormProps<T>) => ReactNode;\n  /** Detail tabs — custom render tabs shown only in editing mode. FR-010. */\n  detailTabs?: MasterPatternViewDetailTabConfig<T>[];\n  /**\n   * Handler for \"Habilitar compañía\" in the form's Acciones menu.\n   * When provided, replaces the default bare openCompanyEnableModal so the caller\n   * can load getAssignedCompanyIds before the modal opens (mirrors the list row action).\n   */\n  onHamburgerEnableCompany?: () => void;\n  /** Handler for \"Auditoría de Cambios\" in the form's Acciones menu — omit to hide the item. */\n  onHamburgerAudit?: () => void;\n  /** Called when the user clicks \"Reintentar\" after a getById failure. */\n  onRetryLoad?: () => void;\n  /**\n   * Fields used to build the form title when viewing or editing a record.\n   * Non-empty values are joined with `\" - \"`.\n   * Falls back to the automatic `code → name` convention when omitted.\n   */\n  recordTitleFields?: string[];\n  /** Disables the company selector in the form action bar. */\n  companyDisabled?: boolean;\n  /**\n   * Called in view mode to determine whether the active record can be edited.\n   * - `true`   — allow (default)\n   * - `false`  — hide the Editar button\n   * - `string` — show the button but display a warning toast with the returned message on click\n   */\n  canEdit?: (record: T) => boolean | string | { disabled: true; reason?: string };\n  /**\n   * Permission configuration. When `canUpdate` is `false`, the detail view's \"Editar\" button\n   * is hidden — same NEVER-HIDE exception RowActions.tsx applies to the list row's Editar slot,\n   * so a user without update permission can't reach edit mode from either the grid or the detail view.\n   */\n  permissions?: MasterPatternViewPermissions;\n  /** Translation function — threaded to FormActionBar, TabBar and inner tab content. */\n  t?: (key: string, defaultValue?: string) => string;\n  /**\n   * Shows the tab content area's own scrollbar instead of hiding it. Hidden by\n   * default (`scrollbar-none`) since a full-page master usually has other visual\n   * cues that content continues below the fold. Set to `true` when this form is\n   * embedded in a confined popup/modal (e.g. `MasterPatternViewCreateForm` with\n   * `chrome='modal'/'sidebar'`) — there, a hidden scrollbar is the ONLY thing that\n   * would tell the user there's more content to scroll to, so hiding it just reads\n   * as content silently cut off.\n   * @default false\n   */\n  showScrollbar?: boolean;\n}\n\nfunction MasterPatternViewFormInner<T extends MasterPatternViewEntity>(\n  {\n    definition,\n    entityName,\n    navigationType = 'sidebar',\n    showBackButton = true,\n    formWidth,\n    formHeight,\n    tabs: tabConfigs,\n    headerFields,\n    onSave,\n    onCancel,\n    onRequestRefresh,\n    toast: toastProp,\n    showInternalToasts = true,\n    companies,\n    onCompanyChange,\n    assignedCompanyIds,\n    renderForm,\n    detailTabs,\n    onHamburgerEnableCompany: onHamburgerEnableCompanyProp,\n    onHamburgerAudit,\n    onRetryLoad,\n    recordTitleFields,\n    companyDisabled,\n    canEdit,\n    permissions,\n    t = (key: string, defaultValue?: string) => defaultValue ?? key,\n    showScrollbar = false,\n  }: MasterPatternViewFormProps<T>,\n  ref: React.ForwardedRef<MasterPatternViewRef>,\n) {\n  const { showWarning } = useToast(toastProp, showInternalToasts);\n  const mode = useMasterViewStore((s) => s.mode);\n  const activeTabKey = useMasterViewStore((s) => s.activeTabKey);\n  const errors = useMasterViewStore((s) => s.errors);\n  const values = useMasterViewStore((s) => s.values);\n  const isDirty = useMasterViewStore((s) => s.isDirty);\n  const setActiveTabKey = useMasterViewStore((s) => s.setActiveTabKey);\n  const setValues = useMasterViewStore((s) => s.setValues);\n  const openEdit = useMasterViewStore((s) => s.openEdit);\n  const activeRecord = useMasterViewStore((s) => s.activeRecord);\n  const openCreate = useMasterViewStore((s) => s.openCreate);\n  const closeForm = useMasterViewStore((s) => s.closeForm);\n  const setIsDirty = useMasterViewStore((s) => s.setIsDirty);\n  const openChangeStatusModal = useMasterViewStore((s) => s.openChangeStatusModal);\n  const setPendingAction = useMasterViewStore((s) => s.setPendingAction);\n  const openCompanyEnableModal = useMasterViewStore((s) => s.openCompanyEnableModal);\n  const activeCompanyContext = useMasterViewStore((s) => s.activeCompanyContext);\n  const toggleShowGlobalValues = useMasterViewStore((s) => s.toggleShowGlobalValues);\n  const isShowGlobalValuesEnabled = useMasterViewStore((s) => s.isShowGlobalValuesEnabled);\n  const globalValues = useMasterViewStore((s) => s.globalValues);\n  const setOverrides = useMasterViewStore((s) => s.setOverrides);\n  const overrides = useMasterViewStore((s) => s.overrides);\n  const revertedFields = useMasterViewStore((s) => s.revertedFields);\n  const setRevertedFields = useMasterViewStore((s) => s.setRevertedFields);\n\n  const isLoadingRecord = useMasterViewStore((s) => s.isLoadingRecord);\n  const recordLoadFailed = useMasterViewStore((s) => s.recordLoadFailed);\n  const isOpen = mode !== 'closed';\n  const isReadOnly = mode === 'viewing';\n\n  // Derive field context for GLOBAL type override rendering.\n  // Must be declared before any useCallback that references it (avoids TDZ).\n  // - viewing mode → undefined (no overlay, no hints, no notice)\n  // - creating mode → undefined (all fields editable, no disabled overlays, no revert buttons)\n  // - editing in global context → 'global'\n  // - editing in company context → 'company'\n  const isCreating = mode === 'creating';\n  const fieldContext: 'global' | 'company' | undefined =\n    !isReadOnly && !isCreating && definition.type === 'GLOBAL'\n      ? activeCompanyContext && activeCompanyContext !== 'global'\n        ? 'company'\n        : 'global'\n      : undefined;\n\n  // Expose imperative ref API\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      resetDirty: () => setIsDirty(false),\n      refresh: () => onRequestRefresh(),\n      openCreate: () => openCreate(),\n      openEdit: (id: string) => {\n        if (activeRecord && (activeRecord as T & { id: string }).id === id) {\n          openEdit(activeRecord as T);\n        }\n      },\n      closeForm: () => closeForm(),\n    }),\n    [setIsDirty, onRequestRefresh, openCreate, openEdit, closeForm, activeRecord],\n  );\n\n  const handleFieldChange = useCallback(\n    (field: string, value: unknown) => {\n      setValues((prev) => ({ ...prev, [field]: value }));\n      setIsDirty(true);\n      // Track overridden fields in company context so service.update can tell the backend\n      // which fields are actively overridden vs which should revert to null (inherit global).\n      if (fieldContext === 'company') {\n        setOverrides({ ...overrides, [field]: value });\n      }\n    },\n    [setValues, setIsDirty, fieldContext, overrides, setOverrides],\n  );\n\n  const handleTabChange = useCallback(\n    (key: string) => {\n      setActiveTabKey(key);\n    },\n    [setActiveTabKey],\n  );\n\n  // Evaluate canEdit against the active record once, then derive the three modes:\n  // - isEditHidden:    ocultar  — button removed from DOM\n  // - isEditGrayed:    inhabilitar — button shown but disabled (+ optional tooltip)\n  // - editBlockReason: mostrar mensaje — button shown, click triggers toast\n  const canUpdate = isActionAllowed(permissions, 'UPDATE', definition.type);\n  const editCheck = canEdit && activeRecord ? canEdit(activeRecord as T) : true;\n  const isEditHidden = !canUpdate || editCheck === false;\n  const isEditGrayed = typeof editCheck === 'object' && editCheck.disabled === true;\n  const editGrayedReason = isEditGrayed ? (editCheck as { disabled: true; reason?: string }).reason : undefined;\n  const editBlockReason = typeof editCheck === 'string' ? editCheck : undefined;\n\n  const handleEdit = useCallback(() => {\n    if (editBlockReason) {\n      showWarning(editBlockReason);\n      return;\n    }\n    if (activeRecord) openEdit(activeRecord as T);\n  }, [activeRecord, openEdit, editBlockReason, showWarning]);\n\n  const handleUseGlobalData = useCallback(() => {\n    // Reset overridable field values back to global values and clear overrides\n    if (Object.keys(globalValues).length > 0) {\n      setValues({ ...values, ...globalValues });\n      setIsDirty(true);\n    }\n    setOverrides({});\n    setRevertedFields([]);\n  }, [globalValues, values, setValues, setIsDirty, setOverrides, setRevertedFields]);\n\n  // Lightweight revert tracker for detail tabs — they manage their own form state,\n  // so we only need to register the field in the store (no setValues call here).\n  const handleDetailTabFieldReverted = useCallback(\n    (fieldName: string) => {\n      if (!revertedFields.includes(fieldName)) {\n        setRevertedFields([...revertedFields, fieldName]);\n      }\n    },\n    [revertedFields, setRevertedFields],\n  );\n\n  const handleFieldRevert = useCallback(\n    (fieldName: string, globalValue: unknown) => {\n      setValues({ ...values, [fieldName]: globalValue });\n      setIsDirty(true);\n      // Remove from overrides store\n      const { [fieldName]: _removed, ...remaining } = overrides;\n      setOverrides(remaining);\n      // Track this field as explicitly reverted so the service sends null to backend\n      if (!revertedFields.includes(fieldName)) {\n        setRevertedFields([...revertedFields, fieldName]);\n      }\n    },\n    [overrides, revertedFields, values, setValues, setIsDirty, setOverrides, setRevertedFields],\n  );\n\n  // Derive a stable form mode string for renderFormField context\n  const formMode = mode === 'creating' ? 'create' : mode === 'editing' ? 'edit' : 'view';\n\n  // Merge definition tabs with prop tabs\n  const allTabConfigs = useMemo(\n    () => tabConfigs ?? definition.tabs ?? [],\n    [tabConfigs, definition.tabs],\n  );\n\n  // Filter tabs whose `visible` condition evaluates to false with current form values\n  const visibleTabConfigs = useMemo(\n    () => allTabConfigs.filter((tab) => !tab.visible || tab.visible(values)),\n    [allTabConfigs, values],\n  );\n\n  // Convert detailTabs to the shape TabBar expects (MasterDetailTabConfig)\n  // Inject activeCompanyContext as _companyId so isVisible always has current company\n  const detailTabConfigs = useMemo(() => {\n    if (!detailTabs || detailTabs.length === 0) return undefined;\n    const companyId = activeCompanyContext && activeCompanyContext !== 'global' ? activeCompanyContext : undefined;\n    if (!activeRecord) {\n      // Creating mode — evaluate isVisible against form values (no id → tabs with isVisible hide)\n      const enrichedValues = { ...values, _companyId: companyId } as unknown as T;\n      return detailTabs\n        .filter((dt) => !dt.isVisible || dt.isVisible(enrichedValues))\n        .map((dt) => ({ key: dt.key, label: dt.label }));\n    }\n    const enrichedRecord = { ...activeRecord, _companyId: companyId } as T;\n    return detailTabs\n      .filter((dt) => !dt.isVisible || dt.isVisible(enrichedRecord))\n      .map((dt) => ({ key: dt.key, label: dt.label }));\n  }, [detailTabs, activeRecord, values, mode, activeCompanyContext]);\n\n  // If the active tab becomes hidden (visible condition), reset to basicData\n  React.useEffect(() => {\n    if (!activeTabKey || activeTabKey === 'basicData') return;\n    const isVisibleRegular = visibleTabConfigs.some((t) => t.key === activeTabKey);\n    const isVisibleDetail = detailTabConfigs?.some((dt) => dt.key === activeTabKey);\n    if (!isVisibleRegular && !isVisibleDetail) {\n      setActiveTabKey('basicData');\n    }\n  }, [activeTabKey, visibleTabConfigs, detailTabConfigs, setActiveTabKey]);\n\n  // Check if current active tab is a detail tab\n  const activeDetailTab = useMemo(() => {\n    if (!detailTabs || !activeTabKey) return undefined;\n    return detailTabs.find((dt) => dt.key === activeTabKey);\n  }, [detailTabs, activeTabKey]);\n\n  // renderForm escape hatch: when provided, replaces the auto-generated form entirely\n  const customFormContent = useMemo(() => {\n    if (!renderForm) return undefined;\n    const formMode = mode === 'creating' ? 'creating'\n      : mode === 'editing' ? 'editing'\n      : 'viewing';\n    return renderForm({\n      values: values as Partial<T>,\n      errors,\n      isDirty,\n      submit: onSave,\n      mode: formMode as 'creating' | 'editing' | 'viewing',\n    });\n  }, [renderForm, values, errors, isDirty, onSave, mode]);\n\n  const loadingOverlay = isLoadingRecord && (\n    <div className=\"absolute inset-0 z-[15] flex items-center justify-center rounded-xl bg-bg-primary/60 dark:bg-dark-bg-primary/60 backdrop-blur-[1px]\">\n      <div className=\"w-6 h-6 rounded-full border-2 border-border-primary dark:border-dark-border-primary border-t-[#0e79fd] animate-spin\" />\n    </div>\n  );\n\n  const errorBanner = recordLoadFailed && (\n    <div className=\"flex items-center gap-3 mx-5 mt-3 px-4 py-3 rounded-lg bg-[#fef2f2] dark:bg-[#450a0a] border border-[#fecaca] dark:border-[#7f1d1d] text-sm text-[#dc2626] dark:text-[#f87171]\">\n      <AlertTriangle size={16} className=\"shrink-0\" />\n      <span className=\"flex-1\">{t('recordLoadFailedError', 'No se pudo cargar la información completa del registro.')}</span>\n      {onRetryLoad && (\n        <button\n          type=\"button\"\n          onClick={onRetryLoad}\n          className=\"flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-semibold border border-[#fecaca] dark:border-[#7f1d1d] hover:bg-[#fee2e2] dark:hover:bg-[#7f1d1d] cursor-pointer bg-transparent transition-colors\"\n        >\n          <RefreshCw size={12} />\n          {t('retryButton', 'Reintentar')}\n        </button>\n      )}\n    </div>\n  );\n\n  const tabContent = (\n    <div className={`flex-1 min-h-0 overflow-y-auto${showScrollbar ? '' : ' scrollbar-none'}`}>\n      {customFormContent ? (\n        // renderForm escape hatch — consumer controls the entire form content\n        customFormContent\n      ) : (\n        <>\n          {/* Regular tabs (BasicDataTab + this definition's own `tabs`) stay MOUNTED\n              even while a detail tab is showing — only their visibility toggles, via\n              CSS, not React mount/unmount. Both are pure/presentational (no local\n              state, no effects — verified), so this is purely a defensive measure:\n              a host whose own `detailTabs`/`definition` props aren't referentially\n              stable across renders (a real bug seen in a consuming app) would\n              otherwise unmount+remount this whole subtree on every detail-tab click,\n              and while these two components don't hold state themselves, unmounting\n              still tears down anything THEY mount internally (e.g. a LookupField's\n              own display-resolution effect) for no reason. Keeping them mounted\n              removes that whole class of \"switched tabs, my field looks reset\" bugs\n              regardless of the exact root cause upstream. */}\n          <div className={activeDetailTab ? 'hidden' : undefined}>\n            <div className={!activeTabKey || activeTabKey === 'basicData' ? undefined : 'hidden'}>\n              <BasicDataTab\n                definition={definition}\n                values={values}\n                errors={errors}\n                onChange={handleFieldChange}\n                headerFields={headerFields}\n                readOnly={isReadOnly}\n                fieldContext={fieldContext}\n                isShowGlobalValuesEnabled={isShowGlobalValuesEnabled}\n                globalValues={globalValues}\n                onFieldRevert={handleFieldRevert}\n                formMode={formMode}\n                companies={companies}\n                activeCompanyId={activeCompanyContext && activeCompanyContext !== 'global' ? activeCompanyContext : undefined}\n              />\n            </div>\n            {visibleTabConfigs.map((tabConfig) => (\n              <div key={tabConfig.key} className={activeTabKey === tabConfig.key ? undefined : 'hidden'}>\n                <ContentTab\n                  definition={definition}\n                  tabConfig={tabConfig}\n                  values={values}\n                  errors={errors}\n                  onChange={handleFieldChange}\n                  readOnly={isReadOnly}\n                  fieldContext={fieldContext}\n                  isShowGlobalValuesEnabled={isShowGlobalValuesEnabled}\n                  globalValues={globalValues}\n                  onFieldRevert={handleFieldRevert}\n                  formMode={formMode}\n                  companies={companies}\n                  activeCompanyId={activeCompanyContext && activeCompanyContext !== 'global' ? activeCompanyContext : undefined}\n                />\n              </div>\n            ))}\n          </div>\n          {activeDetailTab && (\n            // Detail tab custom content — render receives activeRecord (edit/view) or values (create)\n            // Inject activeCompanyContext as _companyId so detailTab render always has the current company.\n            // Unlike the regular tabs above, detail tabs ARE app-owned, dynamically-keyed content (an\n            // unbounded, per-consumer list) — mounting every one of them at once isn't safe to assume\n            // (duplicate data fetches, unknown render cost), so only the active one renders, same as before.\n            // `key` is scoped to the active record (not just the tab): without it, switching records\n            // while staying on the same detail tab reuses the same component instance, so any \"sync\n            // once on mount\" state inside a consumer's render() (e.g. a `hasSynced` flag) leaks from\n            // the previous record into the new one. Keying by record id forces a remount on every switch.\n            <div key={activeRecord ? activeRecord.id : 'create'} className=\"px-5 pt-4 pb-6\">\n              {activeDetailTab.render(\n                {\n                  ...(activeRecord ?? values),\n                  _companyId: activeCompanyContext && activeCompanyContext !== 'global' ? activeCompanyContext : undefined,\n                } as T,\n                mode as 'creating' | 'editing' | 'viewing',\n                {\n                  isShowGlobalValuesEnabled,\n                  globalValues: globalValues as Record<string, unknown> | null,\n                  revertedFields,\n                  onFieldReverted: handleDetailTabFieldReverted,\n                },\n              )}\n            </div>\n          )}\n        </>\n      )}\n    </div>\n  );\n\n  // Derive a human-readable record title.\n  //\n  // Priority for the \"value part\" (the record-identifying bit, before mode decides\n  // how to frame it):\n  //   1. recordTitleFields (explicit consumer override) — fields joined with \" - \"\n  //   2. Automatic convention: code → name\n  //   3. null when neither is available yet\n  //\n  // Editing/viewing show the value part alone (falling back to entityName); creating\n  // prefixes it with entityName (`${entityName}: ${valuePart}`) instead of replacing\n  // it, so switching tabs mid-create doesn't lose the context of what's being typed\n  // in the first tab — falling back to bare entityName only while those fields are\n  // still empty.\n  const formTitle = useMemo(() => {\n    const valuePart = (() => {\n      if (recordTitleFields && recordTitleFields.length > 0) {\n        const parts = recordTitleFields\n          .map((field) => values[field])\n          .filter((v) => v !== undefined && v !== null && v !== '')\n          .map(String);\n        return parts.length > 0 ? parts.join(' - ') : null;\n      }\n\n      // Default convention: code - name\n      const code = values['code'];\n      const name = values['name'];\n      const hasCode = code !== undefined && code !== null && code !== '';\n      const hasName = name !== undefined && name !== null && name !== '';\n      if (hasCode && hasName) return `${String(code)} - ${String(name)}`;\n      if (hasCode) return String(code);\n      if (hasName) return String(name);\n      return null;\n    })();\n\n    if (mode === 'creating') return valuePart ? `${entityName}: ${valuePart}` : entityName;\n    return valuePart ?? entityName;\n  }, [mode, values, entityName, recordTitleFields]);\n\n  const actionBar = (\n    <FormActionBar\n      mode={mode}\n      title={formTitle}\n      isDirty={isDirty}\n      onSave={onSave}\n      onCancel={onCancel}\n      onEdit={handleEdit}\n      editHidden={isEditHidden}\n      editGrayed={isEditGrayed}\n      editGrayedReason={editGrayedReason}\n      onHamburgerCreate={openCreate}\n      onHamburgerChangeStatus={() => {\n        if (!activeRecord) return;\n        setPendingAction({ type: 'change-status', payload: activeRecord });\n        openChangeStatusModal();\n      }}\n      onHamburgerEnableCompany={onHamburgerEnableCompanyProp ?? openCompanyEnableModal}\n      onHamburgerAudit={onHamburgerAudit}\n      onHamburgerUseGlobalData={handleUseGlobalData}\n      onHamburgerToggleShowGlobal={toggleShowGlobalValues}\n      showGlobalValues={isShowGlobalValuesEnabled}\n      companies={companies}\n      activeCompanyId={activeCompanyContext}\n      onCompanyChange={onCompanyChange}\n      assignedCompanyIds={assignedCompanyIds}\n      definitionType={definition.type}\n      recordIsActive={typeof values?.isActive === 'boolean' ? (values.isActive as boolean) : undefined}\n      compact={navigationType === 'sidebar'}\n      saveDisabled={recordLoadFailed}\n      companyDisabled={companyDisabled}\n      t={t}\n    />\n  );\n\n  const tabBar = (\n    <TabBar\n      definition={{ ...definition, tabs: visibleTabConfigs }}\n      activeTabKey={activeTabKey || 'basicData'}\n      errors={errors}\n      onTabChange={handleTabChange}\n      navigationType={navigationType}\n      formMode={mode}\n      detailTabConfigs={detailTabConfigs as TabBarProps['detailTabConfigs']}\n      t={t}\n    />\n  );\n\n  if (navigationType === 'inline') {\n    // Same inner content as modal/sidebar (action bar + card with tabs/fields), just\n    // without a Panel wrapper — no overlay, no backdrop, no fixed positioning. Doesn't\n    // gate on `isOpen`: the host controls mounting (e.g. only while its own popup is\n    // open), so there's no \"closed\" state to hide here.\n    return (\n      <div className=\"flex flex-col h-full min-h-0\">\n        <div className=\"flex-shrink-0\">{actionBar}</div>\n        {errorBanner}\n        <div className=\"bg-background-secondary dark:bg-dark-bg-secondary flex flex-col flex-1 min-h-0 overflow-hidden\">\n          <div className=\"flex-1 min-h-0 mx-3 mb-3 flex flex-col\">\n            <div className=\"relative bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-[0_1px_3px_rgba(0,0,0,0.06)] flex-1 min-h-0 flex flex-col overflow-hidden\">\n              {tabBar}\n              {tabContent}\n              {loadingOverlay}\n            </div>\n          </div>\n        </div>\n      </div>\n    );\n  }\n\n  if (navigationType === 'modal') {\n    return (\n      <ModalPanel isOpen={isOpen} onClose={onCancel} width={formWidth} maxHeight={formHeight}>\n        <div className=\"flex-shrink-0\">{actionBar}</div>\n        {errorBanner}\n        <div className=\"bg-background-secondary dark:bg-dark-bg-secondary flex flex-col flex-1 min-h-0 overflow-hidden\">\n          <div className=\"flex-1 min-h-0 mx-3 mb-3 flex flex-col\">\n            <div className=\"relative bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-[0_1px_3px_rgba(0,0,0,0.06)] flex-1 min-h-0 flex flex-col overflow-hidden\">\n              {tabBar}\n              {tabContent}\n              {loadingOverlay}\n            </div>\n          </div>\n        </div>\n      </ModalPanel>\n    );\n  }\n\n  if (navigationType === 'page') {\n    return (\n      <PagePanel isOpen={isOpen}>\n        {/* \"Volver\" nav — mirrors MasterCrud's page-mode header (MasterCrud.tsx:1571-1575).\n            Unlike sidebar/modal (which close via backdrop/X), page mode replaces the whole\n            screen with no popup, so a persistent back link is the way out — unless the host\n            explicitly says there's nowhere to go back to (showBackButton={false}), e.g. this\n            page-mode form is itself embedded inside the host's own popup/route. */}\n        {showBackButton && (\n          <nav className=\"px-5 pt-3.5\">\n            <button\n              type=\"button\"\n              onClick={onCancel}\n              className=\"inline-flex items-center gap-1 text-sm text-content-tertiary dark:text-dark-content-tertiary hover:text-[#1355b7] transition-colors\"\n            >\n              <ArrowLeftIcon className=\"w-4 h-4\" />\n              <span>{t('back', 'Volver')}</span>\n            </button>\n          </nav>\n        )}\n        {actionBar}\n        {errorBanner}\n        <div className=\"flex flex-col mx-5\">\n          <div className=\"relative bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-[0_1px_3px_rgba(0,0,0,0.06)] mb-5 overflow-hidden\">\n            {tabBar}\n            {tabContent}\n            {loadingOverlay}\n          </div>\n        </div>\n      </PagePanel>\n    );\n  }\n\n  return (\n    <SidebarPanel isOpen={isOpen} width={formWidth} onBackdropClick={isDirty ? undefined : onCancel}>\n      <div className=\"flex-shrink-0\">{actionBar}</div>\n      {errorBanner}\n      <div className=\"bg-background-secondary dark:bg-dark-bg-secondary flex flex-col flex-1 min-h-0 overflow-hidden\">\n        <div className=\"flex-1 min-h-0 mx-3 mb-3 flex flex-col\">\n          <div className=\"relative bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-[0_1px_3px_rgba(0,0,0,0.06)] flex-1 min-h-0 flex flex-col overflow-hidden\">\n            {tabBar}\n            {tabContent}\n            {loadingOverlay}\n          </div>\n        </div>\n      </div>\n    </SidebarPanel>\n  );\n}\n\nexport const MasterPatternViewForm = forwardRef(MasterPatternViewFormInner) as <\n  T extends MasterPatternViewEntity,\n>(\n  props: MasterPatternViewFormProps<T> & { ref?: React.ForwardedRef<MasterPatternViewRef> },\n) => React.ReactElement | null;\n","/**\n * Memoized field engine hook.\n *\n * Caches all fieldEngine derived values so engine functions run only once\n * per `definition.fields` change, not on every render.\n *\n * @internal\n * @module hooks/useFieldEngine\n * @see FMPV-MVWC-E001-S004 R-001 — fieldEngine memoization\n */\nimport { useMemo } from 'react';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport {\n  getAllFields,\n  deriveListColumns,\n  deriveFormInputs,\n  deriveFilterControls,\n  deriveQuickFilters,\n  deriveSortableFields,\n  validateFieldDefinitions,\n  type ListColumnDescriptor,\n  type FormInputDescriptor,\n  type FilterControlDescriptor,\n  type QuickFilterDescriptor,\n  type SortableFieldDescriptor,\n} from '../engine/fieldEngine';\n\nexport interface FieldEngineCache {\n  listColumns: ListColumnDescriptor[];\n  filterControls: FilterControlDescriptor[];\n  quickFilters: QuickFilterDescriptor[];\n  sortableFields: SortableFieldDescriptor[];\n  /** Get form inputs for a specific tab key (or all if undefined). */\n  getFormInputs: (tabKey?: string) => FormInputDescriptor[];\n}\n\n/**\n * Returns a memoized cache of all field engine outputs derived from\n * `definition.fields`. Recomputes only when `definition.fields` reference changes.\n *\n * @param definition - The master view definition\n * @returns Memoized derived column, input, filter, and sort descriptors\n */\nexport function useFieldEngine(definition: MasterPatternViewDefinition): FieldEngineCache {\n  return useMemo(() => {\n    const allFields = getAllFields(definition);\n    validateFieldDefinitions(allFields);\n    return {\n      listColumns: deriveListColumns(allFields),\n      filterControls: deriveFilterControls(allFields),\n      quickFilters: deriveQuickFilters(allFields),\n      sortableFields: deriveSortableFields(allFields),\n      getFormInputs: (tabKey?: string) => deriveFormInputs(allFields, tabKey),\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [definition]);\n}\n","/**\n * FilterPanel — filter panel with basic field controls + advanced filters.\n *\n * Visually matches MasterCrudAdvancedSearch.tsx:\n * - Basic fields: `grid grid-cols-1 md:grid-cols-3 gap-4` (not a cramped flex-wrap row).\n * - Advanced filters: `<details>` with the same summary header (chevron + label + hint),\n *   a header row (# / Columna / Condición / Valor) above the condition rows, and a\n *   connector badge (\"Y\"/\"O\") rendered BETWEEN rows (not just once at the top).\n *\n * Layout:\n * 1. Basic row: one control per filterable field, in declaration order — text/number/date\n *    inputs, select for enum fields, and a plain Activo/Inactivo/Todos select for boolean\n *    fields (e.g. \"Estado\") — exactly like MasterCrudAdvancedSearch's `enumOptionsFor`.\n *    There is no separate hardcoded status control; a status filter is just a boolean field.\n * 2. Advanced filters panel (<details>, collapsible):\n *    - Connector selector: Y (AND) / O (OR), segmented pill buttons\n *    - Condition rows: [#N] [Campo ▼] [Operador ▼] [Valor] [×], with a connector badge\n *      between consecutive rows\n *    - \"+ Agregar condición\" button\n * 3. Chips row: visible when advanced conditions have values and panel is closed\n * 4. Action row: [Limpiar] [Buscar]\n *\n * @module components/toolbar/FilterPanel\n * @see FMPV-MVWC-E002-S001 I-005\n */\nimport React, { useState, useCallback, useMemo } from 'react';\nimport {\n  Eraser, Search,\n  ChevronDown, Plus, X,\n} from 'lucide-react';\nimport { Button } from '../../../Button/Button';\nimport { LookupField } from '../../../LookupField/LookupField';\nimport type { LookupRecord } from '../../../LookupField/LookupField.types';\nimport type { MasterPatternViewDefinition, MasterPatternViewLookupConfig } from '../../types/definition.types';\nimport { getAllFields } from '../../engine/fieldEngine';\nimport type { ActiveFilter } from '../../store/types';\nimport { useFieldEngine } from '../../hooks/useFieldEngine';\nimport type { FilterOperator } from '../../types/definition.types';\n\nexport interface FilterPanelProps {\n  definition: MasterPatternViewDefinition;\n  activeFilters: ActiveFilter[];\n  onSearch: (filters: ActiveFilter[]) => void;\n  onClear: () => void;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\ninterface FilterValues {\n  [field: string]: {\n    value: string;\n    valueTo?: string;\n    operator: FilterOperator;\n    booleanValue?: boolean | null;\n  };\n}\n\ninterface AdvCondition {\n  id: string;\n  field: string;\n  operator: string;\n  value: string;\n  /** Human-readable label for lookup conditions (chip display) */\n  displayLabel?: string;\n}\n\nfunction resolveDisplay(record: LookupRecord, cfg: MasterPatternViewLookupConfig): string {\n  if (cfg.displayTemplate) {\n    return cfg.displayTemplate.replace(/\\{(\\w+)\\}/g, (_, k) => String(record[k] ?? ''));\n  }\n  if (cfg.displayValue) return String(record[cfg.displayValue] ?? '');\n  return cfg.displayFields.map((f) => String(record[f] ?? '')).join(' ');\n}\n\nlet _idSeq = 0;\nfunction newId() { return `cond-${++_idSeq}`; }\n\n/**\n * Reconstructs the panel's full state (basic values, advanced conditions, connector)\n * from `activeFilters` — the last filters actually searched. Needed because FilterPanel\n * is conditionally rendered (`{isFilterPanelOpen && <FilterPanel .../>}` in\n * MasterPatternView.tsx), so it fully unmounts on close and loses local state; without\n * this, reopening the panel always came back empty, even right after a search.\n *\n * `handleBuscar` marks an advanced search by including a `__connector` entry — its\n * presence (not `advOpen`, which is always reset to `false` after a search) is what\n * tells us which shape to rebuild.\n */\nfunction buildInitialFilterState(activeFilters: ActiveFilter[]): {\n  filterValues: FilterValues;\n  advConditions: AdvCondition[];\n  connector: 'AND' | 'OR';\n} {\n  const connectorEntry = activeFilters.find((f) => f.field === '__connector');\n\n  if (connectorEntry) {\n    const advConditions: AdvCondition[] = activeFilters\n      .filter((f) => f.field !== '__connector' && !f.field.startsWith('__'))\n      .map((f) => ({\n        id: newId(),\n        field: f.field,\n        operator: f.operator,\n        value: String(f.value ?? ''),\n        // The lookup's friendly label isn't part of ActiveFilter, so it can't survive\n        // a remount — the chip falls back to the raw value (id) for lookup fields.\n        displayLabel: '',\n      }));\n    return {\n      filterValues: {},\n      advConditions,\n      connector: (connectorEntry.value as 'AND' | 'OR') ?? 'AND',\n    };\n  }\n\n  const filterValues: FilterValues = {};\n  for (const f of activeFilters) {\n    if (f.field.startsWith('__')) continue;\n    filterValues[f.field] = {\n      value: String(f.value ?? ''),\n      operator: (f.operator as FilterOperator) ?? 'contains',\n    };\n  }\n  return { filterValues, advConditions: [], connector: 'AND' };\n}\n\n// ── Shared styles — sized like MasterCrudAdvancedSearch.tsx (controlCls/condCtrlCls) ──\nconst inputClass =\n  'w-full px-3 py-2 text-sm border border-border-primary dark:border-dark-border-primary rounded-md bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary ' +\n  'focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors';\nconst selectClass =\n  'px-2.5 py-1.5 text-sm border border-border-primary dark:border-dark-border-primary rounded-md bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary ' +\n  'outline-none focus:border-[#93d1fd] transition-colors cursor-pointer';\nconst labelClass = 'block text-[11px] font-semibold text-content-tertiary dark:text-dark-content-tertiary tracking-[0.3px] mb-1';\n\n/**\n * Compact LookupField overrides injected via <style> tag.\n * Tailwind v4 breaks BEM double-underscore selectors in arbitrary variants,\n * so we inject plain CSS scoped via [data-testid=\"filter-panel\"].\n */\nconst LOOKUP_COMPACT_CSS = `\n[data-testid=\"filter-panel\"] .lookup-field {\n  gap: 0 !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__trigger {\n  height: 36px !important; padding: 8px 12px !important; font-size: 0.875rem !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__placeholder,\n[data-testid=\"filter-panel\"] .lookup-field__selected-text {\n  font-size: 0.875rem !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__clear {\n  width: 0.875rem !important; height: 0.875rem !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__chevron {\n  width: 0.875rem !important; height: 0.875rem !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__search {\n  height: 36px !important; padding: 8px 2rem !important; font-size: 0.875rem !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__search-icon {\n  width: 0.875rem !important; height: 0.875rem !important;\n}\n[data-testid=\"filter-panel\"] .lookup-field__search-clear {\n  width: 1rem !important; height: 1rem !important;\n}\n`;\n\nexport function FilterPanel({\n  definition,\n  activeFilters,\n  onSearch,\n  onClear,\n  t,\n}: FilterPanelProps) {\n  const tt = useMemo(\n    () => t ?? ((key: string, defaultValue?: string) => defaultValue ?? key),\n    [t],\n  );\n\n  // ── Operator sets by data type ─────────────────────────────────────────────\n  // Grouped in a single useMemo (keyed on `tt`) so the arrays and the lookup\n  // function below share one stable reference per translation change, instead\n  // of being recreated as fresh objects on every render.\n  const { LOOKUP_OPS, getOpsForDataType } = useMemo(() => {\n    const STRING_OPS = [\n      { value: 'contains', label: tt('opContains', 'contiene') },\n      { value: 'starts_with', label: tt('opStartsWith', 'empieza con') },\n      { value: 'equals', label: tt('opEquals', 'es igual a') },\n      { value: 'not_equals', label: tt('opNotEquals', 'no es igual a') },\n    ];\n    const NUMBER_OPS = [\n      { value: 'equals', label: tt('opEquals', 'es igual a') },\n      { value: 'not_equals', label: tt('opNotEquals', 'no es igual a') },\n      { value: 'gt', label: tt('opGt', 'mayor que') },\n      { value: 'gte', label: tt('opGte', 'mayor o igual a') },\n      { value: 'lt', label: tt('opLt', 'menor que') },\n      { value: 'lte', label: tt('opLte', 'menor o igual a') },\n    ];\n    const DATE_OPS = [\n      { value: 'gte', label: tt('opFrom', 'desde') },\n      { value: 'lte', label: tt('opTo', 'hasta') },\n      { value: 'equals', label: tt('opEquals', 'es igual a') },\n    ];\n    const BOOLEAN_OPS = [\n      { value: 'equals', label: tt('opEquals', 'es igual a') },\n    ];\n    const LOOKUP_OPS = [\n      { value: 'equals', label: tt('opEquals', 'es igual a') },\n    ];\n    function getOpsForDataType(dataType: string) {\n      if (dataType === 'number' || dataType === 'decimal') return NUMBER_OPS;\n      if (dataType === 'date') return DATE_OPS;\n      if (dataType === 'boolean') return BOOLEAN_OPS;\n      return STRING_OPS;\n    }\n    return { STRING_OPS, NUMBER_OPS, DATE_OPS, BOOLEAN_OPS, LOOKUP_OPS, getOpsForDataType };\n  }, [tt]);\n\n  const { filterControls } = useFieldEngine(definition);\n  const [initialFilterState] = useState(() => buildInitialFilterState(activeFilters));\n  const [filterValues, setFilterValues] = useState<FilterValues>(initialFilterState.filterValues);\n\n  // Advanced filters state — seeded from activeFilters so reopening the panel (it fully\n  // unmounts on close) shows the same conditions/connector that were last searched.\n  // advOpen stays false: this mirrors the state right after a search (handleBuscar\n  // always collapses it), which is when the summary chips below are meant to show.\n  const [advOpen, setAdvOpen] = useState(false);\n  const [connector, setConnector] = useState<'AND' | 'OR'>(initialFilterState.connector);\n  const [advConditions, setAdvConditions] = useState<AdvCondition[]>(initialFilterState.advConditions);\n\n  const hasFilterableFields = filterControls.length > 0;\n\n  const getFieldValue = (fieldName: string) =>\n    filterValues[fieldName] ?? { value: '', operator: 'contains' as FilterOperator };\n\n  const setFieldValue = useCallback((fieldName: string, value: string) => {\n    setFilterValues((prev) => ({\n      ...prev,\n      [fieldName]: { ...getFieldValue(fieldName), ...prev[fieldName], value },\n    }));\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const setFieldProp = useCallback((fieldName: string, prop: string, val: unknown) => {\n    setFilterValues((prev) => ({\n      ...prev,\n      [fieldName]: { ...getFieldValue(fieldName), ...prev[fieldName], [prop]: val },\n    }));\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // ── Advanced conditions helpers ──────────────────────────────────────────\n\n  const addCondition = useCallback(() => {\n    const first = filterControls[0];\n    const isFirstLookup = first?.inputType === 'lookup';\n    const defaultOp = isFirstLookup\n      ? 'equals'\n      : getOpsForDataType(first?.dataType ?? 'string')[0]?.value ?? 'contains';\n    setAdvConditions((prev) => [\n      ...prev,\n      { id: newId(), field: first?.fieldName ?? '', operator: defaultOp, value: '', displayLabel: '' },\n    ]);\n  }, [filterControls, getOpsForDataType]);\n\n  const removeCondition = useCallback((id: string) => {\n    setAdvConditions((prev) => prev.filter((c) => c.id !== id));\n  }, []);\n\n  const updateCondition = useCallback(\n    (id: string, patch: Partial<Omit<AdvCondition, 'id'>>) => {\n      setAdvConditions((prev) =>\n        prev.map((c) => {\n          if (c.id !== id) return c;\n          const updated = { ...c, ...patch };\n          // Reset operator, value, and displayLabel when field changes\n          if (patch.field && patch.field !== c.field) {\n            const fc = filterControls.find((x) => x.fieldName === patch.field);\n            const isNextLookup = fc?.inputType === 'lookup';\n            updated.operator = isNextLookup\n              ? 'equals'\n              : getOpsForDataType(fc?.dataType ?? 'string')[0]?.value ?? 'contains';\n            updated.value = '';\n            updated.displayLabel = '';\n          }\n          return updated;\n        }),\n      );\n    },\n    [filterControls, getOpsForDataType],\n  );\n\n  const handleAdvToggle = useCallback((nextOpen: boolean) => {\n    setAdvOpen(nextOpen);\n\n    if (nextOpen) {\n      // Switching to advanced mode → clear basic filters\n      setFilterValues({});\n      // Auto-add first condition when opening empty panel\n      if (advConditions.length === 0) {\n        const first = filterControls[0];\n        const isFirstLookup = first?.inputType === 'lookup';\n        const defaultOp = isFirstLookup\n          ? 'equals'\n          : getOpsForDataType(first?.dataType ?? 'string')[0]?.value ?? 'contains';\n        setAdvConditions([{ id: newId(), field: first?.fieldName ?? '', operator: defaultOp, value: '', displayLabel: '' }]);\n      }\n    }\n    // NOTA: antes, al cerrar (`else`), esto vaciaba advConditions/connector (\"switching to\n    // basic mode\"). El <details> nativo dispara `toggle` cuando su atributo `open` cambia\n    // — también cuando `handleBuscar` lo cierra programáticamente (`setAdvOpen(false)`) al\n    // buscar. Ese wipe corría JUSTO DESPUÉS de que handleBuscar ya había leído advConditions\n    // para el onSearch, borrando las condiciones recién buscadas antes de que el chip\n    // \"Filtros activos\" llegara a pintarse. Ya no se limpia nada al cerrar: las condiciones\n    // sobreviven tanto a un `handleBuscar` como a que el usuario colapse el acordeón a mano.\n  }, [advConditions.length, filterControls, getOpsForDataType]);\n\n  const activeAdvCount = advConditions.filter((c) => c.value.trim()).length;\n\n  // ── Buscar / Limpiar ─────────────────────────────────────────────────────\n\n  const handleBuscar = useCallback(() => {\n    const basicFilters: ActiveFilter[] = filterControls\n      .map((fc): ActiveFilter | null => {\n        const fv = filterValues[fc.fieldName];\n        if (!fv) return null;\n        if (fc.dataType === 'boolean') {\n          if (fv.booleanValue === null || fv.booleanValue === undefined) return null;\n          return { field: fc.fieldName, operator: 'equals', value: fv.booleanValue };\n        }\n        if (!fv.value && !fv.valueTo) return null;\n        return { field: fc.fieldName, operator: fv.operator ?? 'contains', value: fv.value };\n      })\n      .filter((f): f is ActiveFilter => f !== null);\n\n    const activeAdv = advConditions.filter((c) => c.value.trim());\n    const connectorFilter: ActiveFilter[] =\n      activeAdv.length > 0\n        ? [{ field: '__connector', operator: 'equals', value: connector }]\n        : [];\n    const advFilters: ActiveFilter[] = activeAdv.map((c) => ({\n      field: c.field,\n      operator: c.operator,\n      value: c.value,\n    }));\n\n    const isAdvancedActive = advOpen || activeAdv.length > 0;\n    setAdvOpen(false);\n    onSearch([\n      ...(isAdvancedActive ? [] : basicFilters),\n      ...connectorFilter,\n      ...advFilters,\n    ]);\n  }, [filterControls, filterValues, connector, advConditions, advOpen, onSearch]);\n\n  const handleLimpiar = useCallback(() => {\n    setFilterValues({});\n    setAdvConditions([]);\n    setConnector('AND');\n    setAdvOpen(false);\n    onClear();\n  }, [onClear]);\n\n  // ── Render ───────────────────────────────────────────────────────────────\n\n  return (\n    <div className=\"px-5 py-3.5 bg-[#f8f9fc] dark:bg-zinc-900 border-b border-border-primary dark:border-dark-border-primary\" data-testid=\"filter-panel\">\n      <style dangerouslySetInnerHTML={{ __html: LOOKUP_COMPACT_CSS }} />\n\n      {/* ── Basic filter fields — grid, matches MasterCrudAdvancedSearch.tsx:124 ──── */}\n      <div\n        {...((advOpen || activeAdvCount > 0) ? { inert: true } : {})}\n        className={`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 transition-opacity duration-200 ${(advOpen || activeAdvCount > 0) ? 'opacity-50 pointer-events-none' : ''}`}\n      >\n        {filterControls.map((fc) => {\n          const fv = getFieldValue(fc.fieldName);\n\n          // Boolean fields render as a plain Activo/Inactivo/Todos select — same\n          // treatment as any other enum field, matching MasterCrudAdvancedSearch's\n          // `enumOptionsFor`. There is no separate hardcoded \"Estado\" control.\n          if (fc.dataType === 'boolean') {\n            const boolStr = fv.booleanValue === true ? 'true' : fv.booleanValue === false ? 'false' : '';\n            return (\n              <div key={fc.fieldName} data-testid={`filter-${fc.fieldName}`}>\n                <label className={labelClass}>{fc.label}</label>\n                <select\n                  value={boolStr}\n                  onChange={(e) => setFieldProp(fc.fieldName, 'booleanValue', e.target.value === '' ? null : e.target.value === 'true')}\n                  className={`${inputClass} cursor-pointer`}\n                >\n                  <option value=\"\">{tt('all', 'Todos')}</option>\n                  <option value=\"true\">{tt('active', 'Activo')}</option>\n                  <option value=\"false\">{tt('inactive', 'Inactivo')}</option>\n                </select>\n              </div>\n            );\n          }\n\n          if (fc.dataType === 'date') {\n            return (\n              <div key={fc.fieldName} data-testid={`filter-${fc.fieldName}`}>\n                <label className={labelClass}>{fc.label} {tt('opFrom', 'desde')}</label>\n                <input\n                  type=\"date\"\n                  value={fv.value}\n                  onChange={(e) => setFieldValue(fc.fieldName, e.target.value)}\n                  className={inputClass}\n                />\n              </div>\n            );\n          }\n\n          if (fc.inputType === 'select') {\n            const field = getAllFields(definition).find((f) => f.fieldName === fc.fieldName);\n            return (\n              <div key={fc.fieldName} data-testid={`filter-${fc.fieldName}`}>\n                <label className={labelClass}>{fc.label}</label>\n                <select\n                  value={fv.value}\n                  onChange={(e) => setFieldValue(fc.fieldName, e.target.value)}\n                  className={`${inputClass} cursor-pointer`}\n                >\n                  <option value=\"\">{tt('all', 'Todos')}</option>\n                  {(field?.options ?? []).map((opt) => (\n                    <option key={opt.value} value={String(opt.value)}>{opt.label}</option>\n                  ))}\n                </select>\n              </div>\n            );\n          }\n\n          if (fc.dataType === 'number' || fc.dataType === 'decimal') {\n            return (\n              <div key={fc.fieldName} data-testid={`filter-${fc.fieldName}`}>\n                <label className={labelClass}>{fc.label}</label>\n                <input\n                  type=\"number\"\n                  value={fv.value}\n                  onChange={(e) => setFieldValue(fc.fieldName, e.target.value)}\n                  placeholder={fc.label}\n                  className={inputClass}\n                />\n              </div>\n            );\n          }\n\n          // Lookup: render LookupField in the basic filter bar\n          if (fc.inputType === 'lookup') {\n            const fieldDef = getAllFields(definition).find((f) => f.fieldName === fc.fieldName);\n            if (fieldDef?.lookupConfig) {\n              return (\n                <div key={fc.fieldName} data-testid={`filter-${fc.fieldName}`}>\n                  <label className={labelClass}>{fc.label}</label>\n                  <LookupField\n                    entity={fieldDef.lookupConfig.entity}\n                    fetcher={fieldDef.lookupConfig.fetcher}\n                    displayFields={fieldDef.lookupConfig.displayFields}\n                    displayTemplate={fieldDef.lookupConfig.displayTemplate}\n                    displayValue={fieldDef.lookupConfig.displayValue}\n                    filters={\n                      fieldDef.lookupConfig.getFilters\n                        ? fieldDef.lookupConfig.getFilters(\n                            Object.fromEntries(\n                              Object.entries(filterValues).map(([k, v]) => [k, v.value]),\n                            ),\n                          )\n                        : fieldDef.lookupConfig.filters\n                    }\n                    minChars={fieldDef.lookupConfig.minChars}\n                    value={fv.value || null}\n                    onChange={(rec: LookupRecord | null) => {\n                      setFieldValue(fc.fieldName, rec?.Id ?? '');\n                      if (rec && fieldDef.lookupConfig?.onFilterSelect) {\n                        fieldDef.lookupConfig.onFilterSelect(\n                          rec as Record<string, unknown>,\n                          (fieldName: string, val: unknown) =>\n                            setFieldValue(fieldName, String(val ?? '')),\n                        );\n                      }\n                    }}\n                  />\n                </div>\n              );\n            }\n          }\n\n          // Default: text\n          return (\n            <div key={fc.fieldName} data-testid={`filter-${fc.fieldName}`}>\n              <label className={labelClass}>{fc.label}</label>\n              <input\n                type=\"text\"\n                value={fv.value}\n                onChange={(e) => setFieldValue(fc.fieldName, e.target.value)}\n                placeholder={fc.label}\n                className={inputClass}\n                data-testid={`filter-${fc.fieldName}-value`}\n              />\n            </div>\n          );\n        })}\n      </div>\n\n      {/* ── Filtros avanzados — <details>, misma estructura que MasterCrudAdvancedSearch.tsx:146 ── */}\n      {hasFilterableFields && (\n        <details\n          className=\"mt-4 border border-border-primary dark:border-dark-border-primary rounded-lg overflow-hidden\"\n          open={advOpen}\n          onToggle={(e) => handleAdvToggle((e.target as HTMLDetailsElement).open)}\n        >\n          <summary\n            className=\"flex items-center gap-2 cursor-pointer select-none px-4 py-3 bg-white dark:bg-dark-bg-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n            style={{ listStyle: 'none' }}\n            data-testid=\"filter-adv-toggle\"\n          >\n            <ChevronDown className={`w-4 h-4 text-primary-600 flex-shrink-0 transition-transform duration-200 ${advOpen ? 'rotate-180' : ''}`} />\n            <span className=\"text-sm font-semibold text-[#1355b7] dark:text-primary-400\">{tt('advancedFilters', 'Filtros avanzados')}</span>\n            <span className=\"hidden sm:inline text-xs text-content-tertiary font-normal\">{tt('advancedFiltersHint', '— combina varias condiciones personalizadas')}</span>\n            {activeAdvCount > 0 && (\n              <span className=\"bg-primary-600 text-white rounded-full px-1.5 text-[10px] font-bold leading-[18px]\">\n                {activeAdvCount}\n              </span>\n            )}\n          </summary>\n\n          <div className=\"border-t border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-secondary px-4 py-4 flex flex-col gap-4\" data-testid=\"adv-filters-panel\">\n            {/* Conector lógico global (Y/O) — segmented pills, igual al prototipo */}\n            <div className=\"flex flex-wrap items-center gap-x-3 gap-y-2\">\n              <span className=\"text-[11px] font-semibold text-content-secondary tracking-[0.3px] uppercase\">\n                {tt('joinConditionsWith', 'Unir condiciones con')}\n              </span>\n              <div role=\"radiogroup\" aria-label={tt('joinConditionsWith', 'Unir condiciones con')} className=\"inline-flex rounded-md border border-border-primary dark:border-dark-border-primary overflow-hidden bg-white dark:bg-dark-bg-primary shadow-[0_1px_2px_0_rgba(16,24,40,0.05)]\">\n                {([\n                  { v: 'AND' as const, label: tt('connectorAndLabel', 'Y') },\n                  { v: 'OR' as const, label: tt('connectorOrLabel', 'O') },\n                ]).map((opt, i) => {\n                  const active = connector === opt.v;\n                  return (\n                    <button\n                      key={opt.v}\n                      type=\"button\"\n                      role=\"radio\"\n                      aria-checked={active}\n                      onClick={() => setConnector(opt.v)}\n                      className={`px-4 py-1.5 text-sm font-semibold transition-colors ${i === 1 ? 'border-l border-border-primary dark:border-dark-border-primary' : ''} ${active ? 'bg-primary-600 text-white' : 'bg-white dark:bg-dark-bg-primary text-content-secondary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'}`}\n                    >\n                      {opt.label}\n                    </button>\n                  );\n                })}\n              </div>\n              <span className=\"text-xs text-content-tertiary\">\n                {connector === 'AND'\n                  ? tt('connectorAndHint', 'Se deben cumplir todas las condiciones')\n                  : tt('connectorOrHint', 'Basta con que se cumpla una condición')}\n              </span>\n            </div>\n\n            {/* Tarjeta de condiciones */}\n            <div className=\"rounded-lg bg-white dark:bg-dark-bg-primary overflow-hidden shadow-[0_1px_2px_0_rgba(16,24,40,0.05)] ring-1 ring-black/[0.04]\">\n              <div className=\"hidden md:flex items-center gap-2 px-3 py-2 bg-white dark:bg-dark-bg-primary border-b border-border-primary dark:border-dark-border-primary text-[11px] font-semibold text-content-secondary tracking-[0.3px] uppercase\">\n                <span className=\"w-5 flex-shrink-0 text-center\">#</span>\n                <span className=\"w-[170px]\">{tt('column', 'Columna')}</span>\n                <span className=\"w-[150px]\">{tt('condition', 'Condición')}</span>\n                <span className=\"flex-1 min-w-0\">{tt('value', 'Valor')}</span>\n                <span className=\"w-8 flex-shrink-0\" />\n              </div>\n\n              {advConditions.map((cond, idx) => {\n                const fc = filterControls.find((c) => c.fieldName === cond.field);\n                const isLookup = fc?.inputType === 'lookup';\n                const ops = isLookup ? LOOKUP_OPS : getOpsForDataType(fc?.dataType ?? 'string');\n                const fieldDef = getAllFields(definition).find((f) => f.fieldName === cond.field);\n                const isSelect = fc?.inputType === 'select';\n                const isBoolean = fc?.dataType === 'boolean';\n                const isDate = fc?.dataType === 'date';\n                const isNumber = fc?.dataType === 'number' || fc?.dataType === 'decimal';\n\n                return (\n                  <React.Fragment key={cond.id}>\n                    <div className=\"flex flex-col md:flex-row md:items-center gap-2 px-3 py-2.5\" data-testid={`adv-condition-${idx}`}>\n                      <span className=\"w-5 flex-shrink-0 text-center text-xs font-bold text-content-tertiary select-none\">{idx + 1}</span>\n\n                      <select\n                        value={cond.field}\n                        onChange={(e) => updateCondition(cond.id, { field: e.target.value })}\n                        className={`${selectClass} w-full md:w-[170px]`}\n                        data-testid={`adv-condition-${idx}-field`}\n                      >\n                        {filterControls.map((f) => (\n                          <option key={f.fieldName} value={f.fieldName}>{f.label}</option>\n                        ))}\n                      </select>\n\n                      <select\n                        value={cond.operator}\n                        onChange={(e) => updateCondition(cond.id, { operator: e.target.value })}\n                        className={`${selectClass} w-full md:w-[150px]`}\n                        data-testid={`adv-condition-${idx}-operator`}\n                      >\n                        {ops.map((op) => (\n                          <option key={op.value} value={op.value}>{op.label}</option>\n                        ))}\n                      </select>\n\n                      {isLookup && fieldDef?.lookupConfig ? (\n                        <div className=\"w-full md:flex-1 md:min-w-0\" data-testid={`adv-condition-${idx}-value`}>\n                          <LookupField\n                            entity={fieldDef.lookupConfig.entity}\n                            fetcher={fieldDef.lookupConfig.fetcher}\n                            displayFields={fieldDef.lookupConfig.displayFields}\n                            displayTemplate={fieldDef.lookupConfig.displayTemplate}\n                            displayValue={fieldDef.lookupConfig.displayValue}\n                            filters={\n                              fieldDef.lookupConfig.getFilters\n                                ? fieldDef.lookupConfig.getFilters(\n                                    Object.fromEntries(\n                                      advConditions\n                                        .filter((c) => c.value)\n                                        .map((c) => [c.field, c.value]),\n                                    ),\n                                  )\n                                : fieldDef.lookupConfig.filters\n                            }\n                            minChars={fieldDef.lookupConfig.minChars}\n                            value={cond.value || null}\n                            onChange={(rec: LookupRecord | null) => updateCondition(cond.id, {\n                              value: rec?.Id ?? '',\n                              displayLabel: rec && fieldDef.lookupConfig\n                                ? resolveDisplay(rec, fieldDef.lookupConfig)\n                                : '',\n                            })}\n                          />\n                        </div>\n                      ) : isSelect ? (\n                        <select\n                          value={cond.value}\n                          onChange={(e) => updateCondition(cond.id, { value: e.target.value })}\n                          className={`${selectClass} w-full md:flex-1 md:min-w-0`}\n                          data-testid={`adv-condition-${idx}-value`}\n                        >\n                          <option value=\"\">{tt('selectPlaceholder', 'Seleccionar...')}</option>\n                          {(fieldDef?.options ?? []).map((opt) => (\n                            <option key={opt.value} value={String(opt.value)}>{opt.label}</option>\n                          ))}\n                        </select>\n                      ) : isBoolean ? (\n                        <select\n                          value={cond.value}\n                          onChange={(e) => updateCondition(cond.id, { value: e.target.value })}\n                          className={`${selectClass} w-full md:flex-1 md:min-w-0`}\n                          data-testid={`adv-condition-${idx}-value`}\n                        >\n                          <option value=\"\">{tt('selectPlaceholder', 'Seleccionar...')}</option>\n                          <option value=\"true\">{tt('yes', 'Sí')}</option>\n                          <option value=\"false\">{tt('no', 'No')}</option>\n                        </select>\n                      ) : (\n                        <input\n                          type={isDate ? 'date' : isNumber ? 'number' : 'text'}\n                          value={cond.value}\n                          onChange={(e) => updateCondition(cond.id, { value: e.target.value })}\n                          placeholder={tt('valuePlaceholder', 'Valor...')}\n                          className={`${selectClass} w-full md:flex-1 md:min-w-0`}\n                          data-testid={`adv-condition-${idx}-value`}\n                        />\n                      )}\n\n                      <button\n                        type=\"button\"\n                        onClick={() => removeCondition(cond.id)}\n                        title={tt('removeConditionTitle', 'Eliminar condición')}\n                        aria-label={tt('removeConditionTitle', 'Eliminar condición')}\n                        className=\"flex-shrink-0 inline-flex items-center justify-center w-8 h-8 self-end md:self-auto rounded-md text-content-tertiary hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors\"\n                        data-testid={`adv-condition-${idx}-remove`}\n                      >\n                        <X size={16} />\n                      </button>\n                    </div>\n\n                    {/* Conector entre condiciones — refleja el selector global Y/O */}\n                    {idx < advConditions.length - 1 && (\n                      <div className=\"flex items-center gap-2 px-3\">\n                        <span className=\"ml-5 inline-flex items-center justify-center h-5 min-w-[26px] px-2 rounded-full text-[10px] font-bold tracking-wide bg-primary-50 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300 border border-primary-100 dark:border-primary-800 select-none\">\n                          {connector === 'AND' ? tt('connectorAndLabel', 'Y') : tt('connectorOrLabel', 'O')}\n                        </span>\n                        <span className=\"h-px flex-1 bg-border-primary/70 dark:bg-dark-border-primary/70\" />\n                      </div>\n                    )}\n                  </React.Fragment>\n                );\n              })}\n            </div>\n\n            <div>\n              <button\n                type=\"button\"\n                onClick={addCondition}\n                className=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold text-primary-600 border border-dashed border-[#93d1fd] hover:bg-[#eff8ff] dark:hover:bg-primary-900/20 transition-colors\"\n                data-testid=\"adv-add-condition\"\n              >\n                <Plus size={14} />\n                {tt('addConditionLabel', 'Agregar condición')}\n              </button>\n            </div>\n          </div>\n        </details>\n      )}\n\n      {/* ── Chips: active advanced conditions when panel is closed ─────────── */}\n      {!advOpen && activeAdvCount > 0 && (\n        <div className=\"flex items-center flex-wrap gap-1.5 pt-2.5\" data-testid=\"adv-chips\">\n          <span className=\"text-[11px] text-content-tertiary dark:text-dark-content-tertiary font-semibold\">{tt('activeFiltersLabel', 'Filtros activos:')}</span>\n          {advConditions\n            .filter((c) => c.value.trim())\n            .map((c) => {\n              const fc = filterControls.find((x) => x.fieldName === c.field);\n              return (\n                <span\n                  key={c.id}\n                  className=\"inline-flex items-center gap-1.5 bg-[#eff8ff] border border-[#93d1fd] rounded-md px-2.5 py-0.5 text-[11px] text-[#1355b7]\"\n                >\n                  {fc?.label ?? c.field}:{' '}\n                  {fc?.inputType === 'lookup'\n                    ? (c.displayLabel || c.value)\n                    : fc?.dataType === 'boolean'\n                      ? (c.value === 'true' ? tt('yes', 'Sí') : c.value === 'false' ? tt('no', 'No') : c.value)\n                      : c.value}\n                </span>\n              );\n            })}\n          <button\n            type=\"button\"\n            onClick={handleLimpiar}\n            className=\"text-[11px] text-content-tertiary dark:text-dark-content-tertiary underline cursor-pointer bg-transparent border-none p-0\"\n          >\n            {tt('clearAdvancedFilters', 'Limpiar filtros avanzados')}\n          </button>\n        </div>\n      )}\n\n      {/* ── Limpiar / Buscar — siempre al fondo del panel ─────────────────── */}\n      <div className=\"flex items-center justify-end gap-2 mt-3.5\">\n        <Button\n          type=\"outline\"\n          size=\"base\"\n          className=\"!h-9 !px-3 !text-sm font-medium\"\n          leftIcon={<Eraser size={14} />}\n          onClick={handleLimpiar}\n          data-testid=\"filter-panel-clear\"\n        >\n          {tt('clear', 'Limpiar')}\n        </Button>\n        <Button\n          type=\"default\"\n          size=\"base\"\n          className=\"!h-9 !px-3 !text-sm font-medium\"\n          leftIcon={<Search size={14} />}\n          onClick={handleBuscar}\n          data-testid=\"filter-panel-search\"\n        >\n          {tt('search', 'Buscar')}\n        </Button>\n      </div>\n    </div>\n  );\n}\n","/**\n * ToolbarActions — right-side toolbar buttons: Create + global custom actions.\n *\n * - \"Crear\" always visible and enabled; shows warning toast when canCreate=false (NEVER-HIDE)\n * - globalActions render custom action buttons after \"Crear\"\n * - Uses native styled buttons to guarantee mock-matching appearance\n *\n * @module components/toolbar/ToolbarActions\n * @see FMPV-MVWC-E002-S002 I-002\n */\nimport React, { useCallback } from 'react';\nimport { motion } from 'framer-motion';\nimport { PlusIcon, DocumentArrowDownIcon, ArrowUpTrayIcon } from '@heroicons/react/24/outline';\nimport { Button } from '../../../Button/Button';\nimport type { MasterPatternViewDefinition } from '../../types/definition.types';\nimport type { MasterPatternViewPermissions } from '../../types/permissions.types';\nimport type { MasterPatternViewCustomAction, MasterPatternViewDefaultActions } from '../../types/props.types';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport { isActionAllowed, getDisabledToastMessage } from '../../engine/permissionEngine';\nimport { useToast, type ToastCallback } from '../../hooks/useToast';\n\nexport interface ToolbarActionsProps<T extends MasterPatternViewEntity = MasterPatternViewEntity> {\n  definition: MasterPatternViewDefinition;\n  permissions?: MasterPatternViewPermissions;\n  defaultActions?: MasterPatternViewDefaultActions<T>;\n  onCreateClick: () => void;\n  globalActions?: MasterPatternViewCustomAction<T>[];\n  selectedRecords?: T[];\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  showExport?: boolean;\n  showImport?: boolean;\n  onExport?: () => void;\n  onImport?: () => void;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\n\nexport function ToolbarActions<T extends MasterPatternViewEntity = MasterPatternViewEntity>({\n  definition,\n  permissions,\n  defaultActions,\n  onCreateClick,\n  globalActions = [],\n  selectedRecords = [],\n  toast: toastProp,\n  showInternalToasts = true,\n  showExport = false,\n  showImport = false,\n  onExport,\n  onImport,\n  t,\n}: ToolbarActionsProps<T>) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const { showWarning } = useToast(toastProp, showInternalToasts);\n  const canCreate = isActionAllowed(permissions, 'CREATE', definition.type);\n\n  const handleCreateClick = useCallback(() => {\n    if (!canCreate) {\n      showWarning(getDisabledToastMessage('CREATE'));\n      return;\n    }\n    onCreateClick();\n  }, [canCreate, showWarning, onCreateClick]);\n\n  return (\n    <div className=\"flex items-center gap-2\" data-testid=\"toolbar-actions\">\n      {/* \"Crear\" — hidden only when defaultActions.create.show === false; otherwise NEVER-HIDE */}\n      {defaultActions?.create?.show !== false && (\n        <motion.span\n          className=\"inline-block\"\n          whileHover={{ scale: 1.03 }}\n          whileTap={{ scale: 0.97 }}\n          transition={{ type: 'spring', bounce: 0.35, duration: 0.35 }}\n        >\n          <Button\n            type=\"default\"\n            size=\"base\"\n            className=\"!text-sm font-medium\"\n            leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n            onClick={handleCreateClick}\n            data-testid=\"toolbar-create-button\"\n          >\n            {tt('create', 'Nuevo')}\n          </Button>\n        </motion.span>\n      )}\n\n      {/* Export button */}\n      {showExport && (\n        <Button\n          type=\"outline\"\n          size=\"sm\"\n          leftIcon={<DocumentArrowDownIcon className=\"w-4 h-4\" />}\n          onClick={onExport}\n          data-testid=\"toolbar-export-button\"\n        >\n          {tt('export', 'Exportar')}\n        </Button>\n      )}\n\n      {/* Import button */}\n      {showImport && (\n        <Button\n          type=\"outline\"\n          size=\"sm\"\n          leftIcon={<ArrowUpTrayIcon className=\"w-4 h-4\" />}\n          onClick={onImport}\n          data-testid=\"toolbar-import-button\"\n        >\n          {tt('import', 'Importar')}\n        </Button>\n      )}\n\n      {/* Custom global actions */}\n      {globalActions.map((action) => {\n        const isDisabled = action.isDisabled?.() ?? false;\n        return (\n          <Button\n            key={action.key}\n            type=\"default\"\n            size=\"sm\"\n            leftIcon={action.icon}\n            onClick={() => !isDisabled && action.onExecute()}\n            disabled={isDisabled}\n            data-testid={`global-action-${action.key}`}\n          >\n            {action.label}\n          </Button>\n        );\n      })}\n    </div>\n  );\n}\n","export default \"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='iso-8859-1'?%3e%3c!--%20Generator:%20Adobe%20Illustrator%2027.1.1,%20SVG%20Export%20Plug-In%20.%20SVG%20Version:%206.00%20Build%200)%20--%3e%3csvg%20version='1.1'%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20x='0px'%20y='0px'%20viewBox='0%200%202000%202000'%20style='enable-background:new%200%200%202000%202000;'%20xml:space='preserve'%3e%3cpath%20style='fill:%23313131;'%20d='M1757.6,1550.49H268.703c-0.747,0-1.463-0.3-1.99-0.83c-0.528-0.53-0.825-1.24-0.825-1.99%20c0-0.74,0.297-1.46,0.825-1.99c0.527-0.53,1.243-0.82,1.99-0.82H1757.6c0.75,0,1.46,0.29,1.99,0.82c0.53,0.53,0.82,1.25,0.82,1.99%20c0,0.75-0.29,1.46-0.82,1.99C1759.06,1550.19,1758.35,1550.49,1757.6,1550.49z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1456.99,919.459c0,0,182.17,77.91,208.69,127.761c30.56,57.42-15.76,492.64-138.07,514.21%20c-122.32,21.57-519.71,38.71-519.71,38.71v-52.47l-73.628-52.64l59.356-143.71c0,0-126.503,100.07-183.877-48.01%20c-57.375-148.07-74.623-307.562-74.623-307.562L880.5,951.433l67.147,170.907c0,0,124.323-243.007,182.703-262.305%20c48.26-15.897,190.39,24.972,190.39,24.972l7.07,69.962L1456.99,919.459z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1007.9,1602.95c-0.35,0.01-0.71-0.06-1.04-0.2c-0.34-0.13-0.64-0.33-0.89-0.58%20c-0.28-0.26-0.5-0.58-0.65-0.93c-0.15-0.35-0.23-0.72-0.23-1.1v-51.07l-72.439-51.79c-0.519-0.37-0.898-0.9-1.074-1.51%20c-0.176-0.61-0.139-1.26,0.105-1.85l55.551-134.63c-17.811,11.87-62.103,36.71-105.967,24.77%20c-32.132-8.76-57.104-35.58-74.308-79.73c-56.518-146.41-74.532-306.69-74.532-308.288c-0.07-0.652,0.089-1.308,0.451-1.855%20s0.903-0.95,1.53-1.14l145.35-44.314c0.679-0.203,1.409-0.144,2.046,0.164c0.638,0.309,1.137,0.844,1.399,1.502l64.896,165.141%20c19.342-37.24,126.912-240.147,181.472-258.116c48.52-16.009,186.19,23.261,192.05,24.927c0.54,0.157,1.02,0.473,1.37,0.906%20c0.36,0.434,0.58,0.966,0.63,1.526l6.76,66.629l125.96-34.654c0.61-0.182,1.27-0.134,1.84,0.135%20c7.48,3.197,183.39,78.811,210.07,129.007c22.99,43.21,3.51,304.14-62.6,439.72c-22.99,47.12-49.06,73.58-77.48,78.58%20c-121.17,21.35-516.08,38.57-520.15,38.75H1007.9z%20M937.74,1494.04l71.81,51.34c0.35,0.25,0.65,0.59,0.85,0.98%20c0.2,0.39,0.31,0.83,0.32,1.27v49.54c36.59-1.62,401.12-18.22,516.39-38.53c26.55-4.68,51.23-30.08,73.38-75.5%20c28.62-58.66,51.95-150.24,64.16-251.21c10.4-86.89,9.84-162.3-1.38-183.4c-24.77-46.61-192.52-120.063-206.39-126.098%20l-128.35,35.262c-0.4,0.115-0.81,0.141-1.22,0.076c-0.4-0.065-0.79-0.22-1.13-0.453c-0.33-0.232-0.62-0.538-0.82-0.893%20c-0.21-0.355-0.33-0.752-0.37-1.161l-6.89-68.025c-16.73-4.684-142.91-38.978-186.89-24.499%20c-56.52,18.689-179.802,258.501-181.041,260.891c-0.245,0.48-0.626,0.88-1.095,1.16c-0.47,0.27-1.009,0.4-1.552,0.38%20c-0.543-0.03-1.067-0.21-1.508-0.53c-0.441-0.32-0.781-0.76-0.979-1.26l-66.246-168.5l-140.621,42.783%20c2.387,20.267,21.346,168.407,74.105,304.547c16.415,42.38,40.103,68.07,70.412,76.33c52.713,14.37,108.533-29.07,109.096-29.52%20c0.488-0.38,1.091-0.59,1.712-0.59c0.62,0,1.223,0.21,1.711,0.59c0.498,0.38,0.858,0.9,1.025,1.5s0.131,1.24-0.102,1.81%20L937.74,1494.04z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1252.38,839.048V410.046h-0.41c-86.98-5.899-180.81-9.119-278.608-9.119%20c-82.841,0-162.823,2.251-238.234,6.597h0.495v429.295h-0.27c75.343-4.279,155.235-6.598,238.009-6.598%20c97.948,0,191.918,3.243,279.018,9.142V839.048z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1252.38,842.201h-0.18c-89.26-6.057-183.07-9.187-278.837-9.187%20c-80.883,0-160.775,2.252-237.469,6.575h-0.405c-0.745,0.031-1.473-0.233-2.025-0.735c-0.552-0.501-0.884-1.2-0.925-1.945%20c-0.024-0.473,0.069-0.945,0.27-1.373V409.101c-0.305-0.42-0.489-0.916-0.531-1.434c-0.043-0.517,0.057-1.037,0.29-1.501%20c0.232-0.465,0.587-0.857,1.027-1.133c0.44-0.277,0.947-0.427,1.466-0.435C812.048,400.229,892.255,398,973.453,398%20c95.747,0,189.547,3.062,278.807,9.12h0.43c0.71,0.051,1.37,0.368,1.85,0.886c0.48,0.518,0.74,1.199,0.74,1.906v429.474%20c0.01,0.372-0.06,0.74-0.2,1.084c-0.14,0.345-0.35,0.657-0.61,0.92s-0.58,0.47-0.92,0.609c-0.34,0.139-0.71,0.208-1.08,0.202%20H1252.38z%20M973.363,827.429c94.817,0,187.727,3.018,276.197,9.007V412.681c-88.45-5.944-181.35-9.007-276.197-9.007%20c-79.982,0-158.996,2.252-234.924,6.418v423.755C814.367,829.591,893.403,827.429,973.363,827.429z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1119.73,667.758h-0.19c-43.45-2.95-89.12-4.504-135.73-4.504c-39.383,0-78.293,1.081-115.604,3.198%20h-0.203c-0.734,0.019-1.446-0.247-1.988-0.743c-0.542-0.495-0.87-1.182-0.917-1.914c-0.023-0.262-0.023-0.526,0-0.788V455.689%20c-0.14-0.321-0.224-0.664-0.247-1.013c-0.031-0.742,0.23-1.466,0.726-2.017c0.497-0.552,1.19-0.887,1.931-0.933%20c37.536-2.139,76.559-3.22,116.234-3.22c46.658,0,92.318,1.509,135.918,4.503c0.73,0.038,1.43,0.347,1.95,0.867%20c0.52,0.52,0.82,1.214,0.86,1.948v209.164c0.01,0.384-0.07,0.764-0.22,1.117c-0.15,0.353-0.38,0.67-0.66,0.932%20C1121.08,667.497,1120.42,667.753,1119.73,667.758z%20M983.81,657.67c45.67,0,90.43,1.441,133.1,4.256V458.414%20c-42.78-2.838-87.48-4.279-133.1-4.279c-38.46,0-76.559,1.036-113.015,3.04V660.71c36.569-2.004,74.555-3.04,113.038-3.04H983.81z'%20/%3e%3cpath%20style='fill:%23313131;'%20d='M867.756,660.057l93.582-142.783l52.152,86.918l49.04-41.613l57.22,102.365L867.756,660.057z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1119.73,667.759c-0.5-0.003-0.99-0.138-1.43-0.391c-0.43-0.253-0.78-0.615-1.03-1.05l-55.55-99.37%20l-46.43,39.383c-0.31,0.262-0.67,0.454-1.06,0.563c-0.39,0.108-0.79,0.132-1.19,0.068c-0.4-0.07-0.79-0.225-1.12-0.454%20c-0.34-0.229-0.63-0.527-0.84-0.875l-49.832-83.066L870.12,661.589c-0.198,0.32-0.457,0.598-0.764,0.816%20c-0.306,0.219-0.653,0.374-1.021,0.455c-0.367,0.082-0.747,0.09-1.117,0.022c-0.371-0.067-0.724-0.209-1.038-0.415%20c-0.315-0.206-0.585-0.474-0.795-0.786c-0.209-0.313-0.354-0.664-0.426-1.033c-0.071-0.37-0.068-0.75,0.01-1.118%20c0.078-0.368,0.229-0.717,0.444-1.026l93.583-142.76c0.255-0.406,0.611-0.737,1.034-0.962c0.422-0.226,0.897-0.336,1.375-0.322%20c0.478,0.014,0.944,0.146,1.357,0.386c0.413,0.24,0.759,0.58,1.007,0.988l50.441,84.057l46.5-39.338%20c0.31-0.265,0.69-0.458,1.09-0.564c0.4-0.106,0.82-0.123,1.22-0.05c0.41,0.073,0.8,0.234,1.14,0.473%20c0.34,0.238,0.62,0.548,0.83,0.907l57.21,102.364c0.19,0.322,0.3,0.677,0.35,1.044c0.04,0.367,0.01,0.74-0.09,1.096%20c-0.1,0.357-0.27,0.689-0.5,0.979s-0.51,0.531-0.84,0.709C1120.69,667.715,1120.2,667.801,1119.73,667.759z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1026.53,535.897c10.28,0,18.62-8.337,18.62-18.622c0-10.284-8.34-18.622-18.62-18.622%20c-10.29,0-18.63,8.338-18.63,18.622C1007.9,527.56,1016.24,535.897,1026.53,535.897z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1026.53,538.712c-4.24,0-8.39-1.257-11.91-3.613c-3.53-2.355-6.28-5.703-7.9-9.62%20c-1.62-3.917-2.05-8.227-1.22-12.386c0.83-4.158,2.87-7.978,5.87-10.976c3-2.997,6.82-5.039,10.97-5.866%20c4.16-0.827,8.47-0.403,12.39,1.22c3.92,1.622,7.26,4.37,9.62,7.895s3.61,7.67,3.61,11.909c0,5.684-2.26,11.133-6.28,15.152%20C1037.66,536.446,1032.21,538.706,1026.53,538.712z%20M1026.53,501.468c-3.12,0-6.17,0.925-8.76,2.657%20c-2.59,1.732-4.61,4.193-5.81,7.073c-1.19,2.881-1.5,6.05-0.89,9.107c0.6,3.058,2.11,5.867,4.31,8.071%20c2.2,2.204,5.01,3.706,8.07,4.314c3.06,0.608,6.23,0.296,9.11-0.897c2.88-1.193,5.34-3.214,7.07-5.806s2.66-5.639,2.66-8.757%20c0-4.18-1.66-8.189-4.62-11.145C1034.72,503.129,1030.71,501.468,1026.53,501.468z'/%3e%3cpath%20style='fill:%23313131;'%20d='M800.338,708.717c-0.746,0.018-1.469-0.262-2.01-0.777c-0.54-0.515-0.854-1.224-0.872-1.97%20c-0.018-0.747,0.261-1.47,0.777-2.01c0.515-0.541,1.224-0.855,1.97-0.872c1.329,0,134.812-6.598,386.647,0%20c0.37,0.008,0.73,0.09,1.07,0.239c0.34,0.15,0.64,0.365,0.9,0.632c0.26,0.268,0.46,0.583,0.59,0.928%20c0.13,0.345,0.2,0.713,0.19,1.083c-0.01,0.371-0.08,0.738-0.23,1.079s-0.36,0.649-0.63,0.905c-0.27,0.257-0.59,0.456-0.94,0.587%20c-0.34,0.131-0.71,0.191-1.09,0.176c-251.605-6.575-384.908,0-386.214,0H800.338z'/%3e%3cpath%20style='fill:%23313131;'%20d='M800.542,749.002c-0.747,0.018-1.47-0.261-2.01-0.777c-0.541-0.515-0.855-1.224-0.872-1.97%20c-0.018-0.747,0.261-1.47,0.776-2.01c0.515-0.541,1.224-0.854,1.971-0.872c1.306,0,134.811-6.598,386.643,0%20c0.37,0.008,0.74,0.09,1.07,0.24c0.34,0.15,0.64,0.365,0.9,0.633c0.25,0.268,0.45,0.583,0.58,0.928%20c0.13,0.345,0.19,0.712,0.18,1.081c0,0.372-0.08,0.741-0.22,1.083c-0.15,0.343-0.36,0.652-0.63,0.909%20c-0.27,0.257-0.59,0.456-0.94,0.586s-0.72,0.187-1.09,0.169c-251.592-6.598-384.895,0-386.223,0H800.542z'/%3e%3cpath%20style='fill:%23313131;'%20d='M800.542,789.263c-0.747,0.018-1.47-0.262-2.01-0.777c-0.541-0.515-0.855-1.224-0.872-1.97%20c-0.018-0.747,0.261-1.47,0.776-2.01c0.515-0.541,1.224-0.855,1.971-0.873c1.306,0,134.811-6.597,386.643,0%20c0.37,0.009,0.74,0.091,1.07,0.241c0.34,0.15,0.64,0.365,0.9,0.633c0.25,0.268,0.45,0.583,0.58,0.928%20c0.13,0.345,0.19,0.712,0.18,1.081c0,0.373-0.07,0.743-0.22,1.087c-0.14,0.344-0.36,0.654-0.63,0.912%20c-0.27,0.258-0.59,0.457-0.94,0.586c-0.35,0.128-0.72,0.183-1.09,0.162c-251.592-6.575-384.895,0-386.223,0H800.542z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M151.814,984.759c0-58.14,170.727-108.781,423.057-135.104h-0.225V420.293h-0.675%20c-251.835,26.39-422.157,76.987-422.157,135.104V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M151.815,987.574c-0.747,0-1.463-0.297-1.991-0.824c-0.527-0.528-0.824-1.244-0.824-1.991V555.42%20c0-58.545,158.748-109.975,424.678-137.852h0.698c0.404-0.053,0.814-0.018,1.203,0.102c0.389,0.121,0.747,0.324,1.049,0.596%20c0.29,0.267,0.521,0.591,0.68,0.951c0.159,0.36,0.242,0.75,0.243,1.143v428.191c0.113,0.242,0.181,0.501,0.203,0.766%20c0.076,0.74-0.145,1.48-0.613,2.058c-0.469,0.578-1.147,0.947-1.886,1.027c-125.783,13.128-231.457,32.335-305.584,55.528%20c-75.186,23.53-114.839,50.079-114.839,76.807c0.004,0.389-0.073,0.775-0.225,1.133c-0.153,0.358-0.378,0.68-0.661,0.947%20c-0.284,0.267-0.62,0.472-0.987,0.602C152.593,987.549,152.203,987.602,151.815,987.574z%20M571.832,423.423%20c-124.476,13.15-228.957,32.245-302.544,55.28c-75.028,23.508-114.659,50.034-114.659,76.717v410.447%20c30.286-50.394,181.401-93.898,417.203-118.734V423.423z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M182.754,859.876c0-35.825,79.216-67.011,196.284-83.314l-0.315-268.115%20c-116.843,16.258-195.902,51.07-195.902,86.85L182.754,859.876z'/%3e%3cpath%20style='fill:%23313131;'%20d='M182.753,862.693c-0.37,0.003-0.738-0.068-1.08-0.209c-0.343-0.14-0.655-0.347-0.917-0.609%20c-0.262-0.262-0.469-0.574-0.609-0.916c-0.141-0.343-0.211-0.711-0.208-1.081V595.366c0-37.694,77.842-72.866,198.31-89.642%20c0.398-0.051,0.802-0.017,1.186,0.1s0.739,0.313,1.041,0.577s0.545,0.589,0.712,0.954c0.168,0.364,0.256,0.76,0.259,1.161%20l0.315,267.349v0.338c0.103,0.74-0.089,1.491-0.536,2.089c-0.447,0.599-1.112,0.997-1.851,1.109%20c-117.766,16.347-193.852,47.917-193.852,80.477c0,0.739-0.29,1.448-0.809,1.974C184.196,862.379,183.492,862.681,182.753,862.693z%20M375.818,511.759c-112.182,16.055-190.25,50.281-190.25,83.607v247.286c19.32-29.092,87.48-53.929,190.565-68.475L375.818,511.759z%20'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M151.814,984.759c0,26.211,34.722,50.911,95.992,72.531h-0.248V627.858l0.698,0.248%20c-61.562-21.662-96.442-46.408-96.442-72.686V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M247.806,1060.1c-0.322,0-0.642-0.05-0.945-0.16C181.92,1037.02,149,1011.73,149,984.759v-429.34%20c0-0.746,0.297-1.462,0.824-1.99c0.528-0.528,1.244-0.825,1.991-0.825c0.746,0,1.462,0.297,1.99,0.825%20c0.528,0.528,0.824,1.244,0.824,1.99c0,23.936,32.403,48.03,93.695,69.804h0.18l0.698,0.248c0.701,0.25,1.274,0.766,1.594,1.437%20c0.321,0.671,0.363,1.441,0.118,2.143c-0.126,0.337-0.308,0.649-0.541,0.923v426.186c0.261,0.67,0.261,1.42,0,2.1%20c-0.191,0.53-0.538,0.99-0.997,1.32C248.918,1059.91,248.371,1060.09,247.806,1060.1z%20M154.629,574.446v410.313%20c0,23.461,31.142,47.081,90.07,68.451V629.884C196.512,612.613,166.383,594.059,154.629,574.446z'/%3e%3cpath%20style='fill:%23313131;'%20d='M430.175,770.752c-0.745-0.006-1.457-0.304-1.984-0.831c-0.526-0.526-0.825-1.239-0.831-1.984%20v-88.921c-0.005-0.685,0.243-1.349,0.695-1.864c0.453-0.515,1.079-0.845,1.76-0.928l118.712-15.92%20c0.401-0.053,0.81-0.021,1.198,0.096c0.388,0.116,0.747,0.314,1.053,0.58c0.299,0.265,0.538,0.591,0.701,0.956%20c0.163,0.365,0.247,0.761,0.245,1.16v88.539c-0.004,0.679-0.251,1.335-0.698,1.847c-0.446,0.513-1.061,0.848-1.734,0.945%20l-118.712,16.28L430.175,770.752z%20M432.945,681.471v83.314l113.082-15.514v-82.887L432.945,681.471z'/%3e%3cpath%20style='fill:%23313131;'%20d='M487.28,747.043c-0.4,0.001-0.796-0.082-1.161-0.245c-0.365-0.163-0.691-0.402-0.956-0.701%20l-26.818-30.174c-0.433-0.565-0.635-1.274-0.566-1.983s0.405-1.366,0.939-1.837c0.534-0.471,1.227-0.723,1.939-0.703%20c0.713,0.019,1.391,0.308,1.898,0.808l24.049,27.134l25.647-51.79c0.332-0.672,0.917-1.185,1.626-1.426%20c0.709-0.24,1.485-0.189,2.157,0.142s1.185,0.916,1.425,1.626c0.241,0.709,0.19,1.485-0.141,2.157l-27.517,55.483%20c-0.216,0.423-0.536,0.786-0.93,1.053c-0.393,0.268-0.848,0.432-1.321,0.478L487.28,747.043z'/%3e%3cpath%20style='fill:%23313131;'%20d='M412.003,521.35c-0.686,0.003-1.35-0.244-1.867-0.695c-0.516-0.452-0.85-1.076-0.939-1.757%20c-0.088-0.68,0.075-1.369,0.459-1.938c0.384-0.568,0.962-0.977,1.626-1.149c41.983-10.096,84.624-17.229,127.606-21.347%20c0.369-0.035,0.74,0.002,1.094,0.11s0.682,0.285,0.968,0.52c0.285,0.235,0.522,0.525,0.695,0.851%20c0.174,0.327,0.282,0.684,0.317,1.052c0.036,0.369-0.002,0.74-0.11,1.094c-0.108,0.354-0.285,0.682-0.52,0.968%20c-0.235,0.285-0.524,0.522-0.851,0.695c-0.326,0.174-0.684,0.282-1.052,0.317c-42.694,4.085-85.049,11.166-126.751,21.189%20C412.458,521.318,412.231,521.348,412.003,521.35z'/%3e%3cpath%20style='fill:%23313131;'%20d='M412.003,568.863c-0.686,0.003-1.35-0.244-1.867-0.695c-0.516-0.452-0.85-1.077-0.939-1.757%20c-0.088-0.68,0.075-1.369,0.459-1.938c0.384-0.569,0.962-0.977,1.626-1.15c41.983-10.095,84.624-17.228,127.606-21.346%20c0.744-0.072,1.485,0.155,2.062,0.63c0.576,0.475,0.94,1.16,1.012,1.903c0.072,0.744-0.155,1.485-0.63,2.062%20c-0.475,0.576-1.16,0.94-1.903,1.012c-42.694,4.085-85.049,11.165-126.751,21.189C412.458,568.831,412.231,568.861,412.003,568.863z%20'/%3e%3cpath%20style='fill:%23313131;'%20d='M412.003,617.095c-0.686,0.004-1.35-0.244-1.867-0.695c-0.516-0.452-0.85-1.076-0.939-1.756%20c-0.088-0.681,0.075-1.37,0.459-1.939c0.384-0.568,0.962-0.977,1.626-1.149c41.981-10.109,84.622-17.242,127.606-21.347%20c0.369-0.035,0.74,0.002,1.094,0.11c0.354,0.108,0.682,0.285,0.968,0.52c0.285,0.236,0.522,0.525,0.695,0.851%20c0.174,0.327,0.282,0.684,0.317,1.052c0.036,0.369-0.002,0.74-0.11,1.094c-0.108,0.354-0.285,0.683-0.52,0.968%20c-0.235,0.285-0.524,0.522-0.851,0.695c-0.326,0.174-0.684,0.282-1.052,0.317c-42.696,4.072-85.052,11.153-126.751,21.189%20C412.456,617.053,412.23,617.083,412.003,617.095z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1847.15,984.759c0-58.14-170.73-108.781-423.06-135.104h0.21V420.293h0.67%20c251.84,26.39,422.18,76.987,422.18,135.104V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,987.574c-0.75,0-1.46-0.297-1.99-0.825c-0.53-0.527-0.82-1.243-0.82-1.99%20c0-26.728-39.75-53.276-114.84-76.807c-74.15-23.148-179.69-42.355-305.41-55.505h-0.38c-0.71-0.122-1.36-0.505-1.8-1.076%20c-0.45-0.571-0.66-1.287-0.61-2.009c0-0.158,0-0.315,0-0.45V420.293c0-0.394,0.09-0.783,0.25-1.142c0.16-0.36,0.39-0.681,0.68-0.945%20c0.3-0.263,0.64-0.462,1.02-0.583c0.37-0.122,0.77-0.163,1.16-0.122h0.67c265.93,27.876,424.71,79.396,424.71,137.851v429.407%20c0,0.716-0.27,1.406-0.76,1.929S1847.87,987.528,1847.15,987.574z%20M1427.11,847.11c235.8,24.769,386.92,68.341,417.23,118.734%20V555.42c0-26.683-39.66-53.209-114.69-76.717c-73.47-23.035-178.04-42.13-302.54-55.28V847.11z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,987.574c-0.75,0-1.46-0.297-1.99-0.825c-0.53-0.527-0.82-1.243-0.82-1.99%20c0-26.728-39.75-53.276-114.84-76.807c-74.15-23.148-179.69-42.355-305.41-55.505h-0.38c-0.71-0.122-1.36-0.505-1.8-1.076%20c-0.45-0.571-0.66-1.287-0.61-2.009c0-0.158,0-0.315,0-0.45V420.293c0-0.394,0.09-0.783,0.25-1.142c0.16-0.36,0.39-0.681,0.68-0.945%20c0.3-0.263,0.64-0.462,1.02-0.583c0.37-0.122,0.77-0.163,1.16-0.122h0.67c265.93,27.876,424.71,79.396,424.71,137.851v429.407%20c0,0.716-0.27,1.406-0.76,1.929S1847.87,987.528,1847.15,987.574z%20M1427.11,847.11c235.8,24.769,386.92,68.341,417.23,118.734%20V555.42c0-26.683-39.66-53.209-114.69-76.717c-73.47-23.035-178.04-42.13-302.54-55.28V847.11z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,987.574c-0.75,0-1.46-0.297-1.99-0.825c-0.53-0.527-0.82-1.243-0.82-1.99%20c0-26.728-39.75-53.276-114.84-76.807c-74.15-23.148-179.69-42.355-305.41-55.505h-0.38c-0.71-0.122-1.36-0.505-1.8-1.076%20c-0.45-0.571-0.66-1.287-0.61-2.009c0-0.158,0-0.315,0-0.45V420.293c0-0.394,0.09-0.783,0.25-1.142c0.16-0.36,0.39-0.681,0.68-0.945%20c0.3-0.263,0.64-0.462,1.02-0.583c0.37-0.122,0.77-0.163,1.16-0.122h0.67c265.93,27.876,424.71,79.396,424.71,137.851v429.407%20c0,0.716-0.27,1.406-0.76,1.929S1847.87,987.528,1847.15,987.574z%20M1427.11,847.11c235.8,24.769,386.92,68.341,417.23,118.734%20V555.42c0-26.683-39.66-53.209-114.69-76.717c-73.47-23.035-178.04-42.13-302.54-55.28V847.11z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,951.433c0-43.503-62.8-81.423-155.62-101.148V529.029h0.25%20c92.64,19.748,155.37,57.622,155.37,101.081V951.433z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,954.247c-0.75,0-1.46-0.296-1.99-0.824c-0.53-0.528-0.83-1.244-0.83-1.99%20c0-40.532-58.7-78.226-153.11-98.356h-0.14c-0.72-0.143-1.35-0.557-1.77-1.157c-0.42-0.601-0.59-1.34-0.48-2.063V529.029%20c-0.01-0.43,0.07-0.857,0.25-1.247c0.18-0.391,0.45-0.735,0.79-1.005c0.32-0.264,0.7-0.454,1.11-0.555s0.84-0.111,1.25-0.031h0.25%20c97.16,20.716,157.62,60.505,157.62,103.828v321.414c0,0.381-0.08,0.758-0.23,1.109s-0.37,0.667-0.64,0.93%20c-0.28,0.264-0.6,0.468-0.96,0.601S1847.53,954.266,1847.15,954.247z%20M1694.41,848.033c78.81,17.091,132.99,46.769,149.92,80.635%20V630.087c0-40.059-57.35-77.347-149.92-97.636V848.033z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1847.15,984.759c0,26.211-34.72,50.911-95.99,72.531h0.25V627.858l-0.7,0.248%20c61.54-21.662,96.44-46.408,96.44-72.686V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1751.16,1060.1c-0.58,0.01-1.14-0.17-1.61-0.5c-0.48-0.33-0.83-0.8-1.03-1.34%20c-0.14-0.34-0.21-0.69-0.21-1.05s0.07-0.72,0.21-1.05V629.974c-0.24-0.268-0.42-0.582-0.54-0.923c-0.24-0.699-0.2-1.467,0.11-2.137%20c0.32-0.67,0.89-1.189,1.58-1.443l0.72-0.248h0.16c61.31-21.707,93.72-45.8,93.72-69.804c0-0.746,0.29-1.462,0.82-1.99%20c0.53-0.528,1.25-0.825,1.99-0.825c0.75,0,1.46,0.297,1.99,0.825c0.53,0.528,0.83,1.244,0.83,1.99v429.34%20c0,27.021-32.92,52.261-97.86,75.181C1751.75,1060.04,1751.46,1060.1,1751.16,1060.1z%20M1754.22,629.862v423.328%20c58.97-21.37,90.07-45.04,90.07-68.454v-410.29C1832.56,594.059,1802.41,612.613,1754.22,629.862z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,531.777c-0.25-0.006-0.51-0.044-0.76-0.113c-100.97-28.664-207.16-38.122-208.27-38.279%20c-0.73-0.077-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.039c0.07-0.736,0.42-1.417,0.98-1.895%20c0.56-0.479,1.29-0.718,2.03-0.664c1.06,0,107.81,9.615,209.3,38.415c0.67,0.172,1.25,0.585,1.63,1.158%20c0.39,0.574,0.55,1.268,0.45,1.952c-0.09,0.684-0.43,1.31-0.96,1.757c-0.52,0.448-1.2,0.687-1.89,0.672V531.777z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,583.363c-0.26,0.007-0.51-0.031-0.76-0.113c-100.97-28.642-207.16-38.122-208.27-38.279%20c-0.73-0.077-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.303-0.63-2.039c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.478,1.29-0.717,2.03-0.663c1.06,0,107.81,9.592,209.3,38.415c0.65,0.189,1.21,0.605,1.57,1.172%20c0.37,0.567,0.52,1.247,0.43,1.917c-0.09,0.669-0.42,1.282-0.93,1.728s-1.16,0.694-1.84,0.699V583.363z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,634.86c-0.25,0.031-0.51,0.031-0.76,0c-100.97-28.665-207.16-38.145-208.27-38.28%20c-0.73-0.076-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.038c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.479,1.29-0.717,2.03-0.664c1.06,0,107.81,9.615,209.3,38.415c0.65,0.189,1.21,0.605,1.57,1.172%20c0.37,0.567,0.52,1.248,0.43,1.917s-0.42,1.283-0.93,1.728c-0.51,0.446-1.16,0.694-1.84,0.7V634.86z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,686.651c-0.25,0.031-0.51,0.031-0.76,0c-100.97-28.664-207.16-38.122-208.27-38.279%20c-0.74-0.066-1.43-0.426-1.91-1c-0.49-0.574-0.72-1.316-0.65-2.063c0.06-0.746,0.42-1.436,1-1.917c0.57-0.482,1.31-0.715,2.06-0.65%20c1.06,0.113,107.81,9.615,209.3,38.438c0.65,0.189,1.21,0.605,1.57,1.172c0.37,0.567,0.52,1.247,0.43,1.917%20c-0.09,0.669-0.42,1.282-0.93,1.728s-1.16,0.694-1.84,0.699V686.651z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1665.68,738.149c-0.26,0.007-0.52-0.031-0.76-0.113c-100.97-28.642-207.16-38.122-208.27-38.279%20c-0.37-0.027-0.73-0.128-1.07-0.297c-0.33-0.169-0.62-0.402-0.87-0.686c-0.24-0.285-0.42-0.614-0.53-0.97%20c-0.12-0.356-0.16-0.73-0.13-1.102c0.04-0.372,0.14-0.734,0.32-1.064c0.17-0.33,0.41-0.623,0.7-0.86%20c0.28-0.238,0.62-0.415,0.97-0.523c0.36-0.108,0.74-0.144,1.11-0.105c1.06,0,107.81,9.592,209.3,38.415%20c0.65,0.189,1.21,0.605,1.57,1.172c0.37,0.567,0.52,1.247,0.43,1.917c-0.09,0.669-0.43,1.282-0.93,1.728%20c-0.51,0.446-1.16,0.694-1.84,0.699V738.149z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,789.757c-0.25-0.006-0.51-0.043-0.76-0.112c-100.97-28.665-207.16-38.145-208.27-38.28%20c-0.73-0.076-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.038c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.479,1.29-0.717,2.03-0.664c1.06,0,107.81,9.615,209.3,38.415c0.67,0.173,1.25,0.585,1.63,1.159%20c0.39,0.573,0.55,1.268,0.45,1.952c-0.09,0.684-0.43,1.309-0.96,1.757c-0.52,0.447-1.2,0.687-1.89,0.671V789.757z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,841.345c-0.25-0.006-0.51-0.043-0.76-0.112c-100.97-28.665-207.16-38.122-208.27-38.28%20c-0.73-0.076-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.038c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.479,1.29-0.717,2.03-0.664c1.06,0,107.81,9.593,209.3,38.415c0.65,0.189,1.21,0.605,1.57,1.172%20c0.37,0.568,0.52,1.248,0.43,1.917c-0.09,0.669-0.42,1.283-0.93,1.729c-0.51,0.445-1.16,0.693-1.84,0.699V841.345z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1353.64,725.516c11.45,0,20.73-14.174,20.73-31.659s-9.28-31.66-20.73-31.66%20c-11.46,0-20.74,14.175-20.74,31.66S1342.18,725.516,1353.64,725.516z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1353.66,728.308c-12.99,0-23.55-15.447-23.58-34.452c0-19.005,10.56-34.474,23.56-34.474%20c12.99,0,23.55,15.469,23.55,34.451c0.16,8.439-2.11,16.746-6.53,23.936C1366.16,724.525,1360.17,728.308,1353.66,728.308z%20M1335.64,693.856c0,15.627,8.22,28.822,18.02,28.822c4.5,0,9.01-2.837,12.29-7.993c3.83-6.262,5.78-13.492,5.61-20.829%20c0-15.65-8.22-28.845-18.01-28.845c-9.71,0-18.02,13.218-18.02,28.845H1335.64z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1320.74,885.051l7.07,69.961l129.18-35.555l52.08-176.244l-137.08-38.392L1320.74,885.051z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1327.81,957.828c-0.57-0.005-1.13-0.177-1.6-0.495c-0.34-0.233-0.62-0.538-0.82-0.892%20c-0.21-0.354-0.34-0.749-0.37-1.158l-7.14-69.939c-0.08-0.348-0.08-0.71,0-1.058l51.25-180.139c0.2-0.716,0.68-1.321,1.33-1.684%20c0.65-0.363,1.42-0.454,2.14-0.253l137.08,38.393c0.36,0.095,0.7,0.263,0.99,0.492c0.3,0.229,0.54,0.515,0.72,0.841%20c0.18,0.326,0.3,0.685,0.34,1.055c0.03,0.371,0,0.746-0.11,1.102l-51.88,176.176c-0.14,0.458-0.39,0.874-0.73,1.209%20c-0.35,0.335-0.77,0.577-1.23,0.705l-129.18,35.532C1328.34,957.79,1328.08,957.828,1327.81,957.828z%20M1323.6,885.322l6.75,66.088%20l124.46-34.248l50.75-171.966l-131.61-36.906L1323.6,885.322z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1344,804.822c0,0,27.24-14.501,75.32,0c26.52,8.017-0.9-54.379-0.9-54.379l-54.9-15.357%20L1344,804.822z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1423.53,808.357c-1.71-0.027-3.4-0.308-5.02-0.833c-46.23-13.96-72.93-0.36-73.2-0.225%20c-0.49,0.264-1.04,0.378-1.59,0.326c-0.55-0.053-1.07-0.268-1.5-0.618c-0.42-0.348-0.74-0.813-0.9-1.337%20c-0.17-0.524-0.17-1.085-0.02-1.613l19.52-69.804c0.1-0.357,0.27-0.69,0.49-0.982c0.23-0.291,0.52-0.535,0.84-0.717%20c0.32-0.181,0.67-0.298,1.04-0.343c0.37-0.045,0.74-0.017,1.1,0.083l54.92,15.469c0.4,0.113,0.77,0.313,1.08,0.585%20c0.32,0.272,0.57,0.611,0.74,0.991c3.29,7.476,19.19,45.283,9.66,56.046c-0.9,0.998-2,1.782-3.24,2.296%20C1426.21,808.195,1424.87,808.426,1423.53,808.357z%20M1378.29,795.523c14.2,0.141,28.29,2.372,41.84,6.62%20c3.06,0.923,5.18,0.765,6.31-0.496c5.13-5.809-2.66-31.524-10.07-48.817l-50.89-14.254l-17.23,61.473%20C1357.95,796.905,1368.1,795.376,1378.29,795.523z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1354.22,667.691l-9.32,41.905c-2.22,9.824-2.49,19.99-0.78,29.917%20c1.72,9.926,5.37,19.416,10.76,27.928c5.38,8.511,12.4,15.876,20.63,21.673c8.24,5.796,17.54,9.91,27.37,12.105l13.76,3.108%20c9.82,2.208,19.99,2.46,29.91,0.74c9.92-1.72,19.41-5.378,27.92-10.764c8.5-5.387,15.87-12.396,21.67-20.629%20c5.8-8.233,9.92-17.527,12.12-27.352l9.44-41.928c4.7-20.967,0.89-42.943-10.61-61.099c-11.49-18.156-29.72-31.006-50.68-35.725%20l-5.3-1.194c-10.38-2.338-21.13-2.607-31.62-0.791c-10.5,1.816-20.53,5.682-29.52,11.376c-9,5.694-16.79,13.105-22.92,21.809%20C1360.91,647.474,1356.56,657.302,1354.22,667.691z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1432.56,808.786c-5.97,0.002-11.92-0.662-17.74-1.982l-11.51-2.589%20c-10.33-2.319-20.11-6.65-28.77-12.748c-8.66-6.098-16.03-13.842-21.69-22.789c-5.67-8.948-9.52-18.925-11.32-29.36%20c-1.81-10.434-1.54-21.123,0.78-31.455l9.16-40.802c4.88-21.689,18.17-40.553,36.95-52.444c18.79-11.891,41.52-15.835,63.21-10.965%20l5.32,1.194c21.67,4.902,40.52,18.201,52.41,36.981c11.89,18.78,15.84,41.508,10.99,63.199l-9.16,40.778%20c-4.25,18.894-15.15,35.629-30.71,47.152c-0.6,0.385-1.33,0.529-2.03,0.401c-0.7-0.127-1.33-0.516-1.75-1.088%20c-0.43-0.571-0.62-1.283-0.54-1.991c0.08-0.709,0.42-1.361,0.96-1.826c14.48-10.716,24.63-26.286,28.58-43.863l9.16-40.779%20c4.52-20.235,0.84-41.437-10.25-58.955c-11.09-17.519-28.68-29.923-48.9-34.493l-5.29-1.193c-10.02-2.252-20.39-2.508-30.51-0.754%20c-10.12,1.754-19.79,5.484-28.47,10.977c-8.68,5.493-16.19,12.641-22.1,21.036c-5.92,8.396-10.12,17.874-12.37,27.894l-9.17,40.847%20c-2.16,9.612-2.4,19.555-0.72,29.263c1.68,9.707,5.26,18.988,10.53,27.313c5.27,8.324,12.12,15.529,20.18,21.202%20c8.05,5.674,17.15,9.705,26.76,11.863l11.5,2.568c13.56,3.061,27.69,2.281,40.83-2.252c0.35-0.137,0.73-0.201,1.11-0.19%20c0.37,0.012,0.74,0.1,1.09,0.259c0.34,0.159,0.65,0.385,0.9,0.665c0.26,0.28,0.45,0.609,0.58,0.966%20c0.12,0.357,0.17,0.736,0.15,1.113c-0.03,0.377-0.13,0.745-0.3,1.083c-0.17,0.337-0.41,0.636-0.7,0.88%20c-0.29,0.244-0.62,0.427-0.99,0.538C1450.31,807.335,1441.46,808.803,1432.56,808.786z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1354.22,667.69c0,0,11.91-19.636,23.37-26.751c11.47-7.116,92.87,13.308,99.55,18.802%20c5.77,4.751,9.89,13.195,12.5,29.881c2.86,18.351,25.45,25.985,25.45,25.985l2.52-11.259l19.41-80.838%20c0.12-0.513,0.14-1.046,0.05-1.566c-0.08-0.521-0.27-1.02-0.55-1.466c-0.28-0.447-0.65-0.833-1.08-1.136%20c-0.44-0.303-0.92-0.516-1.44-0.628l-153.07-33.393c-0.99-0.215-2.03-0.043-2.89,0.48c-0.87,0.523-1.5,1.359-1.77,2.335%20L1354.22,667.69z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1515.09,718.422c-0.31,0.001-0.61-0.045-0.9-0.135c-0.99-0.338-24.23-8.422-27.34-28.237%20c-2.25-14.816-5.85-23.486-11.51-28.147c-6.05-4.976-86.46-24.634-96.28-18.554c-10.76,6.755-22.32,25.602-22.52,25.782%20c-0.34,0.615-0.89,1.081-1.56,1.306c-0.66,0.225-1.39,0.194-2.03-0.088c-0.65-0.282-1.16-0.794-1.45-1.436%20c-0.28-0.642-0.31-1.367-0.09-2.033l22.06-79.554c0.46-1.678,1.55-3.115,3.04-4.012c1.48-0.898,3.26-1.187,4.96-0.807l153.12,33.461%20c0.88,0.19,1.72,0.556,2.46,1.076c0.73,0.519,1.36,1.182,1.84,1.948s0.8,1.621,0.94,2.513c0.14,0.892,0.11,1.804-0.11,2.682%20l-19.41,80.815l-2.5,11.258c-0.09,0.383-0.26,0.744-0.49,1.058c-0.24,0.314-0.54,0.575-0.88,0.766%20C1516.02,718.312,1515.56,718.428,1515.09,718.422z%20M1386.38,636.819c26.3,0,87.25,16.392,92.54,20.738%20c6.76,5.607,10.97,15.357,13.51,31.637c1.99,12.655,14.8,19.861,20.65,22.518l1.8-7.949l19.41-80.882%20c0.04-0.148,0.05-0.302,0.03-0.453c-0.03-0.151-0.08-0.296-0.16-0.426c-0.08-0.127-0.19-0.237-0.31-0.322s-0.26-0.144-0.41-0.173%20l-153.12-33.483c-0.29-0.057-0.59-0.002-0.84,0.152c-0.25,0.155-0.43,0.398-0.51,0.681l-17.72,64.017%20c4.16-5.516,9.18-10.334,14.86-14.276C1379.33,637.169,1382.86,636.558,1386.38,636.819z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1418.49,711.871h-0.61l-23.26-5.224c-0.49-0.107-0.93-0.34-1.3-0.676%20c-0.36-0.337-0.63-0.764-0.77-1.238c-0.32-0.968-1.26-3.941,10.13-32.02c0.28-0.693,0.82-1.246,1.51-1.537%20c0.69-0.291,1.47-0.297,2.16-0.017c0.69,0.281,1.25,0.825,1.54,1.514c0.29,0.688,0.29,1.464,0.01,2.157%20c-3.68,8.778-6.9,17.745-9.63,26.863l20.85,4.684c0.67,0.151,1.27,0.547,1.68,1.113c0.4,0.566,0.58,1.261,0.5,1.951%20c-0.08,0.69-0.41,1.327-0.93,1.788s-1.19,0.714-1.88,0.709V711.871z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1448.86,687.056c-0.63-0.005-1.24-0.217-1.73-0.603c-0.5-0.387-0.86-0.927-1.01-1.536%20c-3.72-14.907-20.27-16.46-21.08-16.506c-0.74-0.063-1.43-0.418-1.91-0.988c-0.49-0.57-0.72-1.308-0.66-2.051%20c0.03-0.369,0.13-0.728,0.29-1.057c0.17-0.33,0.4-0.623,0.68-0.862c0.28-0.239,0.61-0.42,0.96-0.531s0.72-0.151,1.09-0.117%20c0.22,0,21.39,1.869,26.1,20.738c0.09,0.359,0.11,0.733,0.05,1.1c-0.05,0.367-0.18,0.719-0.37,1.037%20c-0.19,0.318-0.44,0.595-0.74,0.816c-0.29,0.221-0.63,0.38-0.99,0.47C1449.32,687.018,1449.09,687.048,1448.86,687.056z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1379.31,671.97c-0.53,0-1.04-0.146-1.48-0.421c-0.45-0.274-0.81-0.667-1.04-1.135%20c-0.24-0.468-0.33-0.991-0.29-1.512c0.05-0.52,0.24-1.017,0.55-1.436c9.01-11.889,26.06-9.322,26.78-9.209%20c0.36,0.057,0.71,0.186,1.03,0.379c0.31,0.193,0.59,0.447,0.81,0.746c0.21,0.299,0.37,0.638,0.46,0.997%20c0.08,0.36,0.1,0.733,0.04,1.098c-0.06,0.365-0.19,0.715-0.38,1.031c-0.19,0.315-0.45,0.589-0.75,0.807%20c-0.29,0.217-0.63,0.373-0.99,0.46c-0.36,0.086-0.74,0.101-1.1,0.044c-0.14,0-14.41-2.117-21.41,7.07%20c-0.27,0.338-0.61,0.612-0.99,0.799C1380.16,671.875,1379.74,671.972,1379.31,671.97z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1428.35,692.641c2.01,0,3.65-1.633,3.65-3.647c0-2.015-1.64-3.648-3.65-3.648%20c-2.02,0-3.65,1.633-3.65,3.648C1424.7,691.008,1426.33,692.641,1428.35,692.641z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1390.36,685.727c2.02,0,3.65-1.633,3.65-3.648c0-2.014-1.63-3.647-3.65-3.647%20c-2.01,0-3.65,1.633-3.65,3.647C1386.71,684.094,1388.35,685.727,1390.36,685.727z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1523.27,735.838c7.49-15.802,5.16-32.587-5.19-37.49c-10.35-4.904-24.81,3.93-32.29,19.731%20c-7.49,15.802-5.17,32.587,5.18,37.491C1501.33,760.473,1515.78,751.639,1523.27,735.838z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1497.07,759.653h-1.3c-0.75-0.051-1.45-0.396-1.94-0.96c-0.49-0.564-0.74-1.3-0.69-2.047%20c0.05-0.746,0.4-1.442,0.96-1.934c0.57-0.492,1.3-0.74,2.05-0.689c8.56,0.563,18.82-7.588,24.43-19.432%20c6.76-14.141,4.93-29.588-3.85-33.776c-6.24-2.95-14.82,0.247-21.87,8.196c-0.49,0.558-1.19,0.897-1.93,0.941%20c-0.75,0.045-1.48-0.209-2.04-0.705c-0.56-0.495-0.9-1.193-0.94-1.938c-0.05-0.745,0.21-1.478,0.7-2.036%20c8.74-9.863,19.93-13.51,28.49-9.547c11.73,5.561,14.66,24.048,6.53,41.229C1519.34,750.533,1507.7,759.653,1497.07,759.653z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1509.39,729.974h-0.25l-5.83-0.518c-0.54-0.048-1.05-0.251-1.48-0.584%20c-0.43-0.333-0.75-0.781-0.93-1.292c-0.17-0.511-0.2-1.062-0.07-1.588c0.12-0.526,0.4-1.004,0.79-1.377l11.51-11.011%20c0.26-0.279,0.57-0.501,0.92-0.654c0.35-0.153,0.73-0.234,1.11-0.236s0.76,0.073,1.12,0.221c0.35,0.149,0.67,0.368,0.93,0.643%20c0.26,0.276,0.47,0.602,0.61,0.96c0.13,0.357,0.19,0.738,0.17,1.12c-0.02,0.382-0.11,0.756-0.28,1.099%20c-0.16,0.344-0.4,0.65-0.69,0.9l-7.05,6.755c0.7,0.125,1.33,0.51,1.76,1.079c0.43,0.569,0.62,1.278,0.55,1.986%20c-0.07,0.708-0.41,1.361-0.95,1.829c-0.54,0.467-1.23,0.714-1.94,0.691V729.974z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1349.9,689.691c-0.51,0-1-0.139-1.44-0.401c-0.43-0.262-0.78-0.637-1.02-1.086l-4.5-8.331%20c-0.2-0.325-0.33-0.687-0.38-1.064c-0.06-0.377-0.04-0.761,0.06-1.129s0.27-0.712,0.51-1.011c0.23-0.3,0.53-0.549,0.86-0.732%20s0.7-0.296,1.08-0.333s0.76,0.004,1.12,0.119c0.37,0.115,0.7,0.303,0.99,0.552c0.29,0.249,0.52,0.554,0.69,0.896l4.5,8.354%20c0.18,0.323,0.29,0.679,0.33,1.046c0.04,0.366,0.01,0.737-0.09,1.091c-0.11,0.354-0.28,0.684-0.52,0.97%20c-0.23,0.286-0.52,0.524-0.84,0.698C1350.84,689.57,1350.37,689.694,1349.9,689.691z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1429.07,743.8c-8.87,0-15.76-7.318-18.44-12.092c-0.3-0.511-0.43-1.103-0.37-1.692%20c0.05-0.589,0.3-1.145,0.69-1.589c0.39-0.444,0.91-0.753,1.49-0.883c0.58-0.131,1.18-0.076,1.72,0.156%20c2.77,1.076,5.73,1.543,8.69,1.368c2.96-0.175,5.85-0.987,8.47-2.381c4.51-2.252,7.86-5.652,8.65-8.715%20c0.13-0.647,0.48-1.228,0.99-1.64c0.52-0.413,1.16-0.629,1.82-0.611c0.64,0.021,1.25,0.255,1.73,0.663%20c0.49,0.408,0.82,0.968,0.95,1.588c0.14,0.766,3.22,18.712-9.57,24.184C1433.76,743.174,1431.43,743.734,1429.07,743.8z%20M1420.54,734.793c1.71,1.64,3.87,2.745,6.21,3.181c2.33,0.435,4.74,0.183,6.94-0.727c1.78-0.917,3.3-2.28,4.4-3.957%20s1.75-3.611,1.88-5.613c-1.86,1.638-3.93,3.024-6.15,4.121c-4.12,2.065-8.68,3.071-13.28,2.927V734.793z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1013.69,1586.72c-1.42,8.19-3.22,12.97-5.27,13.01c-2.05,0.05-3.92-4.3-5.63-11.89%20c-3.263-14.23-5.807-39.97-6.438-69.37c-0.643-20.29,0.049-40.6,2.072-60.8c1.531-12.99,3.786-20.92,6.416-20.96%20c2.64-0.05,5.36,8.19,7.48,21.72c2.75,19.73,4.25,39.61,4.5,59.52C1017.56,1546.82,1016.14,1572.17,1013.69,1586.72z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1008.35,1602.52c-3.46,0-7.11-3.28-10.511-26.09c-4.906-38.45-5.767-77.31-2.567-115.95%20c2.409-23.21,5.988-26.48,9.498-26.54c3.52-0.07,7.21,3.01,10.63,26.09c2.61,19.2,4.05,38.54,4.33,57.92%20c0.57,19.36-0.01,38.74-1.76,58.03c-2.41,23.21-5.99,26.48-9.48,26.54H1008.35z%20M1004.91,1440.4c-3.22,5.99-6.756,34.25-5.765,78.11%20c0.995,43.87,5.715,71.92,9.205,77.78c3.2-5.99,6.76-34.27,5.75-78.12c-0.97-43.95-5.72-72.03-9.21-77.88L1004.91,1440.4z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1016.91,1517.99c-0.25-19.91-1.75-39.79-4.5-59.51l-5.2-0.27l-4.82-0.27l-3.875-0.22l-3.603-0.21%20l-4.751-0.24l-5.742-0.34l-4.954-0.25l-11.552-0.61l-11.258-0.52l-10.809-0.45l-4.323-0.15c-3.333-0.14-6.755-0.25-10.088-0.34%20c-4.098-0.14-8.241-0.23-12.362-0.32h-2.251c-52.128-0.92-104.954,1.8-140.847,15.95c-2.094,0.83-4.278,1.71-6.485,2.67%20c-2.207,0.97-4.503,1.96-6.868,3.02l-3.535,1.62l-7.183,3.45l-3.648,1.82l-3.648,1.87c-19.477,10.11-38.752,22.14-48.727,31.93%20l-1.734,1.8c-0.811,0.9-1.554,1.76-2.252,2.59c-2.544,3.4-3.58,6.4-2.567,8.78c0.171,0.41,0.374,0.8,0.608,1.17%20c4.143,6.4,15.425,1.49,17.113,0.75l-0.18,0.11c-4.03,2.45-32.38,20.15-25.85,34.02c0.073,0.2,0.156,0.38,0.248,0.57%20c5.607,10.45,28.575-3.76,37.469-9.8c-6.553,4.91-19.568,16.35-15.289,26.75l0.202,0.43c0.233,0.43,0.555,0.81,0.946,1.1%20c7.633,6.08,41.387-7,47.467-9.41l0.36-0.13h-0.293h-0.135c-4.503,1.93-22.517,10.53-20.266,19.99c0.12,0.53,0.301,1.05,0.541,1.53%20c0.13,0.27,0.297,0.52,0.495,0.75c6.08,6.98,43.211-3.83,88.111-9.6c3.603-0.45,7.25-0.9,10.921-1.26%20c16.955-1.78,45.71,7.64,86.534,6.76c6.68-0.14,13.285-0.37,19.815-0.7l2.252-0.11l3.693-0.21c6.125-0.36,12.129-0.76,18.014-1.21%20c5.164-0.41,10.238-0.84,15.222-1.31l5.044-0.45l9.975-0.97l5.472-0.54l4.823-0.49c3.71-0.36,7.34-0.74,10.89-1.13%20C1016.15,1572.17,1017.56,1546.82,1016.91,1517.99z'/%3e%3cpath%20style='fill:%23313131;'%20d='M741.186,1602.77c-5.247,0-8.58-0.92-10.494-2.99c-0.39-0.45-0.716-0.95-0.968-1.49%20c-0.341-0.67-0.591-1.38-0.743-2.12c-0.332-1.88-0.21-3.82,0.358-5.65c0.568-1.83,1.565-3.5,2.907-4.86%20c-11.799,3.53-24.274,5.74-29.475,1.6l-0.338-0.27c-0.551-0.5-1.029-1.06-1.419-1.69c-0.028-0.07-0.066-0.14-0.112-0.2l-0.203-0.43%20c-1.016-2.35-1.466-4.9-1.313-7.45c0.152-2.55,0.903-5.03,2.191-7.23c-6.89,3.06-12.429,4.05-16.55,2.95%20c-1.394-0.35-2.697-0.99-3.817-1.89c-1.12-0.9-2.031-2.03-2.668-3.32c-0.157-0.29-0.27-0.54-0.383-0.78%20c-4.503-10.47,6.756-22.34,16.461-30c-1.467-0.16-2.878-0.64-4.129-1.42c-1.252-0.78-2.311-1.83-3.1-3.08%20c-0.322-0.5-0.601-1.03-0.833-1.58c-1.351-3.24-0.36-7.11,2.928-11.55c0.69-0.93,1.443-1.81,2.251-2.63%20c0.086-0.12,0.184-0.22,0.293-0.32l1.666-1.73c9.3-9.21,27.291-21.01,49.404-32.45h0.225l3.445-1.78l3.603-1.78%20c2.544-1.26,4.954-2.43,7.34-3.53l3.581-1.65c2.364-1.08,4.661-2.09,6.912-3.04c2.252-0.94,4.504-1.86,6.553-2.7%20c30.894-12.16,75.996-17.29,141.86-16.14c0.698,0,1.531,0,2.251,0c4.121,0,8.264,0.18,12.385,0.31c3.378,0,6.755,0.2,10.11,0.34%20l4.346,0.16l10.854,0.45c3.783,0.16,7.565,0.34,11.258,0.54l12.227,0.63c1.441,0,2.837,0.16,4.279,0.2l28.011,1.56%20c0.64,0.03,1.25,0.29,1.73,0.72c0.48,0.43,0.8,1.01,0.9,1.64c2.78,19.86,4.28,39.87,4.51,59.92c0.63,27.99-0.61,53.88-3.27,69.26%20c-0.12,0.59-0.43,1.13-0.88,1.54c-0.45,0.4-1.01,0.65-1.62,0.71l-21.185,2.26l-6.237,0.6l-8.827,0.81%20c-4.954,0.45-10.043,0.9-15.222,1.29c-6.62,0.52-12.565,0.92-18.172,1.24l-3.738,0.2h-0.72c-0.54,0-1.081,0-1.644,0%20c-6.44,0.34-13.127,0.56-19.838,0.72c-19.27,0.14-38.518-1.36-57.532-4.5c-12.069-1.72-21.594-3.09-28.754-2.26%20c-3.671,0.39-7.274,0.81-10.854,1.26c-15.402,1.96-29.835,4.51-42.58,6.76C760.866,1600.86,748.932,1602.77,741.186,1602.77z%20M753.232,1578h-0.157c-10.133,4.62-19.816,11.6-18.6,16.78c0.064,0.32,0.17,0.63,0.316,0.92c2.904,3.22,23.238-0.29,42.895-3.69%20c12.813-2.25,27.314-4.73,42.783-6.76c3.603-0.45,7.273-0.9,10.989-1.28c7.836-0.81,17.676,0.61,30.128,2.39%20c18.707,3.1,37.646,4.61,56.609,4.5c6.755-0.14,13.285-0.38,19.748-0.7h1.531h0.788l3.648-0.2c5.584-0.32,11.506-0.72,18.014-1.22%20c5.134-0.4,10.193-0.83,15.176-1.28l8.76-0.81l6.215-0.61l19.045-1.94c2.37-15.24,3.43-39.67,2.86-66.08%20c-0.27-18.99-1.64-37.94-4.09-56.77l-25.719-1.42l-4.278-0.22l-12.205-0.63l-11.259-0.52l-10.605-0.45l-4.504-0.18l-10.11-0.32%20c-4.121-0.13-8.219-0.25-12.34-0.31h-2.251c-65.301-1.15-109.638,3.87-139.811,15.76c-2.072,0.81-4.233,1.69-6.417,2.63%20c-2.185,0.95-4.504,1.94-6.756,3l-3.535,1.62c-2.252,1.08-4.706,2.25-7.093,3.4l-3.648,1.8l-3.602,1.87h-0.203%20c-21.234,11.01-39.113,22.72-47.85,31.34l-1.531,1.58c-0.04,0.07-0.093,0.13-0.157,0.18c-0.7,0.72-1.361,1.47-1.982,2.25%20c-1.959,2.64-2.747,4.75-2.252,5.99c0.101,0.26,0.229,0.51,0.383,0.74c2.252,3.72,9.863,1.45,13.511-0.27h0.247%20c0.689-0.25,1.449-0.23,2.124,0.06c0.675,0.29,1.212,0.82,1.502,1.5c0.211,0.52,0.262,1.09,0.146,1.64%20c-0.117,0.55-0.395,1.05-0.799,1.44c-0.151,0.15-0.317,0.28-0.496,0.39l-0.338,0.22c-10.38,6.49-28.822,21.12-24.769,30.44%20c0.054,0.15,0.122,0.28,0.203,0.41c0.283,0.57,0.688,1.06,1.187,1.45c0.498,0.39,1.078,0.66,1.695,0.8%20c4.886,1.29,14.524-2.48,26.481-10.33c0.599-0.34,1.302-0.45,1.975-0.31c0.673,0.15,1.269,0.54,1.677,1.09%20c0.407,0.55,0.598,1.24,0.535,1.92c-0.063,0.69-0.375,1.33-0.877,1.8c-5.382,4.37-13.871,12.83-10.448,20.56v0.18%20c0.07,0.11,0.153,0.2,0.247,0.29h0.113c4.008,3.36,22.765-0.79,44.584-9.86l0.406-0.14c0.377-0.09,0.771-0.11,1.155-0.05%20c0.385,0.07,0.752,0.21,1.08,0.42c0.327,0.21,0.608,0.49,0.824,0.81c0.216,0.33,0.362,0.69,0.431,1.07%20c0.166,0.61,0.126,1.25-0.115,1.83c-0.24,0.58-0.668,1.06-1.214,1.37V1578z'/%3e%3cpath%20style='fill:%23313131;'%20d='M752.85,1578c-0.644,0-1.267-0.22-1.767-0.63c-0.5-0.4-0.846-0.97-0.98-1.6%20c-0.134-0.63-0.049-1.28,0.242-1.86c0.291-0.57,0.769-1.03,1.356-1.29c29.701-13.51,69.804-24.14,87.976-27.72%20c0.734-0.14,1.496,0.01,2.116,0.43c0.621,0.42,1.05,1.06,1.194,1.8c0.143,0.73-0.011,1.49-0.429,2.12%20c-0.418,0.62-1.066,1.05-1.801,1.19c-18.013,3.51-57.464,14.05-86.737,27.31C753.65,1577.91,753.252,1578,752.85,1578z'/%3e%3cpath%20style='fill:%23313131;'%20d='M714.412,1562.33c-0.442,0-0.877-0.11-1.268-0.31c-0.392-0.21-0.729-0.5-0.984-0.86%20c-0.218-0.3-0.375-0.64-0.462-1c-0.086-0.36-0.101-0.74-0.042-1.1c0.059-0.37,0.189-0.72,0.384-1.03%20c0.194-0.32,0.449-0.59,0.75-0.81c25.985-18.58,90.07-43.8,113.871-48.48c0.37-0.09,0.756-0.11,1.133-0.05%20c0.377,0.06,0.738,0.2,1.061,0.4c0.322,0.21,0.599,0.48,0.815,0.79c0.215,0.32,0.364,0.67,0.438,1.05%20c0.073,0.37,0.07,0.76-0.011,1.13c-0.08,0.38-0.236,0.73-0.457,1.04c-0.222,0.31-0.504,0.57-0.831,0.77%20c-0.326,0.2-0.689,0.33-1.067,0.39c-22.878,4.5-86.692,29.67-111.664,47.55C715.589,1562.15,715.007,1562.33,714.412,1562.33z'/%3e%3cpath%20style='fill:%23313131;'%20d='M707.14,1534.38c-0.43,0.02-0.857-0.07-1.247-0.25c-0.391-0.18-0.735-0.45-1.005-0.78%20c-0.233-0.29-0.406-0.62-0.511-0.98c-0.104-0.35-0.137-0.72-0.098-1.09c0.04-0.37,0.152-0.73,0.33-1.05%20c0.178-0.33,0.418-0.61,0.707-0.84c19.162-15.52,73.001-40.81,108.511-48.21c0.372-0.11,0.763-0.14,1.148-0.09%20c0.384,0.05,0.754,0.18,1.086,0.38c0.333,0.2,0.62,0.46,0.845,0.78c0.224,0.31,0.381,0.67,0.46,1.05c0.08,0.38,0.08,0.77,0.001,1.15%20c-0.08,0.38-0.236,0.74-0.461,1.06c-0.224,0.31-0.512,0.58-0.844,0.78c-0.332,0.2-0.702,0.33-1.086,0.38%20c-34.182,7.14-87.818,32.29-106.125,47.11C708.362,1534.16,707.761,1534.37,707.14,1534.38z'/%3e%3cpath%20style='fill:%23313131;'%20d='M956.023,1029.28c-57.982,76.8-226.727,80.7-226.727,80.7s-39.653-256.115-58.05-279.218%20c-18.397-23.103-101.328,0.923-103.22-30.624c-1.891-31.547,86.625-25.58,84.778-42.175%20c-1.846-16.595-174.622-24.026-165.188-48.052c9.435-24.026,87.188-22.72,87.188-22.72c-3.31-29.093,41.094-31.682,41.094-31.682%20c0-15.92,42.4-17.271,42.4-17.271c0.924-8.286,83.855-28.732,179.667,88.246c58.703,71.605,88.561,156.608,103.58,218.283%20c2.409,9.886,4.503,19.163,6.102,27.674C951.537,991.208,954.334,1010.18,956.023,1029.28z'/%3e%3cpath%20style='fill:%23313131;'%20d='M729.297,1112.86c-0.673,0-1.324-0.24-1.835-0.68c-0.511-0.44-0.851-1.04-0.958-1.71%20c-13.668-88.31-43.256-260.117-57.464-277.861c-7.633-9.548-29.07-10.223-49.808-10.899c-25.986-0.81-52.871-1.666-54.042-21.324%20c-1.216-20.716,29.835-26.773,54.762-31.659c12.88-2.522,30.534-5.967,30.038-10.381c-1.914-5.449-41.387-11.821-70.209-16.46%20c-52.826-8.534-87.818-14.951-94.28-26.12c-0.616-1.025-0.985-2.179-1.079-3.37c-0.094-1.192,0.091-2.389,0.538-3.498%20c9.007-23.17,70.772-24.589,86.872-24.566c-0.111-5.878,1.941-11.591,5.765-16.055c9.75-11.597,29.07-14.636,35.803-15.38%20c3.377-14.433,34.766-16.978,43.188-17.406c2.332-2.232,5.228-3.789,8.376-4.503c3.243-0.946,80.297-22.09,175.208,93.762%20c59.671,72.822,89.529,159.514,104.098,219.41c2.252,9.3,4.301,18.644,6.125,27.809c3.882,18.891,6.694,37.991,8.422,57.191%20c0.042,0.68-0.157,1.35-0.563,1.89c-58.14,77.01-221.977,81.72-228.912,81.88L729.297,1112.86z%20M571.675,689.961%20c-23.103,0-74.533,3.625-81.356,20.986c-0.131,0.329-0.183,0.683-0.152,1.035c0.032,0.352,0.145,0.692,0.332,0.992%20c5.517,9.66,52.511,17.248,90.273,23.35c52.488,8.467,73.969,12.768,74.915,21.392c1.081,9.57-14.636,12.655-34.542,16.528%20c-22.787,4.503-51.137,10.02-50.213,25.805c0.833,14.523,24.026,15.266,48.57,16.055c22.022,0.698,44.787,1.418,54.041,12.97%20c18.014,22.382,53.885,250.076,58.253,278.066c20.896-0.9,168.183-9.66,221.459-78.81c-1.75-18.61-4.501-37.105-8.242-55.415%20c-1.801-9.007-3.85-18.374-6.079-27.584c-14.412-59.333-43.977-145.17-102.972-217.158%20c-73.993-90.317-138.077-94.731-155.979-93.943c-12.001,0.541-17.811,3.446-18.802,4.504c-0.128,0.614-0.456,1.167-0.933,1.575%20c-0.477,0.407-1.075,0.645-1.701,0.677c-10.291,0.337-39.676,3.693-39.676,14.456c0.001,0.714-0.271,1.401-0.761,1.921%20c-0.49,0.519-1.16,0.831-1.873,0.871c-0.248,0-24.094,1.576-34.204,13.51c-1.737,2.044-3.018,4.435-3.756,7.014%20c-0.737,2.578-0.916,5.285-0.523,7.938c0.055,0.404,0.021,0.814-0.099,1.203c-0.121,0.389-0.325,0.747-0.599,1.049%20c-0.271,0.296-0.601,0.532-0.97,0.691s-0.767,0.238-1.169,0.232L571.675,689.961z'/%3e%3cpath%20style='fill:%23313131;'%20d='M625.265,691.56h-0.157c-0.338,0-34.407-1.801-50.214-1.576c-0.37,0.012-0.739-0.051-1.084-0.185%20c-0.346-0.134-0.66-0.336-0.925-0.595c-0.265-0.259-0.475-0.569-0.617-0.91c-0.143-0.342-0.214-0.71-0.211-1.08%20c0-0.735,0.287-1.441,0.8-1.967s1.212-0.83,1.947-0.848c15.987-0.225,50.236,1.577,50.574,1.599c0.7,0.078,1.346,0.415,1.81,0.945%20c0.463,0.531,0.711,1.216,0.694,1.92c-0.017,0.705-0.297,1.377-0.786,1.885c-0.489,0.507-1.15,0.813-1.853,0.857L625.265,691.56z'/%3e%3cpath%20style='fill:%23313131;'%20d='M661.564,663.908h-0.608c-0.316,0-31.525-6.755-44.743-5.539c-0.366,0.037-0.737,0.001-1.09-0.106%20c-0.353-0.106-0.682-0.282-0.967-0.517c-0.284-0.234-0.52-0.523-0.692-0.849c-0.173-0.326-0.279-0.683-0.313-1.05%20c-0.037-0.368-0.002-0.74,0.105-1.095c0.107-0.354,0.282-0.684,0.516-0.971c0.234-0.286,0.523-0.524,0.849-0.699%20c0.326-0.175,0.684-0.283,1.052-0.32c14.073-1.396,45.17,5.359,46.498,5.629c0.662,0.17,1.241,0.572,1.629,1.133%20c0.389,0.561,0.563,1.244,0.489,1.923c-0.074,0.679-0.39,1.309-0.891,1.773c-0.501,0.465-1.152,0.733-1.834,0.756V663.908z'/%3e%3cpath%20style='fill:%23313131;'%20d='M696.871,648.37c-0.267,0.01-0.534-0.028-0.788-0.112c-0.248,0-24.544-7.138-37.672-7.138%20c-0.746,0-1.462-0.297-1.99-0.825c-0.528-0.528-0.824-1.244-0.824-1.99c-0.003-0.369,0.067-0.734,0.206-1.076%20c0.139-0.341,0.344-0.651,0.604-0.913c0.259-0.262,0.568-0.469,0.908-0.611c0.34-0.142,0.705-0.215,1.074-0.215%20c13.938,0,38.279,7.071,39.248,7.363c0.715,0.219,1.315,0.71,1.673,1.366c0.358,0.657,0.444,1.428,0.241,2.147%20c-0.174,0.577-0.528,1.083-1.01,1.444C698.059,648.17,697.473,648.367,696.871,648.37z'/%3e%3cpath%20style='fill:%23313131;'%20d='M725.243,897.684c-0.642-0.011-1.261-0.24-1.756-0.649c-0.494-0.409-0.836-0.974-0.968-1.603%20l-4.616-19.297c-0.143-0.714-0.003-1.456,0.39-2.069c0.393-0.613,1.008-1.05,1.716-1.22c0.709-0.169,1.455-0.057,2.083,0.313%20c0.627,0.37,1.087,0.968,1.282,1.67l4.504,19.275c0.087,0.361,0.102,0.735,0.043,1.102c-0.058,0.366-0.188,0.718-0.383,1.034%20c-0.194,0.316-0.45,0.59-0.751,0.807c-0.301,0.217-0.642,0.372-1.003,0.457C725.61,897.581,725.429,897.641,725.243,897.684z'/%3e%3cpath%20style='fill:%23313131;'%20d='M736.659,945.466c-0.641-0.011-1.26-0.24-1.755-0.65c-0.495-0.409-0.837-0.973-0.969-1.602%20l-4.616-19.274c-0.173-0.729-0.05-1.497,0.343-2.134c0.392-0.638,1.022-1.093,1.751-1.267c0.728-0.173,1.496-0.049,2.134,0.343%20c0.637,0.393,1.093,1.023,1.266,1.752l4.503,19.274c0.088,0.358,0.103,0.73,0.046,1.094c-0.057,0.363-0.186,0.712-0.378,1.026%20c-0.193,0.314-0.446,0.587-0.744,0.803c-0.299,0.216-0.637,0.37-0.995,0.455C737.059,945.372,736.862,945.433,736.659,945.466z'/%3e%3cpath%20style='fill:%23313131;'%20d='M748.188,993.248c-0.647-0.003-1.273-0.228-1.773-0.638c-0.501-0.41-0.844-0.98-0.974-1.614%20l-4.503-19.275c-0.143-0.714-0.003-1.456,0.39-2.069c0.393-0.613,1.008-1.051,1.717-1.22c0.708-0.169,1.454-0.057,2.082,0.313%20c0.627,0.37,1.087,0.968,1.282,1.67l4.504,19.275c0.087,0.359,0.103,0.732,0.046,1.097c-0.057,0.366-0.185,0.716-0.377,1.032%20c-0.193,0.316-0.445,0.591-0.744,0.809s-0.637,0.375-0.997,0.462L748.188,993.248z'/%3e%3cpath%20style='fill:%23313131;'%20d='M759.447,1041.05c-0.646-0.01-1.27-0.23-1.77-0.64c-0.499-0.41-0.844-0.98-0.978-1.61l-4.503-19.28%20c-0.102-0.36-0.129-0.74-0.079-1.12c0.049-0.37,0.173-0.73,0.365-1.06c0.193-0.33,0.448-0.61,0.753-0.83%20c0.304-0.23,0.651-0.39,1.019-0.48c0.368-0.09,0.75-0.1,1.123-0.04c0.373,0.07,0.73,0.21,1.049,0.41%20c0.318,0.2,0.593,0.47,0.806,0.78c0.213,0.32,0.362,0.67,0.436,1.04l4.616,19.27c0.169,0.73,0.043,1.49-0.349,2.13%20c-0.393,0.63-1.02,1.08-1.745,1.25C759.954,1040.97,759.703,1041.03,759.447,1041.05z'/%3e%3cpath%20style='fill:%23313131;'%20d='M770.931,1088.83c-0.646,0-1.271-0.22-1.769-0.63c-0.497-0.41-0.835-0.98-0.956-1.62l-4.616-19.27%20c-0.102-0.37-0.129-0.75-0.079-1.13c0.049-0.37,0.173-0.73,0.365-1.06c0.193-0.32,0.448-0.61,0.753-0.83%20c0.304-0.23,0.651-0.39,1.019-0.48c0.368-0.08,0.75-0.1,1.123-0.03c0.374,0.06,0.73,0.2,1.049,0.4c0.318,0.21,0.593,0.47,0.806,0.78%20c0.214,0.32,0.362,0.67,0.436,1.04l4.616,19.28c0.169,0.72,0.044,1.49-0.348,2.13c-0.392,0.63-1.02,1.09-1.746,1.27%20C771.372,1088.75,771.153,1088.8,770.931,1088.83z'/%3e%3cpath%20style='fill:%23313131;'%20d='M895.43,998.562c-3.514,0-6.949-1.042-9.871-2.994c-2.921-1.953-5.198-4.727-6.543-7.974%20c-1.345-3.246-1.697-6.818-1.011-10.264c0.685-3.447,2.377-6.612,4.862-9.097c2.485-2.485,5.65-4.177,9.097-4.862%20c3.446-0.686,7.018-0.334,10.265,1.011c3.246,1.344,6.021,3.622,7.973,6.543c1.952,2.922,2.994,6.357,2.994,9.871%20c0,4.711-1.872,9.23-5.204,12.562C904.661,996.69,900.142,998.562,895.43,998.562z%20M895.43,968.681%20c-2.402,0-4.749,0.713-6.745,2.047c-1.997,1.335-3.552,3.232-4.47,5.451c-0.918,2.219-1.157,4.66-0.687,7.015%20c0.47,2.355,1.628,4.518,3.328,6.214c1.699,1.697,3.864,2.851,6.22,3.316c2.356,0.466,4.797,0.223,7.014-0.699%20c2.217-0.922,4.111-2.482,5.442-4.48c1.331-1.999,2.039-4.348,2.035-6.749c0-1.593-0.314-3.17-0.925-4.642%20c-0.61-1.471-1.504-2.807-2.631-3.933c-1.128-1.125-2.466-2.017-3.938-2.624C898.6,968.989,897.023,968.678,895.43,968.681z'/%3e%3cpath%20style='fill:%23313131;'%20d='M839.676,1021.78c-3.514,0-6.951-1.04-9.876-2.98c-2.925-1.95-5.205-4.73-6.553-7.97%20c-1.349-3.25-1.704-6.82-1.021-10.27c0.683-3.448,2.374-6.615,4.857-9.102c2.484-2.487,5.65-4.182,9.097-4.869%20s7.02-0.337,10.268,1.007c3.247,1.344,6.023,3.621,7.976,6.544c1.954,2.922,2.996,6.36,2.996,9.87%20c-0.006,4.71-1.876,9.22-5.202,12.55S844.383,1021.77,839.676,1021.78z%20M839.676,991.898c-2.402-0.004-4.752,0.704-6.751,2.036%20c-1.999,1.332-3.558,3.227-4.48,5.446c-0.921,2.22-1.163,4.66-0.696,7.02c0.468,2.35,1.624,4.52,3.323,6.22%20c1.699,1.7,3.863,2.85,6.22,3.32c2.356,0.47,4.798,0.22,7.017-0.7s4.114-2.48,5.446-4.48c1.332-2,2.04-4.35,2.036-6.75%20c-0.006-3.21-1.284-6.287-3.555-8.557C845.965,993.182,842.888,991.904,839.676,991.898z'/%3e%3cpath%20style='fill:%23313131;'%20d='M947.647,975.257h-0.293c-3.71-0.383-7.205-1.926-9.988-4.409c-2.784-2.482-4.714-5.779-5.517-9.422%20c-0.802-3.642-0.437-7.445,1.045-10.868c1.482-3.422,4.004-6.291,7.21-8.199c0.373-0.233,0.799-0.372,1.238-0.403%20c0.44-0.031,0.88,0.045,1.283,0.223c0.408,0.168,0.77,0.428,1.06,0.761c0.289,0.332,0.497,0.727,0.607,1.153%20c2.251,9.3,4.301,18.645,6.124,27.809c0.08,0.408,0.069,0.829-0.034,1.233c-0.102,0.403-0.292,0.779-0.557,1.099%20c-0.265,0.321-0.598,0.579-0.974,0.756C948.474,975.167,948.063,975.258,947.647,975.257z%20M939.878,949.858%20c-1.176,1.421-2.013,3.092-2.446,4.886c-0.434,1.793-0.452,3.662-0.055,5.464c0.397,1.802,1.2,3.49,2.348,4.935%20c1.147,1.445,2.609,2.609,4.274,3.404C942.716,962.355,941.342,956.095,939.878,949.858z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M873.52,931.212c-2.967-0.005-5.852-0.977-8.216-2.769c-2.365-1.792-4.082-4.306-4.889-7.161%20c-38.505-135.51-105.72-189.146-106.395-189.754c-2.709-2.264-4.434-5.489-4.815-8.998c-0.381-3.509,0.612-7.029,2.772-9.821%20c2.16-2.792,5.317-4.638,8.809-5.152c3.492-0.513,7.048,0.347,9.919,2.399c3.018,2.252,74.758,58.951,115.942,203.895%20c0.979,3.476,0.54,7.198-1.22,10.35c-1.759,3.153-4.697,5.48-8.169,6.471C876.043,931.026,874.785,931.208,873.52,931.212z'/%3e%3cpath%20style='fill:%23313131;'%20d='M873.52,934.027c-3.566-0.026-7.027-1.204-9.868-3.359c-2.841-2.155-4.908-5.171-5.894-8.597%20c-38.1-134.114-104.774-187.795-105.427-188.336c-3.449-2.669-5.696-6.6-6.247-10.926c-0.551-4.326,0.639-8.694,3.308-12.143%20c2.67-3.449,6.6-5.696,10.926-6.247c4.327-0.551,8.695,0.639,12.144,3.308c3.062,2.365,75.5,59.536,116.932,205.337%20c1.17,4.18,0.644,8.652-1.464,12.446c-2.108,3.795-5.627,6.604-9.794,7.819C876.637,933.775,875.083,934.01,873.52,934.027z%20M762.396,709.957c-2.253-0.002-4.451,0.7-6.286,2.008c-1.834,1.309-3.214,3.158-3.946,5.289c-0.732,2.132-0.78,4.439-0.136,6.598%20c0.644,2.16,1.946,4.064,3.726,5.447c0.675,0.541,68.633,54.853,107.363,191.218c0.651,2.26,2.016,4.249,3.891,5.67%20c1.875,1.42,4.159,2.196,6.512,2.211c1.005-0.009,2.005-0.153,2.972-0.428c2.756-0.786,5.089-2.633,6.486-5.136%20c1.397-2.503,1.745-5.458,0.967-8.217c-40.936-144.111-111.956-200.112-114.974-202.431%20C767.089,710.732,764.775,709.948,762.396,709.957z'/%3e%3cpath%20style='fill:%23313131;'%20d='M993.627,1354.13c-0.458,0-0.91-0.11-1.315-0.33c-0.405-0.21-0.751-0.52-1.009-0.9%20c-0.257-0.38-0.418-0.82-0.468-1.27c-0.05-0.46,0.012-0.92,0.18-1.35l101.895-255.93c0.13-0.35,0.33-0.67,0.59-0.94%20c0.25-0.28,0.56-0.49,0.91-0.64c0.34-0.16,0.71-0.24,1.08-0.24c0.38-0.01,0.75,0.06,1.1,0.2s0.66,0.35,0.93,0.61%20c0.26,0.26,0.48,0.58,0.62,0.92c0.14,0.35,0.22,0.72,0.22,1.09c-0.01,0.38-0.08,0.75-0.23,1.09l-101.958,255.94%20c-0.207,0.51-0.558,0.94-1.01,1.26C994.71,1353.95,994.177,1354.12,993.627,1354.13z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1007.9,1602.95c-0.52,0-1.03-0.14-1.48-0.42c-0.44-0.27-0.8-0.67-1.03-1.13%20c-0.24-0.47-0.34-1-0.29-1.52c0.05-0.52,0.24-1.01,0.55-1.43c0.25-0.34,12.75-18.29,8.6-86.76c-3.62-59.65-12.47-73.39-12.56-73.52%20c-0.27-0.39-0.44-0.84-0.49-1.3c-0.05-0.47,0.02-0.95,0.2-1.38c0.18-0.43,0.46-0.82,0.83-1.11c0.36-0.3,0.8-0.5,1.26-0.58%20l455.12-81.9c0.37-0.07,0.75-0.07,1.12,0c0.37,0.07,0.72,0.22,1.03,0.43c0.31,0.21,0.58,0.48,0.78,0.8%20c0.21,0.31,0.35,0.66,0.41,1.03c0.07,0.38,0.06,0.75-0.02,1.12c-0.08,0.37-0.24,0.72-0.46,1.02c-0.22,0.31-0.5,0.57-0.82,0.76%20c-0.32,0.2-0.68,0.33-1.05,0.38l-451.4,81.29c3.04,7.27,9,26.77,11.68,72.69c4.35,71.72-9.18,89.82-9.77,90.54%20c-0.27,0.32-0.61,0.58-0.99,0.75C1008.74,1602.88,1008.32,1602.97,1007.9,1602.95z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1432.02,1360.75h-0.61c-0.73-0.16-1.36-0.6-1.76-1.23s-0.54-1.39-0.38-2.12l37.09-166.16%20c0.16-0.72,0.61-1.36,1.24-1.76s1.4-0.53,2.12-0.36c0.73,0.16,1.37,0.61,1.77,1.24s0.53,1.39,0.36,2.12l-37.08,166.14%20c-0.16,0.61-0.51,1.15-1.01,1.54C1433.26,1360.54,1432.65,1360.75,1432.02,1360.75z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1464.26,894.848l10.61,32.537L1370.5,1028.6l-42.69-73.586L1464.26,894.848z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1327.81,955.013l-7.07-69.961l4.07-14.322l-28.62,7.791l-50.44,104.008L1327.81,955.013z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1370.5,1031.42h-0.38c-0.42-0.07-0.83-0.23-1.18-0.47c-0.36-0.24-0.65-0.56-0.87-0.93l-42.78-73.565%20c-0.21-0.344-0.33-0.726-0.37-1.123c-0.05-0.396-0.01-0.796,0.12-1.175c0.12-0.379,0.32-0.728,0.59-1.022%20c0.27-0.295,0.6-0.53,0.96-0.688l136.46-60.144c0.36-0.162,0.75-0.245,1.14-0.244c0.4,0,0.79,0.084,1.15,0.245%20c0.35,0.162,0.68,0.398,0.94,0.693c0.26,0.294,0.46,0.641,0.57,1.017l10.61,32.538c0.17,0.499,0.19,1.036,0.06,1.547%20s-0.4,0.974-0.78,1.335l-104.37,101.196C1371.87,1031.12,1371.2,1031.4,1370.5,1031.42z%20M1331.82,956.32l39.31,67.75l100.52-97.473%20l-9.01-27.899L1331.82,956.32z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1245.82,985.344c-0.47-0.001-0.94-0.123-1.36-0.355c-0.42-0.233-0.77-0.567-1.02-0.972%20c-0.25-0.406-0.4-0.869-0.42-1.345c-0.03-0.477,0.07-0.952,0.28-1.381l50.44-103.985c0.16-0.346,0.38-0.658,0.66-0.917%20c0.28-0.259,0.6-0.46,0.96-0.592l28.62-7.769c0.48-0.131,0.99-0.131,1.47-0.001c0.48,0.129,0.92,0.385,1.27,0.74%20c0.35,0.355,0.6,0.797,0.73,1.281c0.12,0.483,0.11,0.991-0.02,1.471l-3.92,13.803l7,69.398c0.07,0.634-0.08,1.272-0.42,1.809%20c-0.35,0.537-0.87,0.939-1.47,1.141l-82.05,27.516C1246.33,985.276,1246.08,985.329,1245.82,985.344z%20M1298.24,880.908%20l-46.97,96.825l73.59-24.769l-6.76-67.71c-0.08-0.348-0.08-0.71,0-1.058l2.71-9.525L1298.24,880.908z'/%3e%3cpath%20style='fill:%23313131;'%20d='M976.898,1205.36c-0.576,0-1.139-0.17-1.61-0.51c-0.472-0.33-0.83-0.79-1.025-1.34l-29.273-80.2%20c-0.256-0.7-0.224-1.48,0.091-2.16c0.314-0.68,0.885-1.2,1.587-1.46c0.702-0.25,1.477-0.22,2.154,0.09%20c0.678,0.32,1.203,0.89,1.46,1.59l29.273,80.23c0.157,0.43,0.208,0.88,0.149,1.33c-0.059,0.45-0.226,0.88-0.488,1.25%20c-0.261,0.37-0.609,0.67-1.013,0.88C977.799,1205.26,977.351,1205.37,976.898,1205.36z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1156.81,1411.87c-0.36,0.01-0.72-0.05-1.06-0.16c-0.69-0.27-1.25-0.8-1.56-1.48%20c-0.31-0.67-0.34-1.45-0.08-2.14l171-454.045c0.13-0.346,0.32-0.663,0.58-0.933c0.25-0.27,0.55-0.487,0.89-0.64%20c0.34-0.153,0.7-0.238,1.07-0.25c0.37-0.012,0.74,0.049,1.08,0.179c0.35,0.13,0.67,0.327,0.94,0.58%20c0.26,0.252,0.48,0.555,0.63,0.892c0.16,0.337,0.24,0.7,0.25,1.07c0.02,0.369-0.04,0.737-0.17,1.083l-170.93,454.014%20c-0.21,0.54-0.57,1-1.04,1.33C1157.94,1411.69,1157.38,1411.87,1156.81,1411.87z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1331.14,1015.11c-2.19,0-4.34-0.65-6.17-1.87c-1.82-1.22-3.24-2.95-4.08-4.98%20c-0.84-2.03-1.06-4.26-0.64-6.41c0.43-2.158,1.49-4.136,3.04-5.688c1.55-1.553,3.53-2.61,5.69-3.039%20c2.15-0.428,4.38-0.208,6.41,0.632c2.03,0.84,3.76,2.263,4.98,4.089c1.22,1.825,1.87,3.976,1.87,6.166c0,2.95-1.17,5.77-3.25,7.85%20C1336.91,1013.94,1334.09,1015.11,1331.14,1015.11z%20M1331.14,998.562c-1.08,0-2.14,0.322-3.04,0.924%20c-0.9,0.604-1.6,1.454-2.02,2.464c-0.41,1-0.52,2.1-0.3,3.16c0.21,1.06,0.73,2.04,1.5,2.8c0.77,0.77,1.75,1.28,2.81,1.49%20c1.06,0.21,2.16,0.1,3.16-0.32c1-0.42,1.85-1.12,2.45-2.02c0.6-0.91,0.92-1.97,0.91-3.05c0-1.45-0.58-2.83-1.61-3.85%20C1333.98,999.135,1332.59,998.562,1331.14,998.562z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1275.66,1161.21c-2.2,0-4.35-0.65-6.18-1.87c-1.83-1.21-3.25-2.95-4.1-4.98%20c-0.84-2.03-1.06-4.26-0.63-6.42c0.42-2.15,1.48-4.13,3.04-5.68c1.55-1.56,3.53-2.62,5.69-3.04c2.15-0.43,4.39-0.21,6.41,0.63%20c2.03,0.85,3.77,2.27,4.99,4.1c1.21,1.83,1.86,3.98,1.86,6.18c-0.01,2.93-1.18,5.75-3.25,7.82%20C1281.41,1160.03,1278.6,1161.2,1275.66,1161.21z%20M1275.66,1144.66c-1.08-0.01-2.14,0.31-3.05,0.91c-0.9,0.6-1.6,1.45-2.02,2.45%20c-0.42,1-0.53,2.1-0.32,3.16c0.21,1.06,0.72,2.04,1.49,2.81c0.76,0.77,1.74,1.29,2.8,1.5c1.06,0.22,2.16,0.11,3.16-0.31%20c1.01-0.41,1.86-1.11,2.46-2.01c0.61-0.9,0.93-1.96,0.93-3.04c0-1.45-0.58-2.84-1.6-3.86%20C1278.49,1145.24,1277.11,1144.66,1275.66,1144.66z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1220.11,1311.87c-2.2,0-4.35-0.64-6.18-1.86c-1.83-1.22-3.25-2.95-4.1-4.98%20c-0.84-2.03-1.06-4.27-0.63-6.42c0.42-2.16,1.48-4.14,3.04-5.69c1.55-1.55,3.53-2.61,5.69-3.04c2.15-0.43,4.39-0.21,6.41,0.64%20c2.03,0.84,3.77,2.27,4.99,4.1c1.21,1.82,1.86,3.97,1.86,6.17c-0.01,2.94-1.18,5.75-3.25,7.83%20C1225.86,1310.7,1223.04,1311.86,1220.11,1311.87z%20M1220.11,1295.32c-1.08,0-2.14,0.31-3.05,0.91c-0.9,0.6-1.61,1.45-2.02,2.45%20c-0.42,1-0.53,2.1-0.32,3.17c0.21,1.06,0.72,2.04,1.49,2.8c0.76,0.77,1.74,1.29,2.8,1.51c1.06,0.21,2.16,0.1,3.16-0.31%20c1.01-0.41,1.86-1.12,2.46-2.02c0.61-0.9,0.93-1.96,0.93-3.04c0-1.45-0.58-2.83-1.6-3.86%20C1222.94,1295.9,1221.56,1295.33,1220.11,1295.32z'/%3e%3cpath%20style='fill:%23313131;'%20d='M753.84,1108.49l2.567,12.14c0,0,108.399-10.58,168.182-56.95l-1.643-4.23%20C922.946,1059.45,866.562,1100.84,753.84,1108.49z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1093.74,1099.69l-121.549,265.34l21.369-13.71L1093.74,1099.69z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1466.7,1202.55l-35.06,157.06l-21.91,3.67L1466.7,1202.55z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1245.75,982.53l82.06-27.516l3.89,6.71L1245.75,982.53z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1370.5,1028.6l-42.69-73.586l-9.05,3.04L1370.5,1028.6z'/%3e%3c/svg%3e\"","/**\n * EmptyState — renders pre-search and post-search empty state variants.\n *\n * Pre-search  : nodata illustration + search icon + \"Ingresa criterios y presiona Buscar\"\n * Post-search : nodata illustration + info icon  + \"Sin resultados\"\n *\n * @module components/list/EmptyState\n * @see FMPV-MVWC-E002-S004 I-004\n */\nimport React from 'react';\nimport nodataImg from '../../assets/nodata.svg';\n\nexport interface EmptyStateProps {\n  hasSearched: boolean;\n  /**\n   * compact=true: removes outer padding — for use inside siesa-ui-kit Table whose\n   * empty-state wrapper already provides py-12 (48px) spacing on each side.\n   */\n  compact?: boolean;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function EmptyState({ hasSearched, compact = false, t }: EmptyStateProps) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  return (\n    <div\n      data-testid={hasSearched ? 'empty-state-post-search' : 'empty-state-pre-search'}\n      className={`flex flex-col items-center gap-4 ${compact ? '' : 'py-12 px-10'}`}\n    >\n      <img\n        src={nodataImg}\n        alt={hasSearched ? tt('emptyNoResultsTitle', 'Sin resultados') : tt('emptyEnterCriteriaAlt', 'Ingresa criterios')}\n        className=\"w-44 h-44 object-contain\"\n      />\n\n      <div className=\"flex items-start gap-2.5 bg-blue-50 dark:bg-blue-950/40 border border-blue-200 dark:border-blue-800 rounded-xl px-4 py-3.5 max-w-[420px] w-full\">\n        <span className=\"text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5\">\n          {hasSearched ? (\n            <svg xmlns=\"http://www.w3.org/2000/svg\" width={20} height={20} fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" strokeWidth={1.5} strokeLinecap=\"round\" strokeLinejoin=\"round\">\n              <path d=\"M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z\" />\n            </svg>\n          ) : (\n            <svg width={18} height={18} fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" strokeLinejoin=\"round\" viewBox=\"0 0 24 24\">\n              <circle cx={11} cy={11} r={8} />\n              <path d=\"m21 21-4.35-4.35\" />\n            </svg>\n          )}\n        </span>\n\n        <div>\n          <strong className=\"block text-sm font-semibold text-blue-700 dark:text-blue-300\">\n            {hasSearched ? tt('emptyNoResultsTitle', 'Sin resultados') : tt('emptyEnterCriteriaTitle', 'Ingresa criterios y presiona Buscar')}\n          </strong>\n          <span className=\"block text-xs text-blue-600/80 dark:text-blue-400/80 mt-0.5\">\n            {hasSearched\n              ? tt('emptyNoResultsDesc', 'No hay registros que coincidan con los filtros.')\n              : tt('emptyEnterCriteriaDesc', 'Usa los filtros del panel superior para encontrar registros.')}\n          </span>\n        </div>\n      </div>\n    </div>\n  );\n}\n","/**\n * RowActions — per-row action buttons.\n *\n * Visual/UX parity with MasterCrudTable's RowActionsCell:\n * - ≤3 visible actions → all rendered inline (direct).\n * - 4+ visible actions → 2 direct actions (priority: edit slot, then the\n *   \"company-enable\" special action) + the remaining actions collapsed into\n *   a \"more actions\" kebab (portal, fixed position).\n *\n * Exception to the NEVER-HIDE permission invariant (see engine/permissionEngine.ts):\n * the \"Editar\" slot does NOT follow never-hide — it matches MasterCrud's actual\n * behavior exactly (MasterCrud.tsx: `if (canRead && canUpdate) defaultActions.push({id:'edit',...})`):\n * when the user lacks UPDATE permission the slot is simply omitted, with no toast.\n * Unlike MasterCrud (which has no per-row read-only fallback at all — canRead only\n * gates the whole list), the MPV replaces the omitted \"Editar\" with \"Visualizar\"\n * whenever canRead is true and canUpdate is false, so a read-only user always has\n * a way to open the row instead of being left with zero actions. Consumers can\n * still force the \"view\" slot on/off explicitly via `defaultActions.view.show`,\n * which always wins over this fallback. \"Cambiar estado\" and custom actions keep\n * the never-hide + warning-toast behavior unchanged.\n *\n * @module components/list/RowActions\n * @see FMPV-MVWC-E002-S003 I-005\n */\nimport React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { motion } from 'framer-motion';\nimport { Pencil } from 'lucide-react';\nimport {\n  EyeIcon,\n  MinusCircleIcon,\n  CheckCircleIcon,\n  EllipsisVerticalIcon,\n  Bars3Icon,\n} from '@heroicons/react/24/outline';\nimport type { MasterPatternViewPermissions } from '../../types/permissions.types';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterPatternViewCustomAction, MasterPatternViewDefaultActions } from '../../types/props.types';\nimport { isActionAllowed, getDisabledToastMessage } from '../../engine/permissionEngine';\nimport { useToast, type ToastCallback } from '../../hooks/useToast';\n\nexport interface RowActionsProps<T extends MasterPatternViewEntity = MasterPatternViewEntity> {\n  row: T;\n  permissions?: MasterPatternViewPermissions;\n  onOpenView: (row: T) => void;\n  onOpenEdit: (row: T) => void;\n  onChangeStatus?: (row: T) => void;\n  actions?: MasterPatternViewCustomAction<T>[];\n  rowActions?: (row: T) => React.ReactNode;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  defaultActions?: MasterPatternViewDefaultActions<T>;\n  /**\n   * 'table' (default): MasterCrudTable's rule — ≤3 direct, 4+ collapses to 2 direct + kebab.\n   * 'card': MasterCRUDCard's rule — only \"company-enable\" (MasterCrud's 'link') stays direct;\n   * everything else always collapses into ONE hamburger (Bars3Icon), regardless of count.\n   */\n  variant?: 'table' | 'card';\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\ninterface ResolvedRowAction {\n  id: string;\n  label: string;\n  icon: React.ReactNode;\n  onClick: () => void;\n  disabled: boolean;\n  testId: string;\n  /** 'danger' (red, deactivating) / 'success' (green, activating) — only changeStatus uses this. */\n  tone?: 'danger' | 'success';\n}\n\nfunction resolveActionConfig<T>(\n  value: boolean | ((row: T) => boolean) | undefined,\n  row: T,\n  defaultValue: boolean,\n): boolean {\n  if (value === undefined) return defaultValue;\n  if (typeof value === 'function') return value(row);\n  return value;\n}\n\n// Priority ids for the \"2 direct actions\" slot when 4+ actions collapse — mirrors\n// MasterCrudTable's ['edit', 'link'] priority (company-enable is MPV's analog to 'link').\nconst PRIORITY_IDS = ['edit', 'company-enable'];\nconst MAX_DIRECT = 3;\n\n// Small elastic \"pop\" on hover/press — shared by every row-action button (direct\n// icons AND the kebab trigger), so none of them feels like the odd one out.\nconst bounceTransition = { type: 'spring' as const, bounce: 0.55, duration: 0.4 };\n\nexport function RowActions<T extends MasterPatternViewEntity = MasterPatternViewEntity>({\n  row,\n  permissions,\n  onOpenView,\n  onOpenEdit,\n  onChangeStatus,\n  actions = [],\n  rowActions,\n  toast: toastProp,\n  showInternalToasts = true,\n  defaultActions,\n  variant = 'table',\n  t,\n}: RowActionsProps<T>) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const { showWarning } = useToast(toastProp, showInternalToasts);\n  const canRead = isActionAllowed(permissions, 'READ', 'UNIVERSAL');\n  const canUpdate = isActionAllowed(permissions, 'UPDATE', 'UNIVERSAL');\n  const canChangeStatus = isActionAllowed(permissions, 'CHANGE_STATUS', 'UNIVERSAL');\n\n  // Defaults to appearing only as the read-only fallback (canRead && !canUpdate) —\n  // MasterCrud has no \"Visualizar\" action at all, but leaving the row with zero\n  // actions when the user can't edit is worse than showing one. Explicit\n  // defaultActions.view.show (true or false) always overrides this default.\n  const showView = resolveActionConfig(defaultActions?.view?.show, row, canRead && !canUpdate);\n  const disabledView = resolveActionConfig(defaultActions?.view?.disabled, row, false);\n  const showEdit = resolveActionConfig(defaultActions?.edit?.show, row, true);\n  const disabledEdit = resolveActionConfig(defaultActions?.edit?.disabled, row, false);\n  const showChangeStatus = resolveActionConfig(defaultActions?.changeStatus?.show, row, true);\n  const disabledChangeStatus = resolveActionConfig(defaultActions?.changeStatus?.disabled, row, false);\n\n  const handleView = useCallback(() => {\n    if (!canRead) {\n      showWarning(getDisabledToastMessage('READ'));\n      return;\n    }\n    onOpenView(row);\n  }, [canRead, showWarning, onOpenView, row]);\n\n  // \"Editar\"/\"Detalle\" share this slot — permission decides which one renders,\n  // so no permission check/toast is needed on click for either.\n  const handleEdit = useCallback(() => {\n    onOpenEdit(row);\n  }, [onOpenEdit, row]);\n\n  const handleChangeStatus = useCallback(() => {\n    if (!canChangeStatus) {\n      showWarning(getDisabledToastMessage('CHANGE_STATUS'));\n      return;\n    }\n    onChangeStatus?.(row);\n  }, [canChangeStatus, showWarning, onChangeStatus, row]);\n\n  const resolvedActions: ResolvedRowAction[] = [];\n\n  if (showView) {\n    resolvedActions.push({\n      id: 'view',\n      label: tt('viewAction', 'Visualizar'),\n      icon: <EyeIcon className=\"w-[15px] h-[15px]\" />,\n      onClick: handleView,\n      disabled: disabledView,\n      testId: 'row-action-view',\n    });\n  }\n\n  // Matches MasterCrud exactly: no UPDATE permission → the slot is omitted, period.\n  if (showEdit && canUpdate) {\n    resolvedActions.push({\n      id: 'edit',\n      label: tt('edit', 'Editar'),\n      icon: <Pencil size={15} />,\n      onClick: handleEdit,\n      disabled: disabledEdit,\n      testId: 'row-action-edit',\n    });\n  }\n\n  actions\n    .filter((a) => !a.position || a.position === 'row')\n    .forEach((action) => {\n      resolvedActions.push({\n        id: action.key,\n        label: action.label,\n        icon: action.icon,\n        onClick: () => action.onExecute(row),\n        disabled: action.isDisabled?.(row) ?? false,\n        testId: `row-action-${action.key}`,\n      });\n    });\n\n  // Last in order, always — matches MasterCrud's activate/deactivate action (order: 200,\n  // after edit/link/audit). Red \"Desactivar\" while active, green \"Activar\" while inactive.\n  if (showChangeStatus) {\n    resolvedActions.push({\n      id: 'changeStatus',\n      label: row.isActive ? tt('disableRecordAction', 'Desactivar registro') : tt('enableRecordAction', 'Activar registro'),\n      icon: row.isActive\n        ? <MinusCircleIcon className=\"w-[15px] h-[15px]\" />\n        : <CheckCircleIcon className=\"w-[15px] h-[15px]\" />,\n      onClick: handleChangeStatus,\n      disabled: disabledChangeStatus,\n      testId: 'row-action-change-status',\n      tone: row.isActive ? 'danger' : 'success',\n    });\n  }\n\n  let directActions: ResolvedRowAction[];\n  let menuActions: ResolvedRowAction[];\n  if (variant === 'card') {\n    // MasterCRUDCard's rule: only \"company-enable\" (MasterCrud's 'link') stays direct;\n    // everything else always collapses into ONE hamburger, regardless of count.\n    directActions = resolvedActions.filter((a) => a.id === 'company-enable');\n    menuActions = resolvedActions.filter((a) => a.id !== 'company-enable');\n  } else if (resolvedActions.length <= MAX_DIRECT) {\n    // MasterCrudTable's rule: ≤3 → todas directas.\n    directActions = resolvedActions;\n    menuActions = [];\n  } else {\n    // 4+ → prioriza Editar + Habilitar compañía como directas, resto al kebab.\n    const priority = resolvedActions.filter((a) => PRIORITY_IDS.includes(a.id)).slice(0, 2);\n    const fill =\n      priority.length < 2\n        ? resolvedActions.filter((a) => !priority.includes(a)).slice(0, 2 - priority.length)\n        : [];\n    directActions = [...priority, ...fill];\n    menuActions = resolvedActions.filter((a) => !directActions.includes(a));\n  }\n\n  // Hover matches Button's own `type=\"outline\"` exactly (same one \"Cancelar\" on the detail\n  // page uses) — bg-{color}-100/950 + brightness filter + transition-all, not the flat\n  // hardcoded-hex background these had before.\n  const actionBtnClass =\n    'inline-flex items-center justify-center w-7 h-7 bg-white dark:bg-zinc-900 border border-[#93d1fd] dark:border-blue-800 text-blue-600 dark:text-blue-400 rounded-md shadow-[0_1px_2px_rgba(0,0,0,0.04)] cursor-pointer transition-all duration-150 hover:bg-primary-100 dark:hover:bg-primary-950 hover:brightness-98 dark:hover:brightness-102 disabled:opacity-50 disabled:cursor-not-allowed';\n  const actionBtnClassDanger =\n    'inline-flex items-center justify-center w-7 h-7 bg-white dark:bg-zinc-900 border border-red-300 dark:border-red-800 text-red-600 dark:text-red-400 rounded-md shadow-[0_1px_2px_rgba(0,0,0,0.04)] cursor-pointer transition-all duration-150 hover:bg-red-100 dark:hover:bg-red-950 hover:brightness-98 dark:hover:brightness-102 disabled:opacity-50 disabled:cursor-not-allowed';\n  const actionBtnClassSuccess =\n    'inline-flex items-center justify-center w-7 h-7 bg-white dark:bg-zinc-900 border border-emerald-300 dark:border-emerald-800 text-emerald-600 dark:text-emerald-400 rounded-md shadow-[0_1px_2px_rgba(0,0,0,0.04)] cursor-pointer transition-all duration-150 hover:bg-emerald-100 dark:hover:bg-emerald-950 hover:brightness-98 dark:hover:brightness-102 disabled:opacity-50 disabled:cursor-not-allowed';\n\n  const toneClass = (action: ResolvedRowAction) =>\n    action.tone === 'danger' ? actionBtnClassDanger : action.tone === 'success' ? actionBtnClassSuccess : actionBtnClass;\n\n  return (\n    <div className=\"flex items-center gap-1\" data-testid={`row-actions-${row.id}`}>\n      {directActions.map((action) => (\n        <motion.button\n          key={action.id}\n          type=\"button\"\n          onClick={(e) => {\n            // Prevent bubbling to the table row's onClick (opens the view modal) —\n            // the row is clickable, but action buttons must not trigger it too.\n            e.stopPropagation();\n            if (!action.disabled) action.onClick();\n          }}\n          disabled={action.disabled}\n          whileHover={action.disabled ? undefined : { scale: 1.15 }}\n          whileTap={action.disabled ? undefined : { scale: 0.9 }}\n          transition={bounceTransition}\n          data-testid={action.testId}\n          aria-label={action.label}\n          title={action.label}\n          className={toneClass(action)}\n        >\n          {/* MasterCRUDCard.tsx just renders the 'link' action's own configured icon\n              (MasterCrudCard.tsx:189, `leftIcon={linkAction.icon}`) — no chain-icon\n              override. The card variant renders the action's icon as-is, same as table:\n              for 'company-enable' that's Building2 (see injectedRowActions). */}\n          {action.icon}\n        </motion.button>\n      ))}\n\n      {menuActions.length > 0 && (\n        variant === 'card' ? (\n          <RowActionsMenu\n            actions={menuActions}\n            className=\"inline-flex items-center justify-center p-2 rounded-lg text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-all duration-150\"\n            triggerIcon={<Bars3Icon className=\"w-5 h-5\" />}\n            triggerLabel={tt('moreOptions', 'Más opciones')}\n            t={tt}\n          />\n        ) : (\n          <RowActionsMenu actions={menuActions} className={actionBtnClass} t={tt} />\n        )\n      )}\n\n      {/* rowActions escape hatch — does not participate in the collapse rule */}\n      {rowActions?.(row)}\n    </div>\n  );\n}\n\ninterface RowActionsMenuProps {\n  actions: ResolvedRowAction[];\n  className: string;\n  /** Defaults to EllipsisVerticalIcon (table kebab) — pass Bars3Icon for the card variant. */\n  triggerIcon?: React.ReactNode;\n  /** Defaults to \"Más acciones\" (table) — pass \"Más opciones\" for the card variant. */\n  triggerLabel?: string;\n  t: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * Per-row \"more actions\" trigger — portal to document.body with fixed positioning,\n * mirroring MasterCrudTable.tsx's RowActionsCell / MasterCRUDCard.tsx's Dropdown so\n * the menu isn't clipped by the table's sticky column / overflow-auto container.\n */\nfunction RowActionsMenu({ actions, className, triggerIcon, triggerLabel, t }: RowActionsMenuProps) {\n  const [open, setOpen] = useState(false);\n  const btnRef = useRef<HTMLButtonElement>(null);\n  const menuRef = useRef<HTMLDivElement>(null);\n  const [pos, setPos] = useState<{ top: number; left: number }>({ top: -9999, left: -9999 });\n\n  const reposition = useCallback(() => {\n    const btn = btnRef.current;\n    const menu = menuRef.current;\n    if (!btn) return;\n    const r = btn.getBoundingClientRect();\n    const mw = menu?.offsetWidth || 210;\n    const mh = menu?.offsetHeight || 0;\n    let top = r.bottom + 4;\n    if (mh && top + mh > window.innerHeight - 8) top = r.top - mh - 4;\n    const left = Math.max(8, r.right - mw);\n    setPos({ top, left });\n  }, []);\n\n  useLayoutEffect(() => {\n    if (open) reposition();\n  }, [open, reposition]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onDocClick = (e: MouseEvent) => {\n      if (menuRef.current?.contains(e.target as Node) || btnRef.current?.contains(e.target as Node)) return;\n      setOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === 'Escape') setOpen(false);\n    };\n    const onScroll = () => setOpen(false);\n    document.addEventListener('click', onDocClick);\n    document.addEventListener('keydown', onKey);\n    window.addEventListener('resize', onScroll);\n    document.addEventListener('scroll', onScroll, true);\n    return () => {\n      document.removeEventListener('click', onDocClick);\n      document.removeEventListener('keydown', onKey);\n      window.removeEventListener('resize', onScroll);\n      document.removeEventListener('scroll', onScroll, true);\n    };\n  }, [open]);\n\n  return (\n    <>\n      <motion.button\n        ref={btnRef}\n        type=\"button\"\n        title={triggerLabel ?? t('moreActions', 'Más acciones')}\n        aria-label={triggerLabel ?? t('moreActions', 'Más acciones')}\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        onClick={(e) => {\n          e.stopPropagation();\n          setOpen((v) => !v);\n        }}\n        whileHover={{ scale: 1.15 }}\n        whileTap={{ scale: 0.9 }}\n        transition={bounceTransition}\n        data-testid=\"row-actions-more-button\"\n        className={className}\n      >\n        {triggerIcon ?? <EllipsisVerticalIcon className=\"w-[15px] h-[15px]\" />}\n      </motion.button>\n      {open &&\n        createPortal(\n          <div\n            ref={menuRef}\n            role=\"menu\"\n            data-testid=\"row-actions-more-menu\"\n            style={{ position: 'fixed', top: pos.top, left: pos.left }}\n            className=\"z-[60] min-w-[210px] bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-md shadow-md py-1\"\n          >\n            {actions.map((action, idx) => (\n              <React.Fragment key={action.id}>\n                {/* Single separator at the midpoint — not one per item. */}\n                {idx > 0 && idx === Math.floor(actions.length / 2) && (\n                  <hr className=\"my-1 border-zinc-100 dark:border-zinc-800\" />\n                )}\n                <button\n                  type=\"button\"\n                  role=\"menuitem\"\n                  disabled={action.disabled}\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    action.onClick();\n                    setOpen(false);\n                  }}\n                  data-testid={action.testId}\n                  className={`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors disabled:opacity-40 disabled:cursor-not-allowed hover:bg-zinc-50 dark:hover:bg-zinc-800 ${\n                    action.tone === 'danger'\n                      ? 'text-red-600 dark:text-red-400'\n                      : action.tone === 'success'\n                        ? 'text-emerald-600 dark:text-emerald-400'\n                        : 'text-zinc-700 dark:text-zinc-300'\n                  }`}\n                >\n                  <span className=\"w-4 h-4 flex-shrink-0 inline-flex items-center justify-center\">{action.icon}</span>\n                  <span>{action.label}</span>\n                </button>\n              </React.Fragment>\n            ))}\n          </div>,\n          document.body,\n        )}\n    </>\n  );\n}\n","/**\n * CompanyStatusBadge — per-company enablement indicator.\n * Blue circle + check when enabled, dashed outline when not — same circle/badge\n * treatment as MasterCrudTable's CompanyStatusBadge, but using the actual lucide\n * `Building2` icon (the same one the Acciones column button uses) instead of a\n * hand-copied SVG that only looked similar.\n *\n * @module components/list/CompanyStatusBadge\n */\nimport React from 'react';\nimport { Building2 } from 'lucide-react';\n\nexport interface CompanyStatusBadgeProps {\n  enabled: boolean;\n  enabledLabel: string;\n  notEnabledLabel: string;\n}\n\nexport function CompanyStatusBadge({ enabled, enabledLabel, notEnabledLabel }: CompanyStatusBadgeProps) {\n  if (enabled) {\n    return (\n      <span title={enabledLabel} className=\"inline-flex items-center justify-center w-7 h-7 rounded-full bg-[#dbeefe] dark:bg-primary-900/20 text-primary-600 dark:text-primary-500 relative\">\n        <Building2 size={17} />\n        <span className=\"absolute -bottom-0.5 -right-0.5 bg-white dark:bg-dark-bg-primary rounded-full leading-none p-px\">\n          <svg className=\"w-2.5 h-2.5 text-green-600\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\" viewBox=\"0 0 24 24\"><path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M4.5 12.75l6 6 9-13.5\" /></svg>\n        </span>\n      </span>\n    );\n  }\n  return (\n    <span title={notEnabledLabel} className=\"inline-flex items-center justify-center w-7 h-7 rounded-full border border-dashed border-border-primary dark:border-dark-border-primary text-content-secondary dark:text-dark-content-secondary\">\n      <Building2 size={17} strokeWidth={1.75} />\n    </span>\n  );\n}\n","/**\n * ListTable — data table for master entity list.\n * Uses siesa-ui-kit Table with columns derived from fieldEngine.\n * Renders RowActions as last column. Shows loading skeleton when isLoading=true.\n * Column headers with filterable fields show an inline per-column filter input\n * toggled by a small Filter icon button (matches mock .th-filter pattern).\n *\n * @module components/list/ListTable\n * @see FMPV-MVWC-E002-S003 I-002\n */\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Table } from '../../../Table/Table';\nimport type { TableColumn } from '../../../Table/Table.types';\nimport { ChevronsUpDown, ChevronUp, ChevronDown, Filter, Globe, Building2 } from 'lucide-react';\nimport type { MasterPatternViewDefinition } from '../../types/definition.types';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterPatternViewPermissions } from '../../types/permissions.types';\nimport type { MasterPatternViewCustomAction, MasterPatternViewDefaultActions } from '../../types/props.types';\nimport { useFieldEngine } from '../../hooks/useFieldEngine';\nimport { getAllFields } from '../../engine/fieldEngine';\nimport { useMasterViewStore } from '../../store/MasterViewContext';\nimport { EmptyState } from './EmptyState';\nimport { RowActions } from './RowActions';\nimport { CompanyStatusBadge } from './CompanyStatusBadge';\nimport type { ToastCallback } from '../../hooks/useToast';\n\nexport interface ListTableProps<T extends MasterPatternViewEntity = MasterPatternViewEntity> {\n  definition: MasterPatternViewDefinition;\n  data: T[];\n  sortBy: string;\n  sortOrder: 'asc' | 'desc';\n  onSort: (field: string, direction: 'asc' | 'desc') => void;\n  onOpenView: (row: T) => void;\n  onOpenEdit: (row: T) => void;\n  onChangeStatus?: (row: T) => void;\n  isLoading?: boolean;\n  permissions?: MasterPatternViewPermissions;\n  actions?: MasterPatternViewCustomAction<T>[];\n  rowActions?: (row: T) => React.ReactNode;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** Active company context — undefined or 'global' means global view */\n  activeCompanyContext?: string;\n  /**\n   * When provided, a dedicated leftmost column renders a per-row company-enable badge\n   * (mirrors MasterCrud's showCompanyStatusColumn) — only shown while a specific company\n   * is active. Clicking it (row.isAssigned decides the badge's enabled/not-enabled look)\n   * opens the same \"Habilitar por compañía\" panel as the Acciones-column action does in\n   * global scope.\n   */\n  onCompanyStatusClick?: (row: T) => void | Promise<void>;\n  /** When true, disables pointer events on the sticky actions column to prevent interaction through modal overlays */\n  modalOpen?: boolean;\n  defaultActions?: MasterPatternViewDefaultActions<T>;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\n// Shared class for the inline column filter input / select\nconst colFilterInputClass =\n  'w-full border border-zinc-200 dark:border-zinc-700 rounded-md px-1.5 py-[3px] text-[11px] text-content-primary dark:text-dark-content-primary bg-white dark:bg-zinc-900 outline-none focus:border-blue-300 dark:focus:border-blue-700 focus:ring-2 focus:ring-blue-600/10';\n\nfunction SortIcon({ field, sortBy, sortOrder }: { field: string; sortBy: string; sortOrder: 'asc' | 'desc' }) {\n  if (sortBy !== field) return <ChevronsUpDown size={12} data-testid=\"icon-chevrons-up-down\" className=\"text-zinc-300 dark:text-zinc-600 flex-shrink-0\" />;\n  if (sortOrder === 'asc') return <ChevronUp size={12} data-testid=\"icon-chevron-up\" className=\"text-blue-600 dark:text-blue-400 flex-shrink-0\" />;\n  return <ChevronDown size={12} data-testid=\"icon-chevron-down\" className=\"text-blue-600 dark:text-blue-400 flex-shrink-0\" />;\n}\n\nexport function ListTable<T extends MasterPatternViewEntity = MasterPatternViewEntity>({\n  definition,\n  data,\n  sortBy,\n  sortOrder,\n  onSort,\n  onOpenView,\n  onOpenEdit,\n  onChangeStatus,\n  isLoading = false,\n  permissions,\n  actions,\n  rowActions,\n  toast: toastProp,\n  showInternalToasts = true,\n  activeCompanyContext,\n  onCompanyStatusClick,\n  modalOpen = false,\n  defaultActions,\n  t,\n}: ListTableProps<T>) {\n  const tt = useMemo(\n    () => t ?? ((key: string, defaultValue?: string) => defaultValue ?? key),\n    [t],\n  );\n  const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n  const { listColumns } = useFieldEngine(definition);\n\n  // Store — column filters live in their own slice, independent of FilterPanel filters.\n  // Both are merged in useMasterList before calling service.getAll().\n  const storeColumnFilters = useMasterViewStore((s) => s.columnFilters);\n  const setStoreColumnFilters = useMasterViewStore((s) => s.setColumnFilters);\n  const setSearchParams = useMasterViewStore((s) => s.setSearchParams);\n\n  // Local state: controls the input display value (immediate feedback while typing)\n  const [openColumnFilter, setOpenColumnFilter] = useState<string | null>(null);\n  const [columnFilters, setColumnFilters] = useState<Record<string, string>>({});\n\n  // Ref to avoid stale closure inside the debounce timeout\n  const filtersRef = useRef(storeColumnFilters);\n  useEffect(() => { filtersRef.current = storeColumnFilters; }, [storeColumnFilters]);\n\n  // Debounce timers per field\n  const debounceRef = useRef<Record<string, ReturnType<typeof setTimeout>>>({});\n\n  // Sync local input state when column filters are cleared externally (e.g. \"Limpiar filtros\")\n  useEffect(() => {\n    setColumnFilters((prev) => {\n      const next = { ...prev };\n      let changed = false;\n      for (const field of Object.keys(prev)) {\n        if (prev[field] && !storeColumnFilters.some((f) => f.field === field)) {\n          next[field] = '';\n          changed = true;\n        }\n      }\n      return changed ? next : prev;\n    });\n  }, [storeColumnFilters]);\n\n  // Sends the column filter to the backend via the store.\n  // Text fields are debounced 350 ms; boolean selects fire immediately.\n  const handleColumnFilter = useCallback(\n    (field: string, value: string, isBooleanField: boolean) => {\n      setColumnFilters((prev) => ({ ...prev, [field]: value }));\n\n      const commit = () => {\n        const filterValue: unknown = isBooleanField\n          ? value === 'true' ? true : value === 'false' ? false : undefined\n          : value;\n        const operator = isBooleanField ? 'equals' : 'contains';\n        const next = [\n          ...filtersRef.current.filter((f) => f.field !== field),\n          ...(value ? [{ field, operator, value: filterValue }] : []),\n        ];\n        setStoreColumnFilters(next);\n        setSearchParams({ page: 1 });\n      };\n\n      if (isBooleanField) {\n        commit();\n      } else {\n        clearTimeout(debounceRef.current[field]);\n        debounceRef.current[field] = setTimeout(commit, 350);\n      }\n    },\n    [setSearchParams],\n  );\n\n  const columns = useMemo((): TableColumn<T>[] => {\n    const fieldMap = new Map(getAllFields(definition).map((f) => [f.fieldName, f]));\n\n    const dataColumns: TableColumn<T>[] = listColumns.map((col) => {\n      const fieldDef = fieldMap.get(col.fieldName);\n      const isFilterable = !!(fieldDef?.filterable || fieldDef?.quickFilter);\n      // Lookup fields are filterable in the advanced panel but cannot be filtered inline\n      // (free-text input against a relational field would silently produce no results).\n      const isLookupField = fieldDef?.inputType === 'lookup';\n      const isBooleanField = fieldDef?.dataType === 'boolean' || fieldDef?.inputType === 'boolean';\n      const isOverridable = !!(fieldDef?.isOverridable);\n\n      let renderFn: ((value: unknown, row: T) => React.ReactNode) | undefined;\n      if (fieldDef?.renderCell) {\n        const baseRender = (value: unknown, row: T) => fieldDef.renderCell!(value, row) as React.ReactNode;\n        renderFn = (value: unknown, row: T) => {\n          const base = baseRender(value, row);\n          if (!isCompanyCtx || !isOverridable) return base;\n          const r = row as Record<string, unknown>;\n          const overrides = r['_overrides'] as Record<string, unknown> | undefined;\n          const overrideBadge = isOverridable\n            ? overrides?.[col.fieldName] !== undefined\n              ? <span title={tt('companyOverrideTooltip', 'Valor sobreescrito por la compañía')} className=\"inline-flex items-center justify-center w-5 h-5 rounded-md bg-blue-50 border border-blue-200 text-blue-700 dark:bg-blue-950/40 dark:border-blue-800 dark:text-blue-400 ml-1 flex-shrink-0 cursor-help\"><Building2 size={12} /></span>\n              : <span title={tt('companyGlobalValueTooltip', 'Valor global')} className=\"inline-flex items-center justify-center w-5 h-5 rounded-md bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-400 dark:text-zinc-500 ml-1 flex-shrink-0 cursor-help\"><Globe size={12} /></span>\n            : null;\n          return <span className=\"inline-flex items-center\">{base}{overrideBadge}</span>;\n        };\n      } else if (isBooleanField) {\n        renderFn = (value: unknown, row: T) => {\n          const base = value ? (\n            <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-emerald-600/10 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-300\">\n              {tt('active', 'Activo')}\n            </span>\n          ) : (\n            <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-zinc-200 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400\">\n              {tt('inactive', 'Inactivo')}\n            </span>\n          );\n          if (!isCompanyCtx || !isOverridable) return base;\n          const r = row as Record<string, unknown>;\n          const overrides = r['_overrides'] as Record<string, unknown> | undefined;\n          const overrideBadge = isOverridable\n            ? overrides?.[col.fieldName] !== undefined\n              ? <span title={tt('companyOverrideTooltip', 'Valor sobreescrito por la compañía')} className=\"inline-flex items-center justify-center w-5 h-5 rounded-md bg-blue-50 border border-blue-200 text-blue-700 dark:bg-blue-950/40 dark:border-blue-800 dark:text-blue-400 ml-1 flex-shrink-0 cursor-help\"><Building2 size={12} /></span>\n              : <span title={tt('companyGlobalValueTooltip', 'Valor global')} className=\"inline-flex items-center justify-center w-5 h-5 rounded-md bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-400 dark:text-zinc-500 ml-1 flex-shrink-0 cursor-help\"><Globe size={12} /></span>\n            : null;\n          return <span className=\"inline-flex items-center\">{base}{overrideBadge}</span>;\n        };\n      } else if (isCompanyCtx && isOverridable) {\n        renderFn = (value: unknown, row: T) => {\n          const base = value !== undefined && value !== null ? String(value) : '';\n          const r = row as Record<string, unknown>;\n          const overrides = r['_overrides'] as Record<string, unknown> | undefined;\n          const overrideBadge = isOverridable\n            ? overrides?.[col.fieldName] !== undefined\n              ? <span title={tt('companyOverrideTooltip', 'Valor sobreescrito por la compañía')} className=\"inline-flex items-center justify-center w-5 h-5 rounded-md bg-blue-50 border border-blue-200 text-blue-700 dark:bg-blue-950/40 dark:border-blue-800 dark:text-blue-400 ml-1 flex-shrink-0 cursor-help\"><Building2 size={12} /></span>\n              : <span title={tt('companyGlobalValueTooltip', 'Valor global')} className=\"inline-flex items-center justify-center w-5 h-5 rounded-md bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-400 dark:text-zinc-500 ml-1 flex-shrink-0 cursor-help\"><Globe size={12} /></span>\n            : null;\n          return <span className=\"inline-flex items-center\">{base}{overrideBadge}</span>;\n        };\n      }\n\n      const isFilterOpen = openColumnFilter === col.fieldName;\n      // hasActiveFilter reflects the store (backend filter active), not just the input\n      const hasActiveFilter = storeColumnFilters.some((f) => f.field === col.fieldName);\n\n      return {\n        header: (\n          <div data-testid={`sort-header-${col.fieldName}`}>\n            {/* Label row: label on left | filter + sort icons on right */}\n            <div\n              className=\"flex items-center justify-between w-full gap-1 cursor-pointer select-none\"\n              onClick={() => {\n                const nextDir = sortBy === col.fieldName && sortOrder === 'asc' ? 'desc' : 'asc';\n                onSort(col.fieldName, nextDir);\n              }}\n            >\n              <span className=\"truncate min-w-0\">{col.label}</span>\n              <span className=\"flex items-center gap-0.5 flex-shrink-0\">\n                {isFilterable && !isLookupField && (\n                  <button\n                    type=\"button\"\n                    data-testid={`filter-icon-${col.fieldName}`}\n                    className={`p-0.5 rounded border-0 bg-transparent leading-none transition-colors ${\n                      isFilterOpen || hasActiveFilter\n                        ? 'text-blue-600 dark:text-blue-400'\n                        : 'text-zinc-400 dark:text-zinc-500 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-950/30'\n                    }`}\n                    onClick={(e) => {\n                      e.stopPropagation();\n                      setOpenColumnFilter((prev) =>\n                        prev === col.fieldName ? null : col.fieldName,\n                      );\n                    }}\n                  >\n                    <Filter size={11} />\n                  </button>\n                )}\n                <SortIcon field={col.fieldName} sortBy={sortBy} sortOrder={sortOrder} />\n              </span>\n            </div>\n\n            {/* Inline filter row — shown when toggled */}\n            {isFilterable && !isLookupField && isFilterOpen && (\n              <div className=\"mt-1\" onClick={(e) => e.stopPropagation()}>\n                {isBooleanField ? (\n                  <select\n                    autoFocus\n                    value={columnFilters[col.fieldName] ?? ''}\n                    onChange={(e) => handleColumnFilter(col.fieldName, e.target.value, true)}\n                    className={colFilterInputClass}\n                    data-testid={`col-filter-${col.fieldName}`}\n                  >\n                    <option value=\"\">{tt('all', 'Todos')}</option>\n                    <option value=\"true\">{tt('active', 'Activo')}</option>\n                    <option value=\"false\">{tt('inactive', 'Inactivo')}</option>\n                  </select>\n                ) : (\n                  <input\n                    autoFocus\n                    type=\"text\"\n                    value={columnFilters[col.fieldName] ?? ''}\n                    onChange={(e) => handleColumnFilter(col.fieldName, e.target.value, false)}\n                    placeholder={tt('filterPlaceholder', 'Filtrar...')}\n                    className={colFilterInputClass}\n                    data-testid={`col-filter-${col.fieldName}`}\n                  />\n                )}\n              </div>\n            )}\n          </div>\n        ),\n        accessor: col.fieldName as keyof T,\n        render: renderFn,\n      };\n    });\n\n    const actionsColumn: TableColumn<T> = {\n      header: (\n        // The xy header wrapper has `sticky right-0` (position:sticky) → it's a containing block.\n        // An absolute child with top:0/bottom:0 fills the full header cell height without negative-margin hacks.\n        // data-testid matches the `sort-header-*` selector in master-pattern-view.css so this\n        // header cell gets the same grey background as the data-column headers.\n        <div className=\"w-full text-center\" data-testid=\"sort-header-actions\">\n          <div\n            aria-hidden=\"true\"\n            style={{\n              position: 'absolute',\n              left: 0,\n              top: 0,\n              bottom: 0,\n              width: '1px',\n              backgroundColor: 'var(--color-border-primary)',\n              pointerEvents: 'none',\n            }}\n          />\n          {tt('actions', 'Acciones')}\n        </div>\n      ),\n      accessor: 'id' as keyof T,\n      align: 'center',\n      stickyRight: true,\n      // Ancho justo para 3 botones con separación táctil (idéntico a MasterCrudTable.tsx:440-444:\n      // 3×28px + 2×gap-1(4px) + 32px de padding de celda ≈ 140px). `fixedWidth` evita que la\n      // columna se expanda más de lo necesario.\n      width: '140px',\n      fixedWidth: true,\n      render: (_value: unknown, row: T) => (\n        // The md cell wrapper has `sticky right-0` (position:sticky) → it's a containing block.\n        // The absolute border div fills top-to-bottom of the cell regardless of row height,\n        // eliminating white gaps when rows grow taller than min-h-[56px].\n        <>\n          <div\n            aria-hidden=\"true\"\n            style={{\n              position: 'absolute',\n              left: 0,\n              top: 0,\n              bottom: 0,\n              width: '1px',\n              backgroundColor: 'var(--color-border-primary)',\n              pointerEvents: 'none',\n            }}\n          />\n          <div style={modalOpen ? { pointerEvents: 'none' } : undefined}>\n            <RowActions\n              row={row}\n              permissions={permissions}\n              onOpenView={onOpenView}\n              onOpenEdit={onOpenEdit}\n              onChangeStatus={onChangeStatus}\n              actions={actions}\n              rowActions={rowActions}\n              toast={toastProp}\n              showInternalToasts={showInternalToasts}\n              defaultActions={defaultActions}\n              t={tt}\n            />\n          </div>\n        </>\n      ),\n    };\n\n    // Dedicated company-status column (mirrors MasterCrud's showCompanyStatusColumn) —\n    // only while a specific company is active; in global scope the same panel opens from\n    // the \"Habilitar compañías\" action in the Acciones column instead (see MasterPatternView.tsx).\n    const companyStatusColumn: TableColumn<T> | null = isCompanyCtx && onCompanyStatusClick ? {\n      header: (\n        <span\n          data-testid=\"sort-header-company-status\"\n          className=\"inline-flex items-center justify-center w-full text-content-secondary dark:text-dark-content-secondary\"\n          title={tt('companyStatus', 'Habilitación en la compañía seleccionada')}\n        >\n          <Building2 size={16} />\n        </span>\n      ),\n      accessor: 'id' as keyof T,\n      align: 'center',\n      width: '46px',\n      fixedWidth: true,\n      render: (_value: unknown, row: T) => {\n        const enabled = (row as Record<string, unknown>)['isAssigned'] === true;\n        return (\n          <button\n            type=\"button\"\n            onClick={(e) => { e.stopPropagation(); onCompanyStatusClick(row); }}\n            className=\"inline-flex\"\n          >\n            <CompanyStatusBadge\n              enabled={enabled}\n              enabledLabel={tt('enabledInCompany', 'Habilitado en la compañía seleccionada')}\n              notEnabledLabel={tt('notEnabledInCompany', 'No habilitado en la compañía seleccionada')}\n            />\n          </button>\n        );\n      },\n    } : null;\n\n    return companyStatusColumn ? [companyStatusColumn, ...dataColumns, actionsColumn] : [...dataColumns, actionsColumn];\n  }, [\n    listColumns,\n    sortBy,\n    sortOrder,\n    onSort,\n    permissions,\n    onOpenView,\n    onOpenEdit,\n    onChangeStatus,\n    actions,\n    rowActions,\n    isCompanyCtx,\n    onCompanyStatusClick,\n    toastProp,\n    showInternalToasts,\n    definition,\n    openColumnFilter,\n    columnFilters,\n    storeColumnFilters,\n    handleColumnFilter,\n    modalOpen,\n    defaultActions,\n    tt,\n  ]);\n\n  // Pass a styled EmptyState as emptyMessage — the Table's empty-state wrapper (py-12)\n  // provides the outer spacing, so compact=true removes EmptyState's own padding.\n  // Cast needed because siesa-ui-kit types emptyMessage as string, but React renders\n  // any ReactNode correctly.\n  const emptyContent = (\n    <EmptyState hasSearched compact t={tt} />\n  ) as unknown as string;\n\n  return (\n    <div className=\"mpv-list-table\">\n      <Table<T>\n        // key: fuerza un remount cuando entra/sale la columna de compañía (isCompanyCtx).\n        // Sin esto, el grid CSS (celdas en display:contents) queda desincronizado del\n        // nuevo conteo de columnas — bug conocido del navegador al cambiar la cantidad\n        // de hijos de un contenedor display:contents sin remount — y la tabla se ve\n        // \"escalonada\" (cada fila corrida una columna) al pasar de compañía a Global o viceversa.\n        key={isCompanyCtx ? 'with-company-col' : 'without-company-col'}\n        columns={columns}\n        data={data}\n        loading={isLoading}\n        loadingRows={5}\n        // MasterCrud's table has no row-click-to-view behavior — only the explicit\n        // Acciones buttons (Visualizar/Editar) open a record. Matched here: no onRowClick.\n        variant=\"fullWidth\"\n        showBorder={false}\n        showShadow={false}\n        showPadding={false}\n        dense\n        emptyMessage={emptyContent}\n        data-testid=\"list-table\"\n      />\n    </div>\n  );\n}\n","/**\n * ListCard — card grid view for master entity list.\n *\n * Renders the same data as ListTable but in a responsive card grid.\n * Field layout within each card is driven by the `cardPosition` property\n * on each field definition:\n *   - `'title'`    → large title in the CardHeader (first matching field wins)\n *   - `'subtitle'` → secondary text below the title\n *   - `'body'`     → shown as label/value pairs in CardContent (default)\n *   - `'footer'`   → shown at the bottom of the card\n *\n * When no field has `cardPosition` configured (backward compat), the first\n * `showInList` field becomes the title and the rest go to the body.\n *\n * @module components/list/ListCard\n */\nimport React, { useMemo } from 'react';\nimport { Building2, Globe } from 'lucide-react';\nimport type { MasterPatternViewDefinition } from '../../types/definition.types';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterPatternViewPermissions } from '../../types/permissions.types';\nimport type { MasterPatternViewCustomAction, MasterPatternViewDefaultActions } from '../../types/props.types';\nimport { getAllFields } from '../../engine/fieldEngine';\nimport { useFieldEngine } from '../../hooks/useFieldEngine';\nimport { RowActions } from './RowActions';\nimport type { ToastCallback } from '../../hooks/useToast';\nimport {\n  Card,\n  CardHeader,\n  CardTitle,\n  CardAction,\n  CardContent,\n  CardFooter,\n} from '../../../Card/Card';\n\nexport interface ListCardProps<T extends MasterPatternViewEntity = MasterPatternViewEntity> {\n  definition: MasterPatternViewDefinition;\n  data: T[];\n  onOpenView: (row: T) => void;\n  onOpenEdit: (row: T) => void;\n  onChangeStatus?: (row: T) => void;\n  isLoading?: boolean;\n  permissions?: MasterPatternViewPermissions;\n  actions?: MasterPatternViewCustomAction<T>[];\n  rowActions?: (row: T) => React.ReactNode;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** Active company context — undefined or 'global' means global view */\n  activeCompanyContext?: string;\n  /**\n   * When provided, a per-card company-enable badge renders next to the title (mirrors\n   * MasterCrud's showCompanyStatusColumn) — only while a specific company is active.\n   * Clicking it opens the same \"Habilitar por compañía\" panel as the Acciones-column\n   * action does in global scope.\n   */\n  onCompanyStatusClick?: (row: T) => void | Promise<void>;\n  /** When true, disables pointer events to prevent interaction through modal overlays */\n  modalOpen?: boolean;\n  defaultActions?: MasterPatternViewDefaultActions<T>;\n  /**\n   * Custom render function for card content.\n   * When provided, replaces the auto-generated CardContent body.\n   * Receives the row data and its zero-based index.\n   */\n  renderCardContent?: (row: T, index: number) => React.ReactNode;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\n/** Format a raw field value for display inside a card. */\nfunction formatValue(\n  value: unknown,\n  dataType: string,\n  tt: (key: string, defaultValue?: string) => string,\n): React.ReactNode {\n  if (value === null || value === undefined || value === '') {\n    return <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">—</span>;\n  }\n  if (dataType === 'boolean' || typeof value === 'boolean') {\n    return value ? (\n      <span className=\"inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-[#ecfccb] text-[#4d7c0f]\">\n        {tt('active', 'Activo')}\n      </span>\n    ) : (\n      <span className=\"inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-background-secondary dark:bg-dark-bg-secondary text-content-tertiary dark:text-dark-content-tertiary\">\n        {tt('inactive', 'Inactivo')}\n      </span>\n    );\n  }\n  return String(value);\n}\n\n/** Skeleton placeholder for a single card while loading. */\nfunction CardSkeleton() {\n  return (\n    <div className=\"animate-pulse rounded-xl border border-border-primary dark:border-dark-border-primary bg-bg-primary dark:bg-dark-bg-secondary p-6 flex flex-col gap-4\">\n      <div className=\"flex items-start justify-between\">\n        <div className=\"flex flex-col gap-2 flex-1\">\n          <div className=\"h-4 bg-background-secondary dark:bg-dark-bg-primary rounded w-2/3\" />\n          <div className=\"h-3 bg-background-secondary dark:bg-dark-bg-primary rounded w-1/2\" />\n        </div>\n        <div className=\"flex gap-1 ml-4\">\n          <div className=\"w-7 h-7 rounded-md bg-background-secondary dark:bg-dark-bg-primary\" />\n          <div className=\"w-7 h-7 rounded-md bg-background-secondary dark:bg-dark-bg-primary\" />\n          <div className=\"w-7 h-7 rounded-md bg-background-secondary dark:bg-dark-bg-primary\" />\n        </div>\n      </div>\n      <div className=\"flex flex-col gap-2\">\n        <div className=\"h-3 bg-background-secondary dark:bg-dark-bg-primary rounded w-full\" />\n        <div className=\"h-3 bg-background-secondary dark:bg-dark-bg-primary rounded w-4/5\" />\n        <div className=\"h-3 bg-background-secondary dark:bg-dark-bg-primary rounded w-3/5\" />\n      </div>\n    </div>\n  );\n}\n\nexport function ListCard<T extends MasterPatternViewEntity = MasterPatternViewEntity>({\n  definition,\n  data,\n  onOpenView,\n  onOpenEdit,\n  onChangeStatus,\n  isLoading = false,\n  permissions,\n  actions,\n  rowActions,\n  toast: toastProp,\n  showInternalToasts = true,\n  activeCompanyContext,\n  onCompanyStatusClick,\n  modalOpen = false,\n  renderCardContent,\n  defaultActions,\n  t,\n}: ListCardProps<T>) {\n  const tt = useMemo(\n    () => t ?? ((key: string, defaultValue?: string) => defaultValue ?? key),\n    [t],\n  );\n  const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n  const { listColumns } = useFieldEngine(definition);\n\n  // Build a map from fieldName → full field definition (for cardPosition, dataType, label, etc.)\n  const fieldMap = useMemo(\n    () => new Map(getAllFields(definition).map((f) => [f.fieldName, f])),\n    [definition],\n  );\n\n  // Derive which fields go where in the card.\n  // Only consider fields that are present in listColumns (i.e. showInList !== false)\n  // and where showInCard !== false.\n  //\n  // Body columns render in field order — boolean fields (no custom renderCell) render\n  // as an Activo/Inactivo badge instead of a \"Label: Valor\" line, but stay in place\n  // among the other fields (matches MasterCRUDCard.tsx:220-231: the status badge is\n  // just another entry in `contentFields.map(...)`, not hoisted to the header).\n  const { titleCol, subtitleCol, bodyColumns, footerColumns } = useMemo(() => {\n    const visibleCols = listColumns.filter((col) => {\n      const fd = fieldMap.get(col.fieldName);\n      return fd?.showInCard !== false;\n    });\n\n    const anyHasPosition = visibleCols.some((col) => {\n      const fd = fieldMap.get(col.fieldName);\n      return !!fd?.cardPosition;\n    });\n\n    let titleCol = null;\n    let subtitleCol = null;\n    let bodyColumns: typeof visibleCols = [];\n    let footerColumns: typeof visibleCols = [];\n\n    if (!anyHasPosition) {\n      // Fallback: first field → title, rest → body\n      const [first, ...rest] = visibleCols;\n      titleCol = first ?? null;\n      bodyColumns = rest;\n    } else {\n      titleCol =\n        visibleCols.find((col) => fieldMap.get(col.fieldName)?.cardPosition === 'title') ?? null;\n      subtitleCol =\n        visibleCols.find((col) => fieldMap.get(col.fieldName)?.cardPosition === 'subtitle') ?? null;\n      footerColumns = visibleCols.filter(\n        (col) => fieldMap.get(col.fieldName)?.cardPosition === 'footer',\n      );\n      bodyColumns = visibleCols.filter((col) => {\n        const pos = fieldMap.get(col.fieldName)?.cardPosition;\n        return !pos || pos === 'body';\n      });\n    }\n\n    return { titleCol, subtitleCol, bodyColumns, footerColumns };\n  }, [listColumns, fieldMap]);\n\n  if (isLoading) {\n    return (\n      <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 p-4\">\n        {Array.from({ length: 6 }).map((_, i) => (\n          <CardSkeleton key={i} />\n        ))}\n      </div>\n    );\n  }\n\n  return (\n    <div\n      className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 p-4\"\n      style={{ pointerEvents: modalOpen ? 'none' : undefined }}\n    >\n      {data.map((row, index) => {\n        const r = row as Record<string, unknown>;\n        const overrides = r['_overrides'] as Record<string, unknown> | undefined;\n\n        // Title value and company-context badge\n        const titleValue = titleCol ? r[titleCol.fieldName] : null;\n        const titleFd = titleCol ? fieldMap.get(titleCol.fieldName) : null;\n        const isGlobal = isCompanyCtx && titleFd?.isOverridable;\n\n        const titleNode = (\n          <span className=\"inline-flex items-center gap-1.5 flex-wrap\">\n            <span>\n              {titleFd?.renderCell\n                ? (titleFd.renderCell(titleValue, row) as React.ReactNode)\n                : titleValue !== null && titleValue !== undefined\n                  ? String(titleValue)\n                  : <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">—</span>\n              }\n            </span>\n            {isGlobal && (\n              overrides?.[titleCol!.fieldName] !== undefined ? (\n                <span\n                  title={tt('companyOverrideTooltip', 'Valor sobreescrito por la compañía')}\n                  className=\"inline-flex items-center justify-center w-5 h-5 rounded-[4px] bg-[#eff8ff] border border-[#93d1fd] text-[#1355b7] flex-shrink-0 cursor-help\"\n                >\n                  <Building2 size={12} />\n                </span>\n              ) : (\n                <span\n                  title={tt('companyGlobalValueTooltip', 'Valor global')}\n                  className=\"inline-flex items-center justify-center w-5 h-5 rounded-[4px] bg-background-secondary dark:bg-dark-bg-secondary border border-border-primary dark:border-dark-border-primary text-content-tertiary dark:text-dark-content-tertiary flex-shrink-0 cursor-help\"\n                >\n                  <Globe size={12} />\n                </span>\n              )\n            )}\n          </span>\n        );\n\n        const subtitleFd = subtitleCol ? fieldMap.get(subtitleCol.fieldName) : null;\n        const subtitleValue = subtitleCol ? r[subtitleCol.fieldName] : null;\n\n        return (\n          <Card key={row.id} className=\"gap-4 py-4\">\n            <CardHeader className=\"px-4\">\n              <CardTitle className=\"text-sm\">\n                <div className=\"flex flex-col gap-0.5\">\n                  {titleNode}\n                  {subtitleCol && subtitleValue !== null && subtitleValue !== undefined && (\n                    <span className={`text-xs font-normal text-content-secondary dark:text-dark-content-secondary leading-none${titleFd?.renderCell ? ' pl-[1.125rem]' : ''}`}>\n                      {subtitleFd?.renderCell\n                        ? (subtitleFd.renderCell(subtitleValue, row) as React.ReactNode)\n                        : String(subtitleValue)\n                      }\n                    </span>\n                  )}\n                </div>\n              </CardTitle>\n              <CardAction>\n                <div className=\"flex items-center gap-2\">\n                  <RowActions<T>\n                    row={row}\n                    permissions={permissions}\n                    onOpenView={onOpenView}\n                    onOpenEdit={onOpenEdit}\n                    onChangeStatus={onChangeStatus}\n                    actions={actions}\n                    rowActions={rowActions}\n                    toast={toastProp}\n                    showInternalToasts={showInternalToasts}\n                    defaultActions={defaultActions}\n                    variant=\"card\"\n                    t={tt}\n                  />\n                </div>\n              </CardAction>\n            </CardHeader>\n\n            <CardContent className=\"px-4\">\n              {renderCardContent ? (\n                renderCardContent(row, index)\n              ) : (\n                <div className=\"flex flex-col gap-1.5\">\n                  {/* Body fields in definition order — boolean fields (no custom renderCell)\n                      render as a status badge instead of \"Label: Valor\", same as\n                      MasterCRUDCard.tsx's contentFields loop. */}\n                  {bodyColumns.map((col) => {\n                    const fd = fieldMap.get(col.fieldName);\n                    const value = r[col.fieldName];\n                    const isStatusField = fd?.dataType === 'boolean' && !fd?.renderCell;\n\n                    if (isStatusField) {\n                      return (\n                        <div key={col.fieldName} className=\"mt-1\">\n                          {formatValue(value, 'boolean', tt)}\n                        </div>\n                      );\n                    }\n\n                    const displayValue = fd?.renderCell\n                      ? (fd.renderCell(value, row) as React.ReactNode)\n                      : formatValue(value, fd?.dataType ?? 'string', tt);\n\n                    return (\n                      <div key={col.fieldName} className=\"flex items-baseline gap-1 text-xs min-w-0\">\n                        <span className=\"shrink-0 font-medium text-content-tertiary dark:text-dark-content-tertiary\">\n                          {col.label}:\n                        </span>\n                        <span className=\"text-content-primary dark:text-dark-content-primary truncate\">\n                          {displayValue}\n                        </span>\n                      </div>\n                    );\n                  })}\n                </div>\n              )}\n            </CardContent>\n\n            {footerColumns.length > 0 && (\n              <CardFooter className=\"px-4 pt-0 gap-4 flex-wrap\">\n                {footerColumns.map((col) => {\n                  const fd = fieldMap.get(col.fieldName);\n                  const value = r[col.fieldName];\n                  const displayValue = fd?.renderCell\n                    ? (fd.renderCell(value, row) as React.ReactNode)\n                    : formatValue(value, fd?.dataType ?? 'string', tt);\n                  return (\n                    <div key={col.fieldName} className=\"flex flex-col gap-0.5\">\n                      <span className=\"text-[10px] font-medium text-content-tertiary dark:text-dark-content-tertiary uppercase tracking-wide\">\n                        {col.label}\n                      </span>\n                      <span className=\"text-xs text-content-primary dark:text-dark-content-primary\">\n                        {displayValue}\n                      </span>\n                    </div>\n                  );\n                })}\n              </CardFooter>\n            )}\n          </Card>\n        );\n      })}\n    </div>\n  );\n}\n","/**\n * PaginationBar — exact visual/behavioral replica of the internal `Pagination`\n * component used by `Table.tsx` (MasterCrud's pagination), which is not exported\n * by that module. Three sections: left (page-size selector + \"por página\" +\n * total records), center (Primera/Anterior/números/Siguiente/Última — icon-only\n * nav), right (\"Ir a página\" input).\n *\n * @module components/list/PaginationBar\n * @see FMPV-MVWC-E002-S004 I-002\n */\nimport React, { useState } from 'react';\n\nconst ChevronLeftIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m15 18-6-6 6-6\" /></svg>\n);\nconst ChevronRightIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m9 18 6-6-6-6\" /></svg>\n);\nconst ChevronsLeftIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m11 17-5-5 5-5\" /><path d=\"m18 17-5-5 5-5\" /></svg>\n);\nconst ChevronsRightIcon = () => (\n  <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m6 17 5-5-5-5\" /><path d=\"m13 17 5-5-5-5\" /></svg>\n);\n\nexport interface PaginationBarProps {\n  currentPage: number;\n  totalPages: number;\n  totalRecords: number;\n  pageSize: number;\n  pageSizeOptions: number[];\n  onPageChange: (page: number) => void;\n  onPageSizeChange: (pageSize: number) => void;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function PaginationBar({\n  currentPage,\n  totalPages,\n  totalRecords,\n  pageSize,\n  pageSizeOptions,\n  onPageChange,\n  onPageSizeChange,\n  t,\n}: PaginationBarProps) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const [goToValue, setGoToValue] = useState('');\n\n  const multiPage = totalPages > 1;\n\n  // Hasta 3 páginas se muestran todas; con más, una ventana de 2 alrededor de la\n  // actual — primera/última se cubren con los chevrons dobles (sin puntos suspensivos).\n  const getPageNumbers = (): number[] => {\n    if (totalPages <= 3) {\n      return Array.from({ length: totalPages }, (_, i) => i + 1);\n    }\n    const start = Math.min(Math.max(currentPage, 1), totalPages - 1);\n    return [start, start + 1];\n  };\n  const pageNumbers = getPageNumbers();\n\n  const handleGoTo = () => {\n    const n = parseInt(goToValue, 10);\n    if (!isNaN(n) && n >= 1 && n <= totalPages) onPageChange(n);\n    setGoToValue('');\n  };\n\n  const previousLabel = tt('paginationPrev', 'Anterior');\n  const nextLabel = tt('paginationNext', 'Siguiente');\n\n  const formControlCls =\n    'text-sm text-content-primary dark:text-dark-content-primary bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded py-1 focus:outline-none focus:border-[#93d1fd] transition-colors disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer';\n\n  const navIconBtnCls =\n    'inline-flex items-center justify-center w-8 h-8 rounded-md cursor-pointer text-primary-600 dark:text-primary-600 hover:bg-primary-100 dark:hover:bg-primary-900/20 active:scale-95 transition-all duration-150 disabled:opacity-40 disabled:cursor-not-allowed';\n\n  const navNumBtnCls = (active: boolean) =>\n    `inline-flex items-center justify-center min-w-8 h-8 px-3 rounded-md cursor-pointer text-sm font-bold transition-all duration-150 ${\n      active\n        ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-600'\n        : 'text-primary-600 dark:text-primary-600 hover:bg-primary-100 dark:hover:bg-primary-900/20 active:scale-95'\n    }`;\n\n  const navSection = (\n    <nav className=\"flex items-center gap-0.5\" aria-label={tt('pagination', 'Paginación')} data-testid=\"pagination\">\n      <button type=\"button\" title={previousLabel} aria-label=\"Primera página\" onClick={() => currentPage > 1 && onPageChange(1)} disabled={!multiPage || currentPage === 1} className={navIconBtnCls}>\n        <ChevronsLeftIcon />\n      </button>\n      <button type=\"button\" title={previousLabel} aria-label={previousLabel} onClick={() => currentPage > 1 && onPageChange(currentPage - 1)} disabled={!multiPage || currentPage === 1} className={navIconBtnCls}>\n        <ChevronLeftIcon />\n      </button>\n\n      {multiPage && pageNumbers.map((page) => (\n        <button\n          key={page}\n          type=\"button\"\n          onClick={() => onPageChange(page)}\n          aria-current={page === currentPage ? 'page' : undefined}\n          className={navNumBtnCls(page === currentPage)}\n        >\n          {page}\n        </button>\n      ))}\n\n      <button type=\"button\" title={nextLabel} aria-label={nextLabel} onClick={() => currentPage < totalPages && onPageChange(currentPage + 1)} disabled={!multiPage || currentPage === totalPages} className={navIconBtnCls}>\n        <ChevronRightIcon />\n      </button>\n      <button type=\"button\" title={nextLabel} aria-label=\"Última página\" onClick={() => currentPage < totalPages && onPageChange(totalPages)} disabled={!multiPage || currentPage === totalPages} className={navIconBtnCls}>\n        <ChevronsRightIcon />\n      </button>\n    </nav>\n  );\n\n  return (\n    <div className=\"flex items-center justify-between w-full gap-4 flex-wrap px-4 py-2 border-t border-border-primary dark:border-dark-border-primary\">\n      {/* IZQUIERDA — Selector de registros por página + total */}\n      <div className=\"flex items-center gap-1.5 flex-none\">\n        <select\n          value={pageSize}\n          onChange={(e) => onPageSizeChange(Number(e.target.value))}\n          aria-label={tt('recordsPerPage', 'Registros por página')}\n          className={`${formControlCls} px-2`}\n        >\n          {pageSizeOptions.map((size) => (\n            <option key={size} value={size}>{size}</option>\n          ))}\n        </select>\n        <span className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary whitespace-nowrap\">\n          {tt('paginationPerPage', 'por página')}\n        </span>\n        <span className=\"text-content-secondary dark:text-dark-content-secondary select-none px-0.5\">·</span>\n        <span className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary whitespace-nowrap\">\n          {totalRecords.toLocaleString()} {tt('paginationRecords', 'registros')}\n        </span>\n      </div>\n\n      {/* CENTRO — Navegación */}\n      {navSection}\n\n      {/* DERECHA — Ir a página */}\n      <div className=\"flex items-center gap-2 flex-none\">\n        <span className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary whitespace-nowrap\">\n          {tt('paginationGoToPage', 'Página')}\n        </span>\n        <input\n          type=\"number\"\n          min={1}\n          max={totalPages || 1}\n          value={goToValue}\n          onChange={(e) => setGoToValue(e.target.value)}\n          onKeyDown={(e) => { if (e.key === 'Enter') handleGoTo(); }}\n          onBlur={handleGoTo}\n          placeholder={String(currentPage)}\n          disabled={!multiPage}\n          aria-label={tt('paginationGoToPageAria', 'Ir a página')}\n          className={`${formControlCls} w-16 text-center px-2`}\n        />\n      </div>\n    </div>\n  );\n}\n","/**\n * BatchBar — sticky selection bar shown when 1+ rows are selected.\n *\n * Shows selection count, clear button, native \"Cambiar estado masivo\" action,\n * and any consumer-provided batchActions.\n *\n * Returns null when selectedIds is empty (not rendered at all).\n *\n * @module components/list/BatchBar\n * @see FMPV-MVWC-E002-S005 I-002\n */\nimport React, { useState } from 'react';\nimport { Button } from '../../../Button/Button';\nimport { X } from 'lucide-react';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\nimport type { MasterPatternViewPermissions } from '../../types/permissions.types';\nimport type { MasterPatternViewBatchAction } from '../../types/props.types';\nimport type { ToastCallback } from '../../hooks/useToast';\nimport { useToast } from '../../hooks/useToast';\n\nexport interface BatchBarProps<T extends MasterPatternViewEntity = MasterPatternViewEntity> {\n  selectedIds: string[];\n  selectedRecords: T[];\n  onClearSelection: () => void;\n  permissions: MasterPatternViewPermissions;\n  onBatchChangeStatus?: (records: T[]) => void | Promise<void>;\n  batchActions?: MasterPatternViewBatchAction<T>[];\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function BatchBar<T extends MasterPatternViewEntity = MasterPatternViewEntity>({\n  selectedIds,\n  selectedRecords,\n  onClearSelection,\n  permissions,\n  onBatchChangeStatus,\n  batchActions = [],\n  toast: toastProp,\n  showInternalToasts = true,\n  t,\n}: BatchBarProps<T>) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const { showWarning, showError } = useToast(toastProp, showInternalToasts);\n  const [loadingKey, setLoadingKey] = useState<string | null>(null);\n\n  if (selectedIds.length === 0) {\n    return null;\n  }\n\n  const canChangeStatus = permissions.canChangeStatus !== false;\n  const count = selectedIds.length;\n  const recordWord = count !== 1 ? tt('recordsPlural', 'registros') : tt('recordWord', 'registro');\n  const selectedWord = count !== 1 ? tt('selectedPlural', 'seleccionados') : tt('selectedSingular', 'seleccionado');\n  const countLabel = `${count} ${recordWord} ${selectedWord}`;\n\n  const handleChangeStatus = () => {\n    if (!canChangeStatus) {\n      showWarning(tt('batchNoPermissionChangeStatus', 'No tienes permisos para cambiar el estado'));\n      return;\n    }\n    onBatchChangeStatus?.(selectedRecords);\n  };\n\n  const handleBatchAction = async (action: MasterPatternViewBatchAction<T>) => {\n    setLoadingKey(action.key);\n    try {\n      await action.onExecute(selectedRecords);\n    } catch (err) {\n      showError(tt('batchActionError', 'Error al ejecutar la acción'));\n    } finally {\n      setLoadingKey(null);\n    }\n  };\n\n  return (\n    <div\n      data-testid=\"batch-bar\"\n      className=\"flex items-center gap-3 px-4 py-2 bg-primary-50 border-t border-primary-200 sticky bottom-0\"\n    >\n      <span data-testid=\"batch-selection-count\" className=\"text-sm font-medium text-primary-700\">\n        {countLabel}\n      </span>\n\n      <button\n        data-testid=\"batch-clear-button\"\n        onClick={onClearSelection}\n        className=\"p-1 rounded hover:bg-primary-100\"\n        aria-label={tt('clearSelectionAriaLabel', 'Limpiar selección')}\n      >\n        <X size={14} />\n      </button>\n\n      <div className=\"flex items-center gap-2 ml-2\">\n        <Button\n          data-testid=\"batch-change-status-button\"\n          onClick={handleChangeStatus}\n          disabled={!canChangeStatus}\n        >\n          {tt('batchChangeStatus', 'Cambiar estado masivo')}\n        </Button>\n\n        {batchActions.map((action) => {\n          const isDisabled = action.isDisabled?.(selectedRecords) ?? false;\n          const isLoading = loadingKey === action.key;\n          return (\n            <Button\n              key={action.key}\n              data-testid={`batch-action-${action.key}`}\n              onClick={() => !isDisabled && !isLoading && handleBatchAction(action)}\n              disabled={isDisabled || isLoading}\n            >\n              {action.icon && <span className=\"mr-1\">{action.icon}</span>}\n              {action.label}\n            </Button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n","/**\n * DirtyStateDialog — warns user before discarding unsaved form changes.\n *\n * Appears when:\n * - User clicks \"Cancelar\" while isDirty=true\n * - User clicks backdrop in sidebar mode while isDirty=true\n * - User clicks a different row while form has unsaved changes\n *\n * Pixel-matches MasterCrud's own unsaved-changes dialog (MasterCrud.tsx:1989-2020):\n * warning icon, bold title, \"Campos modificados\" diff list, and the same\n * plain/outline/default button hierarchy (Seguir editando / Descartar / Guardar).\n *\n * \"Continuar editando\": dismisses dialog, form stays open.\n * \"Descartar cambios\": closes form, discards all unsaved changes.\n *\n * @module components/modals/DirtyStateDialog\n * @see FMPV-MVWC-E003-S004 I-002\n */\nimport React from 'react';\nimport { Button } from '../../../Button/Button';\n\nexport interface DirtyStateChange {\n  label: string;\n  from: unknown;\n  to: unknown;\n}\n\nexport interface DirtyStateDialogProps {\n  isOpen: boolean;\n  onContinue: () => void;\n  onDiscard: () => void;\n  /** \"Guardar y salir\" — submits the form, which closes it on success. */\n  onSaveAndExit: () => void;\n  /** Fields that changed since the form opened — shown as a \"from → to\" list. */\n  changes?: DirtyStateChange[];\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nfunction formatValue(v: unknown, emptyLabel: string): React.ReactNode {\n  if (v === '' || v === undefined || v === null) {\n    return <span className=\"italic text-content-secondary dark:text-dark-content-secondary\">({emptyLabel})</span>;\n  }\n  // Fields with a custom renderCell (lookups resolving an id to a name, etc.) arrive here\n  // already resolved to a ReactNode — render it as-is instead of String()-ing it, which\n  // would print \"[object Object]\" for anything beyond plain text/numbers.\n  if (React.isValidElement(v)) {\n    return <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">{v}</span>;\n  }\n  return <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">{String(v)}</span>;\n}\n\nexport function DirtyStateDialog({ isOpen, onContinue, onDiscard, onSaveAndExit, changes = [], t }: DirtyStateDialogProps) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  // Always rendered in DOM to avoid animation jank (R-002)\n  if (!isOpen) return null;\n\n  return (\n    <div\n      className=\"fixed inset-0 z-[70] flex items-center justify-center p-4\"\n      role=\"alertdialog\"\n      aria-modal=\"true\"\n      aria-labelledby=\"dirty-dialog-title\"\n    >\n      <div className=\"absolute inset-0 bg-black/50\" onClick={onContinue} />\n      <div\n        data-testid=\"dirty-state-dialog\"\n        className=\"relative w-full max-w-[35rem] bg-bg-primary dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-2xl overflow-hidden\"\n      >\n        <div className=\"p-6\">\n          <div className=\"flex items-start gap-4\">\n            <div className=\"w-10 h-10 flex-shrink-0 rounded-full bg-[#fef9c3] dark:bg-yellow-900/20 flex items-center justify-center\">\n              <svg className=\"w-6 h-6 text-[#a16207]\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" /><path d=\"M12 9v4\" /><path d=\"M12 17h.01\" /></svg>\n            </div>\n            <div className=\"min-w-0 flex-1\">\n              <h2\n                id=\"dirty-dialog-title\"\n                className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\"\n              >\n                {tt('dirtyDialogTitle', 'Tienes cambios sin guardar')}\n              </h2>\n              <p className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary mt-1 leading-5\">\n                {tt('dirtyDialogDesc', 'Si sales ahora perderás los siguientes cambios. ¿Deseas guardarlos antes de volver al listado?')}\n              </p>\n\n              {changes.length > 0 && (\n                <div className=\"mt-3 rounded-lg border border-border-primary dark:border-dark-border-primary overflow-hidden\">\n                  <p className=\"px-3 py-1.5 bg-background-secondary dark:bg-dark-bg-secondary text-[11px] font-semibold uppercase tracking-[0.3px] text-content-secondary dark:text-dark-content-secondary border-b border-border-primary dark:border-dark-border-primary\">\n                    {tt('modifiedFields', 'Campos modificados')}\n                  </p>\n                  <ul\n                    data-testid=\"dirty-dialog-changes\"\n                    className=\"max-h-[11.25rem] overflow-y-auto divide-y divide-border-secondary dark:divide-dark-border-primary\"\n                  >\n                    {changes.map((c, i) => (\n                      <li key={i} className=\"px-3 py-2 text-xs\">\n                        <p className=\"font-semibold text-content-primary dark:text-dark-content-primary\">{c.label}</p>\n                        <p className=\"mt-0.5 text-content-tertiary dark:text-dark-content-tertiary flex items-center gap-1.5 flex-wrap\">\n                          {formatValue(c.from, tt('emptyValue', 'vacío'))}\n                          <svg className=\"w-3 h-3 text-content-secondary dark:text-dark-content-secondary flex-shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M5 12h14\" /><path d=\"m12 5 7 7-7 7\" /></svg>\n                          {formatValue(c.to, tt('emptyValue', 'vacío'))}\n                        </p>\n                      </li>\n                    ))}\n                  </ul>\n                </div>\n              )}\n            </div>\n          </div>\n        </div>\n        <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-border-primary dark:border-dark-border-primary\">\n          <Button\n            type=\"plain\"\n            size=\"base\"\n            className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap\"\n            data-testid=\"dirty-dialog-continue\"\n            onClick={onContinue}\n          >\n            {tt('dirtyDialogContinue', 'Continuar editando')}\n          </Button>\n          <Button\n            type=\"outline\"\n            size=\"base\"\n            className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap !text-error-content !border-error-content\"\n            data-testid=\"dirty-dialog-discard\"\n            onClick={onDiscard}\n          >\n            {tt('dirtyDialogDiscard', 'Descartar y salir')}\n          </Button>\n          <Button\n            type=\"default\"\n            size=\"base\"\n            className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap\"\n            data-testid=\"dirty-dialog-save\"\n            onClick={onSaveAndExit}\n          >\n            {tt('dirtyDialogSaveExit', 'Guardar y salir')}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n","/**\n * ChangeStatusModal — confirmation dialog for changing a record's active status.\n *\n * Delegates to the shared `AlertDialog` component — the same one MasterCrud uses\n * for its activate/deactivate confirmation (MasterCrud.tsx:1954, `type={isActive\n * ? 'danger' : 'success'}`). A prior revision hand-rolled a custom modal (icon\n * square, bordered header/footer, fixed 420px width) that didn't match; this\n * gets pixel-exact parity for free by reusing the same component.\n *\n * @module components/modals/ChangeStatusModal\n * @see FMPV-MVWC-E003-S005 I-001\n */\nimport React from 'react';\nimport { AlertDialog } from '../../../AlertDialog/AlertDialog';\nimport type { MasterPatternViewEntity } from '../../types/service.types';\n\nexport interface ChangeStatusModalProps<T extends MasterPatternViewEntity = MasterPatternViewEntity> {\n  isOpen: boolean;\n  record: T | null;\n  onCancel: () => void;\n  onConfirm: (id: string, newStatus: boolean) => void;\n  isLoading: boolean;\n  companyName?: string;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function ChangeStatusModal<T extends MasterPatternViewEntity = MasterPatternViewEntity>({\n  isOpen,\n  record,\n  onCancel,\n  onConfirm,\n  isLoading,\n  companyName,\n  t,\n}: ChangeStatusModalProps<T>) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  if (!record) return null;\n\n  const isCurrentlyActive = record.isActive;\n  const title = isCurrentlyActive\n    ? tt('confirmDeactivateTitle', '¿Estás seguro de desactivar este registro?')\n    : tt('confirmActivateTitle', '¿Estás seguro de activar este registro?');\n  const baseDesc = isCurrentlyActive\n    ? tt('confirmDeactivateDesc', 'El registro dejará de estar disponible.')\n    : tt('confirmActivateDesc', 'El registro volverá a estar disponible.');\n  const confirmText = isCurrentlyActive\n    ? tt('deactivateAction', 'Desactivar')\n    : tt('activateAction', 'Activar');\n\n  const description = companyName ? (\n    <>\n      {baseDesc} {tt('changeStatusScopeNotePrefix', 'Solo se modificará el estado para ')}\n      <strong>{companyName}</strong>.\n    </>\n  ) : baseDesc;\n\n  const handleConfirm = () => {\n    onConfirm(record.id, !isCurrentlyActive);\n  };\n\n  return (\n    <AlertDialog\n      isOpen={isOpen}\n      type={isCurrentlyActive ? 'danger' : 'success'}\n      title={title}\n      description={description}\n      onCancel={onCancel}\n      onConfirm={handleConfirm}\n      cancelText={tt('cancel', 'Cancelar')}\n      confirmText={confirmText}\n      isProcess={isLoading}\n      data-testid=\"change-status-modal\"\n    />\n  );\n}\n","/**\n * ConflictDialog — shown when server returns 409 (optimistic concurrency conflict).\n *\n * Single action: \"Refrescar datos\" — reloads the list query and the record.\n * Styles match NotEnabledModal corporate mock patterns.\n *\n * @module components/modals/ConflictDialog\n * @see FMPV-MVWC-E003-S003 I-004\n */\nimport React from 'react';\nimport { RefreshCw, X } from 'lucide-react';\nimport { Button } from '../../../Button/Button';\nimport { useMasterViewStore } from '../../store/MasterViewContext';\n\nexport interface ConflictDialogProps {\n  onRefresh: () => void;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function ConflictDialog({ onRefresh, t }: ConflictDialogProps) {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const isOpen = useMasterViewStore((s) => s.isConflictDialogOpen);\n  const closeConflictDialog = useMasterViewStore((s) => s.closeConflictDialog);\n\n  if (!isOpen) return null;\n\n  const handleRefresh = () => {\n    closeConflictDialog();\n    onRefresh();\n  };\n\n  return (\n    <div\n      className=\"fixed inset-0 flex items-center justify-center z-[9000]\"\n      style={{ background: 'rgba(15,23,42,.45)', backdropFilter: 'blur(2px)' }}\n      role=\"alertdialog\"\n      aria-modal=\"true\"\n    >\n      <div\n        data-testid=\"conflict-dialog\"\n        className=\"bg-bg-primary dark:bg-dark-bg-secondary border border-transparent dark:border-dark-border-primary flex flex-col overflow-hidden\"\n        style={{\n          borderRadius: 12,\n          boxShadow: '0 24px 64px rgba(0,0,0,.22),0 4px 16px rgba(0,0,0,.1)',\n          width: 420,\n        }}\n      >\n        {/* Header */}\n        <div\n          className=\"flex items-start justify-between border-b border-border-primary dark:border-dark-border-primary gap-3\"\n          style={{ padding: '18px 20px 14px' }}\n        >\n          <div className=\"flex items-start gap-3\">\n            <div\n              className=\"flex-shrink-0 flex items-center justify-center bg-[#fff7ed] dark:bg-[rgba(234,88,12,0.15)] text-[#ea580c] dark:text-[#fb923c]\"\n              style={{ width: 36, height: 36, borderRadius: 8 }}\n            >\n              <RefreshCw size={18} />\n            </div>\n            <div>\n              <div className=\"font-bold text-content-primary dark:text-dark-content-primary leading-snug\" style={{ fontSize: 14 }}>\n                {tt('conflictTitle', 'Conflicto de versión')}\n              </div>\n              <div className=\"text-content-tertiary dark:text-dark-content-tertiary leading-relaxed\" style={{ fontSize: 12, marginTop: 3 }}>\n                {tt('conflictSubtitle', 'El registro fue modificado por otro usuario')}\n              </div>\n            </div>\n          </div>\n          <button\n            type=\"button\"\n            data-testid=\"conflict-close-button\"\n            onClick={handleRefresh}\n            className=\"flex-shrink-0 flex items-center justify-center p-1 rounded-md border-0 bg-transparent text-content-secondary dark:text-dark-content-secondary cursor-pointer hover:bg-background-secondary dark:hover:bg-dark-bg-primary hover:text-content-tertiary dark:hover:text-dark-content-tertiary transition-colors leading-none\"\n          >\n            <X size={16} />\n          </button>\n        </div>\n\n        {/* Body */}\n        <div style={{ padding: '16px 20px' }}>\n          <p className=\"text-content-primary dark:text-dark-content-primary\" style={{ fontSize: 13, lineHeight: 1.6 }}>\n            {tt('conflictBody', 'Este registro fue modificado por otro usuario mientras lo editabas. Recarga los datos para ver la versión más reciente antes de continuar.')}\n          </p>\n        </div>\n\n        {/* Footer */}\n        <div\n          className=\"flex items-center justify-end gap-2 border-t border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-primary\"\n          style={{ padding: '12px 20px' }}\n        >\n          <Button\n            data-testid=\"conflict-refresh-button\"\n            type=\"default\"\n            size=\"l\"\n            onClick={handleRefresh}\n          >\n            {tt('conflictRefreshButton', 'Refrescar datos')}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n","/**\n * NotEnabledModal — shown when user tries to edit/view/change-status on a record\n * that is NOT yet enabled (assigned) for the active company context.\n *\n * Styles match corporate mock patterns:\n *   .modal-overlay  → fixed inset-0, rgba(15,23,42,.45), backdrop-filter:blur(2px)\n *   .modal          → borderRadius:12, boxShadow double-layer, width:420\n *   .modal-header   → padding:18px 20px 14px, border-bottom, icon-wrap.blue\n *   .modal-body     → padding:16px 20px, gap:12px\n *   .modal-footer   → padding:12px 20px, bg:#f4f4f5, border-top, btn-secondary + btn-primary\n *\n * Trigger determines body text and confirm button label:\n *   OPEN_EDIT     → editing flow\n *   OPEN_VIEW     → view-only flow\n *   CHANGE_STATUS → status toggle flow\n *\n * @module components/modals/NotEnabledModal\n * @see FMPV-MVWC-E004-S005\n */\nimport React from 'react';\nimport { Building2, AlertTriangle, X } from 'lucide-react';\nimport { Button } from '../../../Button/Button';\n\nexport type NotEnabledModalTrigger = 'OPEN_EDIT' | 'CHANGE_STATUS' | 'OPEN_VIEW' | 'COMPANY_SWITCH';\n\nexport interface NotEnabledModalProps {\n  isOpen: boolean;\n  trigger: NotEnabledModalTrigger;\n  /** Display name of the active company (shown in header subtitle and body) */\n  companyName: string;\n  onCancel: () => void;\n  onConfirm: () => void;\n  isLoading: boolean;\n  /** Translation function override — falls back to the current Spanish text when omitted. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function NotEnabledModal({\n  isOpen,\n  trigger,\n  companyName,\n  onCancel,\n  onConfirm,\n  isLoading,\n  t,\n}: NotEnabledModalProps): React.ReactElement | null {\n  const tt = t ?? ((key: string, defaultValue?: string) => defaultValue ?? key);\n  const getActionText = (trig: NotEnabledModalTrigger): string => {\n    switch (trig) {\n      case 'OPEN_EDIT': return tt('notEnabledActionEdit', '¿Desea habilitarlo y continuar con la edición?');\n      case 'CHANGE_STATUS': return tt('notEnabledActionChangeStatus', '¿Desea habilitarlo y cambiar su estado?');\n      case 'OPEN_VIEW': return tt('notEnabledActionView', '¿Desea habilitarlo y continuar con la visualización?');\n      case 'COMPANY_SWITCH': return tt('notEnabledActionCompanySwitch', '¿Desea habilitarlo para continuar con la edición en esta compañía?');\n    }\n  };\n  const getConfirmLabel = (trig: NotEnabledModalTrigger): string => {\n    switch (trig) {\n      case 'CHANGE_STATUS': return tt('notEnabledConfirmChangeStatus', 'Habilitar y cambiar estado');\n      default: return tt('notEnabledConfirmContinue', 'Habilitar y continuar');\n    }\n  };\n  if (!isOpen) return null;\n\n  return (\n    /* Overlay — matches mock .modal-overlay */\n    <div\n      className=\"fixed inset-0 flex items-center justify-center z-[9000]\"\n      style={{ background: 'rgba(15,23,42,.45)', backdropFilter: 'blur(2px)' }}\n      role=\"dialog\"\n      aria-modal=\"true\"\n    >\n      {/* Modal — matches mock .modal */}\n      <div\n        data-testid=\"not-enabled-modal\"\n        className=\"bg-bg-primary dark:bg-dark-bg-secondary border border-transparent dark:border-dark-border-primary flex flex-col overflow-hidden\"\n        style={{\n          borderRadius: 12,\n          boxShadow: '0 24px 64px rgba(0,0,0,.22),0 4px 16px rgba(0,0,0,.1)',\n          maxHeight: '78vh',\n          width: 420,\n        }}\n      >\n        {/* Header — matches mock .modal-header */}\n        <div\n          className=\"flex items-start justify-between border-b border-border-primary dark:border-dark-border-primary gap-3\"\n          style={{ padding: '18px 20px 14px' }}\n        >\n          {/* Left: icon + title / subtitle */}\n          <div className=\"flex items-start gap-3\">\n            {/* Icon wrap blue — matches mock .modal-icon-wrap.blue */}\n            <div\n              className=\"flex-shrink-0 flex items-center justify-center bg-[#eff8ff] dark:bg-[rgba(14,121,253,0.15)] text-[#0e79fd] dark:text-[#60b6fa]\"\n              style={{ width: 36, height: 36, borderRadius: 8 }}\n            >\n              <Building2 size={18} />\n            </div>\n            <div>\n              {/* .modal-title */}\n              <div className=\"font-bold text-content-primary dark:text-dark-content-primary leading-snug\" style={{ fontSize: 14 }}>\n                {tt('notEnabledTitle', 'Registro no habilitado')}\n              </div>\n              {/* .modal-desc */}\n              <div className=\"text-content-tertiary dark:text-dark-content-tertiary leading-relaxed\" style={{ fontSize: 12, marginTop: 3 }}>\n                {companyName}\n              </div>\n            </div>\n          </div>\n\n          {/* Close button — matches mock .modal-close */}\n          <button\n            type=\"button\"\n            data-testid=\"not-enabled-close-button\"\n            onClick={onCancel}\n            className=\"flex-shrink-0 flex items-center justify-center p-1 rounded-md border-0 bg-transparent text-content-secondary dark:text-dark-content-secondary cursor-pointer hover:bg-background-secondary dark:hover:bg-dark-bg-secondary hover:text-content-tertiary dark:hover:text-dark-content-tertiary transition-colors leading-none\"\n          >\n            <X size={16} />\n          </button>\n        </div>\n\n        {/* Body — matches mock .modal-body */}\n        <div\n          className=\"flex-1 overflow-y-auto flex flex-col\"\n          style={{ padding: '16px 20px', gap: 12 }}\n        >\n          <p\n            data-testid=\"not-enabled-body\"\n            className=\"text-content-primary dark:text-dark-content-primary\" style={{ fontSize: 13, lineHeight: 1.6 }}\n          >\n            {tt('notEnabledBodyPrefix', 'Este registro no está habilitado en ')}<strong>{companyName}</strong>.{' '}\n            {getActionText(trigger)}\n          </p>\n\n          {/* Yellow warning callout — matches mock's inline amber callout */}\n          <div\n            className=\"flex items-start gap-2 bg-[#fffdf0] dark:bg-[rgba(251,191,36,0.08)]\"\n            style={{\n              borderLeft: '3px solid #fbbf24',\n              borderRadius: '0 4px 4px 0',\n              padding: '5px 10px',\n            }}\n          >\n            <AlertTriangle size={12} className=\"flex-shrink-0 text-[#d97706] dark:text-[#fbbf24]\" style={{ marginTop: 2 }} />\n            <span className=\"text-[#92400e] dark:text-[#fcd34d]\" style={{ fontSize: 11 }}>\n              {tt('notEnabledWarning', 'Los valores globales se conservarán hasta que se personalicen los campos.')}\n            </span>\n          </div>\n        </div>\n\n        {/* Footer — matches mock .modal-footer (bg:#f4f4f5) */}\n        <div\n          className=\"flex items-center justify-end gap-2 border-t border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-primary\"\n          style={{ padding: '12px 20px' }}\n        >\n          <Button\n            data-testid=\"not-enabled-cancel-button\"\n            type=\"outline\"\n            size=\"base\"\n            className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap\"\n            onClick={onCancel}\n            disabled={isLoading}\n          >\n            {tt('cancel', 'Cancelar')}\n          </Button>\n          <Button\n            data-testid=\"not-enabled-confirm-button\"\n            type=\"default\"\n            size=\"base\"\n            className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap\"\n            onClick={onConfirm}\n            disabled={isLoading}\n          >\n            {isLoading ? tt('notEnabledLoadingLabel', 'Habilitando…') : getConfirmLabel(trigger)}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n","/**\n * useMasterList — TanStack Query integration for the list view.\n *\n * Supports two modes:\n *   - 'pages'    : traditional page-based pagination via useQuery.\n *   - 'infinite' : infinite scroll via useInfiniteQuery; pages are accumulated\n *                  and flattened into the Zustand store on every page arrival.\n *\n * Both query hooks are always called (React hooks rules). Only the active one\n * is enabled via the `enabled` flag.\n *\n * @module hooks/useMasterList\n * @see FMPV-MVWC-E002-S004 I-001\n */\nimport { useEffect } from 'react';\nimport { useQuery, useInfiniteQuery } from '@tanstack/react-query';\nimport { useMasterViewStore } from '../store/MasterViewContext';\nimport type { MasterPatternViewEntity } from '../types/service.types';\nimport type { MasterPatternViewService } from '../types/service.types';\nimport type { MasterPatternViewPermissions } from '../types/permissions.types';\nimport type { ToastCallback } from './useToast';\nimport { useToast } from './useToast';\nimport { isActionAllowed } from '../engine/permissionEngine';\n\nexport interface UseMasterListOptions<T extends MasterPatternViewEntity> {\n  service: MasterPatternViewService<T>;\n  entityName?: string;\n  autoLoad?: boolean;\n  defaultFiltersOpen?: boolean;\n  permissions?: MasterPatternViewPermissions;\n  masterType?: 'UNIVERSAL' | 'COMPANY_SPECIFIC' | 'GLOBAL';\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  mode?: 'pages' | 'infinite';\n  /** Translation function — used for toast messages. Falls back to built-in Spanish strings. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function useMasterList<T extends MasterPatternViewEntity>({\n  service,\n  entityName = 'entity',\n  autoLoad = false,\n  defaultFiltersOpen = false,\n  permissions,\n  masterType = 'UNIVERSAL',\n  toast,\n  showInternalToasts = true,\n  mode = 'pages',\n  t = (key: string, defaultValue?: string) => defaultValue ?? key,\n}: UseMasterListOptions<T>) {\n  const searchParams = useMasterViewStore((s) => s.searchParams);\n  const columnFilters = useMasterViewStore((s) => s.columnFilters);\n  const quickFilterValues = useMasterViewStore((s) => s.quickFilterValues);\n  const hasSearched = useMasterViewStore((s) => s.hasSearched);\n  const setData = useMasterViewStore((s) => s.setData);\n  const setIsLoading = useMasterViewStore((s) => s.setIsLoading);\n  const setHasSearched = useMasterViewStore((s) => s.setHasSearched);\n  const activeCompanyContext = useMasterViewStore((s) => s.activeCompanyContext);\n  const { showError } = useToast(toast, showInternalToasts);\n\n  const canRead = isActionAllowed(permissions, 'READ', masterType);\n  const enabled = (hasSearched || autoLoad || !defaultFiltersOpen) && canRead;\n  const isInfinite = mode === 'infinite';\n\n  // Separate meta-filters (client-side only) from backend service filters.\n  // __view      → applied after fetch to filter rows by isAssigned (not sent to backend)\n  // __status    → mapped to isActive boolean for backend\n  // __connector → connector hint for advanced filters (AND/OR), not a field filter\n  // Same field with multiple conditions → value becomes an array of MasterPatternViewFilterValue\n  // so backends can apply all conditions instead of only the last one.\n  //\n  // columnFilters (from ListTable header inputs) and quickFilterValues (from inline\n  // QuickFilters inputs, converted to ActiveFilter[] with operator 'contains') are both\n  // merged with searchParams.filters (from FilterPanel) here so all three sources remain\n  // independent in the store — each mechanism can be cleared without affecting the others.\n  const quickFiltersAsActive: import('../store/types').ActiveFilter[] = Object.entries(quickFilterValues)\n    .filter(([, v]) => v.trim() !== '')\n    .map(([field, v]) => ({ field, operator: 'contains', value: v.trim() }));\n  const allFilters = [...searchParams.filters, ...columnFilters, ...quickFiltersAsActive];\n  const serviceFilters: Record<string, unknown> = {};\n  let viewFilter: string | undefined;\n\n  for (const f of allFilters) {\n    if (f.field === '__view') {\n      viewFilter = String(f.value);\n    } else if (f.field === '__status') {\n      if (f.value === 'active') serviceFilters['isActive'] = true;\n      else if (f.value === 'inactive') serviceFilters['isActive'] = false;\n    } else if (f.field === '__connector') {\n      // pass connector hint as-is so backends can use AND/OR logic\n      serviceFilters['__connector'] = f.value;\n    } else {\n      const filterValue = { value: f.value, operator: f.operator };\n      const existing = serviceFilters[f.field];\n      if (existing === undefined) {\n        serviceFilters[f.field] = filterValue;\n      } else if (Array.isArray(existing)) {\n        (existing as unknown[]).push(filterValue);\n      } else {\n        serviceFilters[f.field] = [existing, filterValue];\n      }\n    }\n  }\n\n  const companyId = masterType !== 'UNIVERSAL' ? activeCompanyContext : undefined;\n\n  // Base params shared by both modes (page number is handled separately per mode).\n  const baseParams = {\n    pageSize: searchParams.pageSize,\n    search: searchParams.search,\n    sortBy: searchParams.sortBy,\n    sortOrder: searchParams.sortOrder,\n    filters: serviceFilters,\n    companyId,\n  };\n\n  // ── Page-based query ────────────────────────────────────────────────────────\n  // Enabled only when mode === 'pages'.\n  const pageQuery = useQuery({\n    queryKey: ['masterList', entityName, searchParams, columnFilters, quickFilterValues, companyId],\n    queryFn: () => service.getAll({ page: searchParams.page, ...baseParams }),\n    enabled: enabled && !isInfinite,\n    staleTime: 30_000,\n    gcTime: 60_000,\n    refetchOnWindowFocus: false,\n  });\n\n  // ── Infinite query ──────────────────────────────────────────────────────────\n  // Enabled only when mode === 'infinite'.\n  // queryKey excludes page (managed by pageParam) so changing search/filters\n  // resets accumulation automatically.\n  const infiniteQuery = useInfiniteQuery({\n    // pageParam drives pagination — no need to include searchParams.page in the key.\n    // Any change to search/filters/sort lands in baseParams and invalidates this query automatically.\n    queryKey: ['masterList', entityName, baseParams, companyId],\n    queryFn: ({ pageParam }) =>\n      service.getAll({ page: pageParam as number, ...baseParams }),\n    initialPageParam: 1,\n    getNextPageParam: (lastPage) => {\n      const totalPages = Math.ceil(lastPage.total / lastPage.pageSize);\n      return lastPage.page < totalPages ? lastPage.page + 1 : undefined;\n    },\n    enabled: enabled && isInfinite,\n    staleTime: 30_000,\n    gcTime: 60_000,\n    refetchOnWindowFocus: false,\n  });\n\n  // ── Loading state sync ──────────────────────────────────────────────────────\n  useEffect(() => {\n    const active = isInfinite ? infiniteQuery : pageQuery;\n    setIsLoading(active.isLoading || active.isFetching);\n  }, [\n    isInfinite,\n    pageQuery.isLoading,\n    pageQuery.isFetching,\n    infiniteQuery.isLoading,\n    infiniteQuery.isFetching,\n    setIsLoading,\n  ]);\n\n  // ── Page-based data sync ────────────────────────────────────────────────────\n  useEffect(() => {\n    if (!isInfinite && pageQuery.data) {\n      let rows = pageQuery.data.data;\n      let total = pageQuery.data.total;\n      // `__view=company` filters client-side, over whatever page is already loaded —\n      // it never re-fetches, so `pageQuery.data.total` (the server's UNFILTERED count)\n      // no longer describes what's on screen once that filter drops rows. Left as-is,\n      // the pagination bar kept advertising the full unfiltered total/page count (e.g.\n      // \"209 registros\" / page 2 of 2) while rendering a single filtered row — user-visible\n      // as \"the pill doesn't find records that happen to live on a page I'm not viewing\".\n      // Reporting the post-filter row count instead stops the bar from lying about a\n      // total or a further page that isn't actually there to page into; it does NOT make\n      // the filter reach records sitting on pages this fetch never loaded — that needs the\n      // filter to travel to the backend instead, a separate (larger) change.\n      if (viewFilter === 'company') {\n        rows = rows.filter((r) => r.isAssigned === true);\n        total = rows.length;\n      }\n      setData(rows, total);\n      setHasSearched(true);\n    }\n  }, [isInfinite, pageQuery.data, viewFilter, setData, setHasSearched]);\n\n  // ── Infinite data sync ──────────────────────────────────────────────────────\n  // Flatten all accumulated pages into a single array and push to store.\n  useEffect(() => {\n    if (isInfinite && infiniteQuery.data) {\n      let rows = infiniteQuery.data.pages.flatMap((p) => p.data);\n      let total = infiniteQuery.data.pages[0]?.total ?? 0;\n      // Same rationale as the page-based sync above: report what's actually rendered\n      // once `__view=company` drops rows, instead of the server's unfiltered total.\n      if (viewFilter === 'company') {\n        rows = rows.filter((r) => r.isAssigned === true);\n        total = rows.length;\n      }\n      setData(rows, total);\n      setHasSearched(true);\n    }\n  }, [isInfinite, infiniteQuery.data, viewFilter, setData, setHasSearched]);\n\n  // ── Error handling ──────────────────────────────────────────────────────────\n  useEffect(() => {\n    const err = isInfinite ? infiniteQuery.error : pageQuery.error;\n    if (err) showError(t('loadRecordsError', 'Error al cargar los registros'));\n  }, [isInfinite, pageQuery.error, infiniteQuery.error, showError, t]);\n\n  return {\n    fetchNextPage: infiniteQuery.fetchNextPage,\n    hasNextPage: infiniteQuery.hasNextPage ?? false,\n    isFetchingNextPage: infiniteQuery.isFetchingNextPage,\n  };\n}\n","/**\n * useChangeStatus — TanStack Query mutation for change status operations.\n *\n * On success: success toast + list refresh + fire onStatusChangeSuccess.\n * On error: error toast.\n *\n * @module hooks/useChangeStatus\n * @see FMPV-MVWC-E003-S005 I-002\n */\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport type { MasterPatternViewEntity } from '../types/service.types';\nimport type { MasterPatternViewService } from '../types/service.types';\nimport type { ToastCallback } from './useToast';\nimport { useToast } from './useToast';\nimport { useMasterViewStore } from '../store/MasterViewContext';\n\nexport interface UseChangeStatusOptions<T extends MasterPatternViewEntity> {\n  service: MasterPatternViewService<T>;\n  onStatusChangeSuccess?: (record: T) => void;\n  toast?: ToastCallback;\n  showInternalToasts?: boolean;\n  /** Translation function — used for toast messages. Falls back to built-in Spanish strings. */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport function useChangeStatus<T extends MasterPatternViewEntity>({\n  service,\n  onStatusChangeSuccess,\n  toast: toastProp,\n  showInternalToasts = true,\n  t = (key: string, defaultValue?: string) => defaultValue ?? key,\n}: UseChangeStatusOptions<T>) {\n  const { showSuccess, showError } = useToast(toastProp, showInternalToasts);\n  const closeChangeStatusModal = useMasterViewStore((s) => s.closeChangeStatusModal);\n  const clearPendingAction = useMasterViewStore((s) => s.clearPendingAction);\n  const queryClient = useQueryClient();\n\n  const mutation = useMutation({\n    mutationFn: ({ id, newStatus, companyId }: { id: string; newStatus: boolean; companyId?: string }) =>\n      service.changeStatus!(id, newStatus, companyId),\n    onSuccess: (record, { id, newStatus }) => {\n      showSuccess(t('statusChangeSuccess', 'Estado cambiado exitosamente'));\n      // Patch only the affected record in the cache — avoids a full list re-fetch.\n      // Works for both pages mode ({ data: T[] }) and infinite mode ({ pages: [...] }).\n      queryClient.setQueriesData<unknown>(\n        { queryKey: ['masterList'] },\n        (oldData: unknown) => {\n          if (!oldData) return oldData;\n          const patchRow = (r: { id: string }) =>\n            r.id === id ? { ...r, isActive: newStatus } : r;\n          if (Array.isArray((oldData as { pages?: unknown[] }).pages)) {\n            const d = oldData as { pages: { data: { id: string }[] }[] };\n            return { ...d, pages: d.pages.map((p) => ({ ...p, data: p.data.map(patchRow) })) };\n          }\n          const d = oldData as { data: { id: string }[] };\n          return { ...d, data: d.data.map(patchRow) };\n        },\n      );\n      closeChangeStatusModal();\n      clearPendingAction();\n      onStatusChangeSuccess?.(record);\n    },\n    onError: (error: Error) => {\n      showError(error.message || t('statusChangeError', 'Error al cambiar el estado'));\n      closeChangeStatusModal();\n      clearPendingAction();\n    },\n  });\n\n  const executeChangeStatus = (id: string, newStatus: boolean, companyId?: string) => {\n    mutation.mutate({ id, newStatus, companyId });\n  };\n\n  return {\n    executeChangeStatus,\n    isChanging: mutation.isPending,\n  };\n}\n","/**\n * useSortState — reads and writes sort parameters from listSlice.\n * Encapsulates sort param reads/writes to reduce direct store coupling in ListTable.\n *\n * @module hooks/useSortState\n * @see FMPV-MVWC-E002-S003 R-001\n */\nimport { useCallback } from 'react';\nimport { useMasterViewStore } from '../store/MasterViewContext';\n\nexport interface SortState {\n  sortBy: string;\n  sortOrder: 'asc' | 'desc';\n  setSort: (field: string, direction: 'asc' | 'desc') => void;\n}\n\n/**\n * Returns current sort state and a setter from the MasterView store.\n * Components that need sort state should use this hook instead of\n * selecting searchParams directly.\n */\nexport function useSortState(): SortState {\n  const sortBy = useMasterViewStore((s) => s.searchParams.sortBy);\n  const sortOrder = useMasterViewStore((s) => s.searchParams.sortOrder);\n  const setSearchParams = useMasterViewStore((s) => s.setSearchParams);\n\n  const setSort = useCallback(\n    (field: string, direction: 'asc' | 'desc') => {\n      setSearchParams({ sortBy: field, sortOrder: direction });\n    },\n    [setSearchParams],\n  );\n\n  return { sortBy, sortOrder, setSort };\n}\n","import { useCallback } from 'react';\nimport { useTranslation } from '../../LanguageManagement/hooks/useTranslation';\n\ninterface UseMasterPatternViewTranslationProps {\n  locale?: string;\n  uiPrefix?: string;\n  fieldsPrefix?: string;\n  externalTranslations?: Record<string, string>;\n  internalTranslations: Record<string, any>;\n  tProp?: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * Hook interno para gestionar la traducción en MasterPatternView con retrocompatibilidad y agnosticismo.\n *\n * Prioridad de resolución:\n * 1. tProp (Función inyectada por el usuario - Agnosticismo Total)\n * 2. externalTranslations (Mapeo estático por props)\n * 3. Sistema global del proyecto (LanguageManagement / Contexto)\n * 4. Diccionario interno estático (Fallback de seguridad)\n */\nexport const useMasterPatternViewTranslation = ({\n  locale = 'es',\n  uiPrefix = 'masterpatternview',\n  fieldsPrefix,\n  externalTranslations,\n  internalTranslations,\n  tProp,\n}: UseMasterPatternViewTranslationProps) => {\n  let globalI18n: any = null;\n  try {\n    // Intentar usar el sistema del proyecto si no se provee una función externa\n    if (!tProp) {\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      globalI18n = useTranslation();\n    }\n  } catch {\n    globalI18n = null;\n  }\n\n  const { t: globalT, isReady } = globalI18n || {};\n  const activeT = tProp || globalT;\n\n  const t = useCallback((key: string, defaultValue?: string): string => {\n    // 1. Prioridad: Función inyectada o Global\n    if (activeT && (tProp || isReady)) {\n      // Intentar resolver con prefijo de UI\n      const uiKey = `${uiPrefix}.${key}`;\n      const translated = activeT(uiKey, '__NOT_FOUND__');\n\n      if (translated !== '__NOT_FOUND__' && translated !== uiKey) {\n        return translated;\n      }\n\n      // Si no se encontró y es una llave de campo, intentar con prefijo de campos\n      if (fieldsPrefix) {\n        const fieldKey = `${fieldsPrefix}.${key}`;\n        const fieldTranslated = activeT(fieldKey, '__NOT_FOUND__');\n        if (fieldTranslated !== '__NOT_FOUND__' && fieldTranslated !== fieldKey) {\n          return fieldTranslated;\n        }\n      }\n    }\n\n    // 2. Prioridad: Diccionario estático externo\n    if (externalTranslations && externalTranslations[key]) {\n      return externalTranslations[key];\n    }\n\n    // 3. Prioridad: Diccionario interno estático\n    const internalSet = internalTranslations[locale] || internalTranslations.es;\n    if (internalSet && internalSet[key]) {\n      return internalSet[key];\n    }\n\n    // 4. Fallback final\n    return defaultValue || key;\n  }, [activeT, tProp, isReady, uiPrefix, fieldsPrefix, externalTranslations, internalTranslations, locale]);\n\n  return { t, isReady: isReady ?? true };\n};\n","/**\n * Diccionario interno de traducciones (fallback) para MasterPatternView.\n *\n * Usado por `useMasterPatternViewTranslation` como último nivel de la cascada de\n * resolución de i18n, cuando ni `t` (prop), ni `externalTranslations`, ni el\n * sistema global de traducción (`LanguageManagement`) resuelven la llave.\n *\n * @module i18n/internalTranslations\n */\nexport const internalTranslations: Record<string, Record<string, string>> = {\n  es: {\n    // ── Genéricos / reutilizados en múltiples componentes ──────────────────\n    save: 'Guardar',\n    saving: 'Guardando…',\n    cancel: 'Cancelar',\n    create: 'Nuevo',\n    edit: 'Editar',\n    delete: 'Eliminar',\n    confirm: 'Confirmar',\n    back: 'Regresar',\n    search: 'Buscar',\n    clear: 'Limpiar',\n    import: 'Importar',\n    export: 'Exportar',\n    actions: 'Acciones',\n    active: 'Activo',\n    inactive: 'Inactivo',\n    activateAction: 'Activar',\n    deactivateAction: 'Desactivar',\n    activateVerb: 'activar',\n    deactivateVerb: 'desactivar',\n    enableRecordAction: 'Activar registro',\n    disableRecordAction: 'Desactivar registro',\n    discardChanges: 'Cancelar',\n    saveChanges: 'Guardar',\n    global: 'Global',\n    yes: 'Sí',\n    no: 'No',\n    all: 'Todos',\n    // \"enable\"/\"disable\" son específicamente para \"Habilitar por compañía\" (acceso\n    // multi-compañía a un registro GLOBAL) — un concepto distinto al estado\n    // activo/inactivo del registro (ese usa activateAction/deactivateAction y\n    // enableRecordAction/disableRecordAction, que sí dicen \"Activar\"/\"Desactivar\").\n    enable: 'Habilitar',\n    disable: 'Deshabilitar',\n    readOnly: 'Solo lectura',\n    loading: 'Cargando…',\n    changeStatus: 'Cambiar estado',\n    close: 'Cerrar',\n    detail: 'Detalle',\n    moreActions: 'Más acciones',\n    auditChanges: 'Auditoría de Cambios',\n    auditHistory: 'Historial de cambios',\n\n    // ── MasterPatternView.tsx (toolbar / acciones / modales inline) ────────\n    toolbarSearchLabel: 'Buscar...',\n    showAdvancedSearch: 'Mostrar filtros',\n    hideAdvancedSearch: 'Ocultar filtros',\n    recordsToShow: 'Registros a mostrar',\n    viewCompanyOnly: 'Ver solo registros de la compañía seleccionada',\n    showGlobalValuesLabel: 'Mostrar datos globales',\n    enableCompaniesAction: 'Habilitar compañías',\n    loadingMore: 'Cargando más...',\n    companyChangesSavedSuccess: 'Cambios de compañías guardados correctamente',\n    companyChangesSavedError: 'Error al guardar los cambios de compañías',\n    unsavedChangesBlockSwitch: 'Tienes cambios sin guardar. Guarda o cancela los cambios antes de cambiar de compañía.',\n    recordNotEnabledForCompany: 'El registro no está habilitado para {company}. Habilítalo desde la lista antes de editar en ese contexto.',\n    recordEnabledSuccess: 'Registro habilitado correctamente',\n    recordEnabledError: 'Error al habilitar el registro',\n    changeViewAriaLabel: 'Cambiar vista',\n    tableViewTitle: 'Vista tabla',\n    cardsViewTitle: 'Vista cards',\n    displayMode: 'Modo de visualización',\n    listView: 'Listado',\n    cardView: 'Tarjetas',\n    moreOptions: 'Más opciones',\n\n    // ── DirtyStateDialog ─────────────────────────────────────────────────────\n    dirtyDialogTitle: 'Tienes cambios sin guardar',\n    dirtyDialogDesc: 'Si sales ahora perderás los siguientes cambios. ¿Deseas guardarlos antes de volver al listado?',\n    dirtyDialogContinue: 'Seguir editando',\n    dirtyDialogDiscard: 'Descartar y salir',\n    dirtyDialogSaveExit: 'Guardar y salir',\n    modifiedFields: 'Campos modificados',\n    emptyValue: 'vacío',\n\n    // ── ChangeStatusModal ────────────────────────────────────────────────────\n    changeStatusConfirmTemplate: '¿Desea {action} este registro?',\n    changeStatusScopeNotePrefix: 'Solo se modificará el estado para ',\n    confirmDeactivateTitle: '¿Estás seguro de desactivar este registro?',\n    confirmActivateTitle: '¿Estás seguro de activar este registro?',\n    confirmDeactivateDesc: 'El registro dejará de estar disponible.',\n    confirmActivateDesc: 'El registro volverá a estar disponible.',\n\n    // ── NotEnabledModal ──────────────────────────────────────────────────────\n    notEnabledTitle: 'Registro no habilitado',\n    notEnabledActionEdit: '¿Desea habilitarlo y continuar con la edición?',\n    notEnabledActionChangeStatus: '¿Desea habilitarlo y cambiar su estado?',\n    notEnabledActionView: '¿Desea habilitarlo y continuar con la visualización?',\n    notEnabledActionCompanySwitch: '¿Desea habilitarlo para continuar con la edición en esta compañía?',\n    notEnabledConfirmContinue: 'Habilitar y continuar',\n    notEnabledConfirmChangeStatus: 'Habilitar y cambiar estado',\n    notEnabledBodyPrefix: 'Este registro no está habilitado en ',\n    notEnabledWarning: 'Los valores globales se conservarán hasta que se personalicen los campos.',\n    notEnabledLoadingLabel: 'Habilitando…',\n\n    // ── CompanyEnableModal ───────────────────────────────────────────────────\n    companyEnableTitle: 'Habilitar por compañía',\n    companyEnableDesc: 'Gestiona en qué compañías está habilitado este registro.',\n    companySearchPlaceholder: 'Buscar compañía…',\n    enableAllCompanies: 'Habilitar todas',\n    noCompaniesFound: 'No se encontraron compañías',\n    confirmChanges: 'Confirmar cambios',\n    confirmChangesCount: 'Confirmar cambios ({count})',\n\n    // ── ConflictDialog ───────────────────────────────────────────────────────\n    conflictTitle: 'Conflicto de versión',\n    conflictSubtitle: 'El registro fue modificado por otro usuario',\n    conflictBody: 'Este registro fue modificado por otro usuario mientras lo editabas. Recarga los datos para ver la versión más reciente antes de continuar.',\n    conflictRefreshButton: 'Refrescar datos',\n\n    // ── EmptyState ───────────────────────────────────────────────────────────\n    emptyNoResultsTitle: 'Sin resultados',\n    emptyEnterCriteriaTitle: 'Ingresa criterios y presiona Buscar',\n    emptyNoResultsDesc: 'No hay registros que coincidan con los filtros.',\n    emptyEnterCriteriaDesc: 'Usa los filtros del panel superior para encontrar registros.',\n    emptyEnterCriteriaAlt: 'Ingresa criterios',\n\n    // ── FormActionBar ────────────────────────────────────────────────────────\n    useGlobalData: 'Usar datos globales',\n    enableCompanyAction: 'Habilitar compañía',\n    createNewRecord: 'Crear nuevo registro',\n    editUnavailable: 'Editar no disponible',\n\n    // ── DetailTab ────────────────────────────────────────────────────────────\n    addRecordPrefix: 'Agregar ',\n    editRecordPrefix: 'Editar ',\n    deleteConfirmQuestion: '¿Eliminar este registro?',\n    detailEmptyMessage: 'Sin registros. Agrega el primero.',\n\n    // ── TabBar ───────────────────────────────────────────────────────────────\n    basicDataTabLabel: 'Datos básicos',\n\n    // ── FilterPanel ──────────────────────────────────────────────────────────\n    opContains: 'contiene',\n    opStartsWith: 'empieza con',\n    opEquals: 'es igual a',\n    opNotEquals: 'no es igual a',\n    opGt: 'mayor que',\n    opGte: 'mayor o igual a',\n    opLt: 'menor que',\n    opLte: 'menor o igual a',\n    opFrom: 'desde',\n    opTo: 'hasta',\n    statusLabel: 'Estado',\n    advancedFilters: 'Filtros avanzados',\n    advancedFiltersHint: '— combina varias condiciones personalizadas',\n    connectorLabel: 'Conector:',\n    joinConditionsWith: 'Unir condiciones con',\n    connectorAndLabel: 'Y',\n    connectorOrLabel: 'O',\n    connectorAndHint: 'Se deben cumplir todas las condiciones',\n    connectorOrHint: 'Basta con que se cumpla una condición',\n    column: 'Columna',\n    condition: 'Condición',\n    value: 'Valor',\n    selectPlaceholder: 'Seleccionar...',\n    valuePlaceholder: 'Valor...',\n    removeConditionTitle: 'Eliminar condición',\n    addConditionLabel: 'Agregar condición',\n    activeFiltersLabel: 'Filtros activos:',\n    clearAdvancedFilters: 'Limpiar filtros avanzados',\n\n    // ── DateRangeFilterControl ───────────────────────────────────────────────\n    dateFromPlaceholder: 'Desde (YYYY-MM-DD)',\n    dateToPlaceholder: 'Hasta (YYYY-MM-DD)',\n\n    // ── NumberFilterControl ──────────────────────────────────────────────────\n    opEqSymbol: '=',\n    opNeqSymbol: '≠',\n    opGtSymbol: '>',\n    opLtSymbol: '<',\n    opBetween: 'Entre',\n    toPlaceholder: 'Hasta',\n\n    // ── TextFilterControl ────────────────────────────────────────────────────\n    opContainsCap: 'Contiene',\n    opStartsWithCap: 'Empieza con',\n    opEqualToCap: 'Igual a',\n\n    // ── RowActions ───────────────────────────────────────────────────────────\n    viewAction: 'Visualizar',\n\n    // ── PaginationBar ────────────────────────────────────────────────────────\n    paginationPrev: 'Anterior',\n    paginationNext: 'Siguiente',\n    paginationOf: 'de',\n    paginationRecords: 'registros',\n    paginationPerPage: 'por página',\n\n    // ── BatchBar ─────────────────────────────────────────────────────────────\n    recordWord: 'registro',\n    recordsPlural: 'registros',\n    selectedSingular: 'seleccionado',\n    selectedPlural: 'seleccionados',\n    clearSelectionAriaLabel: 'Limpiar selección',\n    batchChangeStatus: 'Cambiar estado masivo',\n    batchNoPermissionChangeStatus: 'No tienes permisos para cambiar el estado',\n    batchActionError: 'Error al ejecutar la acción',\n\n    // ── CompanySelector ──────────────────────────────────────────────────────\n    noCompaniesConfigured: 'No hay compañías configuradas para este maestro.',\n\n    // ── useMasterForm ────────────────────────────────────────────────────────\n    validationRequired: 'Este campo es requerido',\n    validationNumber: 'Debe ser un número válido',\n    validationDateFormat: 'Formato de fecha inválido (YYYY-MM-DD)',\n    validationMaxLength: 'Excede la longitud máxima permitida',\n    createEnabledSuccess: 'Registro creado y habilitado para la compañía exitosamente',\n    createEnabledPartialError: 'Registro creado, pero no se pudo habilitar automáticamente. Habilítelo desde la lista.',\n    createSuccess: 'Registro creado exitosamente',\n    createError: 'Error al crear el registro',\n    updateSuccess: 'Registro actualizado exitosamente',\n    updateError: 'Error al actualizar el registro',\n\n    // ── useMasterList ────────────────────────────────────────────────────────\n    loadRecordsError: 'Error al cargar los registros',\n\n    // ── useChangeStatus ──────────────────────────────────────────────────────\n    statusChangeSuccess: 'Estado cambiado exitosamente',\n    statusChangeError: 'Error al cambiar el estado',\n\n    // ── MasterPatternViewForm ────────────────────────────────────────────────\n    recordLoadFailedError: 'No se pudo cargar la información completa del registro.',\n    retryButton: 'Reintentar',\n\n    // ── ListTable / ListCard (badges, tooltips, column filters) ──────────────\n    companyAssignedTooltip: 'Habilitado para esta compañía',\n    companyOverrideTooltip: 'Valor sobreescrito por la compañía',\n    companyGlobalValueTooltip: 'Valor global',\n    companyStatus: 'Habilitación en la compañía seleccionada',\n    enabledInCompany: 'Habilitado en la compañía seleccionada',\n    notEnabledInCompany: 'No habilitado en la compañía seleccionada',\n    filterPlaceholder: 'Filtrar...',\n  },\n  en: {\n    // ── Generic / shared across multiple components ─────────────────────────\n    save: 'Save',\n    saving: 'Saving…',\n    cancel: 'Cancel',\n    create: 'Create',\n    edit: 'Edit',\n    delete: 'Delete',\n    confirm: 'Confirm',\n    back: 'Back',\n    search: 'Search',\n    clear: 'Clear',\n    import: 'Import',\n    export: 'Export',\n    actions: 'Actions',\n    active: 'Active',\n    inactive: 'Inactive',\n    activateAction: 'Activate',\n    deactivateAction: 'Deactivate',\n    activateVerb: 'activate',\n    deactivateVerb: 'deactivate',\n    enableRecordAction: 'Enable record',\n    disableRecordAction: 'Disable record',\n    discardChanges: 'Cancel',\n    saveChanges: 'Save',\n    global: 'Global',\n    yes: 'Yes',\n    no: 'No',\n    all: 'All',\n    enable: 'Enable',\n    disable: 'Disable',\n    readOnly: 'Read only',\n    loading: 'Loading…',\n    changeStatus: 'Change status',\n    close: 'Close',\n    detail: 'Detail',\n    moreActions: 'More actions',\n    auditChanges: 'Change audit',\n    auditHistory: 'Change history',\n\n    // ── MasterPatternView.tsx (toolbar / actions / inline modals) ──────────\n    toolbarSearchLabel: 'Search...',\n    showAdvancedSearch: 'Show filters',\n    hideAdvancedSearch: 'Hide filters',\n    recordsToShow: 'Records to show',\n    viewCompanyOnly: 'View only records from the selected company',\n    showGlobalValuesLabel: 'Show global data',\n    enableCompaniesAction: 'Enable companies',\n    loadingMore: 'Loading more...',\n    companyChangesSavedSuccess: 'Company changes saved successfully',\n    companyChangesSavedError: 'Error saving company changes',\n    unsavedChangesBlockSwitch: 'You have unsaved changes. Save or cancel the changes before switching companies.',\n    recordNotEnabledForCompany: 'The record is not enabled for {company}. Enable it from the list before editing in that context.',\n    recordEnabledSuccess: 'Record enabled successfully',\n    recordEnabledError: 'Error enabling the record',\n    changeViewAriaLabel: 'Change view',\n    tableViewTitle: 'Table view',\n    cardsViewTitle: 'Card view',\n    displayMode: 'Display mode',\n    listView: 'List',\n    cardView: 'Cards',\n    moreOptions: 'More options',\n\n    // ── DirtyStateDialog ─────────────────────────────────────────────────────\n    dirtyDialogTitle: 'You have unsaved changes',\n    dirtyDialogDesc: 'If you leave now you will lose the following changes. Do you want to save them before returning to the list?',\n    dirtyDialogContinue: 'Keep editing',\n    dirtyDialogDiscard: 'Discard and exit',\n    dirtyDialogSaveExit: 'Save and exit',\n    modifiedFields: 'Modified fields',\n    emptyValue: 'empty',\n\n    // ── ChangeStatusModal ────────────────────────────────────────────────────\n    changeStatusConfirmTemplate: 'Do you want to {action} this record?',\n    changeStatusScopeNotePrefix: 'Only the status will be changed for ',\n    confirmDeactivateTitle: 'Are you sure you want to deactivate this record?',\n    confirmActivateTitle: 'Are you sure you want to activate this record?',\n    confirmDeactivateDesc: 'The record will no longer be available.',\n    confirmActivateDesc: 'The record will be available again.',\n\n    // ── NotEnabledModal ──────────────────────────────────────────────────────\n    notEnabledTitle: 'Record not enabled',\n    notEnabledActionEdit: 'Do you want to enable it and continue editing?',\n    notEnabledActionChangeStatus: 'Do you want to enable it and change its status?',\n    notEnabledActionView: 'Do you want to enable it and continue viewing?',\n    notEnabledActionCompanySwitch: 'Do you want to enable it to continue editing in this company?',\n    notEnabledConfirmContinue: 'Enable and continue',\n    notEnabledConfirmChangeStatus: 'Enable and change status',\n    notEnabledBodyPrefix: 'This record is not enabled in ',\n    notEnabledWarning: 'Global values will be kept until fields are customized.',\n    notEnabledLoadingLabel: 'Enabling…',\n\n    // ── CompanyEnableModal ───────────────────────────────────────────────────\n    companyEnableTitle: 'Enable by company',\n    companyEnableDesc: 'Manage which companies this record is enabled for.',\n    companySearchPlaceholder: 'Search company…',\n    enableAllCompanies: 'Enable all',\n    noCompaniesFound: 'No companies found',\n    confirmChanges: 'Confirm changes',\n    confirmChangesCount: 'Confirm changes ({count})',\n\n    // ── ConflictDialog ───────────────────────────────────────────────────────\n    conflictTitle: 'Version conflict',\n    conflictSubtitle: 'The record was modified by another user',\n    conflictBody: 'This record was modified by another user while you were editing it. Reload the data to see the latest version before continuing.',\n    conflictRefreshButton: 'Refresh data',\n\n    // ── EmptyState ───────────────────────────────────────────────────────────\n    emptyNoResultsTitle: 'No results',\n    emptyEnterCriteriaTitle: 'Enter criteria and press Search',\n    emptyNoResultsDesc: 'There are no records matching the filters.',\n    emptyEnterCriteriaDesc: 'Use the filters in the top panel to find records.',\n    emptyEnterCriteriaAlt: 'Enter criteria',\n\n    // ── FormActionBar ────────────────────────────────────────────────────────\n    useGlobalData: 'Use global data',\n    enableCompanyAction: 'Enable company',\n    createNewRecord: 'Create new record',\n    editUnavailable: 'Edit unavailable',\n\n    // ── DetailTab ────────────────────────────────────────────────────────────\n    addRecordPrefix: 'Add ',\n    editRecordPrefix: 'Edit ',\n    deleteConfirmQuestion: 'Delete this record?',\n    detailEmptyMessage: 'No records. Add the first one.',\n\n    // ── TabBar ───────────────────────────────────────────────────────────────\n    basicDataTabLabel: 'Basic data',\n\n    // ── FilterPanel ──────────────────────────────────────────────────────────\n    opContains: 'contains',\n    opStartsWith: 'starts with',\n    opEquals: 'is equal to',\n    opNotEquals: 'is not equal to',\n    opGt: 'greater than',\n    opGte: 'greater than or equal to',\n    opLt: 'less than',\n    opLte: 'less than or equal to',\n    opFrom: 'from',\n    opTo: 'to',\n    statusLabel: 'Status',\n    advancedFilters: 'Advanced filters',\n    advancedFiltersHint: '— combine several custom conditions',\n    connectorLabel: 'Connector:',\n    joinConditionsWith: 'Join conditions with',\n    connectorAndLabel: 'And',\n    connectorOrLabel: 'Or',\n    connectorAndHint: 'All conditions must be met',\n    connectorOrHint: 'It is enough for one condition to be met',\n    column: 'Column',\n    condition: 'Condition',\n    value: 'Value',\n    selectPlaceholder: 'Select...',\n    valuePlaceholder: 'Value...',\n    removeConditionTitle: 'Remove condition',\n    addConditionLabel: 'Add condition',\n    activeFiltersLabel: 'Active filters:',\n    clearAdvancedFilters: 'Clear advanced filters',\n\n    // ── DateRangeFilterControl ───────────────────────────────────────────────\n    dateFromPlaceholder: 'From (YYYY-MM-DD)',\n    dateToPlaceholder: 'To (YYYY-MM-DD)',\n\n    // ── NumberFilterControl ──────────────────────────────────────────────────\n    opEqSymbol: '=',\n    opNeqSymbol: '≠',\n    opGtSymbol: '>',\n    opLtSymbol: '<',\n    opBetween: 'Between',\n    toPlaceholder: 'To',\n\n    // ── TextFilterControl ────────────────────────────────────────────────────\n    opContainsCap: 'Contains',\n    opStartsWithCap: 'Starts with',\n    opEqualToCap: 'Equal to',\n\n    // ── RowActions ───────────────────────────────────────────────────────────\n    viewAction: 'View',\n\n    // ── PaginationBar ────────────────────────────────────────────────────────\n    paginationPrev: 'Previous',\n    paginationNext: 'Next',\n    paginationOf: 'of',\n    paginationRecords: 'records',\n    paginationPerPage: 'per page',\n\n    // ── BatchBar ─────────────────────────────────────────────────────────────\n    recordWord: 'record',\n    recordsPlural: 'records',\n    selectedSingular: 'selected',\n    selectedPlural: 'selected',\n    clearSelectionAriaLabel: 'Clear selection',\n    batchChangeStatus: 'Bulk change status',\n    batchNoPermissionChangeStatus: 'You do not have permission to change the status',\n    batchActionError: 'Error executing the action',\n\n    // ── CompanySelector ──────────────────────────────────────────────────────\n    noCompaniesConfigured: 'No companies configured for this master.',\n\n    // ── useMasterForm ────────────────────────────────────────────────────────\n    validationRequired: 'This field is required',\n    validationNumber: 'Must be a valid number',\n    validationDateFormat: 'Invalid date format (YYYY-MM-DD)',\n    validationMaxLength: 'Exceeds the maximum allowed length',\n    createEnabledSuccess: 'Record created and enabled for the company successfully',\n    createEnabledPartialError: 'Record created, but it could not be enabled automatically. Enable it from the list.',\n    createSuccess: 'Record created successfully',\n    createError: 'Error creating the record',\n    updateSuccess: 'Record updated successfully',\n    updateError: 'Error updating the record',\n\n    // ── useMasterList ────────────────────────────────────────────────────────\n    loadRecordsError: 'Error loading records',\n\n    // ── useChangeStatus ──────────────────────────────────────────────────────\n    statusChangeSuccess: 'Status changed successfully',\n    statusChangeError: 'Error changing the status',\n\n    // ── MasterPatternViewForm ────────────────────────────────────────────────\n    recordLoadFailedError: 'The complete record information could not be loaded.',\n    retryButton: 'Retry',\n\n    // ── ListTable / ListCard (badges, tooltips, column filters) ──────────────\n    companyAssignedTooltip: 'Enabled for this company',\n    companyOverrideTooltip: 'Value overridden by the company',\n    companyGlobalValueTooltip: 'Global value',\n    companyStatus: 'Enablement in the selected company',\n    enabledInCompany: 'Enabled in the selected company',\n    notEnabledInCompany: 'Not enabled in the selected company',\n    filterPlaceholder: 'Filter...',\n  },\n};\n","/**\n * MasterPatternView — root component for master data management.\n *\n * Composes all sub-systems: store context, toolbar, list, form panel,\n * and modals. Exposes imperative ref API via MasterPatternViewRef.\n *\n * @module components/MasterPatternView\n * @see FMPV-MVWC-E003-S006 I-001\n */\nimport React, { forwardRef, useCallback, useImperativeHandle, useEffect, useLayoutEffect, useMemo, useState, useRef } from 'react';\nimport '../master-pattern-view.css';\nimport { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';\nimport { motion } from 'framer-motion';\nimport {\n  MagnifyingGlassIcon as SearchIcon,\n  FunnelIcon as FilterIcon,\n  ChevronDownIcon,\n  EllipsisVerticalIcon,\n  DocumentArrowDownIcon,\n  ArrowUpTrayIcon,\n  ListBulletIcon,\n  Squares2X2Icon,\n  ClockIcon,\n  XMarkIcon,\n} from '@heroicons/react/24/outline';\nimport { Building2 } from 'lucide-react';\nimport { AuditHistoryPanel } from '../../../audit/components/AuditHistoryPanel';\nimport { Button } from '../../Button/Button';\nimport { Switch } from '../../Switch/Switch';\nimport type { MasterPatternViewEntity } from '../types';\nimport type { MasterPatternViewProps, MasterPatternViewRef } from '../types';\nimport type { MasterPatternViewDefinition } from '../types/definition.types';\nimport { MasterViewProvider } from '../store/MasterViewContext';\nimport { useMasterViewStore } from '../store/MasterViewContext';\nimport { ConfigTableContent } from './ConfigTableContent';\nimport { MasterPatternViewForm } from './form/MasterPatternViewForm';\nimport { getAllFields } from '../engine/fieldEngine';\nimport { FilterPanel } from './toolbar/FilterPanel';\nimport { ToolbarActions } from './toolbar/ToolbarActions';\nimport { ListTable } from './list/ListTable';\nimport { ListCard } from './list/ListCard';\nimport { EmptyState } from './list/EmptyState';\nimport { PaginationBar } from './list/PaginationBar';\nimport { BatchBar } from './list/BatchBar';\nimport { DirtyStateDialog } from './modals/DirtyStateDialog';\nimport { ChangeStatusModal } from './modals/ChangeStatusModal';\nimport { ConflictDialog } from './modals/ConflictDialog';\nimport { CompanyEnableModal } from './modals/CompanyEnableModal';\nimport { NotEnabledModal } from './modals/NotEnabledModal';\nimport type { NotEnabledModalTrigger } from './modals/NotEnabledModal';\nimport { useMasterList } from '../hooks/useMasterList';\nimport { useMasterForm } from '../hooks/useMasterForm';\nimport { useChangeStatus } from '../hooks/useChangeStatus';\nimport { useSortState } from '../hooks/useSortState';\nimport { useToast } from '../hooks/useToast';\nimport { CompanySelector } from './toolbar/CompanySelector';\nimport { useMasterPatternViewTranslation } from '../hooks/useMasterPatternViewTranslation';\nimport { internalTranslations } from '../i18n/internalTranslations';\n\nimport { InternalToastContainer } from './InternalToastContainer';\n\nconst queryClient = new QueryClient();\n\nfunction MasterPatternViewInner<T extends MasterPatternViewEntity>(\n  props: MasterPatternViewProps<T>,\n  ref: React.ForwardedRef<MasterPatternViewRef>,\n) {\n  const {\n    definition,\n    service,\n    configService,\n    renderConfigBody,\n    renderToolbarActions,\n    renderActionsMenuItems,\n    renderBody,\n    title,\n    entityName,\n    permissions,\n    pagination,\n    selectable,\n    batchActions,\n    autoLoad = false,\n    defaultFiltersOpen = false,\n    showExport,\n    showImport,\n    onExport,\n    onImport,\n    globalActions,\n    auditHistory,\n    tabs,\n    headerFields,\n    navigationType = 'sidebar',\n    showBackButton = true,\n    formWidth,\n    formHeight,\n    openRecordId,\n    openRecordMode,\n    onRecordOpen,\n    onRecordClose,\n    onRecordSaved,\n    isLoading: externalIsLoading = false,\n    validate,\n    onCreateSuccess,\n    onUpdateSuccess,\n    onStatusChangeSuccess,\n    onError,\n    toast: toastProp,\n    showInternalToasts = true,\n    companies,\n    defaultCompany,\n    onCompanyChange,\n    renderForm,\n    detailTabs,\n    defaultCreateValues,\n    showViewToggle,\n    renderCardContent,\n    recordTitleFields,\n    defaultActions,\n    canEdit,\n    showCompanySelector,\n    customSave,\n    onFormSave,\n    externalIsDirty,\n    locale,\n    t: tProp,\n    uiPrefix,\n    fieldsPrefix,\n    externalTranslations,\n  } = props;\n\n  // ── Motor de traducción ──────────────────────────────────────────────────\n  const { t } = useMasterPatternViewTranslation({\n    locale,\n    uiPrefix,\n    fieldsPrefix,\n    externalTranslations,\n    internalTranslations,\n    tProp,\n  });\n\n  // Store's own DEFAULT_SEARCH_PARAMS.pageSize (listSlice.ts) is a fixed 20 — this is\n  // the actual value `pagination.defaultPageSize` (documented default: 10, same as\n  // `pageSizeOptions`'s first entry) needs to seed the store with at creation, or a\n  // custom `defaultPageSize` a consumer passes is silently ignored: the page-size\n  // selector still shows it as an option, but the list fetches (and the store reports)\n  // 20 rows from the very first load, before the user ever touches the selector.\n  const initialPageSize = pagination === false ? undefined : (pagination?.defaultPageSize ?? 10);\n\n  // CONFIG_TABLE: toolbar + company context + renderConfigBody\n  if (definition.type === 'CONFIG_TABLE') {\n    return (\n      <MasterViewProvider<T> definition={definition}>\n        <ConfigTableContent\n          definition={definition}\n          configService={configService}\n          renderConfigBody={renderConfigBody}\n          renderToolbarActions={renderToolbarActions}\n          renderActionsMenuItems={renderActionsMenuItems}\n          title={title}\n          companies={companies}\n          defaultCompany={defaultCompany}\n          onCompanyChange={onCompanyChange}\n          toast={toastProp}\n        />\n      </MasterViewProvider>\n    );\n  }\n\n  // CUSTOM: toolbar + company context + renderBody (consumer owns all state)\n  if (definition.type === 'CUSTOM') {\n    return (\n      <MasterViewProvider<T> definition={definition}>\n        <CustomContent\n          definition={definition}\n          renderBody={renderBody}\n          title={title}\n          companies={companies}\n          defaultCompany={defaultCompany}\n          onCompanyChange={onCompanyChange}\n          toast={toastProp}\n          showCompanySelector={showCompanySelector}\n          customSave={customSave}\n          renderActionsMenuItems={renderActionsMenuItems}\n          renderToolbarActions={renderToolbarActions}\n          t={t}\n        />\n      </MasterViewProvider>\n    );\n  }\n\n  return (\n    <MasterViewProvider<T> definition={definition} defaultCreateValues={defaultCreateValues} initialPageSize={initialPageSize}>\n      <MasterPatternViewContent<T>\n        ref={ref}\n        definition={definition}\n        service={service!}\n        title={title}\n        entityName={entityName ?? ''}\n        permissions={permissions}\n        pagination={pagination}\n        selectable={selectable}\n        batchActions={batchActions}\n        autoLoad={autoLoad}\n        defaultFiltersOpen={defaultFiltersOpen}\n        showExport={showExport}\n        showImport={showImport}\n        onExport={onExport}\n        onImport={onImport}\n        globalActions={globalActions}\n        auditHistory={auditHistory}\n        tabs={tabs}\n        headerFields={headerFields}\n        navigationType={navigationType}\n        showBackButton={showBackButton}\n        formWidth={formWidth}\n        formHeight={formHeight}\n        openRecordId={openRecordId}\n        openRecordMode={openRecordMode}\n        onRecordOpen={onRecordOpen}\n        onRecordClose={onRecordClose}\n        onRecordSaved={onRecordSaved}\n        externalIsLoading={externalIsLoading}\n        validate={validate}\n        onCreateSuccess={onCreateSuccess}\n        onUpdateSuccess={onUpdateSuccess}\n        onStatusChangeSuccess={onStatusChangeSuccess}\n        onError={onError}\n        toast={toastProp}\n        showInternalToasts={showInternalToasts}\n        companies={companies}\n        defaultCompany={defaultCompany}\n        onCompanyChange={onCompanyChange}\n        renderForm={renderForm}\n        detailTabs={detailTabs}\n        defaultCreateValues={defaultCreateValues}\n        showViewToggle={showViewToggle}\n        renderCardContent={renderCardContent}\n        recordTitleFields={recordTitleFields}\n        defaultActions={defaultActions}\n        canEdit={canEdit}\n        onFormSave={onFormSave}\n        externalIsDirty={externalIsDirty}\n        t={t}\n      />\n    </MasterViewProvider>\n  );\n}\n\ninterface ContentProps<T extends MasterPatternViewEntity>\n  extends Omit<MasterPatternViewProps<T>, 'isLoading' | 'service' | 'entityName'> {\n  externalIsLoading: boolean;\n  /** Required for GLOBAL / UNIVERSAL / COMPANY_SPECIFIC — guaranteed non-null by MasterPatternViewInner branching */\n  service: import('../types/service.types').MasterPatternViewService<T>;\n  entityName: string;\n}\n\nconst MasterPatternViewContent = forwardRef(function MasterPatternViewContentInner<\n  T extends MasterPatternViewEntity,\n>(\n  {\n    definition,\n    service,\n    title,\n    entityName,\n    permissions,\n    pagination,\n    selectable,\n    batchActions,\n    autoLoad,\n    defaultFiltersOpen,\n    showExport,\n    showImport,\n    onExport,\n    onImport,\n    globalActions,\n    auditHistory,\n    tabs,\n    headerFields,\n    navigationType,\n    showBackButton,\n    formWidth,\n    formHeight,\n    openRecordId,\n    openRecordMode = 'editing',\n    onRecordOpen,\n    onRecordClose,\n    onRecordSaved,\n    externalIsLoading,\n    validate,\n    onCreateSuccess,\n    onUpdateSuccess,\n    onStatusChangeSuccess,\n    onError,\n    toast: toastProp,\n    showInternalToasts = true,\n    companies,\n    defaultCompany,\n    onCompanyChange,\n    renderForm,\n    detailTabs,\n    defaultCreateValues,\n    showViewToggle = true,\n    renderCardContent,\n    recordTitleFields,\n    defaultActions,\n    canEdit,\n    onFormSave,\n    externalIsDirty,\n    t = (key: string, defaultValue?: string) => defaultValue ?? key,\n  }: ContentProps<T>,\n  ref: React.ForwardedRef<MasterPatternViewRef>,\n) {\n  const data = useMasterViewStore((s) => s.data);\n  const total = useMasterViewStore((s) => s.total);\n  const isLoading = useMasterViewStore((s) => s.isLoading);\n  const hasSearched = useMasterViewStore((s) => s.hasSearched);\n  const searchParams = useMasterViewStore((s) => s.searchParams);\n  const selectedIds = useMasterViewStore((s) => s.selectedIds);\n  const isDirty = useMasterViewStore((s) => s.isDirty);\n  const mode = useMasterViewStore((s) => s.mode);\n  const activeRecord = useMasterViewStore((s) => s.activeRecord);\n  const initialCreateValues = useMasterViewStore((s) => s.initialCreateValues);\n  const pendingAction = useMasterViewStore((s) => s.pendingAction);\n  const openCreate = useMasterViewStore((s) => s.openCreate);\n  const openEdit = useMasterViewStore((s) => s.openEdit);\n  const values = useMasterViewStore((s) => s.values);\n  const setValues = useMasterViewStore((s) => s.setValues);\n  const setInitialCreateValues = useMasterViewStore((s) => s.setInitialCreateValues);\n\n  // Sync defaultCreateValues into form when in creating mode and values are async-loaded\n  // (e.g. a company → plan → currency lookup that resolves after openCreate() already ran\n  // with an empty snapshot). A late-arriving default is still a default, not a user edit — so\n  // it's merged into initialCreateValues too, not just values. Without this, the dirty-check\n  // baseline never learns about it and the field reads as \"changed\" (empty → value) the instant\n  // it lands, even though nothing was touched.\n  useEffect(() => {\n    if (mode === 'creating' && defaultCreateValues) {\n      const lateDefaults = Object.fromEntries(\n        Object.entries(defaultCreateValues).filter(\n          ([key, val]) => val !== undefined && values[key] === undefined,\n        ),\n      );\n      if (Object.keys(lateDefaults).length > 0) {\n        setValues({ ...values, ...lateDefaults });\n        setInitialCreateValues(lateDefaults);\n      }\n    }\n  }, [mode, defaultCreateValues]);\n  const openView = useMasterViewStore((s) => s.openView);\n  const updateActiveRecord = useMasterViewStore((s) => s.updateActiveRecord);\n  const setIsLoadingRecord = useMasterViewStore((s) => s.setIsLoadingRecord);\n  const setRecordLoadFailed = useMasterViewStore((s) => s.setRecordLoadFailed);\n  const closeForm = useMasterViewStore((s) => s.closeForm);\n  const setIsDirty = useMasterViewStore((s) => s.setIsDirty);\n  const clearSelection = useMasterViewStore((s) => s.clearSelection);\n  const setSearchParams = useMasterViewStore((s) => s.setSearchParams);\n  const isDirtyStateDialogOpen = useMasterViewStore((s) => s.isDirtyStateDialogOpen);\n  const openDirtyStateDialog = useMasterViewStore((s) => s.openDirtyStateDialog);\n  const closeDirtyStateDialog = useMasterViewStore((s) => s.closeDirtyStateDialog);\n  const isChangeStatusModalOpen = useMasterViewStore((s) => s.isChangeStatusModalOpen);\n  const openChangeStatusModal = useMasterViewStore((s) => s.openChangeStatusModal);\n  const closeChangeStatusModal = useMasterViewStore((s) => s.closeChangeStatusModal);\n  const clearPendingAction = useMasterViewStore((s) => s.clearPendingAction);\n  const setPendingAction = useMasterViewStore((s) => s.setPendingAction);\n  const isCompanyEnableModalOpen = useMasterViewStore((s) => s.isCompanyEnableModalOpen);\n  const openCompanyEnableModal = useMasterViewStore((s) => s.openCompanyEnableModal);\n  const closeCompanyEnableModal = useMasterViewStore((s) => s.closeCompanyEnableModal);\n\n  // Filter state\n  const isFilterPanelOpen = useMasterViewStore((s) => s.isFilterPanelOpen);\n  const activeFilters = useMasterViewStore((s) => s.activeFilters);\n  const toggleFilterPanel = useMasterViewStore((s) => s.toggleFilterPanel);\n  const setActiveFilters = useMasterViewStore((s) => s.setActiveFilters);\n  const clearFilters = useMasterViewStore((s) => s.clearFilters);\n\n\n  // Company context state\n  const activeCompanyContext = useMasterViewStore((s) => s.activeCompanyContext);\n  const setActiveCompanyContext = useMasterViewStore((s) => s.setActiveCompanyContext);\n  const setGlobalValues = useMasterViewStore((s) => s.setGlobalValues);\n\n  // View mode toggle (table / cards)\n  const viewMode = useMasterViewStore((s) => s.viewMode);\n  const setViewMode = useMasterViewStore((s) => s.setViewMode);\n\n  // Auto-switch to cards on narrow viewports — mirrors MasterCrud.tsx:869-875 exactly\n  // (same breakpoint, same matchMedia 'change' listener). Only fires when the\n  // breakpoint is actually crossed, so a manual toggle click still sticks until then.\n  useEffect(() => {\n    const mediaQuery = window.matchMedia('(max-width: 1024px)');\n    const handleDeviceChange = (e: MediaQueryListEvent | MediaQueryList) => {\n      setViewMode(e.matches ? 'cards' : 'table');\n    };\n    handleDeviceChange(mediaQuery);\n    mediaQuery.addEventListener('change', handleDeviceChange);\n    return () => mediaQuery.removeEventListener('change', handleDeviceChange);\n  }, [setViewMode]);\n\n  // Two storages, two different keys, two different jobs:\n  // - sessionStorage (`companySelected`): THIS tab's own last active company. Survives an F5\n  //   of this same tab (sessionStorage isn't cleared by a reload, only by closing the tab) and\n  //   is never shared with any other tab. The master ALWAYS reads from here, never straight\n  //   from localStorage — see the seeding step below for how a brand new tab still inherits\n  //   a value.\n  // - localStorage (`lastCompanySelected`): shared across every tab of the same origin, on\n  //   purpose — it's what lets a BRAND NEW tab (whose sessionStorage always starts empty)\n  //   inherit the last company used anywhere, instead of always starting from Global/first.\n  // 'global' is stored as the literal string 'global' in both, not as an absent key — that way\n  // reading the key unambiguously distinguishes \"last selection was Global\" from \"nothing was\n  // ever selected\".\n  const SESSION_COMPANY_KEY = 'companySelected';\n  const LOCAL_LAST_COMPANY_KEY = 'lastCompanySelected';\n\n  // Seed sessionStorage from localStorage as early as possible — independent of `companies`,\n  // which usually arrives async (a fresh tab has no cache, so it's typically empty/undefined\n  // on this very first render). Doing the seed here, decoupled from the restore effect below,\n  // means it's in place before anything else reads sessionStorage.\n  useEffect(() => {\n    try {\n      if (sessionStorage.getItem(SESSION_COMPANY_KEY) === null) {\n        const localStored = localStorage.getItem(LOCAL_LAST_COMPANY_KEY);\n        if (localStored !== null) sessionStorage.setItem(SESSION_COMPANY_KEY, localStored);\n      }\n    } catch {\n      // storage unavailable (SSR, private browsing) — nothing to seed.\n    }\n  }, []);\n\n  // Restore the active company context from sessionStorage (already seeded above if needed).\n  // GLOBAL type defaults to 'global' (set by overrideSlice) — don't override with first company,\n  // unless a previously-selected company was persisted and still exists.\n  // COMPANY type defaults to the first available company, same override applies.\n  //\n  // `companies` is a host-provided prop that's frequently still empty/undefined on first mount\n  // (it's usually the result of an async fetch, and a brand new tab has no cache to prime it\n  // with) — an effect that only ran once on mount would see an empty list, do nothing, and\n  // never get a second chance once `companies` actually arrives, silently dropping the restore.\n  // So this effect depends on `companies` and keeps retrying every time it changes, but only\n  // ever APPLIES the restore once (guarded by the ref) — later `companies` updates (refetches,\n  // etc.) must not clobber a selection the user has since made manually.\n  const didRestoreCompanyRef = useRef(false);\n  useEffect(() => {\n    if (didRestoreCompanyRef.current) return;\n    if (!companies || companies.length === 0) return;\n    didRestoreCompanyRef.current = true;\n\n    let sessionStored: string | null = null;\n    try {\n      sessionStored = sessionStorage.getItem(SESSION_COMPANY_KEY);\n    } catch {\n      // sessionStorage unavailable (SSR, private browsing).\n    }\n\n    const isValidCompanyId = (id: string | null): id is string =>\n      !!id && id !== 'global' && companies.some((c) => c.id === id);\n    const restoredId = isValidCompanyId(sessionStored) ? sessionStored : null;\n\n    // `defaultCompany` beats sessionStorage, not the other way around. A host that explicitly\n    // passes `defaultCompany` is making an authoritative, freshly-computed claim for THIS\n    // specific mount (e.g. a lookup's \"+\" inheriting the record it was opened from, or a\n    // company already established elsewhere in this same tab's session) — honoring a stored\n    // value over that turns \"open a lookup\" into \"silently re-scope to whatever storage\n    // happens to say right now\". sessionStorage stays the fallback for the one case it's\n    // actually meant for: a fresh mount with no more specific answer available.\n    if (definition.type === 'COMPANY_SPECIFIC') {\n      const initialCompany = defaultCompany ?? (restoredId ? companies.find((c) => c.id === restoredId)! : companies[0]);\n      setActiveCompanyContext(initialCompany.id);\n      // El selector visual restaura la compañía desde storage, pero eso solo\n      // actualiza el store interno de MPV — el consumidor (onCompanyChange) nunca se\n      // entera salvo que dispare un clic manual en el dropdown. Sin este aviso, el\n      // formulario/tabs custom del consumidor quedan pensando que no hay compañía\n      // seleccionada aunque el chip ya muestre una.\n      onCompanyChange?.(initialCompany);\n    } else if (definition.type === 'GLOBAL') {\n      // GLOBAL still defaults to 'global' when neither defaultCompany nor a persisted\n      // company selection is available (including when the stored value IS 'global') —\n      // only set it when one of the two actually resolves to a specific company.\n      const initialCompany = defaultCompany ?? (restoredId ? companies.find((c) => c.id === restoredId) : undefined);\n      if (initialCompany) {\n        setActiveCompanyContext(initialCompany.id);\n        onCompanyChange?.(initialCompany);\n      }\n    }\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [companies]);\n\n  // Persist the active company context in BOTH storages on every change — sessionStorage so a\n  // reload of THIS tab restores its own selection (never another tab's), and localStorage so a\n  // brand new tab still inherits the last company used anywhere. Both storages get the same\n  // literal value, including 'global'. See the read side above for the full rationale.\n  //\n  // Gate on `didRestoreCompanyRef` — NOT just `!!activeCompanyContext` — because on the very\n  // first render `activeCompanyContext` is already non-null: the Zustand store's own initial\n  // state (see overrideSlice) sets it straight to 'global' for GLOBAL-type masters, well before\n  // `companies` has loaded and the restore effect above gets its one shot at correcting it to\n  // the real stored company. Without this guard, THIS effect fires on that very first commit —\n  // right after the seed effect freshly copied the real company from localStorage into\n  // sessionStorage — and stomps both storages back to the placeholder 'global' default,\n  // permanently losing the actual last-used company before restore ever ran.\n  useEffect(() => {\n    if (!activeCompanyContext) return;\n    if (!didRestoreCompanyRef.current) return;\n    try {\n      sessionStorage.setItem(SESSION_COMPANY_KEY, activeCompanyContext);\n    } catch {\n      // sessionStorage unavailable — persistence is a nice-to-have, not required.\n    }\n    try {\n      localStorage.setItem(LOCAL_LAST_COMPANY_KEY, activeCompanyContext);\n    } catch {\n      // localStorage unavailable — persistence is a nice-to-have, not required.\n    }\n  }, [activeCompanyContext]);\n\n  const { showSuccess, showError } = useToast(toastProp, showInternalToasts);\n\n  const [actionsDropdownOpen, setActionsDropdownOpen] = useState(false);\n  // Persistente entre compañías REALES a propósito — es una preferencia de vista\n  // (\"solo quiero ver lo específico de la compañía activa\"), no algo ligado a UNA\n  // compañía en particular. El filtro __view no codifica ningún id de compañía —\n  // solo dice \"acota a la compañía activa\", así que sigue siendo válido tal cual al\n  // pasar de una compañía a otra; no hace falta resetear nada ahí (igual que\n  // \"Mostrar datos globales\", que nunca se reseteó y nadie lo echó en falta).\n  const [showOnlyCompany, setShowOnlyCompany] = useState(false);\n\n  // Excepción: sí se resetea al volver a 'global'. El toggle ni siquiera se muestra en\n  // contexto Global (showMostrarSoloCompania exige isCompanyCtxActive) y el filtro\n  // __view:'company' no tiene compañía a la cual acotarse ahí — dejarlo pegado hacía\n  // que la búsqueda en Global no devolviera resultados.\n  useEffect(() => {\n    if (activeCompanyContext === 'global') {\n      setShowOnlyCompany(false);\n      setSearchParams({ filters: searchParams.filters.filter((f) => f.field !== '__view'), page: 1 });\n    }\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [activeCompanyContext]);\n\n  // NotEnabledModal state — triggered when a GLOBAL record is not yet assigned to the active company\n  const [notEnabledState, setNotEnabledState] = useState<{\n    isOpen: boolean;\n    trigger: NotEnabledModalTrigger;\n    record: T | null;\n    isLoading: boolean;\n  }>({ isOpen: false, trigger: 'OPEN_EDIT', record: null, isLoading: false });\n\n  // Pending company ID for COMPANY_SWITCH trigger — the company the user is trying to switch to\n  const [pendingCompanySwitchId, setPendingCompanySwitchId] = useState<string | null>(null);\n\n  const closeNotEnabled = useCallback(() => {\n    setNotEnabledState({ isOpen: false, trigger: 'OPEN_EDIT', record: null, isLoading: false });\n    setPendingCompanySwitchId(null);\n  }, []);\n\n  const [companyEnableRecord, setCompanyEnableRecord] = useState<T | null>(null);\n  const [assignedCompanyIds, setAssignedCompanyIds] = useState<string[]>([]);\n  const [isCompanyEnableLoading, setIsCompanyEnableLoading] = useState(false);\n\n  // Per-company enablement for the record CURRENTLY OPEN in the form — separate from\n  // `assignedCompanyIds` above (which tracks whatever record the \"Habilitar por compañía\"\n  // modal was opened for, not necessarily the same one). Drives the \"Habilitado\"/\"No\n  // habilitado\" indicator in the form's own CompanySelector dropdown.\n  const [formCompanyIds, setFormCompanyIds] = useState<string[]>([]);\n  useEffect(() => {\n    if (definition.type !== 'GLOBAL' || !service.getAssignedCompanyIds) {\n      setFormCompanyIds([]);\n      return;\n    }\n    if ((mode !== 'editing' && mode !== 'viewing') || !activeRecord) {\n      setFormCompanyIds([]);\n      return;\n    }\n    let cancelled = false;\n    const id = (activeRecord as T & { id: string }).id;\n    service.getAssignedCompanyIds(id).then((ids) => {\n      if (!cancelled) setFormCompanyIds(ids);\n    }).catch(() => {\n      if (!cancelled) setFormCompanyIds([]);\n    });\n    return () => {\n      cancelled = true;\n    };\n  }, [mode, activeRecord, definition.type, service]);\n\n  // \"Auditoría de Cambios\" — mirrors MasterCrud's auditModalState (MasterCrud.tsx:591, 2112-2131)\n  const [auditModalState, setAuditModalState] = useState<{ show: boolean; record: T | null }>({ show: false, record: null });\n  const openAuditModal = useCallback((record: T) => setAuditModalState({ show: true, record }), []);\n  const closeAuditModal = useCallback(() => setAuditModalState({ show: false, record: null }), []);\n  // Tracks whether CompanyEnableModal was opened as a post-create step.\n  // When true, closing or confirming the modal must also close the form.\n  const isPostCreateModalRef = useRef(false);\n  const { sortBy, sortOrder, setSort } = useSortState();\n  const queryClient = useQueryClient();\n\n  // Derive pagination config early — needed by useMasterList (mode) and IntersectionObserver\n  const paginationConfig = pagination === false\n    ? null\n    : { mode: 'pages' as const, defaultPageSize: 10, pageSizeOptions: [10, 25, 50], ...(pagination || {}) };\n\n  // Main list hook\n  const { fetchNextPage, hasNextPage, isFetchingNextPage } = useMasterList({\n    service,\n    entityName,\n    autoLoad,\n    defaultFiltersOpen,\n    permissions,\n    masterType: definition.type as 'UNIVERSAL' | 'COMPANY_SPECIFIC' | 'GLOBAL',\n    toast: toastProp,\n    showInternalToasts,\n    mode: paginationConfig?.mode ?? 'pages',\n    t,\n  });\n\n  // ── Infinite scroll ─────────────────────────────────────────────────────────\n  const scrollContainerRef = useRef<HTMLDivElement>(null);\n  const hasNextPageRef = useRef(hasNextPage);\n  const isFetchingNextPageRef = useRef(isFetchingNextPage);\n  const fetchNextPageRef = useRef(fetchNextPage);\n  useEffect(() => { hasNextPageRef.current = hasNextPage; }, [hasNextPage]);\n  useEffect(() => { isFetchingNextPageRef.current = isFetchingNextPage; }, [isFetchingNextPage]);\n  useEffect(() => { fetchNextPageRef.current = fetchNextPage; }, [fetchNextPage]);\n\n  // Saved scroll position for restoration after data appends.\n  const savedScrollTopRef = useRef(0);\n\n  // Single scroll listener: saves position + triggers next page near bottom.\n  // Using onScroll is more reliable than IntersectionObserver for internal\n  // overflow-auto containers because IntersectionObserver requires the root\n  // to already have its final size at observer-creation time.\n  useEffect(() => {\n    if (paginationConfig?.mode !== 'infinite') return;\n    const container = scrollContainerRef.current;\n    if (!container) return;\n    const handleScroll = () => {\n      savedScrollTopRef.current = container.scrollTop;\n      const { scrollTop, scrollHeight, clientHeight } = container;\n      if (\n        scrollHeight - scrollTop - clientHeight < 200 &&\n        hasNextPageRef.current &&\n        !isFetchingNextPageRef.current\n      ) {\n        fetchNextPageRef.current();\n      }\n    };\n    container.addEventListener('scroll', handleScroll, { passive: true });\n    return () => container.removeEventListener('scroll', handleScroll);\n  }, [paginationConfig?.mode]);\n\n  // Auto-fill: after each data update, if the content is shorter than the\n  // container there is nothing to scroll — load the next page automatically.\n  useEffect(() => {\n    if (paginationConfig?.mode !== 'infinite') return;\n    const container = scrollContainerRef.current;\n    if (!container) return;\n    if (\n      container.scrollHeight <= container.clientHeight &&\n      hasNextPageRef.current &&\n      !isFetchingNextPageRef.current\n    ) {\n      fetchNextPageRef.current();\n    }\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [data, paginationConfig?.mode]);\n\n  // Restore scroll position after data appends (prevents jump-to-top).\n  useLayoutEffect(() => {\n    if (paginationConfig?.mode !== 'infinite') return;\n    const container = scrollContainerRef.current;\n    if (!container || savedScrollTopRef.current === 0) return;\n    container.scrollTop = savedScrollTopRef.current;\n  }, [data, paginationConfig?.mode]);\n\n  /**\n   * Internal create-success handler.\n   * For GLOBAL type in global context: form stays open, CompanyEnableModal opens\n   * on top so the user can assign companies right after saving.\n   * closeForm() is deferred to the modal's onClose/onConfirm handlers.\n   */\n  const handleCreateSuccess = useCallback(\n    (record: T) => {\n      if (\n        definition.type === 'GLOBAL' &&\n        (!activeCompanyContext || activeCompanyContext === 'global')\n      ) {\n        isPostCreateModalRef.current = true;\n        setCompanyEnableRecord(record);\n        setAssignedCompanyIds([]); // brand-new record, no companies assigned yet\n        openCompanyEnableModal();\n      }\n      onCreateSuccess?.(record);\n      onRecordSaved?.(record, 'creating');\n    },\n    [definition.type, activeCompanyContext, onCreateSuccess, onRecordSaved, openCompanyEnableModal],\n  );\n\n  const handleUpdateSuccess = useCallback(\n    (record: T) => {\n      onUpdateSuccess?.(record);\n      onRecordSaved?.(record, 'editing');\n    },\n    [onUpdateSuccess, onRecordSaved],\n  );\n\n  // Form mutation hook\n  const { submit, isSubmitting } = useMasterForm({\n    definition,\n    service,\n    validate,\n    onCreateSuccess: handleCreateSuccess,\n    onUpdateSuccess: handleUpdateSuccess,\n    toast: toastProp,\n    showInternalToasts,\n    onFormSave,\n    onError,\n    t,\n  });\n\n  // \"Campos modificados\" para el DirtyStateDialog — mismo snapshot-diff que\n  // MasterCrudForm.tsx:398-410 (getChanges): compara activeRecord (valores\n  // originales cargados) contra values (el borrador actual), campo por campo.\n  const changedFields = useMemo(() => {\n    if (mode !== 'creating' && mode !== 'editing') return [];\n    // Creating: the baseline is the auto-seeded defaults (e.g. \"Activo\" defaulting to\n    // true), not an empty record — otherwise every field carrying its own default reads\n    // as a user change the instant the create form opens, before anyone touched anything.\n    const original = (mode === 'creating' ? initialCreateValues : (activeRecord ?? {})) as Record<string, unknown>;\n    const draft = values as Record<string, unknown>;\n    const norm = (v: unknown) => (v === undefined || v === null ? '' : v);\n    // Fields with a custom `renderCell` (lookups resolving an id to a name, formatted\n    // dates, etc.) get resolved through it here too — same function the list column\n    // already uses — so the dialog shows \"Peso Colombiano → Dólar\" instead of the raw\n    // guid, matching what the user actually sees for that field everywhere else.\n    // `renderCell` needs the row to already carry the joined display column (true for a\n    // persisted record fetched from the API, false for a lookup the user just picked in\n    // this session — FieldRenderer only puts the raw Id in `draft`). For that case, prefer\n    // the `${fieldName}__display` shadow value FieldRenderer stashes alongside the Id.\n    const resolve = (raw: unknown, row: Record<string, unknown>, f: ReturnType<typeof getAllFields>[number]) => {\n      if (raw !== '' && f.lookupConfig) {\n        const shadow = row[`${f.fieldName}__display`];\n        if (shadow !== undefined && shadow !== null && shadow !== '') return shadow;\n      }\n      return raw !== '' && f.renderCell ? f.renderCell(raw, row) : raw;\n    };\n    const changes: { label: string; from: unknown; to: unknown }[] = [];\n    for (const f of getAllFields(definition)) {\n      if (!f.showInForm) continue;\n      const from = norm(original[f.fieldName]);\n      const to = norm(draft[f.fieldName]);\n      if (String(from) !== String(to)) {\n        changes.push({ label: f.label, from: resolve(from, original, f), to: resolve(to, draft, f) });\n      }\n    }\n    return changes;\n  }, [mode, activeRecord, initialCreateValues, values, definition]);\n\n  // `isDirty` (store flag) is set unconditionally on every field change/revert/global-value\n  // toggle (MasterPatternViewForm.tsx: handleFieldChange, handleUseGlobalData, handleFieldRevert)\n  // and never re-checked against the actual values — so reverting a field back to its original\n  // value kept the discard-confirmation dialog showing. `changedFields` is the real field-by-field\n  // diff (already used to render the dialog's own content), so it's the correct source of truth\n  // for whether there's anything to actually discard.\n  const isEffectivelyDirty = changedFields.length > 0 || (externalIsDirty ?? false);\n\n  // The change-status mutation only patches the list cache — when it's triggered from the\n  // form's own hamburger menu (record being edited === record being deactivated), the open\n  // form keeps showing the stale \"Activo\" badge and pre-change values unless synced here.\n  const handleStatusChangeSuccess = useCallback(\n    (record: T) => {\n      if (\n        activeRecord &&\n        (activeRecord as T & { id: string }).id === (record as T & { id: string }).id\n      ) {\n        updateActiveRecord(record);\n        setValues({ ...(record as Record<string, unknown>) });\n      }\n      onStatusChangeSuccess?.(record);\n    },\n    [activeRecord, updateActiveRecord, setValues, onStatusChangeSuccess],\n  );\n\n  // Change status hook\n  const { executeChangeStatus, isChanging } = useChangeStatus({\n    service,\n    onStatusChangeSuccess: handleStatusChangeSuccess,\n    toast: toastProp,\n    showInternalToasts,\n    t,\n  });\n\n  const showLoading = isLoading || externalIsLoading;\n\n  const totalPages = paginationConfig\n    ? Math.max(1, Math.ceil(total / searchParams.pageSize))\n    : 1;\n\n  // ── Imperative ref API ─────────────────────────────────────────────────────\n\n  const handleOpenCreate = useCallback(() => {\n    if (isEffectivelyDirty) {\n      openDirtyStateDialog();\n    } else {\n      openCreate();\n    }\n  }, [isEffectivelyDirty, openCreate, openDirtyStateDialog]);\n\n  /**\n   * Opens a record for editing, then asynchronously fetches the full record via getById\n   * so the form shows all fields — not just the subset present in the list row.\n   * While the fetch is in-flight, isLoadingRecord blocks form interaction to prevent\n   * user edits from being overwritten when the full data arrives.\n   * For GLOBAL type in company context, also fetches the global baseline so the\n   * \"Mostrar datos globales\" hint can show the correct value for each overridable field.\n   */\n  const openEditRecord = useCallback(\n    (record: T) => {\n      openEdit(record);\n      if (!service.getById) return;\n      setIsLoadingRecord(true);\n      setRecordLoadFailed(false);\n      const id = (record as T & { id: string }).id;\n      const isGlobalType = definition.type === 'GLOBAL';\n      const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n      if (isGlobalType && isCompanyCtx) {\n        // Fetch global entity to populate MPV store globalValues (used for built-in field hints).\n        service.getById(id).then((globalRecord) => {\n          setGlobalValues({ ...(globalRecord as Record<string, unknown>) });\n        }).catch(() => {\n          // getById failed — globalValues stays as snapshot from openEdit\n        });\n        // Fetch company-context entity to update activeRecord and values with complete data.\n        // Detail tabs read entity._globalValues to determine which fields have overrides\n        // and whether to show the RevertToGlobalButton.\n        service.getById(id, activeCompanyContext).then((companyRecord) => {\n          updateActiveRecord(companyRecord);\n          setValues({ ...(companyRecord as Record<string, unknown>) });\n        }).catch(() => {\n          setRecordLoadFailed(true);\n        }).finally(() => {\n          setIsLoadingRecord(false);\n        });\n      } else {\n        // For all other types: fetch the full record so all form fields are populated.\n        service.getById(id).then((fullRecord) => {\n          updateActiveRecord(fullRecord);\n          setValues({ ...(fullRecord as Record<string, unknown>) });\n        }).catch(() => {\n          setRecordLoadFailed(true);\n        }).finally(() => {\n          setIsLoadingRecord(false);\n        });\n      }\n    },\n    [openEdit, definition.type, activeCompanyContext, service, setGlobalValues, updateActiveRecord, setValues, setIsLoadingRecord, setRecordLoadFailed],\n  );\n\n  /**\n   * Opens a record in view mode, then asynchronously fetches the full record via getById\n   * so the form shows all fields — not just the subset present in the list row.\n   * While the fetch is in-flight, isLoadingRecord shows a loading overlay on the form.\n   */\n  const openViewRecord = useCallback(\n    (record: T) => {\n      openView(record);\n      if (!service.getById) return;\n      setIsLoadingRecord(true);\n      setRecordLoadFailed(false);\n      const id = (record as T & { id: string }).id;\n      const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n      const companyId = isCompanyCtx ? activeCompanyContext : undefined;\n      service.getById(id, companyId).then((fullRecord) => {\n        updateActiveRecord(fullRecord);\n        setValues({ ...(fullRecord as Record<string, unknown>) });\n      }).catch(() => {\n        setRecordLoadFailed(true);\n      }).finally(() => {\n        setIsLoadingRecord(false);\n      });\n    },\n    [openView, activeCompanyContext, service, updateActiveRecord, setValues, setIsLoadingRecord, setRecordLoadFailed],\n  );\n\n  // Notifies the host app whenever the form panel opens/closes, regardless of which internal\n  // action triggered it (row click, toolbar create, deep-link) — lets the host sync its URL.\n  const prevModeRef = useRef(mode);\n  useEffect(() => {\n    if (prevModeRef.current === mode) return;\n    if (mode === 'closed') {\n      onRecordClose?.();\n    } else {\n      onRecordOpen?.(activeRecord as T | null, mode);\n    }\n    prevModeRef.current = mode;\n  }, [mode, activeRecord, onRecordOpen, onRecordClose]);\n\n  // Deep-link: openRecordMode='creating' opens the create form on mount — no id to look up,\n  // so this is independent of (and takes priority over) the openRecordId effect below. Guards\n  // with a ref (not just `mode !== 'creating'`) so it fires once per 'creating' session instead\n  // of re-opening every render, but can fire again if the host navigates away and back.\n  const wasAutoCreateModeRef = useRef(false);\n  useEffect(() => {\n    if (openRecordMode !== 'creating') {\n      wasAutoCreateModeRef.current = false;\n      return;\n    }\n    if (wasAutoCreateModeRef.current) return;\n    wasAutoCreateModeRef.current = true;\n    openCreate();\n  }, [openRecordMode, openCreate]);\n\n  // Deep-link: auto-opens the record identified by `openRecordId` (host-controlled, e.g. from\n  // its own router/URL). Falls back to service.getById when the record isn't in the loaded list.\n  const lastOpenedRecordIdRef = useRef<string | null>(null);\n  useEffect(() => {\n    if (openRecordMode === 'creating') return;\n    if (!openRecordId || openRecordId === lastOpenedRecordIdRef.current) return;\n    lastOpenedRecordIdRef.current = openRecordId;\n    const record = data.find((r) => (r as T & { id: string }).id === openRecordId);\n    const openFn = openRecordMode === 'viewing' ? openViewRecord : openEditRecord;\n    if (record) {\n      openFn(record as T);\n    } else if (service.getById) {\n      service.getById(openRecordId).then((loaded) => openFn(loaded)).catch(() => {\n        console.warn(`[MasterPatternView] openRecordId \"${openRecordId}\" not found`);\n      });\n    }\n  }, [openRecordId, openRecordMode, data, service, openEditRecord, openViewRecord]);\n\n  /**\n   * Retries the getById fetch for the currently open record.\n   * Called from the form's error banner when the initial load failed.\n   */\n  const handleRetryLoad = useCallback(() => {\n    if (!activeRecord || !service.getById) return;\n    const id = (activeRecord as T & { id: string }).id;\n    setIsLoadingRecord(true);\n    setRecordLoadFailed(false);\n    const isGlobalType = definition.type === 'GLOBAL';\n    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n    if (isGlobalType && isCompanyCtx) {\n      service.getById(id).then((globalRecord) => {\n        setGlobalValues({ ...(globalRecord as Record<string, unknown>) });\n      }).catch(() => {});\n      service.getById(id, activeCompanyContext).then((companyRecord) => {\n        updateActiveRecord(companyRecord);\n        setValues({ ...(companyRecord as Record<string, unknown>) });\n      }).catch(() => {\n        setRecordLoadFailed(true);\n      }).finally(() => {\n        setIsLoadingRecord(false);\n      });\n    } else {\n      service.getById(id).then((fullRecord) => {\n        updateActiveRecord(fullRecord);\n        setValues({ ...(fullRecord as Record<string, unknown>) });\n      }).catch(() => {\n        setRecordLoadFailed(true);\n      }).finally(() => {\n        setIsLoadingRecord(false);\n      });\n    }\n  }, [activeRecord, service, definition.type, activeCompanyContext, setGlobalValues, updateActiveRecord, setValues, setIsLoadingRecord, setRecordLoadFailed]);\n\n  const handleOpenEdit = useCallback(\n    async (id: string) => {\n      if (isEffectivelyDirty) {\n        openDirtyStateDialog();\n        return;\n      }\n      const record = data.find((r) => r.id === id);\n      if (record) {\n        openEditRecord(record as T);\n      } else if (service.getById) {\n        try {\n          const loaded = await service.getById(id);\n          openEditRecord(loaded);\n        } catch {\n          console.warn(`[MasterPatternView] Record ${id} not found in list and getById failed`);\n        }\n      } else {\n        console.warn(`[MasterPatternView] Record ${id} not found in list and getById not provided`);\n      }\n    },\n    [isEffectivelyDirty, openDirtyStateDialog, data, openEditRecord, service],\n  );\n\n  const handleCloseForm = useCallback(() => {\n    if (isEffectivelyDirty) {\n      openDirtyStateDialog();\n    } else {\n      closeForm();\n    }\n  }, [isEffectivelyDirty, openDirtyStateDialog, closeForm]);\n\n  useImperativeHandle(\n    ref,\n    () => ({\n      resetDirty: () => setIsDirty(false),\n      refresh: () => {\n        queryClient.invalidateQueries({ queryKey: ['masterList'] });\n      },\n      openCreate: handleOpenCreate,\n      openEdit: handleOpenEdit,\n      closeForm: handleCloseForm,\n    }),\n    [setIsDirty, queryClient, handleOpenCreate, handleOpenEdit, handleCloseForm],\n  );\n\n  // ── Event handlers ─────────────────────────────────────────────────────────\n\n  const handleCancel = useCallback(() => {\n    if (isEffectivelyDirty) {\n      openDirtyStateDialog();\n    } else {\n      closeForm();\n    }\n  }, [isEffectivelyDirty, openDirtyStateDialog, closeForm]);\n\n  const handleContinueEditing = useCallback(() => {\n    closeDirtyStateDialog();\n  }, [closeDirtyStateDialog]);\n\n  const handleDiscard = useCallback(() => {\n    closeForm();\n    closeDirtyStateDialog();\n    clearPendingAction();\n  }, [closeForm, closeDirtyStateDialog, clearPendingAction]);\n\n  // \"Guardar y salir\" — mismo patrón que MasterCrud.tsx:2020 (formRef.current.submit()):\n  // cierra el diálogo y dispara el submit normal, que ya se encarga de guardar y cerrar\n  // el formulario en su propio onSuccess (createMutation/updateMutation en useMasterForm).\n  const handleSaveAndExit = useCallback(() => {\n    closeDirtyStateDialog();\n    submit();\n  }, [closeDirtyStateDialog, submit]);\n\n  const handleStatusConfirm = useCallback(\n    (id: string, newStatus: boolean) => {\n      // Pass companyId when in a company context so the service changes\n      // the company-specific status, not the global one\n      const companyId =\n        activeCompanyContext && activeCompanyContext !== 'global'\n          ? activeCompanyContext\n          : undefined;\n      executeChangeStatus(id, newStatus, companyId);\n    },\n    [executeChangeStatus, activeCompanyContext],\n  );\n\n  // Confirm handler: enables the record for the current company, then proceeds with the original action\n  const handleNotEnabledConfirm = useCallback(async () => {\n    if (!notEnabledState.record) return;\n    const { trigger, record } = notEnabledState;\n    // COMPANY_SWITCH uses the pending target company; other triggers use activeCompanyContext\n    const targetCompanyId = trigger === 'COMPANY_SWITCH' ? pendingCompanySwitchId : activeCompanyContext;\n    if (!targetCompanyId) return;\n    const recordId = (record as Record<string, unknown>)['id'] as string;\n    setNotEnabledState((prev) => ({ ...prev, isLoading: true }));\n    try {\n      // For CHANGE_STATUS, pass the target state so the backend creates the assignment\n      // with the correct isActive value directly — avoids a second confirmation modal\n      const initialValues =\n        trigger === 'CHANGE_STATUS'\n          ? { isActive: !((record as Record<string, unknown>)['isActive'] as boolean) }\n          : undefined;\n      await service.companyEnable?.(recordId, targetCompanyId, initialValues);\n      queryClient.invalidateQueries({ queryKey: ['masterList'] });\n      showSuccess(t('recordEnabledSuccess', 'Registro habilitado correctamente'));\n      setNotEnabledState({ isOpen: false, trigger: 'OPEN_EDIT', record: null, isLoading: false });\n      if (trigger === 'COMPANY_SWITCH') {\n        // Switch context and reload the form with the new company's overrides.\n        setActiveCompanyContext(targetCompanyId);\n        setPendingCompanySwitchId(null);\n        openEdit(record!); // resets store state (overrides, isDirty, revertedFields)\n        if (service.getById) {\n          setIsLoadingRecord(true);\n          setRecordLoadFailed(false);\n          // Reload global baseline for override hints.\n          service.getById(recordId).then((gr) => {\n            setGlobalValues({ ...(gr as Record<string, unknown>) });\n          }).catch(() => {});\n          // Reload company-specific data (newly enabled → overrides may be empty/defaults).\n          service.getById(recordId, targetCompanyId).then((companyRecord) => {\n            updateActiveRecord(companyRecord);\n            setValues({ ...(companyRecord as Record<string, unknown>) });\n          }).catch(() => {\n            setRecordLoadFailed(true);\n          }).finally(() => {\n            setIsLoadingRecord(false);\n          });\n        }\n      } else if (trigger === 'OPEN_EDIT') {\n        openEditRecord(record!);\n      } else if (trigger === 'OPEN_VIEW') {\n        openView(record!);\n      }\n      // CHANGE_STATUS: no second modal — companyEnable already applies the target state\n    } catch (err: unknown) {\n      showError((err as Error)?.message ?? t('recordEnabledError', 'Error al habilitar el registro'));\n      setNotEnabledState((prev) => ({ ...prev, isLoading: false }));\n    }\n  }, [notEnabledState, pendingCompanySwitchId, activeCompanyContext, service, queryClient, showSuccess, showError, openEdit, openEditRecord, openView, setActiveCompanyContext, setGlobalValues, setIsLoadingRecord, setRecordLoadFailed, updateActiveRecord, setValues, t]);\n\n  const handleApplyFilters = useCallback(\n    (filters: typeof activeFilters) => {\n      setActiveFilters(filters);\n      // Preserve __view filter if \"Mostrar solo compañía\" toggle is active\n      const withoutView = filters.filter((f) => f.field !== '__view');\n      const viewFilter: typeof filters = showOnlyCompany\n        ? [{ field: '__view', operator: 'equals', value: 'company' }]\n        : [];\n      setSearchParams({ page: 1, filters: [...withoutView, ...viewFilter] });\n    },\n    [setActiveFilters, setSearchParams, showOnlyCompany],\n  );\n\n  const handleClearFilters = useCallback(() => {\n    // clearFilters resets activeFilters, columnFilters, and quickFilterValues in the store\n    clearFilters();\n    setShowOnlyCompany(false);\n    setSearchParams({ page: 1, filters: [], search: '' });\n  }, [clearFilters, setSearchParams]);\n\n  const handleToggleShowOnlyCompany = useCallback(() => {\n    const next = !showOnlyCompany;\n    setShowOnlyCompany(next);\n    const withoutView = searchParams.filters.filter((f) => f.field !== '__view');\n    setSearchParams({\n      filters: next\n        ? [...withoutView, { field: '__view', operator: 'equals', value: 'company' }]\n        : withoutView,\n      page: 1,\n    });\n    setActionsDropdownOpen(false);\n  }, [showOnlyCompany, searchParams.filters, setSearchParams]);\n\n  const selectedRecords = data.filter((r) => selectedIds.includes(r.id)) as T[];\n  const pendingRecord = pendingAction?.payload as T | undefined;\n\n  // Close toolbar dropdown whenever a modal/dialog opens\n  const isAnyModalOpen = isChangeStatusModalOpen || isCompanyEnableModalOpen || isDirtyStateDialogOpen;\n  React.useEffect(() => {\n    if (isAnyModalOpen) setActionsDropdownOpen(false);\n  }, [isAnyModalOpen]);\n\n  const isCompanyCtxActive = !!activeCompanyContext && activeCompanyContext !== 'global';\n  const showMostrarSoloCompania = definition.type === 'GLOBAL' && isCompanyCtxActive;\n  const hasActionsItems = showExport || showImport || (globalActions && globalActions.length > 0) || showMostrarSoloCompania || showViewToggle;\n\n  // Shared by both surfaces that can open the \"Habilitar por compañía\" panel:\n  // the Acciones-column action (global scope, mirrors MasterCrud's 'link' default action)\n  // and the dedicated company-status column (company scope, mirrors MasterCrud's\n  // showCompanyStatusColumn/CompanyStatusBadge — see ListTable's `onCompanyStatusClick`).\n  const handleCompanyEnableClick = useCallback(async (row: T) => {\n    const recordId = (row as T & { id: string }).id;\n    const prevRecordId = companyEnableRecord\n      ? (companyEnableRecord as T & { id: string }).id\n      : null;\n    setCompanyEnableRecord(row);\n\n    if (service.getAssignedCompanyIds) {\n      // Always load from server when available — covers F5 and record switches\n      setIsCompanyEnableLoading(true);\n      try {\n        const ids = await service.getAssignedCompanyIds(recordId);\n        setAssignedCompanyIds(ids);\n      } finally {\n        setIsCompanyEnableLoading(false);\n      }\n    } else if (recordId !== prevRecordId) {\n      // Different record and no server loader — reset so we don't\n      // show stale assignments from another record\n      setAssignedCompanyIds([]);\n    }\n    // Same record + no loader → keep optimistic state from last confirm\n\n    openCompanyEnableModal();\n  }, [companyEnableRecord, service, setCompanyEnableRecord, setIsCompanyEnableLoading, setAssignedCompanyIds, openCompanyEnableModal]);\n\n  // Row-level actions injected by MasterPatternView itself (not passed by the consumer):\n  // \"Habilitar compañías\" (GLOBAL type — shown in both scopes; in company scope it sits\n  // alongside the dedicated company-status column, see `onCompanyStatusClick` below) and\n  // \"Auditoría de Cambios\" (opt-in via the `auditHistory` prop) — mirrors MasterCrud's\n  // 'link' and 'audit' default actions.\n  const injectedRowActions = [\n    ...(definition.type === 'GLOBAL' ? [{\n      key: 'company-enable',\n      label: t('enableCompaniesAction', 'Habilitar compañías'),\n      icon: <Building2 size={18} />,\n      position: 'row' as const,\n      onExecute: async (row?: T) => {\n        if (!row) return;\n        await handleCompanyEnableClick(row);\n      },\n    }] : []),\n    ...(auditHistory?.enabled ? [{\n      key: 'audit',\n      label: t('auditChanges', 'Auditoría de Cambios'),\n      icon: <ClockIcon className=\"w-[15px] h-[15px]\" />,\n      position: 'row' as const,\n      onExecute: (row?: T) => {\n        if (row) openAuditModal(row);\n      },\n    }] : []),\n  ];\n\n  return (\n    <div data-testid=\"master-pattern-view\" className=\"relative flex flex-col w-full h-screen overflow-hidden\">\n      {/* Header, company selector and list are hidden while navigationType='page' has a record\n          open — PagePanel fully replaces them (and is transparent), instead of painting over\n          them like sidebar/modal do. Keeps this content out of the DOM entirely. */}\n      {(navigationType !== 'page' || mode === 'closed') && (\n      <>\n      {/* Header: (Title + CompanySelector) + Búsqueda/Acciones/Crear — apila en columna en\n          pantallas angostas (igual que MasterCrudToolbar.tsx:101-114): título y selector de\n          compañía viven juntos en la columna izquierda, así en angosto quedan ARRIBA de los\n          botones de búsqueda/crear, no debajo — antes el selector era una fila aparte que\n          siempre caía después de los botones. */}\n      <div className=\"flex flex-col md:flex-row md:items-center md:justify-between gap-2 px-5 pt-3.5 pb-2\">\n        <div className=\"flex flex-col items-start gap-1.5 min-w-0\">\n          {title && (\n            <h1 className=\"text-xl font-semibold text-[#1355b7] tracking-tight truncate\" data-testid=\"master-view-title\">\n              {title}\n            </h1>\n          )}\n          {definition.type !== 'UNIVERSAL' && (\n            <CompanySelector\n              companies={companies ?? []}\n              activeCompanyId={activeCompanyContext ?? undefined}\n              showGlobalOption={definition.type === 'GLOBAL'}\n              onCompanyChange={(company) => {\n                setActiveCompanyContext(company.id);\n                onCompanyChange?.(company);\n              }}\n              toast={toastProp}\n              showInternalToasts={showInternalToasts}\n              t={t}\n            />\n          )}\n        </div>\n        <div className=\"flex items-center gap-2 flex-shrink-0 flex-wrap md:flex-nowrap\">\n          {/* Búsqueda rápida — input de texto real (MasterCrudToolbar.tsx:118-131);\n              el ícono de filtro es un botón aparte que abre el FilterPanel. Ambos son\n              mutuamente excluyentes: el input se deshabilita mientras el panel está\n              abierto (igual que `disabled={isAdvancedSearchActive}` en MasterCrud). */}\n          <div className=\"relative flex items-center\">\n            <span className=\"absolute left-2.5 top-1/2 -translate-y-1/2 text-content-tertiary dark:text-dark-content-tertiary pointer-events-none\">\n              <SearchIcon className=\"w-3.5 h-3.5\" />\n            </span>\n            <input\n              type=\"search\"\n              data-testid=\"toolbar-busqueda-input\"\n              placeholder={t('toolbarSearchLabel', 'Buscar...')}\n              value={searchParams.search}\n              autoComplete=\"off\"\n              disabled={isFilterPanelOpen}\n              onChange={(e) => setSearchParams({ search: e.target.value, page: 1 })}\n              className=\"pl-8 pr-10 h-9 w-64 text-sm border border-border-primary dark:border-dark-border-primary rounded-md bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary placeholder:text-content-tertiary dark:placeholder:text-dark-content-tertiary focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors disabled:opacity-60\"\n            />\n            <motion.button\n              type=\"button\"\n              onClick={toggleFilterPanel}\n              aria-expanded={isFilterPanelOpen}\n              title={isFilterPanelOpen ? t('hideAdvancedSearch', 'Ocultar filtros') : t('showAdvancedSearch', 'Mostrar filtros')}\n              data-testid=\"toolbar-busqueda-button\"\n              whileHover={{ scale: 1.1 }}\n              whileTap={{ scale: 0.92 }}\n              transition={{ type: 'spring', bounce: 0.55, duration: 0.4 }}\n              className={`absolute right-1.5 inline-flex items-center justify-center w-7 h-7 rounded-md transition-colors ${\n                isFilterPanelOpen || activeFilters.length > 0\n                  ? 'bg-primary-600 text-white'\n                  : 'text-content-tertiary hover:text-primary-600 hover:bg-[#eff8ff] dark:hover:bg-primary-900/20'\n              }`}\n            >\n              {isFilterPanelOpen ? <ChevronDownIcon className=\"w-3.5 h-3.5 rotate-180\" /> : <FilterIcon className=\"w-3.5 h-3.5\" />}\n            </motion.button>\n          </div>\n\n          <ToolbarActions<T>\n            definition={definition}\n            permissions={permissions}\n            defaultActions={defaultActions}\n            onCreateClick={handleOpenCreate}\n            toast={toastProp}\n            showInternalToasts={showInternalToasts}\n            t={t}\n          />\n\n          {/* Acciones dropdown — always visible, kebab vertical estilo MasterCrud */}\n          <div className=\"relative\">\n            <motion.button\n              type=\"button\"\n              onClick={() => hasActionsItems && setActionsDropdownOpen((v) => !v)}\n              data-testid=\"toolbar-actions-dropdown-button\"\n              aria-haspopup=\"menu\"\n              aria-expanded={actionsDropdownOpen}\n              title={t('moreOptions', 'Más opciones')}\n              whileHover={{ scale: 1.1 }}\n              whileTap={{ scale: 0.92 }}\n              transition={{ type: 'spring', bounce: 0.55, duration: 0.4 }}\n              className=\"inline-flex items-center justify-center w-9 h-9 rounded-md border bg-background-secondary dark:bg-dark-bg-secondary border-border-primary dark:border-dark-border-primary text-content-tertiary dark:text-dark-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n            >\n              <EllipsisVerticalIcon className=\"w-4 h-4\" />\n            </motion.button>\n            {actionsDropdownOpen && hasActionsItems && (\n              <div className=\"absolute right-0 top-full mt-1 bg-bg-primary dark:bg-dark-bg-primary rounded-md border border-border-primary dark:border-dark-border-primary shadow-md z-50 w-64 py-1\">\n                {/* Ver solo registros de la compañía seleccionada — misma etiqueta y mismo\n                    componente Switch que el toggle de alcance de filas de MasterCrud\n                    (MasterCrudToolbar.tsx:191-212, prop viewScope). */}\n                {showMostrarSoloCompania && (\n                  <div className=\"px-1 py-1 border-b border-border-primary dark:border-dark-border-primary\">\n                    <p className=\"px-2 pt-1 pb-1.5 text-[11px] font-semibold text-content-tertiary dark:text-dark-content-tertiary tracking-[0.3px]\">\n                      {t('recordsToShow', 'Registros a mostrar')}\n                    </p>\n                    <button\n                      type=\"button\"\n                      role=\"switch\"\n                      aria-checked={showOnlyCompany}\n                      onClick={handleToggleShowOnlyCompany}\n                      data-testid=\"toolbar-toggle-only-company\"\n                      className=\"w-full flex items-center justify-between gap-3 px-2 py-2 rounded text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                    >\n                      <span className=\"flex-1 text-left select-none\">\n                        {t('viewCompanyOnly', 'Ver solo registros de la compañía seleccionada')}\n                      </span>\n                      <Switch\n                        size=\"sm\"\n                        checked={showOnlyCompany}\n                        onChange={() => {}}\n                        className=\"pointer-events-none shrink-0\"\n                      />\n                    </button>\n                  </div>\n                )}\n                {/* \"Mostrar datos globales\" NO va aquí — a diferencia de MasterCrud (que no tiene\n                    este concepto en su lista), en MPV solo tiene sentido dentro del formulario de\n                    un registro (dónde ver hints de campo sobreescrito vs global). Sigue disponible\n                    ahí mismo, en el menú hamburguesa del form (FormActionBar.tsx:305). */}\n                {/* Modo de visualización (Listado / Tarjetas) — dentro del kebab, como MasterCrud.\n                    El separador con la sección anterior/siguiente es el border-b de este propio\n                    div (como en MasterCrudToolbar.tsx:216) — no un <hr> aparte, que duplicaba la línea. */}\n                {showViewToggle && (\n                  <div className={`px-3 py-2 ${(showImport || showExport) ? 'border-b border-border-primary dark:border-dark-border-primary' : ''}`}>\n                    <p className=\"text-[11px] font-semibold text-content-tertiary dark:text-dark-content-tertiary tracking-[0.3px] mb-2\">\n                      {t('displayMode', 'Modo de visualización')}\n                    </p>\n                    <div className=\"inline-flex w-full border border-border-primary dark:border-dark-border-primary rounded-md overflow-hidden text-sm\">\n                      <button\n                        type=\"button\"\n                        onClick={() => { setViewMode('table'); setActionsDropdownOpen(false); }}\n                        aria-pressed={viewMode === 'table'}\n                        data-testid=\"toolbar-view-table\"\n                        className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 transition-colors ${\n                          viewMode === 'table'\n                            ? 'bg-primary-600 text-white'\n                            : 'bg-white dark:bg-dark-bg-primary text-content-tertiary dark:text-dark-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'\n                        }`}\n                      >\n                        <ListBulletIcon className=\"w-4 h-4\" />\n                        <span>{t('listView', 'Listado')}</span>\n                      </button>\n                      <button\n                        type=\"button\"\n                        onClick={() => { setViewMode('cards'); setActionsDropdownOpen(false); }}\n                        aria-pressed={viewMode === 'cards'}\n                        data-testid=\"toolbar-view-cards\"\n                        className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 transition-colors border-l border-border-primary dark:border-dark-border-primary ${\n                          viewMode === 'cards'\n                            ? 'bg-primary-600 text-white'\n                            : 'bg-white dark:bg-dark-bg-primary text-content-tertiary dark:text-dark-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'\n                        }`}\n                      >\n                        <Squares2X2Icon className=\"w-4 h-4\" />\n                        <span>{t('cardView', 'Tarjetas')}</span>\n                      </button>\n                    </div>\n                  </div>\n                )}\n                {showImport && (\n                  <button type=\"button\" className=\"w-full flex items-center gap-2 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary cursor-pointer\" onClick={() => { onImport?.(); setActionsDropdownOpen(false); }} data-testid=\"toolbar-import-item\">\n                    <ArrowUpTrayIcon className=\"w-[13px] h-[13px]\" /> {t('import', 'Importar')}\n                  </button>\n                )}\n                {showExport && (\n                  <button type=\"button\" className=\"w-full flex items-center gap-2 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary cursor-pointer\" onClick={() => { onExport?.(); setActionsDropdownOpen(false); }} data-testid=\"toolbar-export-item\">\n                    <DocumentArrowDownIcon className=\"w-[13px] h-[13px]\" /> {t('export', 'Exportar')}\n                  </button>\n                )}\n              </div>\n            )}\n          </div>\n        </div>\n      </div>\n\n      {/* Content area: filter-card (conditional) + grid-card.\n          overflow-y-auto AQUÍ (no en el header): el header/buscador vive fuera de este\n          contenedor como hermano, así que nunca se pierde de vista al hacer scroll — sin\n          necesitar `sticky`. Es el ÚNICO scroll de la vista (ni el panel ni la grilla tienen\n          overflow propio) para no anidar scrollbars. */}\n      <div className=\"flex-1 min-h-0 flex flex-col gap-2.5 px-5 pb-5 pt-3 overflow-y-auto\">\n        {/* Filter card — only visible when Búsqueda is active.\n            Se mantiene SIEMPRE montado (se oculta con `hidden`, no con `&&`) para que\n            el estado local de FilterPanel (valores tecleados, condiciones avanzadas,\n            conector Y/O) sobreviva a cerrar/abrir el panel — incluso lo que el usuario\n            escribió pero nunca llegó a buscar. Desmontarlo lo reiniciaba cada vez.\n            Sin max-h/overflow propio: se adapta a su alto natural: si crece mucho, empuja\n            la grilla hacia abajo y el scroll del content-area (arriba) se encarga. */}\n        <div\n          className={`bg-[#f8f9fc] dark:bg-zinc-900 rounded-lg border border-border-primary dark:border-dark-border-primary shadow-sm flex-shrink-0 ${\n            isFilterPanelOpen ? '' : 'hidden'\n          }`}\n        >\n          <FilterPanel\n            definition={definition}\n            activeFilters={activeFilters}\n            onSearch={handleApplyFilters}\n            onClear={handleClearFilters}\n            t={t}\n          />\n        </div>\n\n        {/* Grid card: table + empty state + pagination + batch bar.\n            min-h SOLO cuando el filtro está abierto (isFilterPanelOpen): con el filtro\n            cerrado vuelve a min-h-0 puro — el tamaño de siempre, sin scroll de más. Con el\n            filtro abierto, la grilla no se encoge por debajo de ese piso: el filtro la\n            empuja hacia abajo (dentro del scroll del content-area) en vez de aplastarla. */}\n        <div className={`${viewMode === 'cards' ? 'bg-[#f8f9fc]' : 'bg-background-secondary'} dark:bg-dark-bg-secondary rounded-xl border border-border-primary dark:border-dark-border-primary overflow-hidden flex flex-col flex-1 ${isFilterPanelOpen ? 'min-h-[26rem]' : 'min-h-0'}`}>\n          <div ref={scrollContainerRef} className=\"flex-1 min-h-0 overflow-auto flex flex-col\">\n            {showLoading || hasSearched ? (\n              viewMode === 'cards' ? (\n                <ListCard<T>\n                  definition={definition}\n                  data={data as T[]}\n                  onOpenView={(row) => {\n                    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n                    if (definition.type === 'GLOBAL' && isCompanyCtx && !(row as Record<string, unknown>)['isAssigned']) {\n                      setNotEnabledState({ isOpen: true, trigger: 'OPEN_VIEW', record: row, isLoading: false });\n                      return;\n                    }\n                    openViewRecord(row);\n                  }}\n                  onOpenEdit={(row) => {\n                    if (isEffectivelyDirty) { openDirtyStateDialog(); return; }\n                    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n                    if (definition.type === 'GLOBAL' && isCompanyCtx && !(row as Record<string, unknown>)['isAssigned']) {\n                      setNotEnabledState({ isOpen: true, trigger: 'OPEN_EDIT', record: row, isLoading: false });\n                      return;\n                    }\n                    openEditRecord(row);\n                  }}\n                  onChangeStatus={(row) => {\n                    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n                    if (definition.type === 'GLOBAL' && isCompanyCtx && !(row as Record<string, unknown>)['isAssigned']) {\n                      setNotEnabledState({ isOpen: true, trigger: 'CHANGE_STATUS', record: row, isLoading: false });\n                      return;\n                    }\n                    setPendingAction({ type: 'change-status', payload: row });\n                    openChangeStatusModal();\n                  }}\n                  isLoading={showLoading && !(paginationConfig?.mode === 'infinite' && data.length > 0)}\n                  modalOpen={isAnyModalOpen || notEnabledState.isOpen}\n                  activeCompanyContext={activeCompanyContext ?? undefined}\n                  permissions={permissions}\n                  actions={injectedRowActions}\n                  onCompanyStatusClick={definition.type === 'GLOBAL' ? handleCompanyEnableClick : undefined}\n                  renderCardContent={renderCardContent}\n                  toast={toastProp}\n                  showInternalToasts={showInternalToasts}\n                  defaultActions={defaultActions}\n                  t={t}\n                />\n              ) : (\n                <ListTable<T>\n                  definition={definition}\n                  data={data as T[]}\n                  sortBy={sortBy}\n                  sortOrder={sortOrder}\n                  onSort={setSort}\n                  onOpenView={(row) => {\n                    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n                    if (definition.type === 'GLOBAL' && isCompanyCtx && !(row as Record<string, unknown>)['isAssigned']) {\n                      setNotEnabledState({ isOpen: true, trigger: 'OPEN_VIEW', record: row, isLoading: false });\n                      return;\n                    }\n                    openViewRecord(row);\n                  }}\n                  onOpenEdit={(row) => {\n                    if (isEffectivelyDirty) { openDirtyStateDialog(); return; }\n                    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n                    if (definition.type === 'GLOBAL' && isCompanyCtx && !(row as Record<string, unknown>)['isAssigned']) {\n                      setNotEnabledState({ isOpen: true, trigger: 'OPEN_EDIT', record: row, isLoading: false });\n                      return;\n                    }\n                    openEditRecord(row);\n                  }}\n                  onChangeStatus={(row) => {\n                    const isCompanyCtx = !!activeCompanyContext && activeCompanyContext !== 'global';\n                    if (definition.type === 'GLOBAL' && isCompanyCtx && !(row as Record<string, unknown>)['isAssigned']) {\n                      setNotEnabledState({ isOpen: true, trigger: 'CHANGE_STATUS', record: row, isLoading: false });\n                      return;\n                    }\n                    setPendingAction({ type: 'change-status', payload: row });\n                    openChangeStatusModal();\n                  }}\n                  isLoading={showLoading && !(paginationConfig?.mode === 'infinite' && data.length > 0)}\n                  modalOpen={isAnyModalOpen || notEnabledState.isOpen}\n                  activeCompanyContext={activeCompanyContext ?? undefined}\n                  permissions={permissions}\n                  actions={injectedRowActions}\n                  onCompanyStatusClick={definition.type === 'GLOBAL' ? handleCompanyEnableClick : undefined}\n                  toast={toastProp}\n                  showInternalToasts={showInternalToasts}\n                  defaultActions={defaultActions}\n                  t={t}\n                />\n              )\n            ) : (\n              <EmptyState hasSearched={hasSearched} t={t} />\n            )}\n\n            {/* Filler: when few records don't fill the viewport, absorbs remaining space using\n                the outer bg — no stark gap against the card border */}\n            {hasSearched && data.length > 0 && !showLoading && (\n              <div className={`flex-1 ${viewMode === 'cards' ? 'bg-[#f8f9fc]' : 'bg-bg-primary'} dark:bg-dark-bg-primary`} />\n            )}\n\n            {/* Infinite scroll — loading indicator + bottom padding for scroll trigger */}\n            {paginationConfig?.mode === 'infinite' && (\n              <>\n                {isFetchingNextPage && (\n                  <div className=\"flex justify-center py-3 text-sm text-content-tertiary dark:text-dark-content-tertiary\">\n                    {t('loadingMore', 'Cargando más...')}\n                  </div>\n                )}\n              </>\n            )}\n          </div>\n\n          {paginationConfig?.mode !== 'infinite' && paginationConfig && data.length > 0 && !showLoading && (\n            <PaginationBar\n              currentPage={searchParams.page}\n              totalPages={totalPages}\n              totalRecords={total}\n              pageSize={searchParams.pageSize}\n              pageSizeOptions={paginationConfig.pageSizeOptions ?? [10, 25, 50]}\n              onPageChange={(page) => setSearchParams({ page })}\n              onPageSizeChange={(pageSize) => setSearchParams({ pageSize, page: 1 })}\n              t={t}\n            />\n          )}\n\n          {selectable && (\n            <BatchBar<T>\n              selectedIds={selectedIds}\n              selectedRecords={selectedRecords}\n              onClearSelection={clearSelection}\n              permissions={permissions ?? {}}\n              batchActions={batchActions}\n              toast={toastProp}\n              showInternalToasts={showInternalToasts}\n              t={t}\n            />\n          )}\n        </div>\n      </div>\n      </>\n      )}\n\n      <MasterPatternViewForm<T>\n        definition={definition}\n        entityName={entityName}\n        permissions={permissions}\n        navigationType={navigationType}\n        showBackButton={showBackButton}\n        formWidth={formWidth}\n        formHeight={formHeight}\n        tabs={tabs}\n        headerFields={headerFields}\n        renderForm={renderForm}\n        detailTabs={detailTabs}\n        onSave={submit}\n        onCancel={handleCancel}\n        onRetryLoad={handleRetryLoad}\n        onRequestRefresh={() => {\n          queryClient.invalidateQueries({ queryKey: ['masterList'] });\n        }}\n        companies={companies}\n        assignedCompanyIds={formCompanyIds}\n        onHamburgerEnableCompany={async () => {\n          if (!activeRecord) return;\n          const recordId = (activeRecord as T & { id: string }).id;\n          const prevRecordId = companyEnableRecord\n            ? (companyEnableRecord as T & { id: string }).id\n            : null;\n          setCompanyEnableRecord(activeRecord as T);\n          if (service.getAssignedCompanyIds) {\n            setIsCompanyEnableLoading(true);\n            try {\n              const ids = await service.getAssignedCompanyIds(recordId);\n              setAssignedCompanyIds(ids);\n            } finally {\n              setIsCompanyEnableLoading(false);\n            }\n          } else if (recordId !== prevRecordId) {\n            setAssignedCompanyIds([]);\n          }\n          openCompanyEnableModal();\n        }}\n        onHamburgerAudit={auditHistory?.enabled ? () => {\n          if (activeRecord) openAuditModal(activeRecord as T);\n        } : undefined}\n        onCompanyChange={async (company) => {\n          // While editing a GLOBAL record, a company switch requires special handling:\n          // guard dirty state, check assignment, then reload form with the new company's data.\n          if (\n            definition.type === 'GLOBAL' &&\n            mode === 'editing' &&\n            activeRecord\n          ) {\n            // Block switch when there are unsaved changes — avoids cross-company data corruption.\n            if (isEffectivelyDirty) {\n              showError(t('unsavedChangesBlockSwitch', 'Tienes cambios sin guardar. Guarda o cancela los cambios antes de cambiar de compañía.'));\n              return;\n            }\n\n            const recordId = (activeRecord as T & { id: string }).id;\n\n            // Switching to 'global' context: reload form with the global baseline.\n            if (company.id === 'global') {\n              setActiveCompanyContext('global');\n              onCompanyChange?.(company);\n              if (service.getById) {\n                setIsLoadingRecord(true);\n                setRecordLoadFailed(false);\n                service.getById(recordId).then((globalRecord) => {\n                  updateActiveRecord(globalRecord);\n                  setValues({ ...(globalRecord as Record<string, unknown>) });\n                  setGlobalValues({});\n                }).catch(() => {\n                  setRecordLoadFailed(true);\n                }).finally(() => {\n                  setIsLoadingRecord(false);\n                });\n              }\n              return;\n            }\n\n            // Switching to a specific company: check if the record is assigned.\n            let isAssigned = false;\n            if (service.getAssignedCompanyIds) {\n              try {\n                const ids = await service.getAssignedCompanyIds(recordId);\n                isAssigned = ids.includes(company.id);\n              } catch {\n                isAssigned = false;\n              }\n            } else if (\n              companyEnableRecord &&\n              (companyEnableRecord as T & { id: string }).id === recordId\n            ) {\n              isAssigned = assignedCompanyIds.includes(company.id);\n            }\n\n            // Not assigned → offer to enable it inline instead of just blocking the switch\n            // (regresó en 3a8a918, que lo cambió por un toast de error sin ofrecer habilitar).\n            if (!isAssigned) {\n              setPendingCompanySwitchId(company.id);\n              setNotEnabledState({\n                isOpen: true,\n                trigger: 'COMPANY_SWITCH',\n                record: activeRecord as T,\n                isLoading: false,\n              });\n              return;\n            }\n\n            // Assigned → switch context and reload form with the new company's overrides.\n            setActiveCompanyContext(company.id);\n            onCompanyChange?.(company);\n            if (service.getById) {\n              setIsLoadingRecord(true);\n              setRecordLoadFailed(false);\n              service.getById(recordId).then((globalRecord) => {\n                setGlobalValues({ ...(globalRecord as Record<string, unknown>) });\n              }).catch(() => {});\n              service.getById(recordId, company.id).then((companyRecord) => {\n                updateActiveRecord(companyRecord);\n                setValues({ ...(companyRecord as Record<string, unknown>) });\n              }).catch(() => {\n                setRecordLoadFailed(true);\n              }).finally(() => {\n                setIsLoadingRecord(false);\n              });\n            }\n            return;\n          }\n\n          // Non-edit mode or non-GLOBAL type: normal switch.\n          setActiveCompanyContext(company.id);\n          onCompanyChange?.(company);\n        }}\n        recordTitleFields={recordTitleFields}\n        companyDisabled={isDirty || (definition.type === 'COMPANY_SPECIFIC' && mode !== 'closed')}\n        canEdit={canEdit}\n      />\n\n      <DirtyStateDialog\n        isOpen={isDirtyStateDialogOpen}\n        onContinue={handleContinueEditing}\n        onDiscard={handleDiscard}\n        onSaveAndExit={handleSaveAndExit}\n        changes={changedFields}\n        t={t}\n      />\n\n      <ChangeStatusModal<T>\n        isOpen={isChangeStatusModalOpen}\n        record={pendingRecord ?? null}\n        onCancel={closeChangeStatusModal}\n        onConfirm={handleStatusConfirm}\n        isLoading={isChanging}\n        t={t}\n      />\n\n      {/* Company Enable Modal — GLOBAL type only */}\n      {definition.type === 'GLOBAL' && (\n        <CompanyEnableModal\n          isOpen={isCompanyEnableModalOpen}\n          recordId={companyEnableRecord ? (companyEnableRecord as T & { id: string }).id : ''}\n          recordLabel={\n            companyEnableRecord\n              ? String(\n                  (companyEnableRecord as Record<string, unknown>).code ??\n                    (companyEnableRecord as Record<string, unknown>).name ??\n                    '',\n                ) || undefined\n              : undefined\n          }\n          companies={companies ?? []}\n          assignedCompanyIds={assignedCompanyIds}\n          t={t}\n          onClose={() => {\n            const wasPostCreate = isPostCreateModalRef.current;\n            isPostCreateModalRef.current = false;\n            closeCompanyEnableModal();\n            if (wasPostCreate) closeForm();\n          }}\n          onConfirm={async (changes) => {\n            if (!companyEnableRecord) return;\n            const recordId = (companyEnableRecord as T & { id: string }).id;\n            setIsCompanyEnableLoading(true);\n            try {\n              for (const change of changes) {\n                if (change.action === 'enable') {\n                  await service.companyEnable?.(recordId, change.companyId);\n                } else {\n                  await service.uncompanyEnable?.(recordId, change.companyId);\n                }\n              }\n              // Update local assigned state so next modal open reflects changes\n              setAssignedCompanyIds((prev) => {\n                const next = new Set(prev);\n                for (const change of changes) {\n                  if (change.action === 'enable') next.add(change.companyId);\n                  else next.delete(change.companyId);\n                }\n                return [...next];\n              });\n              showSuccess(t('companyChangesSavedSuccess', 'Cambios de compañías guardados correctamente'));\n              queryClient.invalidateQueries({ queryKey: ['masterList'] });\n              const wasPostCreate = isPostCreateModalRef.current;\n              isPostCreateModalRef.current = false;\n              closeCompanyEnableModal();\n              if (wasPostCreate) closeForm();\n            } catch (err: any) {\n              showError(err?.message ?? t('companyChangesSavedError', 'Error al guardar los cambios de compañías'));\n            } finally {\n              setIsCompanyEnableLoading(false);\n            }\n          }}\n          isLoading={isCompanyEnableLoading}\n        />\n      )}\n\n      {/* Not-Enabled Modal — GLOBAL type: record not yet assigned to the active company */}\n      {definition.type === 'GLOBAL' && (\n        <NotEnabledModal\n          isOpen={notEnabledState.isOpen}\n          trigger={notEnabledState.trigger}\n          companyName={(() => {\n            // COMPANY_SWITCH: activeCompanyContext todavía es el contexto viejo — el modal\n            // pregunta por la compañía DESTINO (pendingCompanySwitchId), no la actual.\n            const targetId = notEnabledState.trigger === 'COMPANY_SWITCH'\n              ? pendingCompanySwitchId\n              : activeCompanyContext;\n            return companies?.find((c) => c.id === targetId)?.name ?? targetId ?? '';\n          })()}\n          onCancel={closeNotEnabled}\n          onConfirm={handleNotEnabledConfirm}\n          isLoading={notEnabledState.isLoading}\n          t={t}\n        />\n      )}\n\n      {/* Audit History Modal — opt-in via the `auditHistory` prop, mirrors MasterCrud.tsx:2112-2131 */}\n      {auditModalState.show && auditHistory && auditModalState.record && (\n        <div className=\"fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4\">\n          <div className=\"bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col relative w-full max-w-3xl max-h-[90vh]\">\n            <div className=\"flex items-center justify-between p-4 border-b border-border-secondary dark:border-dark-border-primary\">\n              <h3 className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\">\n                {t('auditHistory', 'Historial de cambios')}\n              </h3>\n              <Button\n                type=\"outline\"\n                size=\"xs\"\n                iconOnly\n                leftIcon={<XMarkIcon className=\"w-4 h-4\" />}\n                onClick={closeAuditModal}\n                ariaLabel={t('close', 'Cerrar')}\n                className=\"!bg-white dark:!bg-dark-bg-primary\"\n              />\n            </div>\n            <div className=\"flex-1 overflow-hidden\">\n              <AuditHistoryPanel\n                fetchFn={auditHistory.fetchFn}\n                entityId={String((auditModalState.record as T & { id: string }).id ?? '')}\n              />\n            </div>\n          </div>\n        </div>\n      )}\n\n      {showInternalToasts && <InternalToastContainer />}\n\n      <ConflictDialog\n        t={t}\n        onRefresh={async () => {\n          queryClient.invalidateQueries({ queryKey: ['masterList'] });\n          const recordId = (activeRecord as T & { id: string })?.id;\n          if (recordId && service.getById) {\n            const ctxCompanyId =\n              activeCompanyContext && activeCompanyContext !== 'global'\n                ? activeCompanyContext\n                : undefined;\n            const record = await service.getById(recordId, ctxCompanyId);\n            openEditRecord(record);\n          }\n          clearPendingAction();\n        }}\n      />\n    </div>\n  );\n}) as <T extends MasterPatternViewEntity>(\n  props: ContentProps<T> & { ref?: React.ForwardedRef<MasterPatternViewRef> }\n) => React.ReactElement | null;\n\n// ─── CustomContent — escape hatch for CUSTOM type ────────────────────────────\n\ninterface CustomContentProps {\n  definition: MasterPatternViewDefinition;\n  renderBody?: (ctx: import('../types/props.types').CustomBodyContext) => React.ReactNode;\n  title: string;\n  companies?: import('../types/service.types').MasterPatternViewCompany[];\n  defaultCompany?: import('../types/service.types').MasterPatternViewCompany;\n  onCompanyChange?: (company: import('../types/service.types').MasterPatternViewCompany) => void;\n  toast?: (type: 'success' | 'error' | 'warning' | 'info', message: string) => void;\n  showCompanySelector?: boolean;\n  customSave?: import('../types/props.types').CustomSaveConfig;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  renderActionsMenuItems?: (ctx: any) => React.ReactNode;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  renderToolbarActions?: (ctx: any) => React.ReactNode;\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nfunction CustomContent({\n  definition,\n  renderBody,\n  title,\n  companies = [],\n  defaultCompany,\n  onCompanyChange,\n  showCompanySelector,\n  customSave,\n  renderActionsMenuItems,\n  renderToolbarActions,\n  t = (key: string, defaultValue?: string) => defaultValue ?? key,\n}: CustomContentProps) {\n  const companyBehavior = definition.companyBehavior ?? 'NONE';\n  const activeCompanyContext = useMasterViewStore((s) => s.activeCompanyContext);\n  const setActiveCompanyContext = useMasterViewStore((s) => s.setActiveCompanyContext);\n\n  const [isSaving, setIsSaving] = useState(false);\n  const [actionsDropdownOpen, setActionsDropdownOpen] = useState(false);\n  const dropdownRef = useRef<HTMLDivElement>(null);\n\n  React.useEffect(() => {\n    if (companyBehavior === 'COMPANY_SPECIFIC' && companies.length > 0) {\n      const initial = defaultCompany ?? companies[0];\n      setActiveCompanyContext(initial.id);\n      // Mismo aviso que en el efecto de restauración de MasterPatternView: el consumidor\n      // debe enterarse de la compañía inicial igual que se entera de un cambio manual\n      // (ver ctx.setCompanyId más abajo), o su estado de \"compañía seleccionada\" queda\n      // desincronizado del store interno de MPV.\n      if (initial.id !== 'global') onCompanyChange?.(initial);\n    }\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // Close dropdown on outside click\n  useEffect(() => {\n    if (!actionsDropdownOpen) return;\n    const handler = (e: MouseEvent) => {\n      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {\n        setActionsDropdownOpen(false);\n      }\n    };\n    document.addEventListener('mousedown', handler);\n    return () => document.removeEventListener('mousedown', handler);\n  }, [actionsDropdownOpen]);\n\n  const companyId = activeCompanyContext === 'global' ? undefined : (activeCompanyContext ?? undefined);\n  const isCompanyMode = companyBehavior !== 'NONE' && !!activeCompanyContext && activeCompanyContext !== 'global';\n\n  const handleCustomSave = useCallback(async () => {\n    if (!customSave) return;\n    const { onBeforeSave, onSave, onAfterSave } = customSave;\n    if (onBeforeSave) {\n      const canProceed = await onBeforeSave();\n      if (canProceed === false) return;\n    }\n    setIsSaving(true);\n    try {\n      await onSave();\n      await onAfterSave?.();\n    } finally {\n      setIsSaving(false);\n    }\n  }, [customSave]);\n\n  const ctx: import('../types/props.types').CustomBodyContext = {\n    companies,\n    companyId,\n    isCompanyMode,\n    isSaving,\n    setCompanyId: (id) => {\n      setActiveCompanyContext(id ?? '');\n      if (id && id !== 'global') {\n        const company = companies.find((c) => c.id === id);\n        if (company) onCompanyChange?.(company);\n      }\n    },\n  };\n\n  // Determine visibility of toolbar and company selector\n  const hasActionsItems = !!renderActionsMenuItems;\n  const hasSaveButton = !!customSave && !customSave.hidden;\n  const hasToolbar = hasActionsItems || !!renderToolbarActions || hasSaveButton;\n  const displayCompanySelector = showCompanySelector ?? (companyBehavior !== 'NONE');\n\n  return (\n    <div data-testid=\"master-pattern-view\" className=\"relative flex flex-col h-screen overflow-hidden\">\n      {/* Header: Title + Acciones + renderToolbarActions + Save */}\n      <div className=\"flex items-center justify-between px-5 pt-3.5 pb-0\">\n        {title && (\n          <h1 className=\"text-xl font-semibold text-[#1355b7] tracking-tight\" data-testid=\"master-view-title\">\n            {title}\n          </h1>\n        )}\n\n        {hasToolbar && (\n          <div className=\"ml-auto flex items-center gap-2\">\n            {/* Acciones dropdown */}\n            {hasActionsItems && (\n              <div className=\"relative\" ref={dropdownRef}>\n                <motion.button\n                  type=\"button\"\n                  onClick={() => setActionsDropdownOpen((v) => !v)}\n                  data-testid=\"custom-toolbar-actions-dropdown-button\"\n                  aria-haspopup=\"menu\"\n                  aria-expanded={actionsDropdownOpen}\n                  title={t('moreOptions', 'Más opciones')}\n                  whileHover={{ scale: 1.1 }}\n                  whileTap={{ scale: 0.92 }}\n                  transition={{ type: 'spring', bounce: 0.55, duration: 0.4 }}\n                  className=\"inline-flex items-center justify-center w-9 h-9 rounded-md border bg-background-secondary dark:bg-dark-bg-secondary border-border-primary dark:border-dark-border-primary text-content-tertiary dark:text-dark-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                >\n                  <EllipsisVerticalIcon className=\"w-4 h-4\" />\n                </motion.button>\n\n                {actionsDropdownOpen && (\n                  <div className=\"absolute right-0 top-full mt-1 bg-bg-primary dark:bg-dark-bg-primary rounded-md border border-border-primary dark:border-dark-border-primary shadow-md z-50 w-64 py-1\">\n                    {renderActionsMenuItems(ctx)}\n                  </div>\n                )}\n              </div>\n            )}\n\n            {/* Custom toolbar buttons (right of Acciones) */}\n            {renderToolbarActions?.(ctx)}\n\n            {/* Declarative save button */}\n            {hasSaveButton && (\n              <button\n                type=\"button\"\n                onClick={() => void handleCustomSave()}\n                disabled={customSave!.disabled || isSaving}\n                data-testid=\"custom-save-button\"\n                className=\"inline-flex items-center gap-2 px-3 h-9 rounded-md text-sm font-bold cursor-pointer transition-all bg-[#0e79fd] text-white hover:bg-[#0c6be0] disabled:opacity-50\"\n              >\n                {isSaving\n                  ? (customSave!.savingLabel ?? t('saving', 'Guardando…'))\n                  : (customSave!.label ?? t('save', 'Guardar'))}\n              </button>\n            )}\n          </div>\n        )}\n      </div>\n\n      {/* Company selector — shown based on showCompanySelector (default: true when companyBehavior !== 'NONE') */}\n      {displayCompanySelector && (\n        <div className=\"px-5 pb-2 pt-2\">\n          <CompanySelector\n            companies={companies}\n            activeCompanyId={activeCompanyContext ?? undefined}\n            showGlobalOption={companyBehavior === 'GLOBAL'}\n            onCompanyChange={(company) => ctx.setCompanyId(company.id)}\n          />\n        </div>\n      )}\n\n      <div className=\"flex-1 min-h-0 flex flex-col gap-2.5 px-5 pb-5 pt-3\">\n        {renderBody?.(ctx)}\n      </div>\n    </div>\n  );\n}\n\n/**\n * MasterPatternView — complete master data management component.\n *\n * @example\n * ```tsx\n * const ref = useRef<MasterPatternViewRef>(null);\n *\n * <MasterPatternView\n *   ref={ref}\n *   definition={currencyDefinition}\n *   service={currencyService}\n *   title=\"Monedas\"\n *   entityName=\"Moneda\"\n * />\n * ```\n */\nexport const MasterPatternView = forwardRef(function MasterPatternViewWrapper<\n  T extends MasterPatternViewEntity,\n>(\n  props: MasterPatternViewProps<T>,\n  ref: React.ForwardedRef<MasterPatternViewRef>,\n) {\n  // When cacheKey is provided, create an isolated QueryClient per key value.\n  // Prevents cache contamination when two MPV instances share the same entityName\n  // (e.g., a child entity list nested inside a parent MPV's detailTab).\n  // When omitted, falls back to the shared module-level client — zero behavior change.\n  const instanceClient = React.useMemo(\n    () => (props.cacheKey ? new QueryClient() : null),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [props.cacheKey],\n  );\n\n  return (\n    <QueryClientProvider client={instanceClient ?? queryClient}>\n      {MasterPatternViewInner<T>(props, ref)}\n    </QueryClientProvider>\n  );\n}) as <T extends MasterPatternViewEntity>(\n  props: MasterPatternViewProps<T> & { ref?: React.ForwardedRef<MasterPatternViewRef> }\n) => React.ReactElement | null;\n","import React from 'react';\nimport {\n  PencilIcon as HeroPencilIcon,\n  TrashIcon as HeroTrashIcon,\n  PlusIcon as HeroPlusIcon,\n  MagnifyingGlassIcon as HeroMagnifyingGlassIcon,\n  XMarkIcon as HeroXMarkIcon,\n  ArrowLeftIcon as HeroArrowLeftIcon,\n  FunnelIcon as HeroFunnelIcon,\n  ChevronDownIcon as HeroChevronDownIcon,\n  Squares2X2Icon as HeroSquares2X2Icon,\n  ListBulletIcon as HeroListBulletIcon,\n  CalendarIcon as HeroCalendarIcon,\n  EllipsisHorizontalIcon as HeroEllipsisHorizontalIcon,\n  BarsArrowUpIcon as HeroBarsArrowUpIcon,\n  BarsArrowDownIcon as HeroBarsArrowDownIcon,\n  AdjustmentsHorizontalIcon as HeroAdjustmentsHorizontalIcon,\n  ChevronRightIcon as HeroChevronRightIcon,\n  Bars3Icon as HeroBars3Icon,\n  CheckIcon as HeroCheckIcon,\n  GlobeAltIcon as HeroGlobeAltIcon,\n  LinkIcon as HeroLinkIcon,\n  ArrowPathIcon as HeroArrowPathIcon,\n  ArrowUturnLeftIcon as HeroArrowUturnLeftIcon,\n  ExclamationCircleIcon as HeroExclamationCircleIcon,\n  BuildingOffice2Icon as HeroBuildingOffice2Icon,\n  ComputerDesktopIcon as HeroComputerDesktopIcon,\n  DocumentMagnifyingGlassIcon as HeroDocumentMagnifyingGlassIcon,\n  DocumentArrowDownIcon as HeroDocumentArrowDownIcon,\n  MinusCircleIcon as HeroMinusCircleIcon,\n  CheckCircleIcon as HeroCheckCircleIcon,\n  ClockIcon as HeroClockIcon,\n  EllipsisVerticalIcon as HeroEllipsisVerticalIcon,\n  NoSymbolIcon as HeroNoSymbolIcon,\n} from '@heroicons/react/24/outline';\n\n/**\n * Iconos para el componente MasterCrud\n * Basados en Heroicons 24/outline\n *\n * @see docs/icons.md - Sistema de iconos\n */\n\n/** Icono de círculo con menos (Desactivar) */\nexport const MinusCircleIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroMinusCircleIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de círculo con check (Activar) */\nexport const CheckCircleIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroCheckCircleIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de documento con lupa (Auditoría) */\nexport const DocumentMagnifyingGlassIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroDocumentMagnifyingGlassIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de documento con flecha abajo (Descargar) */\nexport const DocumentArrowDownIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroDocumentArrowDownIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de monitor / escritorio */\nexport const ComputerDesktopIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroComputerDesktopIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de advertencia en círculo */\nexport const ExclamationCircleIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroExclamationCircleIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de edificio / oficina */\nexport const BuildingOffice2Icon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroBuildingOffice2Icon className={className} aria-hidden=\"true\" />\n);\n\n/**\n * Icono compuesto \"Habilitar en compañía\": edificio azul + check verde (prototipo).\n * Es el mismo icono que usa el botón de acción \"Habilitar por compañía\" del listado;\n * se comparte con el modal de habilitación para unificar el lenguaje visual.\n *\n * @param className Controla el tamaño del contenedor (por defecto 18×18).\n */\nexport const EnableCompanyIcon: React.FC<{ className?: string }> = ({ className = 'w-[18px] h-[18px]' }) => (\n  <span className={`relative inline-flex ${className}`}>\n    <svg className=\"w-full h-full text-primary-600 dark:text-primary-400\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" viewBox=\"0 0 24 24\" aria-hidden=\"true\">\n      <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M3.75 21h16.5M4.5 3.75h9a.75.75 0 0 1 .75.75V21M4.5 3.75V21M13.5 21V9.75l6 3v8.25M8.25 6.75h.008v.008H8.25V6.75Zm3 0h.008v.008h-.008V6.75Zm-3 3h.008v.008H8.25V9.75Zm3 0h.008v.008h-.008V9.75Zm-3 3h.008v.008H8.25v-.008Zm3 0h.008v.008h-.008v-.008Z\" />\n    </svg>\n    <span className=\"absolute -bottom-1 -right-1 bg-white dark:bg-dark-bg-primary rounded-sm p-px\">\n      <svg className=\"w-2.5 h-2.5 text-green-600\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\" viewBox=\"0 0 24 24\" aria-hidden=\"true\">\n        <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M4.5 12.75l6 6 9-13.5\" />\n      </svg>\n    </span>\n  </span>\n);\n\n/** Icono de deshacer / revertir */\nexport const RevertIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroArrowUturnLeftIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de revertir / rotar */\nexport const ArrowPathIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroArrowPathIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de enlace (link) */\nexport const LinkIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroLinkIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de globo terráqueo */\nexport const GlobeAltIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroGlobeAltIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de verificación (check) */\nexport const CheckIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroCheckIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de hamburguesa (3 rayas) */\nexport const Bars3Icon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroBars3Icon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de ajustes/filtros horizontales */\nexport const AdjustmentsIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroAdjustmentsHorizontalIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de flecha a la derecha */\nexport const ChevronRightIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroChevronRightIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de lápiz para editar */\nexport const PencilIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroPencilIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de papelera para eliminar */\nexport const TrashIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroTrashIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de más para crear */\nexport const PlusIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroPlusIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de lupa para buscar */\nexport const SearchIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroMagnifyingGlassIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de X para cerrar/cancelar */\nexport const CloseIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroXMarkIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de flecha izquierda para volver */\nexport const BackIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroArrowLeftIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de embudo para filtrar */\nexport const FilterIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroFunnelIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Alias de FilterIcon */\nexport const FunnelIcon = FilterIcon;\n\n/** Icono de chevron abajo para dropdowns */\nexport const ChevronDownIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroChevronDownIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de grid (cuadrícula 2x2) */\nexport const GridIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroSquares2X2Icon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de lista */\nexport const ListIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroListBulletIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de calendario */\nexport const CalendarIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroCalendarIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de elipsis horizontal (puntos suspensivos) */\nexport const EllipsisHorizontalIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroEllipsisHorizontalIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de drag handle (6 puntos) */\nexport const DragHandleIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg \n    viewBox=\"0 0 20 20\" \n    fill=\"currentColor\" \n    className={className}\n    aria-hidden=\"true\"\n  >\n    <path d=\"M7 4a1 1 0 100-2 1 1 0 000 2zM13 4a1 1 0 100-2 1 1 0 000 2zM7 11a1 1 0 100-2 1 1 0 000 2zM13 11a1 1 0 100-2 1 1 0 000 2zM7 18a1 1 0 100-2 1 1 0 000 2zM13 18a1 1 0 100-2 1 1 0 000 2z\" />\n  </svg>\n);\n\n/** Icono de orden ascendente */\nexport const SortAscIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroBarsArrowUpIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de orden descendente */\nexport const SortDescIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroBarsArrowDownIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de reloj para historial de auditoría */\nexport const ClockIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroClockIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de puntos verticales (kebab vertical — \"Más acciones/opciones\") */\nexport const EllipsisVerticalIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroEllipsisVerticalIcon className={className} aria-hidden=\"true\" />\n);\n\n/** Icono de símbolo prohibido (Desactivar) */\nexport const NoSymbolIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <HeroNoSymbolIcon className={className} aria-hidden=\"true\" />\n);\n","import React, { useState, useRef, useLayoutEffect, useEffect } from 'react';\nimport { createPortal } from 'react-dom';\nimport { Table } from '../Table/Table';\nimport { Checkbox } from '../Checkbox/Checkbox';\nimport type { TableColumn } from '../Table/Table.types';\nimport type { MasterCrudTableProps, MasterCrudField, MasterCrudAction } from './MasterCrud.types';\nimport { EllipsisVerticalIcon, EnableCompanyIcon } from './icons';\n\n/** Badge de estado por compañía (multicompañía): habilitado / no habilitado (prototipo N9). */\nconst CompanyStatusBadge: React.FC<{ enabled: boolean; enabledLabel: string; notEnabledLabel: string }> = ({ enabled, enabledLabel, notEnabledLabel }) => {\n  if (enabled) {\n    return (\n      <span title={enabledLabel} className=\"inline-flex items-center justify-center w-7 h-7 rounded-full bg-[#dbeefe] dark:bg-primary-900/20 text-primary-600 dark:text-primary-500 relative\">\n        <svg className=\"w-[17px] h-[17px]\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z\" /><path d=\"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2\" /><path d=\"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2\" /><path d=\"M10 6h4\" /><path d=\"M10 10h4\" /></svg>\n        <span className=\"absolute -bottom-0.5 -right-0.5 bg-white dark:bg-dark-bg-primary rounded-full leading-none p-px\">\n          <svg className=\"w-2.5 h-2.5 text-green-600\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"3\" viewBox=\"0 0 24 24\"><path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M4.5 12.75l6 6 9-13.5\" /></svg>\n        </span>\n      </span>\n    );\n  }\n  return (\n    <span title={notEnabledLabel} className=\"inline-flex items-center justify-center w-7 h-7 rounded-full border border-dashed border-border-primary dark:border-dark-border-primary text-content-secondary\">\n      <svg className=\"w-[17px] h-[17px]\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z\" /><path d=\"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2\" /><path d=\"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2\" /><path d=\"M10 6h4\" /><path d=\"M10 10h4\" /></svg>\n    </span>\n  );\n};\n\n// Estilo pixel-exact de los botones de acción de fila (borde azul de marca #93d1fd).\nconst ROW_ACTION_BTN =\n  'inline-flex items-center justify-center w-7 h-7 bg-white dark:bg-dark-bg-primary border border-[#93d1fd] dark:border-primary-800 text-primary-600 dark:text-primary-500 rounded-md shadow-[0_1px_2px_rgba(0,0,0,0.04)] hover:bg-[#eff8ff] dark:hover:bg-primary-900/20 transition-all disabled:opacity-40 disabled:cursor-not-allowed';\n\n/** Chevron de orden (asc/desc/sin orden) del prototipo. */\nconst SortChevron: React.FC<{ state: 'asc' | 'desc' | null }> = ({ state }) => {\n  if (state === 'asc') return (\n    <svg className=\"w-3 h-3 text-primary-600 shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m18 15-6-6-6 6\" /></svg>\n  );\n  if (state === 'desc') return (\n    <svg className=\"w-3 h-3 text-primary-600 shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m6 9 6 6 6-6\" /></svg>\n  );\n  return (\n    <svg className=\"w-3 h-3 text-[#d4d4d8] shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m7 15 5 5 5-5\" /><path d=\"m7 9 5-5 5 5\" /></svg>\n  );\n};\n\ninterface ColumnFilterHeaderProps {\n  title: string;\n  field: string;\n  sortable: boolean;\n  sortState: 'asc' | 'desc' | null;\n  onSort: () => void;\n  filterable: boolean;\n  isEnum: boolean;\n  enumOptions?: { value: string; label: string }[];\n  value: string;\n  onChange: (value: string, operator: 'contains' | 'equals') => void;\n  t: (key: string, defaultValue?: string) => string;\n}\n\n/** Cabecera de columna con orden + embudo de filtro inline (prototipo L2/N4). */\nconst ColumnFilterHeader: React.FC<ColumnFilterHeaderProps> = ({\n  title, sortable, sortState, onSort, filterable, isEnum, enumOptions = [], value, onChange, t,\n}) => {\n  const [open, setOpen] = useState(!!value);\n  const [text, setText] = useState(value || '');\n  const active = !!value;\n\n  // Debounce 350ms para el input de texto (no dispara una petición por tecla).\n  useEffect(() => {\n    if (isEnum) return;\n    const id = window.setTimeout(() => {\n      if (text !== value) onChange(text, 'contains');\n    }, 350);\n    return () => window.clearTimeout(id);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [text]);\n\n  const controlClasses = 'w-full min-w-0 h-[26px] box-border border border-border-primary dark:border-dark-border-primary rounded-[5px] px-1.5 text-[11px] text-content-primary dark:text-dark-content-primary bg-white dark:bg-dark-bg-primary outline-none focus:border-[#93d1fd] focus:ring-2 focus:ring-primary-500/10 transition-colors';\n\n  return (\n    <div className=\"flex flex-col gap-1 w-full\">\n      <div\n        className={`flex items-center justify-between w-full gap-1 min-h-[28px] select-none ${sortable ? 'cursor-pointer' : ''}`}\n        onClick={sortable ? onSort : undefined}\n      >\n        <span className=\"text-sm font-semibold truncate min-w-0 text-content-primary dark:text-dark-content-primary\">{title}</span>\n        <span className=\"flex items-center gap-0.5 flex-shrink-0\">\n          {filterable && (\n            <button\n              type=\"button\"\n              aria-expanded={open}\n              title={open ? t('hideFilter', 'Ocultar filtro') : `${t('filter', 'Filtrar')} ${title}`}\n              aria-label={open ? t('hideFilter', 'Ocultar filtro') : `${t('filter', 'Filtrar')} ${title}`}\n              onClick={(e) => { e.stopPropagation(); setOpen((v) => !v); }}\n              className={`inline-flex items-center justify-center p-0.5 rounded transition-colors hover:bg-[#eff8ff] dark:hover:bg-primary-900/20 ${\n                open || active\n                  ? 'text-primary-600 hover:text-primary-600'\n                  : 'text-content-secondary hover:text-primary-600'\n              }`}\n            >\n              <svg className=\"w-3 h-3\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><polygon points=\"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3\" /></svg>\n            </button>\n          )}\n          {sortable && <SortChevron state={sortState} />}\n        </span>\n      </div>\n      {filterable && open && (\n        <div onClick={(e) => e.stopPropagation()}>\n          {isEnum ? (\n            <select\n              className={`${controlClasses} cursor-pointer`}\n              value={value}\n              onChange={(e) => onChange(e.target.value, 'equals')}\n            >\n              <option value=\"\">{t('all', 'Todos')}</option>\n              {enumOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}\n            </select>\n          ) : (\n            <input\n              type=\"text\"\n              size={1}\n              autoComplete=\"off\"\n              placeholder={`${t('filter', 'Filtrar')}...`}\n              className={controlClasses}\n              value={text}\n              onChange={(e) => setText(e.target.value)}\n            />\n          )}\n        </div>\n      )}\n    </div>\n  );\n};\n\ninterface RowActionsCellProps<T> {\n  row: T;\n  index: number;\n  directActions: MasterCrudAction<T>[];\n  menuActions: MasterCrudAction<T>[];\n  rowActions?: (row: T, index: number) => React.ReactNode;\n  t: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * Celda de acciones de fila (prototipo N7): hasta 2 botones directos + kebab vertical.\n * El menú del kebab se renderiza en document.body (portal) y se posiciona con `fixed`\n * para que aparezca SOBRE la tabla (la celda sticky + overflow-auto lo recortarían).\n */\nfunction RowActionsCell<T>({ row, index, directActions, menuActions, rowActions, t }: RowActionsCellProps<T>) {\n  const [open, setOpen] = useState(false);\n  const btnRef = useRef<HTMLButtonElement>(null);\n  const menuRef = useRef<HTMLDivElement>(null);\n  const [pos, setPos] = useState<{ top: number; left: number }>({ top: -9999, left: -9999 });\n\n  const reposition = React.useCallback(() => {\n    const btn = btnRef.current;\n    const menu = menuRef.current;\n    if (!btn) return;\n    const r = btn.getBoundingClientRect();\n    const mw = menu?.offsetWidth || 210;\n    const mh = menu?.offsetHeight || 0;\n    let top = r.bottom + 4;\n    if (mh && top + mh > window.innerHeight - 8) top = r.top - mh - 4; // abrir hacia arriba si no cabe\n    const left = Math.max(8, r.right - mw);\n    setPos({ top, left });\n  }, []);\n\n  useLayoutEffect(() => {\n    if (open) reposition();\n  }, [open, reposition]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onDocClick = (e: MouseEvent) => {\n      if (menuRef.current?.contains(e.target as Node) || btnRef.current?.contains(e.target as Node)) return;\n      setOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };\n    const onScroll = () => setOpen(false);\n    document.addEventListener('click', onDocClick);\n    document.addEventListener('keydown', onKey);\n    window.addEventListener('resize', onScroll);\n    // scroll en cualquier contenedor (captura) cierra el menú\n    document.addEventListener('scroll', onScroll, true);\n    return () => {\n      document.removeEventListener('click', onDocClick);\n      document.removeEventListener('keydown', onKey);\n      window.removeEventListener('resize', onScroll);\n      document.removeEventListener('scroll', onScroll, true);\n    };\n  }, [open]);\n\n  const renderIcon = (action: MasterCrudAction<T>) => {\n    if (action.id === 'link') return <EnableCompanyIcon />;\n    const icon = typeof action.icon === 'function' ? action.icon(row) : action.icon;\n    return <span className=\"w-[15px] h-[15px] inline-flex items-center justify-center\">{icon}</span>;\n  };\n\n  return (\n    <div className=\"flex items-center justify-center gap-3\">\n      {rowActions && rowActions(row, index)}\n\n      {directActions.map((action) => {\n        const name = typeof action.name === 'function' ? action.name(row) : action.name;\n        const disabled = typeof action.disabled === 'function' ? action.disabled(row) : action.disabled;\n        return (\n          <button\n            key={action.id || name}\n            type=\"button\"\n            title={name}\n            aria-label={name}\n            disabled={disabled}\n            onClick={() => action.action?.(row)}\n            className={ROW_ACTION_BTN}\n          >\n            {renderIcon(action)}\n          </button>\n        );\n      })}\n\n      {menuActions.length > 0 && (\n        <>\n          <button\n            ref={btnRef}\n            type=\"button\"\n            title={t('moreActions', 'Más acciones')}\n            aria-label={t('moreActions', 'Más acciones')}\n            aria-haspopup=\"menu\"\n            aria-expanded={open}\n            onClick={() => setOpen((v) => !v)}\n            className={ROW_ACTION_BTN}\n          >\n            <EllipsisVerticalIcon className=\"w-[15px] h-[15px]\" />\n          </button>\n          {open && createPortal(\n            <div\n              ref={menuRef}\n              role=\"menu\"\n              style={{ position: 'fixed', top: pos.top, left: pos.left }}\n              className=\"z-[60] min-w-[210px] bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-md shadow-md py-1\"\n            >\n              {menuActions.map((action) => {\n                const name = typeof action.name === 'function' ? action.name(row) : action.name;\n                const icon = typeof action.icon === 'function' ? action.icon(row) : action.icon;\n                const disabled = typeof action.disabled === 'function' ? action.disabled(row) : action.disabled;\n                const isDelete = action.id === 'delete' || name.toLowerCase().includes('eliminar') || name.toLowerCase().includes('desactivar');\n                return (\n                  <button\n                    key={action.id || name}\n                    type=\"button\"\n                    role=\"menuitem\"\n                    disabled={disabled}\n                    onClick={() => { action.action?.(row); setOpen(false); }}\n                    className={`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors disabled:opacity-40 ${isDelete ? 'text-error-content hover:bg-error/10' : 'text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'}`}\n                  >\n                    {icon && <span className=\"w-4 h-4 flex-shrink-0 inline-flex items-center justify-center\">{icon}</span>}\n                    <span>{name}</span>\n                  </button>\n                );\n              })}\n            </div>,\n            document.body,\n          )}\n        </>\n      )}\n    </div>\n  );\n}\n\n/**\n * MasterCrudTable - Adaptador de tabla para MasterCrud\n */\nexport const MasterCrudTable = <T extends Record<string, any>>({\n  fields,\n  data,\n  loading = false,\n  emptyMessage,\n  onSort,\n  sortColumn,\n  sortDirection,\n  pagination,\n  showRowActions = true,\n  actions = [],\n  rowActions,\n  className = '',\n  locale = 'es',\n  enableMultiSelect = false,\n  selectedIds = [],\n  onSelectionChange,\n  stickyHeader = false,\n  columnFilterableFields,\n  columnFilters = {},\n  onColumnFilterChange,\n  showCompanyStatusColumn = false,\n  isRecordCompanyEnabled,\n  onCompanyStatusClick,\n  t,\n}: MasterCrudTableProps<T>) => {\n  const finalEmptyMessage = emptyMessage || t('empty', 'No hay registros disponibles');\n\n  // Orden controlado por el padre (MasterCrud): ciclo sin orden → asc → desc.\n  const handleColumnSort = (field: string) => {\n    if (!onSort) return;\n    const next = sortColumn !== field ? 'asc' : sortDirection === 'asc' ? 'desc' : sortDirection === 'desc' ? null : 'asc';\n    onSort(field, next);\n  };\n\n  // Opciones de enum para el filtro por columna (boolean / select).\n  const enumOptionsFor = (field: MasterCrudField<T>): { value: string; label: string }[] | null => {\n    if (field.type === 'boolean') {\n      return [\n        { value: 'true', label: field.config?.trueLabel || t('active', 'Activo') },\n        { value: 'false', label: field.config?.falseLabel || t('inactive', 'Inactivo') },\n      ];\n    }\n    if (field.type === 'select' && field.options?.length) {\n      return field.options.map((o) => ({ value: String(o.value), label: o.label }));\n    }\n    return null;\n  };\n\n  // ===== CONVERTIR FIELDS A COLUMNS =====\n  const columns: TableColumn<T>[] = fields\n    .filter((field) => {\n      if (field.config?.showInList !== undefined) return field.config.showInList;\n      if (field.config?.visibleInTable !== undefined) return field.config.visibleInTable;\n      return true;\n    })\n    .map((field) => {\n      const accessorKey = field.accessorKey as string;\n      const title = t(accessorKey, field.header);\n      const sortable = field.config?.sortable ?? false;\n      const filterable = !!columnFilterableFields?.includes(accessorKey) && !!onColumnFilterChange && field.type !== 'lookup';\n      const enumOptions = enumOptionsFor(field);\n      const useRawHeader = sortable || filterable;\n\n      return {\n        header: useRawHeader ? (\n          <ColumnFilterHeader\n            title={title}\n            field={accessorKey}\n            sortable={sortable}\n            sortState={sortColumn === accessorKey ? (sortDirection ?? null) : null}\n            onSort={() => handleColumnSort(accessorKey)}\n            filterable={filterable}\n            isEnum={!!enumOptions}\n            enumOptions={enumOptions || undefined}\n            value={columnFilters[accessorKey] ?? ''}\n            onChange={(value, operator) => onColumnFilterChange?.(accessorKey, value, operator)}\n            t={t}\n          />\n        ) : title,\n        headerRaw: useRawHeader,\n        accessor: field.accessorKey as keyof T,\n        sortable,\n        align: field.config?.align ?? 'left',\n        width: field.config?.columnWidth,\n        render: field.renderCell\n          ? (value: any, row: T, index: number) => field.renderCell!(value, row, index)\n          : (value: any) => renderCellByType(value, field),\n      };\n    });\n\n  // ===== AGREGAR COLUMNA DE SELECCIÓN =====\n  if (enableMultiSelect) {\n    columns.unshift({\n      header: (\n        <Checkbox\n          checked={data.length > 0 && selectedIds.length === data.length}\n          onChange={(e) => {\n            if (e.target.checked) {\n              onSelectionChange?.(data.map((r: any) => r.id || r.Id || r.codigo));\n            } else {\n              onSelectionChange?.([]);\n            }\n          }}\n          aria-label={t('selectAll', 'Seleccionar todos')}\n        />\n      ),\n      accessor: (() => null) as any,\n      align: 'center',\n      width: '100px', // Aumentado para visibilidad completa\n      fixedWidth: true,\n      render: (_: any, row: T) => {\n        const id = row.id || row.Id || row.codigo;\n        const isSelected = selectedIds.includes(id);\n        return (\n          <div className=\"flex justify-center items-center\">\n            <Checkbox\n              checked={isSelected}\n              onChange={(e) => {\n                if (e.target.checked) {\n                  onSelectionChange?.([...selectedIds, id]);\n                } else {\n                  onSelectionChange?.(selectedIds.filter(item => item !== id));\n                }\n              }}\n              aria-label={t('selectRecord', 'Seleccionar registro')}\n            />\n          </div>\n        );\n      },\n    });\n  }\n\n  // ===== COLUMNA DE ESTADO POR COMPAÑÍA (multicompañía, primera columna) =====\n  if (showCompanyStatusColumn) {\n    columns.unshift({\n      header: (\n        <span className=\"inline-flex items-center justify-center text-content-secondary\" title={t('companyStatus', 'Habilitación en la compañía seleccionada')}>\n          <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z\" /><path d=\"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2\" /><path d=\"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2\" /><path d=\"M10 6h4\" /><path d=\"M10 10h4\" /><path d=\"M10 14h4\" /><path d=\"M10 18h4\" /></svg>\n        </span>\n      ),\n      accessor: (() => null) as any,\n      align: 'center',\n      width: '46px',\n      fixedWidth: true,\n      render: (_: any, row: T) => {\n        const enabled = isRecordCompanyEnabled ? isRecordCompanyEnabled(row) : true;\n        const badge = (\n          <CompanyStatusBadge\n            enabled={enabled}\n            enabledLabel={t('enabledInCompany', 'Habilitado en la compañía seleccionada')}\n            notEnabledLabel={t('notEnabledInCompany', 'No habilitado en la compañía seleccionada')}\n          />\n        );\n        return onCompanyStatusClick ? (\n          <button type=\"button\" onClick={() => onCompanyStatusClick(row)} className=\"inline-flex\">{badge}</button>\n        ) : badge;\n      },\n    });\n  }\n\n  // ===== AGREGAR COLUMNA DE ACCIONES =====\n  if (showRowActions) {\n    columns.push({\n      header: t('actions', 'Acciones'),\n      accessor: (() => null) as any,\n      align: 'center',\n      stickyRight: true,\n      // Ancho JUSTO para 3 botones con separación táctil (3×28px + 2×12px de gap = 108px\n      // + 32px de padding de celda = 140px). `fixedWidth` evita que la columna se expanda:\n      // nunca es más ancha de lo necesario.\n      width: '140px',\n      fixedWidth: true,\n      render: (_: any, row: T, index: number) => {\n        // Regla de acciones por registro (máx. 3 botones):\n        // - Hasta 3 acciones visibles: se muestran TODAS de frente (sin kebab).\n        // - 4 o más: 2 directas + botón \"Más acciones\" (kebab) completando 3; el resto\n        //   (a partir de la 3ª) va dentro del desplegable del kebab.\n        // Se filtra por visibilidad ANTES de repartir para no \"gastar\" un slot.\n        const isVisible = (action: MasterCrudAction<T>) =>\n          typeof action.visible === 'function' ? action.visible(row) : action.visible !== false;\n\n        const visibleActions = actions.filter(isVisible);\n        const MAX_DIRECT = 3;\n\n        let directActions: MasterCrudAction<T>[];\n        let menuActions: MasterCrudAction<T>[];\n        if (visibleActions.length <= MAX_DIRECT) {\n          directActions = visibleActions;\n          menuActions = [];\n        } else {\n          // Prioriza Editar (edit) + Habilitar (link) como directas; si no existen, toma las 2 primeras.\n          const priority = visibleActions.filter((a) => a.id && ['edit', 'link'].includes(a.id)).slice(0, 2);\n          const fill = priority.length < 2\n            ? visibleActions.filter((a) => !priority.includes(a)).slice(0, 2 - priority.length)\n            : [];\n          directActions = [...priority, ...fill];\n          menuActions = visibleActions.filter((a) => !directActions.includes(a));\n        }\n\n        return (\n          <RowActionsCell\n            row={row}\n            index={index}\n            directActions={directActions}\n            menuActions={menuActions}\n            rowActions={rowActions}\n            t={t}\n          />\n        );\n      },\n    });\n  }\n\n  const renderCellByType = (value: any, field: MasterCrudField<T>): React.ReactNode => {\n    if (value === null || value === undefined) return <span className=\"text-content-tertiary dark:text-content-tertiary\">—</span>;\n    switch (field.type) {\n      case 'boolean': {\n        const trueLabel = field.config?.trueLabel || t('active', 'Activo');\n        const falseLabel = field.config?.falseLabel || t('inactive', 'Inactivo');\n        return (\n          <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold ${value ? 'bg-[#ecfccb] text-[#4d7c0f] dark:bg-lime-900/30 dark:text-lime-400' : 'bg-background-secondary text-content-tertiary dark:bg-dark-bg-secondary dark:text-dark-content-tertiary'}`}>\n            {value ? trueLabel : falseLabel}\n          </span>\n        );\n      }\n      case 'date': try { return new Date(value).toLocaleDateString(locale, { year: 'numeric', month: '2-digit', day: '2-digit' }); } catch { return String(value); }\n      case 'number': return <span className=\"tabular-nums\">{typeof value === 'number' ? value.toLocaleString(locale) : value}</span>;\n      case 'select': return field.options?.find((opt) => opt.value === value)?.label ?? String(value);\n      case 'email': return <a href={`mailto:${value}`} className=\"text-primary-600 hover:underline dark:text-primary-600\">{value}</a>;\n      case 'lookup': if (field.lookupConfig && typeof value === 'object' && value !== null) { return field.lookupConfig.displayFields.map(k => (value as any)[k]).filter(v => v !== undefined && v !== null).join(' - ') || String(value); } return String(value);\n      default: return String(value);\n    }\n  };\n\n  const handleSort = (column: keyof T | string, direction: 'asc' | 'desc' | null) => { if (onSort) onSort(String(column), direction); };\n\n  return (\n    <Table\n      columns={columns} data={data} loading={loading} emptyMessage={finalEmptyMessage}\n      variant=\"basic\" showBorder={false} showShadow={false} showPadding={false} fullWidth\n      stickyHeader={stickyHeader} accentHover dense\n      onSort={handleSort} sortColumn={sortColumn} sortDirection={sortDirection}\n      pagination={pagination} className={`${className} !bg-transparent !shadow-none !rounded-none !p-0`}\n      isRowSelected={(row) => {\n        const id = row.id || row.Id || row.codigo;\n        return selectedIds.includes(id);\n      }}\n    />\n  );\n};\n","import type { Fetcher, SearchRequest, SearchResponse } from './api.types'\nimport { ApiError } from './api.types'\n\nconst DEFAULT_HEADERS: Record<string, string> = {\n  'Content-Type': 'application/json',\n}\n\n/**\n * Creates a standard fetcher function for a given base URL.\n * Use this helper for simple cases where you just need to specify the API base URL.\n *\n * @param baseUrl - Base URL for the API (e.g., '/api', 'https://api.example.com')\n * @returns A fetcher function compatible with LookupField\n *\n * @example\n * // Simple usage\n * const fetcher = createFetcher('/api')\n * <LookupField entity=\"customers\" fetcher={fetcher} />\n *\n * @example\n * // With authentication - wrap createFetcher or create custom fetcher\n * const fetcher = createFetcher('/api', {\n *   headers: { Authorization: `Bearer ${token}` }\n * })\n */\nexport function createFetcher(\n  baseUrl: string,\n  options?: { headers?: Record<string, string> }\n): Fetcher {\n  const headers = { ...DEFAULT_HEADERS, ...options?.headers }\n\n  return async <TRecord>(\n    entity: string,\n    request: SearchRequest\n  ): Promise<SearchResponse<TRecord>> => {\n    const url = `${baseUrl}/${entity}/search`\n\n    // Ensure 'Id' is always included in fields (FR20) - PascalCase standard\n    const fields = request.fields.includes('Id') ? request.fields : ['Id', ...request.fields]\n\n    const response = await fetch(url, {\n      method: 'POST',\n      headers,\n      body: JSON.stringify({ ...request, fields }),\n    })\n\n    if (!response.ok) {\n      throw new ApiError(\n        `API Error: ${response.status} ${response.statusText}`,\n        response.status,\n        response.statusText\n      )\n    }\n\n    return response.json()\n  }\n}\n","import React, { useEffect, useRef, useState } from 'react';\nimport { ChevronDownIcon, GlobeAltIcon, BuildingOffice2Icon, CheckIcon } from './icons';\nimport type { MasterCrudCompany } from './MasterCrud.types';\n\ninterface CompanySelectorProps {\n  companies: MasterCrudCompany[];\n  selectedCompany?: MasterCrudCompany;\n  onCompanyChange: (company: MasterCrudCompany, ...args: any[]) => void;\n  className?: string;\n  disabled?: boolean;\n  /**\n   * Cuando es true, la compañía se muestra como etiqueta estática (sin interacción).\n   * Se usa cuando companyRequired=true en MasterCrud: no existe habilitación ni cambio\n   * de contexto posible, por lo que un comboBox no aplica.\n   * Renderiza un <span> (no un <button>) para que no sea posible habilitarlo desde devtools.\n   */\n  readOnly?: boolean;\n  /**\n   * Mapa opcional uuid → habilitado. Cuando se provee, cada opción de compañía muestra\n   * su estado de habilitación (check verde \"Habilitado\" / círculo hueco \"No habilitado\").\n   * Usado en la página de detalle multicompañía (sobrescritura).\n   */\n  companyEnabledMap?: Record<string, boolean>;\n  /** Función de traducción inyectada por el padre */\n  t: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * CompanySelector - Combobox de contexto de compañía para MasterCrud.\n *\n * Diseño alineado al prototipo (azul de marca): trigger `bg-[#eff8ff]` con borde\n * `#93d1fd`, icono Globe/Building2 + ChevronDown; dropdown con opción Global,\n * divisor y compañías (nombre + código), check azul en la opción activa.\n */\nexport const CompanySelector: React.FC<CompanySelectorProps> = ({\n  companies,\n  selectedCompany,\n  onCompanyChange,\n  className = '',\n  disabled = false,\n  readOnly = false,\n  companyEnabledMap,\n  t,\n}) => {\n  const [open, setOpen] = useState(false);\n  const rootRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    if (!open) return;\n    const onDocClick = (e: MouseEvent) => {\n      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };\n    document.addEventListener('mousedown', onDocClick);\n    document.addEventListener('keydown', onKey);\n    return () => {\n      document.removeEventListener('mousedown', onDocClick);\n      document.removeEventListener('keydown', onKey);\n    };\n  }, [open]);\n\n  if (!companies.length) return null;\n\n  const isGlobal = !selectedCompany || String(selectedCompany.uuid) === '000';\n  const ContextIcon = isGlobal ? GlobeAltIcon : BuildingOffice2Icon;\n\n  const companyLabel = selectedCompany?.name\n    || (companies.length > 0 ? t('loading', 'Cargando...') : t('selectCompany', 'Seleccionar Compañía'));\n\n  // Trigger azul de marca (tokens del prototipo → clases del kit con dark:)\n  const triggerClasses = [\n    'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold leading-none select-none transition-colors',\n    'bg-[#eff8ff] dark:bg-primary-900/20 border border-[#93d1fd] dark:border-primary-800 text-[#1355b7] dark:text-primary-300',\n    disabled\n      ? 'opacity-60 cursor-not-allowed'\n      : 'cursor-pointer hover:bg-[#dbeefe] dark:hover:bg-primary-900/40 hover:border-[#3c9bf6]',\n  ].join(' ');\n\n  const iconClasses = 'w-3.5 h-3.5 flex-shrink-0';\n\n  // ── Modo solo lectura (companyRequired=true en la página de edición) ──────\n  // <span> en lugar de <button> para que no exista ningún control interactivo.\n  if (readOnly) {\n    return (\n      <div className={`relative inline-block ${className}`}>\n        <span className={triggerClasses.replace('cursor-pointer', '').replace(/hover:[^\\s]+/g, '')}>\n          <ContextIcon className={iconClasses} aria-hidden=\"true\" />\n          <span className=\"max-w-[180px] truncate\" title={companyLabel}>{companyLabel}</span>\n        </span>\n      </div>\n    );\n  }\n\n  const renderOption = (company: MasterCrudCompany) => {\n    const optIsGlobal = String(company.uuid) === '000';\n    const OptIcon = optIsGlobal ? GlobeAltIcon : BuildingOffice2Icon;\n    const active = selectedCompany?.uuid === company.uuid || (isGlobal && optIsGlobal);\n    const enabled = companyEnabledMap ? companyEnabledMap[String(company.uuid)] : undefined;\n\n    return (\n      <button\n        key={company.uuid}\n        type=\"button\"\n        role=\"menuitem\"\n        onClick={() => { onCompanyChange(company); setOpen(false); }}\n        className=\"w-full flex items-center gap-2 px-3 py-2 text-xs text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n      >\n        <span className=\"w-3 flex-shrink-0 text-[#0e79fd]\">\n          {active && <CheckIcon className=\"w-3 h-3\" />}\n        </span>\n        <span className=\"flex-shrink-0 text-[#1355b7] dark:text-primary-300\">\n          <OptIcon className=\"w-3.5 h-3.5\" />\n        </span>\n        <span className=\"font-medium truncate min-w-0\" title={company.name}>{company.name}</span>\n        <span className=\"ml-auto flex items-center gap-2 flex-shrink-0\">\n          {!optIsGlobal && company.code != null && (\n            <span className=\"text-content-secondary tabular-nums\">{company.code}</span>\n          )}\n          {!optIsGlobal && enabled !== undefined && (\n            enabled ? (\n              <span className=\"inline-flex items-center gap-1 text-[11px] font-semibold text-[#4d7c0f]\">\n                <CheckIcon className=\"w-3 h-3\" />{t('enabled', 'Habilitado')}\n              </span>\n            ) : (\n              <span className=\"inline-flex items-center gap-1 text-[11px] font-medium text-content-secondary\">\n                <span className=\"inline-block w-3 h-3 rounded-full border border-current\" />{t('notEnabled', 'No habilitado')}\n              </span>\n            )\n          )}\n          {optIsGlobal && companyEnabledMap && (\n            <span className=\"text-[11px] text-content-secondary\">{t('masterRecord', 'Registro maestro')}</span>\n          )}\n        </span>\n      </button>\n    );\n  };\n\n  const globalCompanies = companies.filter((c) => String(c.uuid) === '000');\n  const realCompanies = companies.filter((c) => String(c.uuid) !== '000');\n  const wideDropdown = !!companyEnabledMap;\n\n  return (\n    <div className={`relative inline-block ${className}`} ref={rootRef}>\n      <button\n        type=\"button\"\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        disabled={disabled}\n        onClick={() => setOpen((v) => !v)}\n        className={triggerClasses}\n      >\n        <span className=\"flex-shrink-0\"><ContextIcon className={iconClasses} /></span>\n        <span className=\"max-w-[180px] truncate\" title={companyLabel}>{companyLabel}</span>\n        <ChevronDownIcon className={`w-3 h-3 flex-shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />\n      </button>\n\n      {open && (\n        <div\n          role=\"menu\"\n          className={`absolute left-0 top-full mt-1 z-50 ${wideDropdown ? 'min-w-[360px] max-w-[440px]' : 'min-w-[280px] max-w-[380px]'} bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-lg shadow-md py-1`}\n        >\n          {globalCompanies.map(renderOption)}\n          {globalCompanies.length > 0 && realCompanies.length > 0 && (\n            <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n          )}\n          {realCompanies.map(renderOption)}\n        </div>\n      )}\n    </div>\n  );\n};\n","import type { DynamicEntityDefinition, RuleConditionType, RuleActionType } from '../types/DynamicEntity.types';\n\nexport interface RuleEffects {\n    hiddenFields: Set<string>;\n    disabledFields: Set<string>;\n    requiredFields: Set<string>;\n}\n\nexport class RuleEngine {\n    static evaluate(definition: DynamicEntityDefinition, values: Record<string, any>): RuleEffects {\n        const effects: RuleEffects = {\n            hiddenFields: new Set(),\n            disabledFields: new Set(),\n            requiredFields: new Set()\n        };\n\n        if (!definition.rules || definition.rules.length === 0) {\n            return effects;\n        }\n\n        // Map fields by ID for easy lookup\n        const fieldsById = new Map(definition.fields.map(f => [f.id, f]));\n\n        definition.rules.forEach(rule => {\n            const triggerField = fieldsById.get(rule.dependsOnFieldId);\n\n            // Note: RuleEngine logic depends on Trigger Field existing.\n            if (!triggerField) return;\n\n            const triggerValue = values[triggerField.code];\n            const isConditionMet = this.checkCondition(triggerValue, rule.condition, rule.value);\n\n            if (isConditionMet) {\n                const targetField = fieldsById.get(rule.dynamicFieldId);\n                if (targetField) {\n                    this.applyAction(effects, rule.action, targetField.code);\n                }\n            } else {\n                const targetField = fieldsById.get(rule.dynamicFieldId);\n                if (targetField) {\n                    this.applyReverseAction(effects, rule.action, targetField.code);\n                }\n            }\n        });\n\n        return effects;\n    }\n\n    private static checkCondition(actualValue: any, condition: RuleConditionType, ruleValue: string | null): boolean {\n        const strActual = String(actualValue || '');\n        const strRule = String(ruleValue || '');\n\n        switch (condition) {\n            case 'Equals':\n                return strActual === strRule;\n            case 'NotEquals':\n                return strActual !== strRule;\n            case 'In':\n            case 'Contains' as any:\n                return strActual.includes(strRule);\n            case 'Greater':\n            case 'GreaterThan' as any:\n                return Number(actualValue) > Number(ruleValue);\n            case 'Less':\n            case 'LessThan' as any:\n                return Number(actualValue) < Number(ruleValue);\n            default:\n                return false;\n        }\n    }\n\n    private static applyAction(effects: RuleEffects, action: RuleActionType, targetFieldCode: string) {\n        switch (action) {\n            case 'Hide':\n                effects.hiddenFields.add(targetFieldCode);\n                break;\n            case 'Show':\n                effects.hiddenFields.delete(targetFieldCode);\n                break;\n            case 'Disable':\n                effects.disabledFields.add(targetFieldCode);\n                break;\n            case 'Enable':\n                effects.disabledFields.delete(targetFieldCode);\n                break;\n            case 'Require':\n                effects.requiredFields.add(targetFieldCode);\n                break;\n        }\n    }\n\n    private static applyReverseAction(effects: RuleEffects, action: RuleActionType, targetFieldCode: string) {\n        switch (action) {\n            case 'Show':\n                effects.hiddenFields.add(targetFieldCode);\n                break;\n            case 'Hide':\n                effects.hiddenFields.delete(targetFieldCode);\n                break;\n            case 'Enable':\n                effects.disabledFields.add(targetFieldCode);\n                break;\n            case 'Disable':\n                effects.disabledFields.delete(targetFieldCode);\n                break;\n            case 'Require':\n                effects.requiredFields.delete(targetFieldCode);\n                break;\n        }\n    }\n}\n","/**\n * Transporte HTTP inyectable para todo el módulo DynamicEntities.\n *\n * El kit no sabe nada de autenticación: la app anfitriona inyecta su propio\n * `fetch` (ya con `Authorization`, `X-Company-Id`, `Accept-Language`, tracing o\n * reintentos) a través de `DynamicEntitiesProvider`. Si no se inyecta ninguno se\n * usa el `fetch` global y el comportamiento es idéntico al de siempre.\n */\nexport type DynamicEntitiesFetcher = typeof fetch;\n\n/**\n * Normaliza el transporte para poder guardarlo como propiedad de una clase o de\n * un objeto.\n *\n * Envolverlo no es cosmético: `this.http(url)` invocaría el `fetch` global con\n * la instancia como receptor y los navegadores lanzan `Illegal invocation`\n * cuando `fetch` pierde su `window`. La arrow function lo llama siempre como\n * función suelta, que es lo que tanto el `fetch` nativo como cualquier fetcher\n * del anfitrión esperan.\n */\nexport const resolveFetcher = (fetcher?: DynamicEntitiesFetcher): DynamicEntitiesFetcher =>\n    fetcher\n        ? (input, init) => fetcher(input, init)\n        : (input, init) => fetch(input, init);\n","/**\n * Error de transporte del módulo, con el código HTTP a la vista.\n *\n * Sin el `status` no se puede distinguir \"este registro todavía no existe\" (404,\n * esperable al abrir un formulario nuevo) de \"no estás autenticado\" (401), y los\n * dos terminaban silenciados por el mismo `catch`.\n */\nexport class DynamicEntitiesHttpError extends Error {\n    readonly status: number;\n    readonly statusText: string;\n    readonly url: string;\n\n    constructor(message: string, response: { status: number; statusText: string; url?: string }) {\n        super(message);\n        this.name = 'DynamicEntitiesHttpError';\n        this.status = response.status;\n        this.statusText = response.statusText;\n        this.url = response.url ?? '';\n    }\n}\n\nexport const isDynamicEntitiesHttpError = (error: unknown): error is DynamicEntitiesHttpError =>\n    error instanceof DynamicEntitiesHttpError;\n","import type { DynamicEntityDefinition, SaveEavValuesDto } from '../types/DynamicEntity.types';\nimport type { DynamicEntitiesFetcher } from './fetcher';\nimport { resolveFetcher } from './fetcher';\nimport { DynamicEntitiesHttpError } from './DynamicEntitiesHttpError';\n\nexport interface DynamicEntitiesApiOptions {\n    baseUrl: string;\n    /** Transporte del anfitrión. Ausente → `fetch` global. */\n    fetcher?: DynamicEntitiesFetcher;\n}\n\nexport interface DynamicEntitiesApiClient {\n    getDefinition(featureCode: string, entityCode: string): Promise<DynamicEntityDefinition>;\n    saveValues(\n        featureCode: string,\n        entityCode: string,\n        recordId: string,\n        values: SaveEavValuesDto,\n        idEntityMultiple?: string\n    ): Promise<void>;\n    getValues(\n        featureCode: string,\n        entityCode: string,\n        recordId: string,\n        idEntityMultiple?: string\n    ): Promise<SaveEavValuesDto>;\n    deleteRecord(featureCode: string, recordId: string, idEntityMultiple?: string): Promise<void>;\n    getMultipleRecords(\n        featureCode: string,\n        entityCode: string,\n        recordId: string\n    ): Promise<SaveEavValuesDto[]>;\n}\n\n/**\n * Construye el cliente EAV del módulo con un `baseUrl` y un transporte fijos.\n *\n * Preferir esta factory sobre el objeto `DynamicEntitiesApi`: aquí el transporte\n * viaja con el cliente, así que no hay forma de hacer una petición sin las\n * cabeceras del anfitrión.\n */\nexport function createDynamicEntitiesApi({ baseUrl, fetcher }: DynamicEntitiesApiOptions): DynamicEntitiesApiClient {\n    const http = resolveFetcher(fetcher);\n\n    const valuesUrl = (featureCode: string, entityCode: string, recordId: string, idEntityMultiple?: string) =>\n        idEntityMultiple\n            ? `${baseUrl}/ea/${featureCode}/${entityCode}/${recordId}/${idEntityMultiple}`\n            : `${baseUrl}/ea/${featureCode}/${entityCode}/${recordId}`;\n\n    return {\n        async getDefinition(featureCode, entityCode) {\n            const url = `${baseUrl}/dynamic-entities/definition?featureCode=${featureCode}&entityCode=${entityCode}`;\n            const response = await http(url);\n            if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch definition: ${response.status} ${response.statusText}`, response);\n            return response.json();\n        },\n\n        async saveValues(featureCode, entityCode, recordId, values, idEntityMultiple) {\n            const response = await http(valuesUrl(featureCode, entityCode, recordId, idEntityMultiple), {\n                method: 'POST',\n                headers: { 'Content-Type': 'application/json' },\n                body: JSON.stringify(values)\n            });\n            if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to save values: ${response.status} ${response.statusText}`, response);\n        },\n\n        async getValues(featureCode, entityCode, recordId, idEntityMultiple) {\n            const response = await http(valuesUrl(featureCode, entityCode, recordId, idEntityMultiple));\n            if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch values: ${response.status} ${response.statusText}`, response);\n            return response.json();\n        },\n\n        async deleteRecord(featureCode, recordId, idEntityMultiple) {\n            const url = idEntityMultiple\n                ? `${baseUrl}/ea/${featureCode}/${recordId}/${idEntityMultiple}`\n                : `${baseUrl}/ea/${featureCode}/${recordId}`;\n            const response = await http(url, { method: 'DELETE' });\n            if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to delete record: ${response.status} ${response.statusText}`, response);\n        },\n\n        async getMultipleRecords(featureCode, entityCode, recordId) {\n            const response = await http(`${baseUrl}/ea/${featureCode}/${entityCode}/${recordId}/multiple`);\n            if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch records: ${response.status} ${response.statusText}`, response);\n            return response.json();\n        }\n    };\n}\n\n/**\n * Fachada histórica que recibe el `baseUrl` en cada llamada.\n *\n * @deprecated Usar {@link createDynamicEntitiesApi} —o el hook\n * `useDynamicEntitiesApi`, que ya lo cablea con el contexto—. Se mantiene para no\n * romper a quien la importe: acepta el mismo `baseUrl` posicional y un `fetcher`\n * opcional al final de cada firma.\n */\nexport const DynamicEntitiesApi = {\n    getDefinition: (\n        baseUrl: string,\n        featureCode: string,\n        entityCode: string,\n        fetcher?: DynamicEntitiesFetcher\n    ): Promise<DynamicEntityDefinition> =>\n        createDynamicEntitiesApi({ baseUrl, fetcher }).getDefinition(featureCode, entityCode),\n\n    saveValues: (\n        baseUrl: string,\n        featureCode: string,\n        entityCode: string,\n        recordId: string,\n        values: SaveEavValuesDto,\n        idEntityMultiple?: string,\n        fetcher?: DynamicEntitiesFetcher\n    ): Promise<void> =>\n        createDynamicEntitiesApi({ baseUrl, fetcher })\n            .saveValues(featureCode, entityCode, recordId, values, idEntityMultiple),\n\n    getValues: (\n        baseUrl: string,\n        featureCode: string,\n        entityCode: string,\n        recordId: string,\n        idEntityMultiple?: string,\n        fetcher?: DynamicEntitiesFetcher\n    ): Promise<SaveEavValuesDto> =>\n        createDynamicEntitiesApi({ baseUrl, fetcher })\n            .getValues(featureCode, entityCode, recordId, idEntityMultiple),\n\n    deleteRecord: (\n        baseUrl: string,\n        featureCode: string,\n        recordId: string,\n        idEntityMultiple?: string,\n        fetcher?: DynamicEntitiesFetcher\n    ): Promise<void> =>\n        createDynamicEntitiesApi({ baseUrl, fetcher })\n            .deleteRecord(featureCode, recordId, idEntityMultiple),\n\n    getMultipleRecords: (\n        baseUrl: string,\n        featureCode: string,\n        entityCode: string,\n        recordId: string,\n        fetcher?: DynamicEntitiesFetcher\n    ): Promise<SaveEavValuesDto[]> =>\n        createDynamicEntitiesApi({ baseUrl, fetcher })\n            .getMultipleRecords(featureCode, entityCode, recordId)\n};\n","import React, { createContext, useContext, useMemo, useRef } from 'react';\nimport type { DynamicEntitiesFetcher } from './api/fetcher';\nimport { resolveFetcher } from './api/fetcher';\n\n/**\n * Permisos de escritura del usuario sobre el módulo. Cualquier flag ausente se\n * interpreta como permitido, de modo que un anfitrión que no los pase ve la UI\n * completa igual que siempre.\n */\nexport interface DynamicEntitiesPermissions {\n    canCreate?: boolean;\n    canUpdate?: boolean;\n    canDelete?: boolean;\n}\n\n/** Los mismos permisos ya resueltos: sin `undefined`, listos para renderizar. */\nexport type ResolvedDynamicEntitiesPermissions = Required<DynamicEntitiesPermissions>;\n\nexport interface DynamicEntitiesContextType {\n    baseUrl: string;\n    onError?: (error: Error) => void;\n    /**\n     * Reemplaza el `fetch` global en TODAS las peticiones del módulo. El\n     * anfitrión lo usa para añadir `Authorization`, `X-Company-Id`,\n     * `Accept-Language`, tracing o reintentos.\n     *\n     * Ausente → se usa el `fetch` global (comportamiento previo, sin cambios).\n     *\n     * Se inyecta el transporte y no un `token` a propósito: el kit no debe saber\n     * nada de autenticación, y un callback vivo no caduca a media sesión como sí\n     * lo haría una cabecera fotografiada en el mount.\n     */\n    fetcher?: DynamicEntitiesFetcher;\n    /**\n     * Oculta las acciones de escritura que el usuario no puede ejecutar. Sin\n     * esta prop se muestran todas.\n     */\n    permissions?: DynamicEntitiesPermissions;\n}\n\nexport const DynamicEntitiesContext = createContext<DynamicEntitiesContextType | undefined>(undefined);\n\nexport interface DynamicEntitiesProviderProps {\n    baseUrl: string;\n    onError?: (error: Error) => void;\n    /** Ver {@link DynamicEntitiesContextType.fetcher}. */\n    fetcher?: DynamicEntitiesFetcher;\n    /** Ver {@link DynamicEntitiesContextType.permissions}. */\n    permissions?: DynamicEntitiesPermissions;\n    children: React.ReactNode;\n}\n\nexport const DynamicEntitiesProvider: React.FC<DynamicEntitiesProviderProps> = ({\n    baseUrl,\n    onError,\n    fetcher,\n    permissions,\n    children\n}) => {\n    // El anfitrión casi siempre pasa estas props como literales inline\n    // (`fetcher={(url, init) => ...}`, `permissions={{ ... }}`), que cambian de\n    // identidad en cada render. Aguas abajo alimentan `useMemo`/`useEffect` que\n    // disparan peticiones, así que se estabilizan aquí: sin esto un arrow inline\n    // provocaría un bucle de fetch. La ref siempre apunta al último valor, de\n    // modo que un token rotado se usa en la siguiente petición.\n    const latestRef = useRef({ fetcher, onError });\n    latestRef.current = { fetcher, onError };\n\n    const stableFetcher = useMemo<DynamicEntitiesFetcher>(\n        () => (input, init) => {\n            const current = latestRef.current.fetcher;\n            return current ? current(input, init) : fetch(input, init);\n        },\n        []\n    );\n\n    const stableOnError = useMemo<(error: Error) => void>(\n        () => (error: Error) => { latestRef.current.onError?.(error); },\n        []\n    );\n\n    const { canCreate, canUpdate, canDelete } = permissions ?? {};\n    const stablePermissions = useMemo<DynamicEntitiesPermissions>(\n        () => ({ canCreate, canUpdate, canDelete }),\n        [canCreate, canUpdate, canDelete]\n    );\n\n    const value = useMemo<DynamicEntitiesContextType>(\n        () => ({\n            baseUrl,\n            onError: stableOnError,\n            fetcher: stableFetcher,\n            permissions: stablePermissions\n        }),\n        [baseUrl, stableOnError, stableFetcher, stablePermissions]\n    );\n\n    return (\n        <DynamicEntitiesContext.Provider value={value}>\n            {children}\n        </DynamicEntitiesContext.Provider>\n    );\n};\n\nexport const useDynamicEntitiesContext = (): DynamicEntitiesContextType => {\n    const context = useContext(DynamicEntitiesContext);\n    if (!context) {\n        throw new Error('useDynamicEntitiesContext must be used within a DynamicEntitiesProvider');\n    }\n    return context;\n};\n\nexport const useOptionalDynamicEntitiesContext = (): DynamicEntitiesContextType | undefined => {\n    return useContext(DynamicEntitiesContext);\n};\n\n/**\n * Transporte HTTP ya normalizado. Funciona sin provider (cae al `fetch` global)\n * para los componentes que se pueden montar sueltos.\n */\nexport const useDynamicEntitiesFetcher = (): DynamicEntitiesFetcher => {\n    const context = useContext(DynamicEntitiesContext);\n    const fetcher = context?.fetcher;\n    return useMemo(() => resolveFetcher(fetcher), [fetcher]);\n};\n\n/**\n * Permisos resueltos. Sin provider —o sin la prop— devuelve todo en `true`, que\n * es el comportamiento histórico del módulo.\n */\nexport const useDynamicEntitiesPermissions = (): ResolvedDynamicEntitiesPermissions => {\n    const context = useContext(DynamicEntitiesContext);\n    const permissions = context?.permissions;\n\n    return useMemo(() => ({\n        canCreate: permissions?.canCreate ?? true,\n        canUpdate: permissions?.canUpdate ?? true,\n        canDelete: permissions?.canDelete ?? true,\n    }), [permissions?.canCreate, permissions?.canUpdate, permissions?.canDelete]);\n};\n","import { useMemo } from 'react';\nimport { createDynamicEntitiesApi } from '../api/DynamicEntitiesApi';\nimport type { DynamicEntitiesApiClient } from '../api/DynamicEntitiesApi';\nimport { useDynamicEntitiesContext } from '../DynamicEntitiesProvider';\n\n/**\n * Cliente EAV ya cableado con el `baseUrl` y el transporte del provider.\n *\n * Es el único punto por el que deberían pasar los componentes: evita que alguien\n * vuelva a construir una petición sin las cabeceras del anfitrión.\n */\nexport const useDynamicEntitiesApi = (): DynamicEntitiesApiClient => {\n    const { baseUrl, fetcher } = useDynamicEntitiesContext();\n    return useMemo(() => createDynamicEntitiesApi({ baseUrl, fetcher }), [baseUrl, fetcher]);\n};\n","import { useState, useEffect } from 'react';\nimport type { DynamicEntityDefinition } from '../types/DynamicEntity.types';\nimport { useDynamicEntitiesApi } from './useDynamicEntitiesApi';\nimport { useDynamicEntitiesContext } from '../DynamicEntitiesProvider';\n\ninterface UseDynamicDefinitionResult {\n    definition: DynamicEntityDefinition | null;\n    loading: boolean;\n    error: Error | null;\n    reload: () => void;\n}\n\nexport const useDynamicDefinition = (featureCode: string, entityCode: string): UseDynamicDefinitionResult => {\n    const { onError } = useDynamicEntitiesContext();\n    const api = useDynamicEntitiesApi();\n    const [definition, setDefinition] = useState<DynamicEntityDefinition | null>(null);\n    const [loading, setLoading] = useState<boolean>(true);\n    const [error, setError] = useState<Error | null>(null);\n    const [trigger, setTrigger] = useState(0);\n\n    useEffect(() => {\n        let mounted = true;\n        setLoading(true);\n        setError(null);\n\n        api.getDefinition(featureCode, entityCode)\n            .then(data => {\n                if (mounted) {\n                    setDefinition(data);\n                    setLoading(false);\n                }\n            })\n            .catch(err => {\n                if (mounted) {\n                    setError(err);\n                    setLoading(false);\n                    if (onError) onError(err);\n                }\n            });\n\n        return () => {\n            mounted = false;\n        };\n    }, [api, featureCode, entityCode, trigger, onError]);\n\n    const reload = () => setTrigger(prev => prev + 1);\n\n    return { definition, loading, error, reload };\n};\n","export const DynamicFieldType = {\n    Text: 'Text',\n    TextArea: 'TextArea',\n    NumberInteger: 'NumberInteger',\n    NumberDecimal: 'NumberDecimal',\n    Currency: 'Currency',\n    Date: 'Date',\n    Time: 'Time',\n    DateTime: 'DateTime',\n    Checkbox: 'Checkbox',\n    Select: 'Select',\n    Radio: 'Radio',\n    Multiselect: 'Multiselect',\n    Lookup: 'Lookup',\n    Switch: 'Switch',\n    GenericEntity: 'GenericEntity'\n} as const;\n\nexport type DynamicFieldType = (typeof DynamicFieldType)[keyof typeof DynamicFieldType];\n\nexport interface DynamicField {\n    id: string;\n    code: string;\n    type: DynamicFieldType;\n    labels: Record<string, string>; // i18n\n\n    order: number;\n    required: boolean;\n    readonly: boolean;\n    disabled: boolean;\n    visible: boolean;\n    isUnique: boolean;\n\n    regex?: string;\n    mask?: string;\n    minValue?: number;\n    maxValue?: number;\n\n    defaultText?: string;\n    defaultNumeric?: number;\n    defaultDate?: string; // ISO\n\n    genericListId?: string;\n    genericEntityId?: string;\n\n    layouts?: DynamicFieldLayout[];\n}\n\nexport interface DynamicFieldLayout {\n    id?: string;\n    dynamicFieldId?: string;\n    colSpan: number;\n    rowSpan: number;\n    colStart: number;\n    rowStart: number;\n    breakpoint: string;\n}\n","import React from 'react';\nimport type { DynamicField } from '../core/types/DynamicField.types';\nimport { DynamicFieldType } from '../core/types/DynamicField.types';\nimport { Input } from '../../Input/Input';\nimport { Select } from '../../Select/Select';\nimport { Textarea } from '../../Textarea/Textarea';\nimport { Checkbox } from '../../Checkbox/Checkbox';\nimport { Switch } from '../../Switch/Switch';\nimport { RadioGroup, RadioGroupItem } from '../../Radio/Radio';\nimport { LookupField } from '../../LookupField';\nimport { useOptionalDynamicEntitiesContext, useDynamicEntitiesFetcher } from '../core/DynamicEntitiesProvider';\n\n/**\n * Interpreta como booleano lo que llega del backend para un Checkbox o un Switch.\n *\n * 🔴 Antes era `!!value`, y por eso el control se veía ENCENDIDO con el valor `false`: la API\n * entrega el booleano ya convertido a cadena —`\"False\"` con mayúscula, que es el `bool.ToString()`\n * de .NET— y en JavaScript toda cadena no vacía es truthy. `!!\"False\" === true`. El dato viajaba\n * bien de punta a punta; lo único que mentía era el pintado.\n *\n * El `onChange` de ambos controles SÍ emite un booleano de verdad, así que el componente vive en dos\n * formatos: emite `boolean`, recibe `string`. Se normaliza al leer, que es el lado roto.\n */\nconst asBoolean = (value: unknown): boolean => {\n    if (typeof value === 'boolean') return value;\n    if (typeof value === 'string') {\n        const normalized = value.trim().toLowerCase();\n        // '' y cualquier texto que no sea afirmativo cuentan como apagado: un control de dos\n        // estados no puede quedarse sin estado.\n        return normalized === 'true' || normalized === '1';\n    }\n    if (typeof value === 'number') return value !== 0;\n    return false;\n};\n\n// We need a way to resolved generic lists. \n// For now, let's assume options are passed or we have a hook to fetching them.\n// The Definition has \"lists\", so the parent Grid/Renderer should pass the list options.\n\ninterface DynamicFieldRendererProps {\n    field: DynamicField;\n    value: any;\n    onChange: (value: any) => void;\n    error?: string;\n    options?: { label: string; value: string | number }[]; // For Select/Radio\n}\n\nexport const DynamicFieldRenderer: React.FC<DynamicFieldRendererProps> = ({\n    field,\n    value,\n    onChange,\n    error,\n    options = []\n}) => {\n    const ctx = useOptionalDynamicEntitiesContext();\n    // baseUrl ya termina en /api; la API v1 cuelga del mismo prefijo (${baseUrl}/v1/...).\n    // No extraemos el origin para soportar baseUrl relativo (modo MFE detrás del shell).\n    const baseUrl = ctx?.baseUrl ?? '';\n    const http = useDynamicEntitiesFetcher();\n\n    const commonProps = {\n        id: field.code,\n        label: field.labels['es'] || field.code, // Fallback to ES or code\n        disabled: field.disabled || field.readonly,\n        required: field.required,\n        error: !!error,\n    };\n\n    switch (field.type) {\n        case DynamicFieldType.Text:\n            return (\n                <Input\n                    {...commonProps}\n                    inputSize=\"sm\"\n                    value={value || ''}\n                    onChange={(e) => onChange(e.target.value)}\n                />\n            );\n\n        case DynamicFieldType.TextArea:\n            return (\n                <Textarea\n                    {...commonProps}\n                    value={value || ''}\n                    onChange={(e) => onChange(e.target.value)}\n                />\n            );\n\n        case DynamicFieldType.NumberInteger:\n        case DynamicFieldType.NumberDecimal:\n        case DynamicFieldType.Currency:\n            return (\n                <Input\n                    {...commonProps}\n                    type=\"number\"\n                    inputSize=\"sm\"\n                    value={value || ''}\n                    onChange={(e) => onChange(e.target.value)}\n                />\n            );\n\n        case DynamicFieldType.Date:\n            // Input type=\"date\" expects strictly \"YYYY-MM-DD\"\n            const dateValue = value ? new Date(value).toISOString().split('T')[0] : '';\n            return (\n                <Input\n                    {...commonProps}\n                    type=\"date\"\n                    inputSize=\"sm\"\n                    value={dateValue}\n                    onChange={(e) => onChange(e.target.value)}\n                />\n            );\n\n        case DynamicFieldType.Time:\n            // Input type=\"time\" expects \"HH:mm\" or \"HH:mm:ss\"\n            const timeValue = value && value.includes('T')\n                ? value.split('T')[1].slice(0, 5)\n                : (value?.slice(0, 5) || '');\n            return (\n                <Input\n                    {...commonProps}\n                    type=\"time\"\n                    inputSize=\"sm\"\n                    value={timeValue}\n                    onChange={(e) => onChange(e.target.value)}\n                />\n            );\n\n        case DynamicFieldType.DateTime:\n            // Input type=\"datetime-local\" expects \"YYYY-MM-DDTHH:mm\"\n            const dateTimeValue = value ? new Date(value).toISOString().slice(0, 16) : '';\n            return (\n                <Input\n                    {...commonProps}\n                    type=\"datetime-local\"\n                    inputSize=\"sm\"\n                    value={dateTimeValue}\n                    onChange={(e) => onChange(e.target.value)}\n                />\n            );\n\n        case DynamicFieldType.Select:\n        case DynamicFieldType.Multiselect: // Added Multiselect support\n            return (\n                <Select\n                    {...commonProps}\n                    options={options}\n                    value={value}\n                    onChange={(val) => onChange(val)}\n                    placeholder={options.length === 0 ? \"Sin opciones disponibles\" : \"Seleccionar...\"}\n                    disabled={commonProps.disabled || options.length === 0}\n                    selectSize=\"sm\"\n                />\n            );\n\n        case DynamicFieldType.Checkbox:\n            const { error: cbError, ...cbProps } = commonProps;\n            return (\n                <div className=\"mb-4\">\n                    <Checkbox\n                        {...cbProps}\n                        checked={asBoolean(value)}\n                        onChange={(e) => onChange((e.target as HTMLInputElement).checked)}\n                    />\n                    {cbError && error && (\n                        <p className=\"text-sm leading-5 text-error-content mt-1\">{error}</p>\n                    )}\n                </div>\n            );\n\n        case DynamicFieldType.Switch:\n            const { error: swError, ...swProps } = commonProps;\n            return (\n                <div className=\"mb-4\">\n                    <Switch\n                        {...swProps}\n                        checked={asBoolean(value)}\n                        onCheckedChange={(checked) => onChange(checked)}\n                    />\n                    {swError && error && (\n                        <p className=\"text-sm leading-5 text-error-content mt-1\">{error}</p>\n                    )}\n                </div>\n            );\n\n        case DynamicFieldType.Radio:\n            const { error: rdError, ...rdProps } = commonProps;\n            return (\n                <div className=\"mb-4\">\n                    <label className=\"font-bold text-sm leading-5 text-content-primary mb-2 block\">\n                        {commonProps.label}\n                    </label>\n                    {options.length > 0 ? (\n                        <RadioGroup\n                            value={value !== undefined && value !== null ? String(value) : undefined}\n                            onValueChange={(val) => onChange(val)}\n                            disabled={rdProps.disabled}\n                            className=\"flex flex-wrap gap-4\"\n                        >\n                            {options.map(opt => (\n                                <RadioGroupItem\n                                    key={String(opt.value)}\n                                    value={String(opt.value)}\n                                    label={opt.label}\n                                    id={`${field.code}-${opt.value}`}\n                                />\n                            ))}\n                        </RadioGroup>\n                    ) : (\n                        <div className=\"text-sm text-gray-400 italic bg-gray-50 p-2 rounded border border-dashed\">\n                            Sin opciones configuradas (asociar catálogo)\n                        </div>\n                    )}\n                    {rdError && error && (\n                        <p className=\"text-sm leading-5 text-error-content mt-1\">{error}</p>\n                    )}\n                </div>\n            );\n\n        case DynamicFieldType.GenericEntity:\n            const { error: geError, ...geProps } = commonProps;\n            // Since field.genericEntityId points to the entity definition ID, we need to pass it\n            // Wait, we only have the genericEntityId, not the CODE. So we must use a search that filters by GenericEntityID.\n            // Oh right, the /items/search endpoint searches across all items. We MUST add a filter for the specific GenericEntityID!\n            return (\n                <div className=\"mb-4\">\n                    {field.genericEntityId ? (\n                        <LookupField\n                            {...geProps}\n                            entity=\"generic-entities/items\"\n                            displayFields={['Code', 'Value']}\n                            value={value || null}\n                            onChange={(record) => onChange(record?.Id || null)}\n                            fetcher={async (entity, request) => {\n                                // FilterExpression semántica: outer = AND, inner = OR.\n                                // Cada condición forzada va en su PROPIO grupo externo para\n                                // garantizar AND entre ellas. Ponerlas en un mismo inner array\n                                // las convertiría en OR, lo que permitiría que IsDeleted=false\n                                // o IsActive=true devuelva ítems de cualquier entidad.\n                                const baseFilters = [\n                                    [{ GenericEntityID: field.genericEntityId }], // AND: solo esta entidad\n                                    [{ IsDeleted: false }],                        // AND: no eliminados\n                                    [{ IsActive: true }],                          // AND: solo activos\n                                ];\n\n                                // Mapear 'Id' → 'ID' en los filtros que trae el LookupField\n                                const mappedRequestFilters = (request.filters ?? []).map(group =>\n                                    group.map(cond => {\n                                        const mappedCond: any = {};\n                                        for (const key in cond) {\n                                            mappedCond[key === 'Id' ? 'ID' : key] = cond[key as keyof typeof cond];\n                                        }\n                                        return mappedCond;\n                                    })\n                                );\n\n                                const mappedRequest = {\n                                    ...request,\n                                    fields: request.fields.filter(f => f !== 'Id').concat('ID'),\n                                    searchFields: request.searchFields?.map(f => f === 'Id' ? 'ID' : f),\n                                    filters: [...baseFilters, ...mappedRequestFilters]\n                                };\n\n                                const res = await http(`${baseUrl}/v1/generic-entities/items/search`, {\n                                    method: 'POST',\n                                    headers: { 'Content-Type': 'application/json' },\n                                    body: JSON.stringify(mappedRequest)\n                                });\n\n                                if (!res.ok) throw new Error('Error fetching generic entity items');\n                                const data = await res.json();\n\n                                // 2. Map `ID` back to `Id` for LookupField compatibility\n                                return {\n                                    ...data,\n                                    data: data.data.map((item: any) => ({\n                                        ...item,\n                                        Id: item.ID\n                                    }))\n                                };\n                            }}\n                        />\n                    ) : (\n                        <div className=\"text-sm text-orange-600 bg-orange-50 p-2 rounded border border-orange-200\">\n                            ⚠️ Este campo no tiene una Entidad Genérica asignada en su configuración.\n                        </div>\n                    )}\n                    {geError && error && (\n                        <p className=\"text-sm leading-5 text-error-content mt-1\">{error}</p>\n                    )}\n                </div>\n            );\n\n        default:\n            return <div className=\"text-gray-400\">Tipo de campo no soportado: {field.type}</div>;\n    }\n};\n","import React, { useState, useEffect, useMemo, useRef, useImperativeHandle } from 'react';\nimport { RuleEngine } from '../core/logic/RuleEngine';\nimport type { RuleEffects } from '../core/logic/RuleEngine';\nimport { useDynamicDefinition } from '../core/hooks/useDynamicDefinition';\nimport { DynamicFieldRenderer } from './DynamicFieldRenderer';\nimport { useDynamicEntitiesApi } from '../core/hooks/useDynamicEntitiesApi';\nimport { isDynamicEntitiesHttpError } from '../core/api/DynamicEntitiesHttpError';\nimport { useDynamicEntitiesContext } from '../core/DynamicEntitiesProvider';\nimport { DynamicFieldType } from '../core/types/DynamicField.types';\nimport type { DynamicField } from '../core/types/DynamicField.types';\n\n\nexport interface DynamicEntitiesProps {\n    featureCode: string;\n    entityCode: string;\n    recordId?: string;\n    idEntityMultiple?: string;\n    onSaved?: () => void;\n    className?: string;\n    hideSubmitButton?: boolean;\n    hideTitle?: boolean;\n    /**\n     * Avisa si la entidad tiene algo que pintar, en cuanto resuelve su definición y cada vez que\n     * las reglas cambian qué campos son visibles.\n     *\n     * Existe para que el ANFITRIÓN pueda esconder su propio marco. Una entidad recién creada a la\n     * que todavía no le pusieron campos devuelve una definición válida con `fields: []`, y sin este\n     * aviso el anfitrión dibujaba una tarjeta con título y nada dentro. La definición se pide aquí\n     * de todos modos, así que enterarse por este camino no cuesta una petición extra — resolverlo\n     * en el anfitrión sí la costaría, porque `useDynamicDefinition` no cachea.\n     */\n    onRenderableChange?: (renderable: boolean) => void;\n}\n\nexport interface DynamicEntitiesRef {\n    save: (overrideRecordId?: string) => Promise<boolean>;\n}\n\n/**\n * Rellena con `false` los interruptores y casillas que no traen valor.\n *\n * Un interruptor apagado ES un valor, no una ausencia. El formulario solo envía las claves que\n * tiene en estado, así que guardar un registro sin tocar el campo no escribía ninguna fila: el\n * maestro se quedaba sin el dato, y filtrar «igual a No» no encontraba ese registro hasta que\n * alguien lo encendía y lo apagaba. Los demás tipos no llevan valor por omisión —un texto vacío no\n * es un dato— y por eso solo se siembran estos dos.\n *\n * Nunca pisa una clave existente: al editar, lo que llega del servidor manda.\n */\nconst withBooleanDefaults = (\n    fields: DynamicField[] | undefined,\n    values: Record<string, any>,\n): Record<string, any> => {\n    const seeded = { ...values };\n\n    (fields ?? []).forEach(field => {\n        const isBoolean =\n            field.type === DynamicFieldType.Checkbox || field.type === DynamicFieldType.Switch;\n\n        if (isBoolean && field.visible && seeded[field.code] === undefined) {\n            seeded[field.code] = false;\n        }\n    });\n\n    return seeded;\n};\n\nexport const DynamicEntities = React.forwardRef<DynamicEntitiesRef, DynamicEntitiesProps>(({\n    featureCode,\n    entityCode,\n    recordId,\n    idEntityMultiple,\n    onSaved,\n    className,\n    hideSubmitButton,\n    hideTitle,\n    onRenderableChange\n}, ref) => {\n    const { onError } = useDynamicEntitiesContext();\n    const api = useDynamicEntitiesApi();\n    const { definition, loading, error } = useDynamicDefinition(featureCode, entityCode);\n\n    const [values, setValues] = useState<Record<string, any>>({});\n    const [errors, setErrors] = useState<Record<string, string>>({});\n    const [saving, setSaving] = useState(false);\n\n    // Referencia para evitar cierres obsoletos en la función save()\n    const valuesRef = useRef(values);\n\n    useEffect(() => {\n        valuesRef.current = values;\n    }, [values]);\n\n    // La siembra va aquí y no en el `useState` porque la definición llega después del primer\n    // render: hasta que no se sabe qué campos hay, no se sabe cuáles son booleanos.\n    useEffect(() => {\n        if (!definition) return;\n        setValues(prev => withBooleanDefaults(definition.fields, prev));\n    }, [definition]);\n\n    useEffect(() => {\n        if (recordId && !loading && definition) {\n            // For multi-record creation, if idEntityMultiple is provided but it's new, we shouldn't fetch unless we know it exists.\n            // But usually we just attempt fetch.\n            api.getValues(featureCode, entityCode, recordId, idEntityMultiple)\n                .then(data => setValues(withBooleanDefaults(definition.fields, data.values)))\n                .catch(err => {\n                    // Un 404 es esperable: el registro todavía no tiene valores\n                    // EAV. Cualquier otro fallo —401 el primero— sí tiene que\n                    // llegar al anfitrión en vez de quedarse en la consola.\n                    if (isDynamicEntitiesHttpError(err) && err.status === 404) {\n                        console.warn(\"Could not fetch values, assuming new record\", err);\n                        return;\n                    }\n                    console.error(\"Could not fetch values\", err);\n                    onError?.(err as Error);\n                });\n        }\n    }, [recordId, idEntityMultiple, loading, definition, api, featureCode, entityCode]);\n\n    // Rule Engine Integration\n    const ruleEffects: RuleEffects = useMemo(() => {\n        if (!definition || !definition.rules || definition.rules.length === 0) {\n            return { hiddenFields: new Set(), disabledFields: new Set(), requiredFields: new Set() };\n        }\n        return RuleEngine.evaluate(definition, values);\n    }, [definition, values]);\n\n    // Los campos que realmente se pintan: los visibles por definición y no ocultos por una regla.\n    // Se calcula aquí, y no dentro del render, porque de él depende también si la entidad tiene algo\n    // que mostrar.\n    const visibleFields = useMemo(\n        () => (definition?.fields ?? []).filter(f => f.visible && !ruleEffects.hiddenFields.has(f.code)),\n        [definition, ruleEffects],\n    );\n\n    // Se avisa solo cuando la definición ya resolvió: mientras carga no se sabe, y decir \"no hay\n    // nada\" en ese momento haría parpadear el marco del anfitrión.\n    useEffect(() => {\n        if (!loading && definition) onRenderableChange?.(visibleFields.length > 0);\n    }, [loading, definition, visibleFields.length, onRenderableChange]);\n\n    const validate = (valuesToValidate: Record<string, any> = values) => {\n        if (!definition) return true;\n        const newErrors: Record<string, string> = {};\n\n        definition.fields.forEach(field => {\n            const val = valuesToValidate[field.code];\n            // Apply Rule Effects\n            if (ruleEffects.hiddenFields.has(field.code)) return; // Don't validate hidden fields\n\n            if (!field.visible) return; // Base visibility\n            if (field.disabled || ruleEffects.disabledFields.has(field.code)) return; // Don't validate disabled fields? Usually yes.\n\n            const isRequired = field.required || ruleEffects.requiredFields.has(field.code);\n\n            // Required check\n            if (isRequired && (val === undefined || val === null || val === '')) {\n                newErrors[field.code] = 'Este campo es obligatorio';\n            }\n\n            // Regex check\n            if (val && field.regex) {\n                try {\n                    const regex = new RegExp(field.regex);\n                    if (!regex.test(String(val))) {\n                        newErrors[field.code] = 'El formato no es válido';\n                    }\n                } catch (e) {\n                    console.warn(`Invalid regex for field ${field.code}`, field.regex);\n                }\n            }\n\n            // Min/Max check (Numbers & Currency)\n            if (val !== undefined && val !== null &&\n                (field.type === 'NumberInteger' || field.type === 'NumberDecimal' || field.type === 'Currency')) {\n                const num = Number(val);\n                if (field.minValue !== undefined && field.minValue !== null && num < field.minValue) {\n                    newErrors[field.code] = `El valor mínimo es ${field.minValue}`;\n                }\n                if (field.maxValue !== undefined && field.maxValue !== null && num > field.maxValue) {\n                    newErrors[field.code] = `El valor máximo es ${field.maxValue}`;\n                }\n            }\n        });\n\n        setErrors(newErrors);\n        return Object.keys(newErrors).length === 0;\n    };\n\n    const save = async (overrideRecordId?: string): Promise<boolean> => {\n        const currentValues = valuesRef.current;\n\n        if (!validate(currentValues)) return false;\n\n        const finalRecordId = overrideRecordId || recordId;\n        if (!finalRecordId) {\n            console.error(\"No record ID provided for dynamic entities save\");\n            return false;\n        }\n\n        setSaving(true);\n        try {\n            await api.saveValues(featureCode, entityCode, finalRecordId, { values: currentValues }, idEntityMultiple);\n            if (onSaved) onSaved();\n            return true;\n        } catch (err) {\n            if (onError) onError(err as Error);\n            return false;\n        } finally {\n            setSaving(false);\n        }\n    };\n\n    useImperativeHandle(ref, () => ({\n        save\n    }));\n\n    const handleSubmit = async (e: React.FormEvent) => {\n        e.preventDefault();\n        await save();\n    };\n\n    if (loading) return <div>Cargando definición...</div>;\n    if (error) return <div>Error cargando la definición: {error.message}</div>;\n    if (!definition) return <div>No se encontró definición.</div>;\n\n    // Sin fondo propio: el formulario hereda el del contenedor que lo monta. Llevaba `bg-white`\n    // fijo —sin variante oscura—, así que en modo oscuro pintaba un rectángulo blanco encima de la\n    // tarjeta del anfitrión, y en modo claro dibujaba una segunda tarjeta dentro de la que ya había.\n    // Los tres sitios que lo montan (admin, orquestador y MasterDocument) aportan su propio fondo.\n    return (\n        <div className={`space-y-4 p-0 rounded-lg ${className || ''}`}>\n            {!hideTitle && (\n                <h2 className=\"text-xl font-bold mb-4\">{definition.description || definition.entityCode}</h2>\n            )}\n\n            <div className=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n                {visibleFields\n                    .slice()\n                    .sort((a, b) => a.order - b.order)\n                    .map(field => {\n                        // Resolve Options from Definition Lists\n                        let options: { label: string, value: string | number }[] = [];\n                        if (field.genericListId) {\n                            const list = definition.lists?.find(l => l.id === field.genericListId);\n                            if (list) {\n                                options = list.items\n                                    .sort((a, b) => a.order - b.order)\n                                    .map(item => ({ label: item.label, value: item.value }));\n                            }\n                        }\n\n                        const colSpan = field.layouts?.find(l => l.breakpoint === 'md')?.colSpan || 1;\n                        const isFullWidthDefault = field.type === 'TextArea';\n                        const spanClass = isFullWidthDefault ? 'col-span-full md:col-span-full' :\n                            colSpan === 2 ? 'col-span-1 md:col-span-2' :\n                                colSpan === 3 ? 'col-span-1 md:col-span-3' :\n                                    colSpan === 4 ? 'col-span-1 md:col-span-4' :\n                                        'col-span-1 md:col-span-1';\n\n                        return (\n                            <div key={field.id} className={spanClass}>\n                                <DynamicFieldRenderer\n                                    field={{\n                                        ...field,\n                                        disabled: field.disabled || ruleEffects.disabledFields.has(field.code),\n                                        required: field.required || ruleEffects.requiredFields.has(field.code)\n                                    }}\n                                    value={values[field.code]}\n                                    error={errors[field.code]}\n                                    onChange={(val) => {\n                                        setValues(prev => ({ ...prev, [field.code]: val }));\n                                        // Clear error on change\n                                        if (errors[field.code]) setErrors(prev => ({ ...prev, [field.code]: '' }));\n                                    }}\n                                    options={options}\n                                />\n                            </div>\n                        );\n                    })}\n            </div>\n\n            {!hideSubmitButton && (\n                <div className=\"flex justify-end pt-4\">\n                    <button\n                        type=\"button\"\n                        onClick={handleSubmit}\n                        disabled={saving}\n                        className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50\"\n                    >\n                        {saving ? 'Guardando...' : 'Guardar Registro'}\n                    </button>\n                </div>\n            )}\n        </div>\n    );\n});\n","import type { CrudService, GetAllParams, GetAllResponse } from '../../../MasterCrud';\nimport type { DynamicField } from '../../core/types/DynamicField.types';\nimport type { DynamicEntity } from '../../core/types/DynamicEntity.types';\nimport type { DynamicEntitiesFetcher } from '../../core/api/fetcher';\nimport { resolveFetcher } from '../../core/api/fetcher';\nimport { DynamicEntitiesHttpError } from '../../core/api/DynamicEntitiesHttpError';\n\n// We need Feature type definition. \n// Ideally we should have a shared type or define it here.\nexport interface Feature {\n    id: string;\n    code: string;\n    name: string;\n    description?: string;\n    type: 'Master' | 'Document' | 'Transaction'; // Enum from backend\n    active: boolean;\n    allowsPlansAndCriteria: boolean;\n    hasFileManagement?: boolean;\n    createdAt?: string;\n    updatedAt?: string;\n    featureEntities?: FeatureEntity[];\n}\n\nexport interface FeatureEntity {\n    id: string;\n    featureId: string;\n    dynamicEntityId: string;\n    renderMode: 'tab' | 'modal' | 'inline';\n    order: number;\n    properties?: Record<string, any>;\n    dynamicEntity?: DynamicEntity;\n}\n\n\n\nexport interface SystemEntityStatus {\n    id: string;\n    code: string;\n    description?: string;\n    isEnabled: boolean;\n    enabledSystemEntityId?: string;\n    renderMode?: 'tab' | 'inline';\n    enabledBy?: string;\n    enabledAt?: string;\n}\n\nexport interface EnableSystemEntityResult {\n    enabledSystemEntityId: string;\n    featureEntityId: string;\n}\n\nexport class FeatureService implements CrudService<Feature> {\n    private baseUrl: string;\n    private http: DynamicEntitiesFetcher;\n\n    /**\n     * @param baseUrl Raíz de la API.\n     * @param fetcher Transporte del anfitrión (con `Authorization` y demás\n     * cabeceras). Ausente → `fetch` global, igual que antes.\n     */\n    constructor(baseUrl: string, fetcher?: DynamicEntitiesFetcher) {\n        this.baseUrl = baseUrl;\n        this.http = resolveFetcher(fetcher);\n    }\n\n    async getAll(params: GetAllParams): Promise<GetAllResponse<Feature>> {\n        // Backend currently only has GetAll (List<Feature>). Paging is not implemented in Controller yet.\n        // We will mock paging on client side if needed or just return all.\n        // For real prod, backend needs Paging.\n\n        // Los errores se propagan a propósito: devolver una lista vacía hacía que\n        // un 401 se viera exactamente igual que \"no hay maestros creados\".\n        const response = await this.http(`${this.baseUrl}/features`);\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch features: ${response.status} ${response.statusText}`, response);\n\n        const allData = await response.json();\n\n        // Client-side pagination/filtering for MVP\n        // TODO: Implement server-side pagination in backend\n        let data = [...allData];\n\n        if (params.search) {\n            const term = params.search.toLowerCase();\n            data = data.filter(f =>\n                f.code.toLowerCase().includes(term) ||\n                f.description?.toLowerCase().includes(term) ||\n                f.name?.toLowerCase().includes(term)\n            );\n        }\n\n        const total = data.length;\n        const start = (params.page - 1) * params.limit;\n        const paginatedData = data.slice(start, start + params.limit);\n\n        return {\n            data: paginatedData,\n            total\n        };\n    }\n\n    async getById(id: string | number): Promise<Feature> {\n        const response = await this.http(`${this.baseUrl}/features/${id}`);\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch feature: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async getByCode(code: string): Promise<Feature> {\n        const response = await this.http(`${this.baseUrl}/dynamic-entities/features/by-code/${code}`);\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch feature by code: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async getByPath(path: string): Promise<Feature> {\n        const url = `${this.baseUrl}/dynamic-entities/features/by-path/${path}`;\n        const response = await this.http(url);\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch feature by path: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async create(data: Partial<Feature>): Promise<Feature> {\n        const response = await this.http(`${this.baseUrl}/features`, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(data)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to create feature: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async update(id: string | number, feature: Partial<Feature>): Promise<Feature> {\n        const response = await this.http(`${this.baseUrl}/features/${id}`, {\n            method: 'PUT',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(feature)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to update feature: ${response.status} ${response.statusText}`, response);\n        // Return dummy or actual if needed, CrudService expects return\n        // Cast to Feature for now, assuming partial update returns full or we merge\n        return feature as Feature;\n    }\n\n    async setFileManagement(id: string, hasFileManagement: boolean): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/features/${id}/file-management`, {\n            method: 'PATCH',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(hasFileManagement)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to update file management flag: ${response.status} ${response.statusText}`, response);\n    }\n\n    async delete(id: string | number): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/features/${id}`, {\n            method: 'DELETE'\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to delete feature: ${response.status} ${response.statusText}`, response);\n    }\n\n    // Entity Management\n    async createEntity(entity: Partial<DynamicEntity>): Promise<DynamicEntity> {\n        const response = await this.http(`${this.baseUrl}/dynamic-entities`, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(entity)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to create entity: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async updateEntity(id: string, entity: Partial<DynamicEntity>): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/dynamic-entities/${id}`, {\n            method: 'PUT',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(entity)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to update entity: ${response.status} ${response.statusText}`, response);\n    }\n\n    async deleteEntity(id: string): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/dynamic-entities/${id}`, {\n            method: 'DELETE'\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to delete entity: ${response.status} ${response.statusText}`, response);\n    }\n\n    // FeatureEntity Links\n    async addFeatureEntity(featureId: string, featureEntity: Partial<FeatureEntity>): Promise<FeatureEntity> {\n        const response = await this.http(`${this.baseUrl}/features/${featureId}/entities`, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(featureEntity)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to add entity to feature: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async updateFeatureEntity(featureId: string, dynamicEntityId: string, featureEntity: Partial<FeatureEntity>): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/features/${featureId}/entities/${dynamicEntityId}`, {\n            method: 'PUT', // or PATCH\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(featureEntity)\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to update feature entity link: ${response.status} ${response.statusText}`, response);\n    }\n\n    async removeFeatureEntity(featureId: string, dynamicEntityId: string): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/features/${featureId}/entities/${dynamicEntityId}`, {\n            method: 'DELETE'\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to remove entity from feature: ${response.status} ${response.statusText}`, response);\n    }\n\n    // Fields\n    async saveFields(entityId: string, fields: DynamicField[]): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/dynamic-entities/${entityId}/fields`, {\n            method: 'PUT',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(fields)\n        });\n        if (!response.ok) {\n            const errorText = await response.text();\n            console.error(\"Fields Save Validation Error:\", errorText);\n            throw new DynamicEntitiesHttpError(`Failed to save fields: ${response.status} ${response.statusText} — ${errorText}`, response);\n        }\n    }\n\n    // Rules\n    async saveRules(entityId: string, rules: any[]): Promise<void> {\n        const response = await this.http(`${this.baseUrl}/dynamic-entities/${entityId}/rules`, {\n            method: 'PUT',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify(rules)\n        });\n        if (!response.ok) {\n            const errorText = await response.text();\n            console.error(\"Rules Save Validation Error:\", errorText);\n            throw new DynamicEntitiesHttpError(`Failed to save rules: ${response.status} ${response.statusText} — ${errorText}`, response);\n        }\n    }\n\n    // System Entity Management\n    async getSystemEntities(featureId: string): Promise<SystemEntityStatus[]> {\n        const response = await this.http(`${this.baseUrl}/features/${featureId}/system-entities`);\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to fetch system entities: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async enableSystemEntity(\n        featureId: string,\n        dynamicEntityId: string,\n        renderMode: 'tab' | 'inline'\n    ): Promise<EnableSystemEntityResult> {\n        const response = await this.http(`${this.baseUrl}/features/${featureId}/system-entities/enable`, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify({ dynamicEntityId, renderMode })\n        });\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to enable system entity: ${response.status} ${response.statusText}`, response);\n        return response.json();\n    }\n\n    async disableSystemEntity(featureId: string, enabledSystemEntityId: string): Promise<void> {\n        const response = await this.http(\n            `${this.baseUrl}/features/${featureId}/system-entities/${enabledSystemEntityId}/disable`,\n            { method: 'DELETE' }\n        );\n        if (!response.ok) throw new DynamicEntitiesHttpError(`Failed to disable system entity: ${response.status} ${response.statusText}`, response);\n    }\n}\n","import { useMemo } from 'react';\nimport { FeatureService } from './FeatureService';\nimport { useDynamicEntitiesContext } from '../../core/DynamicEntitiesProvider';\n\n/**\n * `FeatureService` ya cableado con el `baseUrl` y el transporte del provider.\n *\n * Construirlo a mano con `new FeatureService(baseUrl)` deja la petición sin las\n * cabeceras del anfitrión; usar siempre este hook dentro de componentes.\n */\nexport const useFeatureService = (): FeatureService => {\n    const { baseUrl, fetcher } = useDynamicEntitiesContext();\n    return useMemo(() => new FeatureService(baseUrl, fetcher), [baseUrl, fetcher]);\n};\n","import React, { useState, useEffect } from 'react';\nimport { useDynamicDefinition } from '../core/hooks/useDynamicDefinition';\nimport { useDynamicEntitiesContext } from '../core/DynamicEntitiesProvider';\nimport { useDynamicEntitiesApi } from '../core/hooks/useDynamicEntitiesApi';\n\ninterface DynamicEntityGridProps {\n    featureCode: string;\n    entityCode: string;\n    masterRecordId: string;\n    onEdit?: (idEntityMultiple: string) => void;\n    onCreate?: () => void;\n    className?: string;\n}\n\nexport const DynamicEntityGrid: React.FC<DynamicEntityGridProps> = ({\n    featureCode,\n    entityCode,\n    masterRecordId,\n    onEdit,\n    onCreate,\n    className\n}) => {\n    const { baseUrl, onError } = useDynamicEntitiesContext();\n    const api = useDynamicEntitiesApi();\n    const { definition, loading: defLoading, error: defError } = useDynamicDefinition(featureCode, entityCode);\n    const [records, setRecords] = useState<Record<string, any>[]>([]);\n    const [loading, setLoading] = useState(false);\n\n    const fetchRecords = async () => {\n        if (!baseUrl || !featureCode || !entityCode || !masterRecordId) return;\n        setLoading(true);\n        try {\n            const data = await api.getMultipleRecords(featureCode, entityCode, masterRecordId);\n            const flatRecords = data.map((d: any) => d.values);\n            setRecords(flatRecords);\n        } catch (err) {\n            if (onError) onError(err as Error);\n            else console.error(err);\n        } finally {\n            setLoading(false);\n        }\n    };\n\n    useEffect(() => {\n        fetchRecords();\n    }, [api, featureCode, entityCode, masterRecordId]);\n\n    const handleDelete = async (idEntityMultiple: string) => {\n        if (!confirm('¿Está seguro de que desea eliminar este registro?')) return;\n        try {\n            await api.deleteRecord(featureCode, masterRecordId, idEntityMultiple);\n            fetchRecords();\n        } catch (err) {\n            if (onError) onError(err as Error);\n            else alert('Error al eliminar');\n        }\n    };\n\n    if (defLoading || loading && records.length === 0) return <div>Cargando...</div>;\n    if (defError) return <div>Error cargando la definición</div>;\n    if (!definition) return <div>Sin definición</div>;\n\n    const columns = definition.fields\n        .filter(f => f.visible)\n        .sort((a, b) => a.order - b.order);\n\n    return (\n        <div className={`bg-white dark:bg-dark-bg-primary rounded border border-gray-200 dark:border-gray-800 text-sm ${className || ''}`}>\n            <div className=\"p-4 flex justify-between items-center bg-gray-50 border-b\">\n                <h3 className=\"font-bold\">{definition.description || entityCode}</h3>\n                <button\n                    onClick={onCreate}\n                    className=\"px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700\"\n                >\n                    Añadir Registro\n                </button>\n            </div>\n            <div className=\"overflow-x-auto\">\n                <table className=\"w-full text-left border-collapse\">\n                    <thead>\n                        <tr className=\"bg-gray-100 border-b\">\n                            {columns.map(col => (\n                                <th key={col.id} className=\"p-3 font-semibold text-gray-700\">\n                                    {col.labels?.['es'] || col.code}\n                                </th>\n                            ))}\n                            <th className=\"p-3 text-right\">Acciones</th>\n                        </tr>\n                    </thead>\n                    <tbody>\n                        {records.length === 0 ? (\n                            <tr>\n                                <td colSpan={columns.length + 1} className=\"p-4 text-center text-gray-500\">\n                                    No se encontraron registros.\n                                </td>\n                            </tr>\n                        ) : (\n                            records.map((record) => (\n                                <tr key={record.id} className=\"border-b hover:bg-gray-50\">\n                                    {columns.map(col => (\n                                        <td key={col.id} className=\"p-3\">\n                                            {record[col.code]}\n                                        </td>\n                                    ))}\n                                    <td className=\"p-3 text-right space-x-2\">\n                                        <button\n                                            onClick={() => onEdit && record.id && onEdit(record.id)}\n                                            className=\"text-blue-600 hover:text-blue-800\"\n                                        >\n                                            Editar\n                                        </button>\n                                        <button\n                                            onClick={() => record.id && handleDelete(record.id)}\n                                            className=\"text-red-600 hover:text-red-800\"\n                                        >\n                                            Eliminar\n                                        </button>\n                                    </td>\n                                </tr>\n                            ))\n                        )}\n                    </tbody>\n                </table>\n            </div>\n        </div>\n    );\n};\n","import React, { useState } from 'react';\nimport { DynamicEntities, type DynamicEntitiesRef } from './DynamicEntities';\nimport { DynamicEntityGrid } from './DynamicEntityGrid';\nimport type { DynamicEntityDefinition } from '../core/types/DynamicEntity.types';\n\nexport interface DynamicEntityMultiRecordProps {\n    featureCode: string;\n    entityCode: string;\n    recordId: string;\n    definition: DynamicEntityDefinition;\n}\n\nexport const DynamicEntityMultiRecord = React.forwardRef<DynamicEntitiesRef, DynamicEntityMultiRecordProps>(({\n    featureCode,\n    entityCode,\n    recordId,\n    definition\n}, ref) => {\n    const [idEntityMultiple, setIdEntityMultiple] = useState<string | null>(null);\n    const [isFormVisible, setIsFormVisible] = useState(false);\n    \n    // Estado para forzar la recreación del formulario y evitar persistencia de estados\n    const [formKey, setFormKey] = useState<number>(0);\n\n    return (\n        <div className=\"w-full flex flex-col gap-6\">\n            {/* Panel de Formulario */}\n            {isFormVisible && (\n                <div className=\"bg-white dark:bg-dark-bg-secondary p-5 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm relative animate-in fade-in slide-in-from-top-4 duration-300\">\n                    <div className=\"flex justify-between items-center mb-4 pb-3 border-b border-gray-100 dark:border-gray-800\">\n                        <h4 className=\"text-base font-semibold text-gray-800 dark:text-gray-200\">\n                            {idEntityMultiple ? 'Editando registro' : 'Nuevo registro'}\n                        </h4>\n                        <button\n                            onClick={() => {\n                                setIsFormVisible(false);\n                                setIdEntityMultiple(null);\n                            }}\n                            className=\"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors p-1 rounded-md\"\n                        >\n                            <svg className=\"w-5 h-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"><path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" /></svg>\n                        </button>\n                    </div>\n                    \n                    <DynamicEntities\n                        key={formKey}\n                        ref={ref}\n                        featureCode={featureCode}\n                        entityCode={entityCode}\n                        recordId={recordId}\n                        idEntityMultiple={idEntityMultiple || undefined}\n                        hideTitle={true}\n                        hideSubmitButton={false} \n                        onSaved={() => {\n                            setIsFormVisible(false);\n                            setIdEntityMultiple(null);\n                            setFormKey(prev => prev + 1);\n                        }}\n                    />\n                </div>\n            )}\n\n            {/* Grilla (Con opacidad dinámica si el formulario está abierto) */}\n            <div className={`transition-opacity duration-300 ${isFormVisible ? 'opacity-50 pointer-events-none' : 'opacity-100'}`}>\n                <DynamicEntityGrid\n                    key={`grid-${formKey}`}\n                    featureCode={featureCode}\n                    entityCode={entityCode}\n                    masterRecordId={recordId}\n                    onCreate={() => {\n                        setIdEntityMultiple(crypto.randomUUID());\n                        setFormKey(prev => prev + 1);\n                        setIsFormVisible(true);\n                    }}\n                    onEdit={(id: string) => {\n                        setIdEntityMultiple(id);\n                        setFormKey(prev => prev + 1);\n                        setIsFormVisible(true);\n                    }}\n                />\n            </div>\n        </div>\n    );\n});\n","import React from 'react';\nimport { ChevronLeftIcon } from '@heroicons/react/24/outline';\nimport { Button } from '../Button/Button';\nimport type { LayoutContentProps } from './LayoutContent.types';\n\n/**\n * Componente LayoutContent del sistema de diseño Siesa\n *\n * Estructura de layout que envuelve una vista completa. Incluye una cabecera\n * superior (Toolbar) pegajosa con título, opción de retorno y botón de acción,\n * junto con un área de contenido principal.\n *\n * Implementa mejores prácticas:\n * - Soporte completo para modo oscuro (dark mode)\n * - Diseño pixel-perfect basado en Figma\n * - Uso estricto de tokens de color del sistema\n *\n * @example\n * ```tsx\n * <LayoutContent \n *   title=\"Entidades Dinámicas\"\n *   onBack={() => history.back()}\n *   primaryAction={{\n *     label: \"Nuevo\",\n *     onClick: () => openModal(),\n *     icon: <PlusIcon />\n *   }}\n * >\n *   <p>Contenido principal aquí</p>\n * </LayoutContent>\n * ```\n */\nexport const LayoutContent: React.FC<LayoutContentProps> = ({\n    title,\n    onBack,\n    primaryAction,\n    toolbarEndContent,\n    children,\n    className = '',\n}) => {\n    // ===== CONTENEDOR PRINCIPAL =====\n    const containerClasses = `\n      flex\n      flex-col\n      w-full\n      h-full\n      relative\n      bg-bg-primary\n      dark:bg-dark-bg-primary\n      ${className}\n    `.trim().replace(/\\s+/g, ' ');\n\n    // ===== TOOLBAR WRAPPER =====\n    const toolbarClasses = `\n      sticky\n      top-0\n      w-full\n      z-10\n      flex\n      items-center\n      min-h-[72px]\n      bg-bg-primary\n      dark:bg-dark-bg-primary\n    `.trim().replace(/\\s+/g, ' ');\n\n    // ===== TOOLBAR INTERIOR =====\n    const toolbarInnerClasses = `\n      flex-1\n      flex\n      items-center\n      justify-between\n      px-5\n      min-h-[72px]\n      rounded-tl-3xl\n      border-b\n      border-border-primary\n      bg-background-secondary\n      dark:bg-dark-bg-primary\n      dark:border-dark-border-primary\n    `.trim().replace(/\\s+/g, ' ');\n\n    // ===== ÁREA DE CONTENIDO =====\n    const contentAreaClasses = `\n      flex-1\n      w-full\n      p-6\n      bg-background-secondary\n      dark:bg-dark-bg-primary\n    `.trim().replace(/\\s+/g, ' ');\n\n    return (\n        <div className={containerClasses}>\n            {/* Cabecera (Toolbar) */}\n            <div className={toolbarClasses}>\n                <div className={toolbarInnerClasses}>\n                    <div className=\"flex items-center gap-2\">\n                        {onBack && (\n                            <Button \n                                type=\"plain\" \n                                size=\"base\"\n                                iconOnly \n                                leftIcon={<ChevronLeftIcon className=\"w-5 h-5 text-primary-600 dark:text-primary-600\" />}\n                                onClick={onBack}\n                                ariaLabel=\"Volver a la vista anterior\"\n                            />\n                        )}\n                        <h1 className=\"text-[20px] font-bold text-[#1355b7] dark:text-[#3c9bf6] tracking-tight leading-[28px] m-0\">\n                            {title}\n                        </h1>\n                    </div>\n                    \n                    <div className=\"flex items-center gap-2 justify-end min-w-[256px]\">\n                        {toolbarEndContent ? (\n                            toolbarEndContent\n                        ) : primaryAction ? (\n                            <Button\n                                type={primaryAction.type || 'default'}\n                                size={primaryAction.size || 'sm'}\n                                leftIcon={primaryAction.icon}\n                                onClick={primaryAction.onClick}\n                                disabled={primaryAction.disabled}\n                            >\n                                {primaryAction.label}\n                            </Button>\n                        ) : null}\n                    </div>\n                </div>\n            </div>\n\n            {/* Contenido Principal */}\n            <div className={contentAreaClasses}>\n                {children}\n            </div>\n        </div>\n    );\n};\n","import React, { useState, useEffect } from 'react';\nimport { useFeatureService } from '../admin/services/useFeatureService';\nimport type { Feature } from '../admin/services/FeatureService';\nimport { useDynamicEntitiesContext } from '../core/DynamicEntitiesProvider';\nimport { useDynamicDefinition } from '../core/hooks/useDynamicDefinition';\nimport { DynamicEntities, type DynamicEntitiesRef } from './DynamicEntities';\nimport { DynamicEntityMultiRecord } from './DynamicEntityMultiRecord';\nimport { Button } from '../../Button/Button';\nimport { LayoutContent } from '../../LayoutContent';\n\nexport interface DynamicFeatureOrchestratorProps {\n    featureCode: string;\n    recordId?: string;\n    className?: string;\n}\n\nexport const EntityContainer = React.forwardRef<DynamicEntitiesRef, {\n    featureCode: string,\n    entityCode: string,\n    recordId?: string,\n    hideTitle?: boolean,\n    hideSubmitButton?: boolean,\n    /** Se reenvía a `DynamicEntities`: avisa si la entidad tiene campos que pintar. */\n    onRenderableChange?: (renderable: boolean) => void\n}>(({ featureCode, entityCode, recordId, hideTitle, hideSubmitButton, onRenderableChange }, ref) => {\n    const { definition, loading } = useDynamicDefinition(featureCode, entityCode);\n\n    if (loading) return <div>Cargando...</div>;\n    if (!definition) return null;\n\n    if (!definition.multiRecord) {\n        return (\n            <div className=\"w-full\">\n                <DynamicEntities\n                    ref={ref}\n                    featureCode={featureCode}\n                    entityCode={entityCode}\n                    recordId={recordId}\n                    hideTitle={hideTitle}\n                    hideSubmitButton={hideSubmitButton}\n                    onRenderableChange={onRenderableChange}\n                />\n            </div>\n        );\n    }\n\n    // MODO MULTI-REGISTRO\n    if (!recordId) {\n        return <div className=\"text-gray-500 italic p-4 text-sm\">Guarde el registro principal primero para habilitar la adición de múltiples registros en {definition.description || entityCode}.</div>;\n    }\n\n    return (\n        <DynamicEntityMultiRecord\n            ref={ref}\n            featureCode={featureCode}\n            entityCode={entityCode}\n            recordId={recordId}\n            definition={definition}\n        />\n    );\n});\n\nexport const DynamicFeatureOrchestrator: React.FC<DynamicFeatureOrchestratorProps> = ({\n    featureCode,\n    recordId,\n    className\n}) => {\n    const { onError } = useDynamicEntitiesContext();\n    const service = useFeatureService();\n    const [feature, setFeature] = useState<Feature | null>(null);\n    const [loading, setLoading] = useState(true);\n    const [activeTab, setActiveTab] = useState<string>('');\n    const [modalOpen, setModalOpen] = useState<string | null>(null);\n\n    useEffect(() => {\n        service.getByCode(featureCode)\n            .then(f => {\n                setFeature(f);\n                if (f.featureEntities && f.featureEntities.length > 0) {\n                    const firstTab = f.featureEntities.find(fe => fe.renderMode === 'tab' || fe.renderMode === 'inline');\n                    if (firstTab && firstTab.dynamicEntity) {\n                        setActiveTab(firstTab.dynamicEntity.code);\n                    }\n                }\n                setLoading(false);\n            })\n            .catch(err => {\n                console.error(err);\n                onError?.(err as Error);\n                setLoading(false);\n            });\n    }, [featureCode, service, onError]);\n\n    if (loading) return <div className=\"p-6 text-gray-500\">Cargando Módulo...</div>;\n    if (!feature) return <div className=\"p-6 text-red-500\">Módulo no encontrado</div>;\n\n    const tabs = feature.featureEntities?.filter(fe => fe.renderMode === 'tab') || [];\n    const modals = feature.featureEntities?.filter(fe => fe.renderMode === 'modal') || [];\n    const inlines = feature.featureEntities?.filter(fe => fe.renderMode === 'inline') || [];\n\n    const endContent = modals.length > 0 ? (\n        <div className=\"flex gap-2\">\n            {modals.map(fe => (\n                <Button\n                    key={fe.id}\n                    onClick={() => setModalOpen(fe.dynamicEntity?.code || null)}\n                >\n                    {fe.dynamicEntity?.description || fe.dynamicEntity?.code}\n                </Button>\n            ))}\n        </div>\n    ) : undefined;\n\n    return (\n        <LayoutContent\n            title={feature.code}\n            className={className}\n            toolbarEndContent={endContent}\n        >\n            <div className=\"flex flex-col gap-6\">\n                {tabs.length > 0 && (\n                    <div className=\"border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-dark-bg-primary overflow-x-auto\">\n                        <nav className=\"-mb-px flex space-x-0\" aria-label=\"Tabs\">\n                            {tabs.map(fe => (\n                                <button\n                                    key={fe.id}\n                                    onClick={() => setActiveTab(fe.dynamicEntity?.code || '')}\n                                    className={`\n                                        whitespace-nowrap px-5 py-3 border-b-2 font-medium text-sm transition-colors focus:outline-none\n                                        ${activeTab === fe.dynamicEntity?.code\n                                            ? 'border-primary-600 text-primary-700 dark:text-primary-500'\n                                            : 'border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800'}\n                                    `}\n                                >\n                                    {fe.dynamicEntity?.description || fe.dynamicEntity?.code}\n                                </button>\n                            ))}\n                        </nav>\n                    </div>\n                )}\n\n                <div className=\"w-full\">\n                    {tabs.map(fe => (\n                        <div key={fe.id} className={activeTab === fe.dynamicEntity?.code ? 'block animate-in fade-in duration-200' : 'hidden'}>\n                            {fe.dynamicEntity && (\n                                <EntityContainer\n                                    featureCode={feature.code}\n                                    entityCode={fe.dynamicEntity.code}\n                                    recordId={recordId}\n                                />\n                            )}\n                        </div>\n                    ))}\n                </div>\n\n                {inlines.length > 0 && (\n                    <div className=\"flex flex-col gap-6 mt-4\">\n                        {inlines.map(fe => (\n                            <div key={fe.id} className=\"w-full\">\n                                <h3 className=\"text-lg font-bold text-gray-800 mb-4 px-1\">\n                                    {fe.dynamicEntity?.description || fe.dynamicEntity?.code}\n                                </h3>\n                                {fe.dynamicEntity && (\n                                    <EntityContainer\n                                        featureCode={feature.code}\n                                        entityCode={fe.dynamicEntity.code}\n                                        recordId={recordId}\n                                    />\n                                )}\n                            </div>\n                        ))}\n                    </div>\n                )}\n\n                {modalOpen && (\n                    <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4\">\n                        <div className=\"bg-white rounded-xl shadow-2xl w-full max-w-3xl overflow-hidden flex flex-col max-h-[90vh]\">\n                            <div className=\"flex justify-between items-center p-5 border-b border-gray-100\">\n                                <h3 className=\"text-xl font-bold text-gray-900\">\n                                    {modals.find(m => m.dynamicEntity?.code === modalOpen)?.dynamicEntity?.description}\n                                </h3>\n                                <button\n                                    onClick={() => setModalOpen(null)}\n                                    className=\"p-1 hover:bg-gray-100 rounded-md transition-colors text-gray-500 hover:text-gray-700\"\n                                >\n                                    <svg className=\"w-5 h-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"><path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" /></svg>\n                                </button>\n                            </div>\n                            <div className=\"p-6 overflow-y-auto\">\n                                <EntityContainer\n                                    featureCode={feature.code}\n                                    entityCode={modalOpen}\n                                    recordId={recordId}\n                                />\n                            </div>\n                        </div>\n                    </div>\n                )}\n            </div>\n        </LayoutContent>\n    );\n};\n","import { createContext } from 'react';\n\ninterface DynamicEntitiesRegistrationContextValue {\n  register: () => void;\n}\n\nexport const DynamicEntitiesRegistrationContext = createContext<DynamicEntitiesRegistrationContextValue | null>(null);\n","import React, { useState, useEffect, useContext } from 'react';\nimport { type DynamicEntitiesRef } from '../DynamicEntities/ui/DynamicEntities';\nimport { EntityContainer } from '../DynamicEntities/ui/DynamicFeatureOrchestrator';\nimport { DynamicEntitiesRegistrationContext } from './DynamicEntitiesRegistrationContext';\n\nexport interface MasterCrudDynamicEntitiesProps {\n    /** Metadatos de la característica dinámica cargada */\n    dynamicFeature: any;\n    /** Código de la característica dinámica */\n    dynamicFeatureCode?: string;\n    /** ID del registro actual (para cargar datos EAV) */\n    recordId?: string | number;\n    /** Función para registrar referencias de componentes dinámicos internos */\n    registerDynamicRef?: (entityCode: string, ref: any) => void;\n    /** Si es true, solo muestra entidades de tipo Planes y Criterios. Si es false, las excluye. */\n    showOnlyPlansAndCriteria?: boolean;\n}\n\nexport const MasterCrudDynamicEntities: React.FC<MasterCrudDynamicEntitiesProps> = ({\n    dynamicFeature,\n    dynamicFeatureCode,\n    recordId,\n    registerDynamicRef,\n    showOnlyPlansAndCriteria,\n}) => {\n    const registrationContext = useContext(DynamicEntitiesRegistrationContext);\n    useEffect(() => {\n        registrationContext?.register();\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n    }, []);\n\n    const [activeDynamicTab, setActiveDynamicTab] = useState<string>('');\n\n    useEffect(() => {\n        if (!activeDynamicTab && dynamicFeature?.featureEntities?.length) {\n            let filtered = dynamicFeature.featureEntities.filter((fe: any) => fe.renderMode !== 'inline' && fe.renderMode !== 'modal');\n            \n            if (showOnlyPlansAndCriteria !== undefined) {\n                filtered = filtered.filter((fe: any) => !!fe.dynamicEntity?.isPlansAndCriteria === showOnlyPlansAndCriteria);\n            }\n\n            if (filtered.length > 0 && filtered[0].dynamicEntity) {\n                setActiveDynamicTab(filtered[0].dynamicEntity.code);\n            }\n        }\n    }, [dynamicFeature, activeDynamicTab, showOnlyPlansAndCriteria]);\n\n    if (!dynamicFeature || !dynamicFeature.featureEntities?.length) return null;\n\n    let inlineEntities = dynamicFeature.featureEntities.filter((e: any) => e.renderMode === 'inline');\n    let tabEntities = dynamicFeature.featureEntities.filter((e: any) => e.renderMode !== 'inline' && e.renderMode !== 'modal');\n\n    if (showOnlyPlansAndCriteria !== undefined) {\n        inlineEntities = inlineEntities.filter((e: any) => !!e.dynamicEntity?.isPlansAndCriteria === showOnlyPlansAndCriteria);\n        tabEntities = tabEntities.filter((e: any) => !!e.dynamicEntity?.isPlansAndCriteria === showOnlyPlansAndCriteria);\n    }\n\n    return (\n        <div className=\"space-y-6\">\n            {/* 1. Entidades en modo 'inline' */}\n            {inlineEntities.length > 0 && (\n                <div className=\"space-y-6\">\n                    {inlineEntities.map((entity: any) => {\n                        if (!entity.dynamicEntity) return null;\n                        return (\n                            <div key={entity.dynamicEntity.code} className=\"bg-transparent p-0\">\n                                <EntityContainer\n                                    ref={(el: DynamicEntitiesRef | null) => { registerDynamicRef?.(entity.dynamicEntity!.code, el); }}\n                                    featureCode={dynamicFeatureCode || ''}\n                                    entityCode={entity.dynamicEntity.code}\n                                    recordId={recordId ? String(recordId) : undefined}\n                                    hideSubmitButton={true}\n                                />\n                            </div>\n                        );\n                    })}\n                </div>\n            )}\n\n            {/* 2. Entidades en modo 'tab' */}\n            {tabEntities.length > 0 && (\n                <div className=\"bg-white dark:bg-dark-bg-primary border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden\">\n                    <div className=\"flex border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-dark-bg-primary overflow-x-auto\">\n                        {tabEntities.map((entity: any) => {\n                            if (!entity.dynamicEntity) return null;\n                            return (\n                                <button\n                                    key={entity.dynamicEntity.code}\n                                    type=\"button\"\n                                    onClick={() => setActiveDynamicTab(entity.dynamicEntity!.code)}\n                                    className={`px-5 py-3 text-sm font-medium whitespace-nowrap transition-colors focus:outline-none ${activeDynamicTab === entity.dynamicEntity.code\n                                        ? 'border-b-2 border-primary-600 text-primary-700 dark:text-primary-500'\n                                        : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 border-b-2 border-transparent'\n                                        }`}\n                                >\n                                    {entity.dynamicEntity.description || entity.dynamicEntity.code}\n                                </button>\n                            );\n                        })}\n                    </div>\n                    <div className=\"p-5 bg-white dark:bg-dark-bg-primary min-h-[200px]\">\n                        {tabEntities.map((entity: any) => {\n                            if (!entity.dynamicEntity) return null;\n                            return (\n                                <div\n                                    key={entity.dynamicEntity.code}\n                                    className={activeDynamicTab === entity.dynamicEntity.code ? 'block animate-in fade-in duration-300' : 'hidden'}\n                                >\n                                    <EntityContainer\n                                        ref={(el: DynamicEntitiesRef | null) => { registerDynamicRef?.(entity.dynamicEntity!.code, el); }}\n                                        featureCode={dynamicFeatureCode || ''}\n                                        entityCode={entity.dynamicEntity.code}\n                                        recordId={recordId ? String(recordId) : undefined}\n                                        hideSubmitButton={true}\n                                        hideTitle={true}\n                                    />\n                                </div>\n                            );\n                        })}\n                    </div>\n                </div>\n            )}\n        </div>\n    );\n};\n","import type { ReactNode } from 'react';\n\n// Extensiones corporativas permitidas por defecto.\n// Excluye ejecutables, scripts y formatos de riesgo.\nexport const DEFAULT_ACCEPTED_EXTENSIONS =\n  '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.jpg,.jpeg,.png,.webp';\n\n/** Tamaño máximo por archivo individual (MB) */\nexport const DEFAULT_MAX_FILE_SIZE_MB = 10;\n\n/** Tamaño máximo acumulado de todos los archivos del registro (MB) */\nexport const DEFAULT_MAX_TOTAL_SIZE_MB = 50;\n\n/**\n * Represents a resource (file or image) in the gallery.\n */\nexport interface GalleryResource {\n  /** Unique identifier of the resource (UUID) */\n  uuid: string;\n  /** URL to view or download the resource */\n  url: string;\n  /** File name */\n  name: string;\n  /** File type (MIME type or extension) */\n  type: string;\n  /** File size in bytes (used to enforce maxTotalSizeMB) */\n  size?: number;\n  /** Indicates if the resource is selected */\n  checked?: boolean;\n}\n\n/**\n * Props for the FileUploaderGallery component\n */\nexport interface FileUploaderGalleryProps {\n  /** Main title appearing in the header */\n  title: string;\n  \n  /** Name of the entity it refers to (e.g., \"Customers\") */\n  entity: string;\n  \n  /** Unique identifier of the associated record */\n  entityId: string | number;\n  \n  /** \n   * Component display mode \n   * @default 'modal'\n   */\n  mode?: 'page' | 'modal';\n  \n  /** \n   * If modal, defines if it appears maximized (full screen) \n   * @default false\n   */\n  isMaximized?: boolean;\n  \n  /** \n   * List of resources or files to display \n   */\n  resources: GalleryResource[];\n  \n  /** \n   * Enables checkboxes to select resources \n   * @default false\n   */\n  allowSelection?: boolean;\n  \n  /** \n   * Text for the main action button \n   * @default 'Aceptar'\n   */\n  acceptButtonText?: string;\n  \n  /** \n   * Indicates if the file upload component is shown \n   * @default true\n   */\n  showFileUploader?: boolean;\n  \n  /** \n   * Defines if the file name is shown below the thumbnail.\n   * Default: false for images, true for other files.\n   */\n  showFileName?: boolean;\n\n  /** \n   * Indicates if the gallery is in a loading state \n   * @default false\n   */\n  isLoading?: boolean;\n\n  /** \n   * Enables the option to delete resources \n   * @default false\n   */\n  allowDeletion?: boolean;\n\n  /** \n   * Error message to display in a system alert\n   */\n  error?: { title: string; message: string } | null;\n\n  /** Callback executed when a resource is accepted/confirmed */\n  onAccept?: (selected: GalleryResource[]) => void;\n  \n  /** Callback executed when closing the modal or cancelling */\n  onClose?: () => void;\n\n  /** Callback executed when navigating back (page mode) */\n  onBack?: () => void;\n\n  /** Callback to handle the upload of a new file */\n  onUpload?: (file: File) => Promise<void>;\n\n  /** Callback to handle the deletion of a resource */\n  onDelete?: (uuid: string) => Promise<void>;\n\n  /** Callback executed when change in resource selection */\n  onResourceCheck?: (uuid: string, checked: boolean, selectedResources: GalleryResource[]) => void;\n\n  /** Additional CSS class for the container */\n  className?: string;\n\n  /**\n   * Embedded mode: hides the header (title/close) and footer (cancel/accept buttons).\n   * Use when rendering inside a form tab where the parent controls the save action.\n   * @default false\n   */\n  embedded?: boolean;\n\n  /**\n   * Extensiones de archivo permitidas, separadas por coma.\n   * Ej: '.pdf,.docx,.jpg'\n   * @default DEFAULT_ACCEPTED_EXTENSIONS\n   */\n  acceptedExtensions?: string;\n\n  /**\n   * Tamaño máximo permitido por archivo individual, en MB.\n   * @default DEFAULT_MAX_FILE_SIZE_MB (10 MB)\n   */\n  maxFileSizeMB?: number;\n\n  /**\n   * Tamaño máximo acumulado de todos los archivos del registro, en MB.\n   * Se valida sumando el campo `size` de los GalleryResource existentes.\n   * @default DEFAULT_MAX_TOTAL_SIZE_MB (50 MB)\n   */\n  maxTotalSizeMB?: number;\n\n  /**\n   * Permite seleccionar y subir múltiples archivos a la vez.\n   * En false, solo se acepta un archivo por operación de subida.\n   * @default true\n   */\n  multipleFiles?: boolean;\n}\n","import React, { useState, useEffect } from 'react';\nimport { \n  XMarkIcon, \n  ChevronLeftIcon, \n  DocumentIcon,\n  PhotoIcon\n} from '@heroicons/react/24/outline';\nimport { Button } from '../Button/Button';\nimport { Checkbox } from '../Checkbox/Checkbox';\nimport { FileUploader } from '../FileUploader/FileUploader';\nimport { AlertDialog } from '../AlertDialog/AlertDialog';\nimport type { FileUploaderGalleryProps, GalleryResource } from './FileUploaderGallery.types';\nimport { DEFAULT_ACCEPTED_EXTENSIONS, DEFAULT_MAX_FILE_SIZE_MB, DEFAULT_MAX_TOTAL_SIZE_MB } from './FileUploaderGallery.types';\n\n/**\n * FileUploaderGallery Item Component with internal loading, error and deletion states\n */\nconst GalleryItem: React.FC<{\n  resource: GalleryResource;\n  allowSelection: boolean;\n  allowDeletion: boolean;\n  onResourceCheck?: any;\n  onDeleteRequest: (resource: GalleryResource) => void;\n  isImage: (type: string) => boolean;\n  showFileName?: boolean;\n}> = ({ \n  resource, \n  allowSelection, \n  allowDeletion, \n  onResourceCheck, \n  onDeleteRequest, \n  isImage, \n  showFileName \n}) => {\n  const [isLoaded, setIsLoaded] = useState(false);\n  const [hasError, setHasError] = useState(false);\n  const esImg = isImage(resource.type);\n  const shouldShowName = showFileName ?? !esImg;\n\n  return (\n    <div className=\"group relative flex flex-col gap-2 animate-in zoom-in-95 duration-200\">\n      <div className=\"relative aspect-[3/4] w-full bg-gray-100 dark:bg-gray-800 rounded-lg border border-border-primary dark:border-dark-border-primary overflow-hidden\">\n        {/* Individual Skeleton while image loads and no error */}\n        {esImg && !isLoaded && !hasError && (\n          <div className=\"absolute inset-0 z-0 animate-pulse bg-gray-200 dark:bg-gray-700\" />\n        )}\n\n        {hasError ? (\n          /* Error State UI */\n          <div className=\"size-full flex flex-col items-center justify-center gap-2 bg-gray-50 dark:bg-gray-900/40 p-4 transition-colors\">\n            <div className=\"relative\">\n              <PhotoIcon className=\"size-10 text-gray-300 dark:text-gray-600\" />\n              <div className=\"absolute -top-1 -right-1 size-4 bg-white dark:bg-dark-bg-primary rounded-full flex items-center justify-center\">\n                <XMarkIcon className=\"size-3 text-red-500\" />\n              </div>\n            </div>\n            <span className=\"text-[10px] leading-tight text-gray-400 dark:text-gray-500 font-medium text-center uppercase tracking-wider\">\n              Recurso no disponible\n            </span>\n          </div>\n        ) : esImg ? (\n          <img \n            src={resource.url} \n            alt={resource.name} \n            onLoad={() => setIsLoaded(true)}\n            onError={() => {\n              setHasError(true);\n              setIsLoaded(true);\n            }}\n            className={`size-full object-cover transition-all duration-500 group-hover:scale-105 ${\n              isLoaded ? 'opacity-100' : 'opacity-0'\n            }`}\n          />\n        ) : (\n          <div className=\"size-full flex items-center justify-center\">\n            <DocumentIcon className=\"size-12 text-gray-400 dark:text-gray-500\" />\n          </div>\n        )}\n\n        {/* Checkbox Overlay */}\n        {allowSelection && (\n          <div className=\"absolute top-2 left-2 z-10\">\n            <Checkbox \n              checked={resource.checked}\n              onChange={(e) => onResourceCheck?.(resource.uuid, e.target.checked)}\n              className=\"!p-0\"\n            />\n          </div>\n        )}\n\n        {/* Delete Overlay */}\n        {allowDeletion && (\n          <div className=\"absolute top-2 right-2 z-10\">\n            <button\n              type=\"button\"\n              onClick={(e) => {\n                e.stopPropagation();\n                onDeleteRequest(resource);\n              }}\n              className=\"p-1 bg-white/80 dark:bg-dark-bg-primary/80 backdrop-blur-sm rounded-full border border-red-200 dark:border-red-900 shadow-sm hover:bg-red-50 dark:hover:bg-red-900/40 transition-all active:scale-90\"\n              title=\"Eliminar recurso\"\n              aria-label=\"Eliminar recurso\"\n            >\n              <XMarkIcon className=\"size-4 text-red-600 dark:text-red-400\" />\n            </button>\n          </div>\n        )}\n      </div>\n\n      {shouldShowName && (\n        <span \n          className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary truncate px-1\"\n          title={resource.name}\n        >\n          {resource.name}\n        </span>\n      )}\n    </div>\n  );\n};\n\n/**\n * FileUploaderGallery from the Siesa design system\n */\nexport const FileUploaderGallery: React.FC<FileUploaderGalleryProps> = ({\n  title,\n  entity,\n  entityId,\n  mode = 'modal',\n  isMaximized = false,\n  resources = [],\n  allowSelection = false,\n  acceptButtonText = 'Aceptar',\n  showFileUploader = true,\n  showFileName,\n  isLoading = false,\n  allowDeletion = false,\n  error = null,\n  onAccept,\n  onClose,\n  onBack,\n  onUpload,\n  onDelete,\n  onResourceCheck,\n  className = '',\n  embedded = false,\n  acceptedExtensions = DEFAULT_ACCEPTED_EXTENSIONS,\n  maxFileSizeMB = DEFAULT_MAX_FILE_SIZE_MB,\n  maxTotalSizeMB = DEFAULT_MAX_TOTAL_SIZE_MB,\n  multipleFiles = true,\n}) => {\n  const [resourceToDelete, setResourceToDelete] = useState<GalleryResource | null>(null);\n  const [internalError, setInternalError] = useState<{ title: string; message: string } | null>(null);\n  const [isDeleting, setIsDeleting] = useState(false);\n\n  // Sync internal error state with prop\n  useEffect(() => {\n    if (error) {\n      setInternalError(error);\n    } else {\n      setInternalError(null);\n    }\n  }, [error]);\n\n  // ===== IMAGE DETECTION LOGIC =====\n  const isImage = (type: string) => {\n    return type.startsWith('image/') || \n           /\\.(jpg|jpeg|png|gif|webp|svg)$/i.test(type);\n  };\n\n  // ===== SKELETON RENDERER (Global) =====\n  const renderSkeletons = () => {\n    return Array.from({ length: 4 }).map((_, i) => (\n      <div key={`skeleton-${i}`} className=\"flex flex-col gap-2 animate-pulse\">\n        <div className=\"aspect-[3/4] w-full bg-gray-200 dark:bg-gray-800 rounded-lg border border-border-primary dark:border-dark-border-primary\" />\n        <div className=\"h-4 w-3/4 bg-gray-200 dark:bg-gray-800 rounded px-1\" />\n      </div>\n    ));\n  };\n\n  // ===== UPLOAD LOGIC =====\n  const handleUploadFunction = async (file: File, onProgress: (p: number) => void) => {\n    // Validar tamaño individual\n    const maxBytes = maxFileSizeMB * 1024 * 1024;\n    if (file.size > maxBytes) {\n      setInternalError({\n        title: 'Archivo demasiado grande',\n        message: `El archivo \"${file.name}\" supera el límite de ${maxFileSizeMB} MB por archivo.`,\n      });\n      throw new Error('file-too-large');\n    }\n\n    // Validar tamaño acumulado con los archivos ya existentes\n    const currentTotalBytes = resources.reduce((sum, r) => sum + (r.size ?? 0), 0);\n    if (currentTotalBytes + file.size > maxTotalSizeMB * 1024 * 1024) {\n      setInternalError({\n        title: 'Límite de almacenamiento superado',\n        message: `El tamaño total de archivos no puede superar ${maxTotalSizeMB} MB. Elimina archivos existentes antes de continuar.`,\n      });\n      throw new Error('total-size-exceeded');\n    }\n\n    if (onUpload) {\n      onProgress(50);\n      await onUpload(file);\n      onProgress(100);\n      return { url: URL.createObjectURL(file), name: file.name };\n    }\n    onProgress(100);\n    return URL.createObjectURL(file);\n  };\n\n  // ===== DELETE LOGIC (Optimistic) =====\n  const confirmDelete = async () => {\n    if (!resourceToDelete || !onDelete) return;\n\n    const resourceId = resourceToDelete.uuid;\n    setResourceToDelete(null);\n    \n    try {\n      setIsDeleting(true);\n      await onDelete(resourceId);\n    } catch (err) {\n      console.error('Error al eliminar recurso:', err);\n    } finally {\n      setIsDeleting(false);\n    }\n  };\n\n  // ===== MAIN CONTAINER CLASSES =====\n  const containerClasses = [\n    mode === 'modal' ? 'fixed inset-0 z-[80] flex items-center justify-center bg-black/50 p-4' : 'w-full h-full',\n    'animate-in fade-in duration-200',\n    className\n  ].join(' ').trim();\n\n  // ===== MODAL/PANEL CLASSES =====\n  const panelClasses = [\n    'bg-white dark:bg-dark-bg-primary',\n    'border border-border-primary dark:border-dark-border-primary',\n    'flex flex-col overflow-hidden',\n    mode === 'modal' ? (isMaximized ? 'w-full h-full rounded-none' : 'w-full max-w-[800px] max-h-[90vh] rounded-2xl shadow-2xl') : 'w-full h-full rounded-none'\n  ].join(' ').trim();\n\n  return (\n    <div className={containerClasses}>\n      <div className={panelClasses}>\n        {/* ===== HEADER ===== */}\n        {!embedded && (\n          <div className=\"bg-[#f4f4f5] dark:bg-dark-bg-primary/50 border-b border-border-primary dark:border-dark-border-primary px-5 py-4 flex items-center justify-between shrink-0\">\n            <div className=\"flex items-center gap-4\">\n              {mode === 'page' && onBack && (\n                <button\n                  type=\"button\"\n                  onClick={onBack}\n                  className=\"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-full transition-colors\"\n                  aria-label=\"Volver\"\n                >\n                  <ChevronLeftIcon className=\"size-6 text-content-primary dark:text-dark-content-primary\" />\n                </button>\n              )}\n              <h3 className=\"text-[20px] font-bold text-content-primary dark:text-dark-content-primary leading-7 tracking-tight\">\n                {title}\n              </h3>\n            </div>\n\n            {mode === 'modal' && (\n              <button\n                type=\"button\"\n                onClick={onClose}\n                className=\"p-1.5 border border-[#93d1fd] dark:border-dark-border-custom bg-white dark:bg-dark-bg-primary rounded-md shadow-sm hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors\"\n                aria-label=\"Cerrar\"\n              >\n                <XMarkIcon className=\"size-4 text-primary-custom-600 dark:text-primary-custom-400\" />\n              </button>\n            )}\n          </div>\n        )}\n\n        {/* ===== BODY ===== */}\n        <div className=\"flex-1 overflow-y-auto p-5 scrollbar-thin scrollbar-thumb-border-primary dark:scrollbar-thumb-dark-border-primary\">\n          <div className=\"grid grid-cols-2 md:grid-cols-4 gap-5 items-stretch\">\n            {/* FileUploader Slot */}\n            {showFileUploader && (\n              <div className=\"col-span-2\">\n                <FileUploader\n                  variant=\"dropzone\"\n                  uploadFunction={handleUploadFunction}\n                  label=\"Subir archivo\"\n                  subLabel=\"o arrastra y suelta aquí\"\n                  accept={acceptedExtensions}\n                  maxSize={maxFileSizeMB * 1024 * 1024}\n                  multiple={multipleFiles}\n                  className=\"h-full\"\n                  classNames={{\n                    dropzoneInactive: 'h-full min-h-[180px] flex flex-col justify-center',\n                    dropzoneActive: 'h-full min-h-[180px] flex flex-col justify-center'\n                  }}\n                />\n              </div>\n            )}\n\n            {/* Skeletons while loading */}\n            {isLoading && renderSkeletons()}\n\n            {/* Resources List */}\n            {!isLoading && resources.map((resource) => (\n              <GalleryItem \n                key={resource.uuid}\n                resource={resource}\n                allowSelection={allowSelection}\n                allowDeletion={allowDeletion}\n                onDeleteRequest={(r) => setResourceToDelete(r)}\n                onResourceCheck={(uuid: string, checked: boolean) => {\n                  const updated = resources.map(r => r.uuid === uuid ? { ...r, checked } : r);\n                  const selected = updated.filter(r => r.checked);\n                  onResourceCheck?.(uuid, checked, selected);\n                }}\n                isImage={isImage}\n                showFileName={showFileName}\n              />\n            ))}\n          </div>\n        </div>\n\n        {/* ===== FOOTER ===== */}\n        {!embedded && <div className=\"bg-[#f4f4f5] dark:bg-dark-bg-primary/50 border-t border-border-primary dark:border-dark-border-primary px-5 py-4 flex items-center justify-end gap-3 shrink-0\">\n          <Button\n            type=\"plain\"\n            size=\"l\"\n            onClick={onClose}\n            className=\"text-primary-600 dark:text-primary-400 hover:bg-primary-50 dark:hover:bg-primary-900/10\"\n          >\n            Cancelar\n          </Button>\n          <Button\n            type=\"default\"\n            size=\"l\"\n            onClick={() => onAccept?.(resources.filter(r => r.checked))}\n          >\n            {acceptButtonText}\n          </Button>\n        </div>}\n      </div>\n\n      {/* ===== CONFIRMATION ALERT ===== */}\n      {resourceToDelete && (\n        <div className=\"fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-[2px] p-4 animate-in fade-in duration-200\">\n          <AlertDialog\n            title=\"Eliminar recurso\"\n            confirmText=\"Eliminar\"\n            cancelText=\"Cancelar\"\n            onConfirm={confirmDelete}\n            onCancel={() => setResourceToDelete(null)}\n          >\n            <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n              {`¿Estás seguro de que deseas eliminar \"${resourceToDelete.name}\"? Esta acción no se puede deshacer.`}\n            </p>\n          </AlertDialog>\n        </div>\n      )}\n\n      {/* ===== ERROR ALERT ===== */}\n      {internalError && (\n        <div className=\"fixed inset-0 z-[110] flex items-center justify-center bg-black/60 backdrop-blur-[2px] p-4 animate-in fade-in duration-200\">\n          <AlertDialog\n            title={internalError.title}\n            confirmText=\"Entendido\"\n            onConfirm={() => setInternalError(null)}\n          >\n            <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n              {internalError.message}\n            </p>\n          </AlertDialog>\n        </div>\n      )}\n    </div>\n  );\n};\n","import { createContext, useContext } from 'react';\n\nexport interface FileGalleryRegistrationContextValue {\n  register: (saveCallback: (recordId: string | number) => Promise<boolean>) => void;\n}\n\nexport const FileGalleryRegistrationContext = createContext<FileGalleryRegistrationContextValue>({\n  register: () => {}\n});\n\nexport const useFileGalleryRegistration = () => useContext(FileGalleryRegistrationContext);\n","import React, { useContext, useEffect, useRef } from 'react';\nimport { FileUploaderGallery } from '../FileUploaderGallery/FileUploaderGallery';\nimport { FileGalleryRegistrationContext } from './FileGalleryRegistrationContext';\nimport type { GalleryResource } from '../FileUploaderGallery/FileUploaderGallery.types';\nimport type { FileManagerConfig } from './MasterCrud.types';\n\nexport interface MasterCrudFileManagerProps {\n  /** Current record ID (undefined in CREATE mode until the record is saved) */\n  entityId?: string | number;\n  /** Entity name passed to the gallery */\n  entityName: string;\n  /** File management configuration (resources, callbacks) */\n  config: FileManagerConfig;\n}\n\n/**\n * MasterCrudFileManager — embedded FileUploaderGallery inside a MasterCrud form tab.\n *\n * Renders the gallery without header/footer (embedded mode) and registers its\n * save callback via FileGalleryRegistrationContext so MasterCrud can trigger it\n * after the record is successfully saved.\n */\nexport const MasterCrudFileManager: React.FC<MasterCrudFileManagerProps> = ({\n  entityId,\n  entityName,\n  config,\n}) => {\n  const { register } = useContext(FileGalleryRegistrationContext);\n  const selectedResourcesRef = useRef<GalleryResource[]>([]);\n\n  const handleResourceCheck = (uuid: string, checked: boolean, selectedResources: GalleryResource[]) => {\n    selectedResourcesRef.current = selectedResources;\n    config.onResourceCheck?.(uuid, checked, selectedResources);\n  };\n\n  const saveFileManagement = async (recordId: string | number): Promise<boolean> => {\n    try {\n      if (config.onAccept) {\n        await config.onAccept(selectedResourcesRef.current, recordId);\n      }\n      return true;\n    } catch {\n      return false;\n    }\n  };\n\n  useEffect(() => {\n    register(saveFileManagement);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return (\n    <FileUploaderGallery\n      title=\"\"\n      entity={config.entity || entityName}\n      entityId={entityId ?? ''}\n      mode=\"page\"\n      embedded\n      resources={config.resources ?? []}\n      allowSelection={config.allowSelection}\n      allowDeletion={config.allowDeletion}\n      showFileUploader={!!entityId && config.showFileUploader !== false}\n      isLoading={config.isLoading}\n      error={config.error}\n      onUpload={config.onUpload && entityId ? (file) => config.onUpload!(file, entityId) : undefined}\n      onDelete={config.onDelete && entityId ? (uuid) => config.onDelete!(uuid, entityId) : undefined}\n      onResourceCheck={handleResourceCheck}\n      acceptedExtensions={config.acceptedExtensions}\n      maxFileSizeMB={config.maxFileSizeMB}\n      maxTotalSizeMB={config.maxTotalSizeMB}\n      multipleFiles={config.multipleFiles}\n      showFileName={config.showFileName}\n      acceptButtonText={config.acceptButtonText}\n      className={config.className}\n    />\n  );\n};\n","import React, { useState, useCallback, useEffect, useImperativeHandle, forwardRef, useRef } from 'react';\nimport { Input } from '../Input/Input';\nimport { Select } from '../Select/Select';\nimport { LookupField } from '../LookupField';\nimport { Switch } from '../Switch/Switch';\nimport { Button } from '../Button/Button';\nimport { AlertDialog } from '../AlertDialog/AlertDialog';\nimport { Dropdown } from '../Dropdown/Dropdown';\nimport { CompanySelector } from './CompanySelector';\nimport type { MasterCrudFormProps, MasterCrudField, FormState } from './MasterCrud.types';\nimport { CloseIcon as XMarkIcon, RevertIcon, GlobeAltIcon, Bars3Icon, PlusIcon, LinkIcon } from './icons';\n\n// Entidades Dinámicas\nimport { DynamicEntities, type DynamicEntitiesRef } from '../DynamicEntities/ui/DynamicEntities';\nimport { MasterCrudDynamicEntities } from './MasterCrudDynamicEntities';\nimport { DynamicEntitiesRegistrationContext } from './DynamicEntitiesRegistrationContext';\nimport { useOptionalDynamicEntitiesContext } from '../DynamicEntities/core/DynamicEntitiesProvider';\nimport { FeatureService, type Feature } from '../DynamicEntities/admin/services/FeatureService';\n\n// Gestión de Archivos\nimport { MasterCrudFileManager } from './MasterCrudFileManager';\nimport { FileGalleryRegistrationContext } from './FileGalleryRegistrationContext';\n\n/**\n * Componente interno para resolver nombres de Lookups en Valores Globales.\n *\n * Construye un SearchRequest completo (con `fields` y el filtro usando `valueField`)\n * para que backends reales que requieren el contrato estricto de LookupField funcionen\n * correctamente y muestren el display text en lugar del GUID/ID crudo.\n */\nconst GlobalLookupResolver = ({\n  id,\n  lookupConfig,\n  t\n}: {\n  id: any,\n  lookupConfig: any,\n  t: (key: string, def?: string) => string\n}) => {\n  const [resolvedValue, setResolvedValue] = React.useState<string | null>(null);\n  const [loading, setLoading] = React.useState(true);\n\n  React.useEffect(() => {\n    if (id === undefined || id === null || id === '') return;\n\n    const fetchResolvedValue = async () => {\n      try {\n        // El campo que actúa como PK en la respuesta del fetcher.\n        // LookupField usa 'Id' (PascalCase) como estándar, pero lookupConfig.valueField\n        // puede declarar un nombre diferente (ej: 'id', 'uuid', 'codigo').\n        const valueField: string = lookupConfig.valueField || 'Id';\n\n        // Construir el array de fields para que el backend sepa qué columnas retornar.\n        // Sin este campo el contrato SearchRequest queda incompleto y backends reales\n        // retornan data vacía o sin las columnas de displayFields → mostraba GUID.\n        const requestFields: string[] = [\n          ...new Set([...lookupConfig.displayFields, valueField])\n        ];\n\n        // Usar valueField como clave del filtro en lugar de 'Id' hardcodeado,\n        // para que el match funcione independientemente de cómo se llame el PK.\n        const filterCondition: Record<string, any> = { [valueField]: id };\n\n        const response = await lookupConfig.fetcher(lookupConfig.entity, {\n          fields: requestFields,\n          filters: [[filterCondition]],\n          page: 1,\n          pageSize: 1\n        });\n\n        if (response.data && response.data[0]) {\n          const record = response.data[0];\n          const text = lookupConfig.displayFields\n            .map((f: string) => record[f])\n            .filter(Boolean)\n            .join(' - ');\n          setResolvedValue(text || String(id));\n        } else {\n          setResolvedValue(String(id));\n        }\n      } catch (e) {\n        setResolvedValue(String(id));\n      } finally {\n        setLoading(false);\n      }\n    };\n\n    fetchResolvedValue();\n  }, [id, lookupConfig]);\n\n  if (loading) return <span className=\"animate-pulse opacity-70 italic text-[11px]\">{t('loading', 'Cargando...')}</span>;\n  return <span>{resolvedValue}</span>;\n};\n\nconst defaultInitialData = {};\n\n/**\n * MasterCrudForm - Generador dinámico de formularios para MasterCrud\n *\n * Genera automáticamente un formulario basado en la definición de campos,\n * reutilizando los componentes atómicos del sistema de diseño.\n */\nexport const MasterCrudForm = forwardRef(<T extends Record<string, any>>(\n  {\n    fields,\n    entityName,\n    dynamicFeatureCode,\n    initialData,\n    isEditing = false,\n    loading = false,\n    onSubmit,\n    onCancel,\n    saveButtonText,\n    cancelButtonText,\n    columns = 2,\n    width = '600px',\n    className = '',\n    actions = [],\n    hideHeaderFooter = false,\n    fullWidthButton = false,\n    isReadOnly = false,\n    idField = 'id',\n    id,\n    selectedCompany,\n    activeByCompany = false,\n    companyRequired = false,\n    showGlobalValues = false,\n    onSearchMatches,\n    canOverrideMultiCompany = true,\n    companies = [],\n    onCompanyChange,\n    onShowGlobalValuesChange,\n    onUseGlobalData,\n    onCreateNew,\n    onLinkCompanies,\n    renderContent,\n    hideDynamicTabs = false,\n    registerDynamicRef: propRegisterDynamicRef,\n    t,\n    showValidationErrorDialog = false, // Restaurado a false por defecto\n    formTabs,\n    featCodeFileManager,\n    fileManagerConfig,\n  }: MasterCrudFormProps<T>,\n  ref: React.Ref<any>\n) => {\n  const effectiveHideDynamicTabs = hideDynamicTabs || !!renderContent;\n\n  // ===== PESTAÑAS DE CAMPOS (formTabs) — renderizado automático en tabs (opcional) =====\n  // Solo aplica cuando se usa el render automático (sin renderContent) y hay >1 pestaña.\n  const hasFieldTabs = !renderContent && Array.isArray(formTabs) && formTabs.length > 1;\n  const fieldTabs = hasFieldTabs ? formTabs! : [];\n  // Devuelve la clave de pestaña de un campo: config.tab, o la pestaña que lo lista en `fields`,\n  // o la primera pestaña como fallback.\n  const getFieldTabKey = React.useCallback((accessorKey: string): string => {\n    if (!hasFieldTabs) return 'main';\n    const byList = fieldTabs.find(ft => ft.fields?.includes(accessorKey));\n    if (byList) return byList.key;\n    const field = fields.find(f => (f.accessorKey as string) === accessorKey);\n    const cfgTab = field?.config?.tab;\n    if (cfgTab && fieldTabs.some(ft => ft.key === cfgTab)) return cfgTab;\n    return fieldTabs[0].key;\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [hasFieldTabs, fieldTabs, fields]);\n\n  const defaultId = React.useId();\n  const formId = id || `form-${defaultId}`;\n\n  // Use translations for defaults if props are not provided\n  const finalSaveText = saveButtonText || t('save');\n  const finalCancelText = cancelButtonText || t('cancel');\n  // ===== ESTADO DEL FORMULARIO =====\n\n  const [formState, setFormState] = useState<FormState<T>>({\n    values: (initialData || defaultInitialData) as Partial<T>,\n    errors: {},\n    touched: {},\n    isSubmitting: false,\n  });\n\n  // Referencia mutable para sincronizar siempre los valores más recientes\n  // Esto previene cierres obsoletos (stale closures) en handleSubmit y callbacks externos\n  const valuesRef = useRef<Partial<T>>((initialData || defaultInitialData) as Partial<T>);\n\n  useEffect(() => {\n    valuesRef.current = formState.values;\n  }, [formState.values]);\n\n  const [errorAlert, setErrorAlert] = useState<{ show: boolean; message: string; title?: string }>({\n    show: false,\n    message: '',\n  });\n\n  const [devDynamicEntitiesWarning, setDevDynamicEntitiesWarning] = useState(false);\n\n  const lastSearchedValue = useRef<string>('');\n  // ref to the actual <form> DOM element, used by the imperative submit() to dispatch a native event\n  const formElementRef = useRef<HTMLFormElement | null>(null);\n\n  // Ref de seguridad para evitar doble envío incluso en micro-tareas\n  const isSubmittingRef = useRef(false);\n\n  // Variable para rastrear el ID del registro inicializado y evitar resets accidentales\n  const initializedRecordIdRef = useRef<string | number | null>(null);\n\n  // ===== SINCRONIZAR DATOS INICIALES =====\n  useEffect(() => {\n    const currentId = (initialData as any)?.[idField];\n    \n    // Solo reseteamos el estado si el ID ha cambiado o si no se ha inicializado nada aún\n    if (initializedRecordIdRef.current !== currentId || (!currentId && !initializedRecordIdRef.current)) {\n      setFormState((prev) => ({\n        ...prev,\n        values: (initialData || defaultInitialData) as Partial<T>,\n        errors: {},\n        touched: {},\n      }));\n      initializedRecordIdRef.current = currentId || null;\n      isSubmittingRef.current = false;\n    }\n  }, [initialData, idField]);\n\n  // ===== LÓGICA DE ENTIDADES DINÁMICAS =====\n  const dynamicContext = useOptionalDynamicEntitiesContext();\n  const [dynamicFeature, setDynamicFeature] = useState<Feature | null>(null);\n  const [activeGlobalTab, setActiveGlobalTab] = useState<string>(() => (hasFieldTabs ? fieldTabs[0].key : 'main'));\n  const dynamicRefs = useRef<Record<string, DynamicEntitiesRef | null>>({});\n\n  // TabBar: indicador deslizante con rebote (S2.3). El rebote lo da el easing de `left`;\n  // el ancho cambia suave sin overshoot. Grosor constante 2.5px.\n  const tabsRowRef = useRef<HTMLDivElement>(null);\n  const tabIndicatorRef = useRef<HTMLSpanElement>(null);\n  const moveTabIndicator = useCallback((instant?: boolean) => {\n    const row = tabsRowRef.current;\n    const ind = tabIndicatorRef.current;\n    if (!row || !ind) return;\n    const active = row.querySelector<HTMLElement>(`[data-tabkey=\"${activeGlobalTab}\"]`);\n    if (!active) return;\n    if (instant) ind.style.transition = 'none';\n    ind.style.left = `${active.offsetLeft}px`;\n    ind.style.width = `${active.offsetWidth}px`;\n    if (instant) { void ind.offsetWidth; ind.style.transition = ''; }\n  }, [activeGlobalTab]);\n  // Cambio de pestaña: reposiciona con animación (rebote).\n  useEffect(() => { moveTabIndicator(); }, [moveTabIndicator]);\n  // Cambio de errores de validación: al aparecer/desaparecer los badges rojos, el ancho de las\n  // pestañas cambia; se re-mide **con animación** para que el subrayado se **deslice** suavemente\n  // hasta quedar bajo la pestaña activa (no \"entre dos\" pestañas), conservando el efecto de\n  // movimiento. (No dependemos de moveTabIndicator para no re-disparar en cada cambio de pestaña.)\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  useEffect(() => { moveTabIndicator(); }, [formState.errors]);\n\n  // Al activar las pestañas de campos (formTabs), si la pestaña activa no es una de ellas\n  // (p. ej. venía en 'main' al alternar \"Con pestañas\"), seleccionar la primera pestaña.\n  useEffect(() => {\n    if (hasFieldTabs && !fieldTabs.some((ft) => ft.key === activeGlobalTab)) {\n      setActiveGlobalTab(fieldTabs[0].key);\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [hasFieldTabs, activeGlobalTab]);\n\n  // ===== DETECCIÓN EN DEV: renderForm sin MasterCrudDynamicEntities =====\n  const dynamicEntitiesRegisteredRef = useRef(false);\n  const registerDynamicEntitiesPresence = useCallback(() => {\n    dynamicEntitiesRegisteredRef.current = true;\n  }, []);\n  const registrationContextValue = React.useMemo(\n    () => ({ register: registerDynamicEntitiesPresence }),\n    [registerDynamicEntitiesPresence]\n  );\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== 'development') return;\n    if (!renderContent || !dynamicFeatureCode) return;\n    if (loading) return; // Mientras loading=true el renderForm puede mostrar skeleton sin MasterCrudDynamicEntities\n    if (!dynamicEntitiesRegisteredRef.current) {\n      setDevDynamicEntitiesWarning(true);\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [loading]); // Re-evalúa cuando el formulario termina de cargar\n\n  useEffect(() => {\n    if (dynamicFeatureCode && dynamicContext?.baseUrl) {\n      const service = new FeatureService(dynamicContext.baseUrl, dynamicContext.fetcher);\n      service.getByPath(dynamicFeatureCode)\n        .then(f => {\n          setDynamicFeature(f);\n        })\n        .catch(err => console.warn(\"[MasterCrudForm] Feature not found or dynamic entities disabled for this feature\", err));\n    }\n  }, [dynamicFeatureCode, dynamicContext?.baseUrl, dynamicContext?.fetcher]);\n\n  const hasStandardDynamicEntities = dynamicFeature?.featureEntities?.some((fe: any) => !fe.dynamicEntity?.isPlansAndCriteria);\n  const hasPlansAndCriteriaEntities = dynamicFeature?.featureEntities?.some((fe: any) => !!fe.dynamicEntity?.isPlansAndCriteria);\n\n  // ===== LÓGICA DE GESTIÓN DE ARCHIVOS =====\n  const fileGallerySaveRef = useRef<((recordId: string | number) => Promise<boolean>) | null>(null);\n  const fileGalleryRegisteredRef = useRef(false);\n  const [devFileManagerWarning, setDevFileManagerWarning] = useState(false);\n\n  const registerFileGallerySave = useCallback((saveCallback: (recordId: string | number) => Promise<boolean>) => {\n    fileGallerySaveRef.current = saveCallback;\n    fileGalleryRegisteredRef.current = true;\n  }, []);\n\n  const fileGalleryRegistrationContextValue = React.useMemo(\n    () => ({ register: registerFileGallerySave }),\n    [registerFileGallerySave]\n  );\n\n  // Detección en DEV: renderForm sin MasterCrudFileManager cuando se requiere.\n  // Solo aplica si el Feature del backend tiene has_file_management=true; si está\n  // desactivado en BD el tab no se renderiza, así que no exigimos el componente.\n  useEffect(() => {\n    if (process.env.NODE_ENV !== 'development') return;\n    if (!renderContent || !featCodeFileManager) return;\n    if (!dynamicFeature?.hasFileManagement) return;\n    if (loading) return;\n    if (!fileGalleryRegisteredRef.current) {\n      setDevFileManagerWarning(true);\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [loading, dynamicFeature]);\n\n  // El tab de gestión de archivos requiere TRES condiciones:\n  //   1. Wiring del desarrollador: `featCodeFileManager` + `fileManagerConfig`\n  //      (o un service con `getFiles/uploadFile/deleteFile`, que MasterCrud\n  //       construye en `effectiveFileManagerConfig`).\n  //   2. Flag del backend: el Feature asociado (`dynamicFeatureCode`) debe tener\n  //      `has_file_management = true` en la columna del proyecto de entidades\n  //      dinámicas. Es la fuente de verdad final — desactivarla en BD oculta el\n  //      tab aun si el desarrollador implementó todas las props.\n  //   3. Registro persistido: en CREATE el registro aún no existe, así que no\n  //      hay entityId para asociar archivos. El tab solo se muestra en EDIT.\n  const fileManagerRecordId = (initialData as any)?.[idField];\n  const hasFileManagement =\n    !!dynamicFeature?.hasFileManagement &&\n    !!featCodeFileManager &&\n    !!fileManagerConfig &&\n    !!fileManagerRecordId;\n\n  // ===== EXPONER MÉTODOS AL PADRE =====\n  useImperativeHandle(ref, () => ({\n    revertAllToGlobal: () => {\n      const globalData = (initialData as any)?._globalValues;\n      if (!globalData) return;\n\n      const overrideableFields = fields.filter(f => f.config?.allowMultiCompanyOverride);\n\n      setFormState(prev => {\n        const newValues = { ...prev.values } as any;\n        overrideableFields.forEach(field => {\n          const accessor = field.accessorKey as string;\n          if (globalData[accessor] !== undefined) {\n            newValues[accessor] = globalData[accessor];\n          }\n        });\n        return { ...prev, values: newValues };\n      });\n    },\n    saveDynamicEntities: async (recordId: string | number) => {\n      const entityCodes = Object.keys(dynamicRefs.current);\n      const activeEntities = entityCodes.filter(code => !!dynamicRefs.current[code]);\n\n      if (activeEntities.length > 0) {\n        const savePromises = activeEntities.map(async (code) => {\n          const entityRef = dynamicRefs.current[code];\n          if (entityRef && typeof entityRef.save === 'function') {\n            return await entityRef.save(String(recordId));\n          }\n          return true;\n        });\n        const results = await Promise.all(savePromises);\n        return !results.some(res => res === false); // Devuelve true si no hay fallos\n      }\n      return true;\n    },\n    // Guardar gestión de archivos tras el guardado del registro base\n    saveFileManagement: async (recordId: string | number): Promise<boolean> => {\n      if (!hasFileManagement || !fileGallerySaveRef.current) return true;\n      return fileGallerySaveRef.current(recordId);\n    },\n    // Método para disparar el submit desde fuera\n    submit: () => {\n      console.log(\"%c[MasterCrudForm] submit() invocado desde ref externa\", \"color: #0ea5e9; font-weight: bold; padding: 2px; border: 1px solid #0ea5e9; border-radius: 4px;\");\n      \n      if (formElementRef.current) {\n        // Disparamos el evento nativo para que cualquier interceptor (como ItemMasterForm) actúe.\n        const event = new Event('submit', { bubbles: true, cancelable: true });\n        formElementRef.current.dispatchEvent(event);\n      }\n      \n      // Ejecutamos SIEMPRE handleSubmit.\n      // Al usar isSubmittingRef, garantizamos que no haya doble ejecución si React ya capturó el evento.\n      // Esto soluciona el bug donde el guardado se detenía si alguien llamaba a e.preventDefault().\n      handleSubmit();\n    },\n    // Cambios sin guardar (dirty state, S2.8): compara los valores actuales contra el snapshot inicial.\n    getChanges: (): { label: string; from: any; to: any }[] => {\n      const initial = (initialData || defaultInitialData) as any;\n      const norm = (v: any) => (v === undefined || v === null ? '' : v);\n      const changes: { label: string; from: any; to: any }[] = [];\n      fields.forEach((f) => {\n        const k = f.accessorKey as string;\n        const from = initial?.[k];\n        const to = (formState.values as any)?.[k];\n        if (String(norm(from)) !== String(norm(to))) {\n          changes.push({ label: typeof f.header === 'string' ? f.header : k, from: norm(from), to: norm(to) });\n        }\n      });\n      return changes;\n    },\n    isDirty: (): boolean => {\n      const initial = (initialData || defaultInitialData) as any;\n      const norm = (v: any) => (v === undefined || v === null ? '' : v);\n      return fields.some((f) => {\n        const k = f.accessorKey as string;\n        return String(norm(initial?.[k])) !== String(norm((formState.values as any)?.[k]));\n      });\n    },\n  }));\n\n  // ===== LÓGICA DE REGISTRO DE REFS DINÁMICOS =====\n  const registerDynamicRef = useCallback((entityCode: string, r: any) => {\n    if (entityCode) {\n      if (r) {\n        dynamicRefs.current[entityCode] = r;\n      }\n\n      if (propRegisterDynamicRef) {\n        propRegisterDynamicRef(entityCode, r);\n      }\n    }\n  }, [propRegisterDynamicRef]);\n\n  // ===== OBTENER VALOR DE UN CAMPO =====\n  const getValue = useCallback(\n    (accessorKey: string): any => {\n      const keys = accessorKey.split('.');\n      let value: any = formState.values;\n      for (const key of keys) {\n        if (value === undefined || value === null) return undefined;\n        value = value[key];\n      }\n      return value;\n    },\n    [formState.values]\n  );\n\n  // ===== ESTABLECER VALOR DE UN CAMPO =====\n  const setValue = useCallback((accessorKey: string, value: any) => {\n    setFormState((prev) => {\n      const keys = accessorKey.split('.');\n      const newValues = { ...prev.values } as any;\n\n      if (keys.length === 1) {\n        newValues[accessorKey] = value;\n      } else {\n        let current = newValues;\n        for (let i = 0; i < keys.length - 1; i++) {\n          if (!current[keys[i]]) {\n            current[keys[i]] = {};\n          }\n          current = current[keys[i]];\n        }\n        current[keys[keys.length - 1]] = value;\n      }\n\n      return {\n        ...prev,\n        values: newValues,\n        touched: { ...prev.touched, [accessorKey]: true },\n      };\n    });\n  }, []);\n\n  // ===== MANEJAR REVERSIÓN INDIVIDUAL =====\n  const handleRevertSingleField = useCallback((field: MasterCrudField<T>) => {\n    const accessor = field.accessorKey as string;\n    const globalData = (initialData as any)?._globalValues;\n\n    if (globalData && globalData[accessor] !== undefined) {\n      setValue(accessor, globalData[accessor]);\n    }\n  }, [initialData, setValue]);\n\n  // ===== CONSTRUIR ITEMS DEL DROPDOWN DE ACCIONES PERSONALIZADAS =====\n  const actionItems = React.useMemo(() => {\n    if (!actions.length) return [];\n\n    // Descartar la opción de Editar si ya estamos en modo Edición\n    const filteredActions = isEditing\n      ? actions.filter(action => action.id !== 'edit')\n      : actions;\n\n    const record = initialData as T;\n\n    return filteredActions.map(action => {\n      const isDisabled = typeof action.disabled === 'function' ? action.disabled(record) : action.disabled;\n      const actionName = typeof action.name === 'function' ? action.name(record) : action.name;\n\n      return {\n        children: actionName,\n        icon: typeof action.icon === 'function' ? action.icon(record) : action.icon,\n        disabled: isDisabled,\n        onClick: () => action.action?.(record),\n        className: actionName.toLowerCase().includes('eliminar') || actionName.toLowerCase().includes('delete')\n          ? 'text-error-content hover:text-error-content dark:text-error-content'\n          : '',\n      };\n    });\n  }, [actions, initialData, isEditing]);\n\n  // ===== CONSTRUIR ITEMS DEL DROPDOWN DE CABECERA =====\n  const headerDropdownItems = React.useMemo(() => {\n    const items: any[] = [...actionItems];\n    const isGlobal = !selectedCompany || String(selectedCompany.uuid) === '000';\n\n    if (activeByCompany && isEditing) {\n      const mcActions: any[] = [];\n\n      // 1. Acciones de sucursal (No Global)\n      if (!isGlobal) {\n        mcActions.push({\n          children: t('useGlobalData', 'Usar datos globales'),\n          icon: <GlobeAltIcon className=\"w-4 h-4\" />,\n          onClick: onUseGlobalData\n        });\n        mcActions.push({\n          children: (\n            <div className=\"flex items-center justify-between w-full gap-4 py-1\">\n              <span className=\"text-sm font-medium\">{t('showGlobalValues', 'Mostrar valores globales')}</span>\n              <Switch\n                checked={showGlobalValues}\n                onChange={() => { }}\n                className=\"!w-auto pointer-events-none\"\n              />\n            </div >\n          ),\n          onClick: () => onShowGlobalValuesChange?.(!showGlobalValues),\n          className: 'hover:bg-transparent',\n        });\n        mcActions.push({ isDivider: true });\n      }\n\n      // 2. Habilitar (Disponible en Global y Sucursal)\n      mcActions.push({\n        children: t('linkCompanies', 'Habilitar compañías'),\n        icon: <LinkIcon className=\"w-4 h-4\" />,\n        onClick: onLinkCompanies\n      });\n\n      // 3. Crear nuevo (Siempre en edición)\n      mcActions.push({\n        children: t('createNew', 'Crear nuevo registro'),\n        icon: <PlusIcon className=\"w-4 h-4\" />,\n        onClick: onCreateNew\n      });\n\n      return [...mcActions, ...items];\n    }\n\n    return items;\n  }, [actionItems, activeByCompany, isEditing, selectedCompany, onUseGlobalData, showGlobalValues, onShowGlobalValuesChange, onLinkCompanies, onCreateNew]);\n\n  // ===== RESOLVER PROPIEDAD DINÁMICA =====\n  const resolveProp = useCallback((prop: boolean | ((data: any) => boolean) | undefined, data: any): boolean => {\n    if (typeof prop === 'function') {\n      return prop(data);\n    }\n    return !!prop;\n  }, []);\n\n  // ===== VALIDAR CAMPO =====\n  const validateField = useCallback(\n    (field: MasterCrudField<T>, value: any): string | undefined => {\n      // Usar valuesRef.current para evitar stale closures\n      const currentValues = valuesRef.current;\n      const isRequired = resolveProp(field.config?.required, currentValues);\n\n      if (isRequired) {\n        if (value === undefined || value === null || value === '') {\n          const fieldName = t(field.accessorKey as string, field.header);\n\n          // Intentar obtener traducciones con prefijo explícito si el t() no lo tiene\n          const theField = t('ui-mastercrud.theField', t('theField', ''));\n          const isRequiredMsg = t('ui-mastercrud.isRequired', t('isRequired', ''));\n\n          // Si t() no devolvió nada útil (devolvió la llave), aplicamos lógica de idioma\n          const isEnglish = t('ui-mastercrud.save', t('save', '')).toLowerCase().includes('save');\n\n          const finalPrefix = theField && !theField.includes('theField')\n            ? theField\n            : (isEnglish ? 'The field' : 'El campo');\n\n          const finalSuffix = isRequiredMsg && !isRequiredMsg.includes('isRequired')\n            ? isRequiredMsg\n            : (isEnglish ? 'is required' : 'es requerido');\n\n          return field.config?.errorMessage || `${finalPrefix} ${fieldName} ${finalSuffix}`;\n        }\n      }\n\n      if (field.config?.validate) {\n        return field.config.validate(value, currentValues as Record<string, any>);\n      }\n\n      if (value !== undefined && value !== null && value !== '') {\n        const strValue = String(value);\n\n        if (field.config?.maxLength !== undefined && strValue.length > field.config.maxLength) {\n          return `${t('maxLengthIs', 'La longitud máxima es de')} ${field.config.maxLength} ${t('characters', 'caracteres')}`;\n        }\n\n        if (field.config?.minLength !== undefined && strValue.length < field.config.minLength) {\n          return `${t('minLengthIs', 'La longitud mínima es de')} ${field.config.minLength} ${t('characters', 'caracteres')}`;\n        }\n\n        switch (field.type) {\n          case 'email':\n            const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n            if (!emailRegex.test(strValue)) {\n              return t('invalidEmail', 'Ingresa un correo electrónico válido');\n            }\n            break;\n\n          case 'number':\n            const numValue = Number(value);\n            if (isNaN(numValue)) {\n              return t('invalidNumber', 'Ingresa un número válido');\n            }\n            if (field.config?.min !== undefined && numValue < field.config.min) {\n              return `${t('minValueIs', 'El valor mínimo es')} ${field.config.min}`;\n            }\n            if (field.config?.max !== undefined && numValue > field.config.max) {\n              return `${t('maxValueIs', 'El valor máximo es')} ${field.config.max}`;\n            }\n            break;\n        }\n      }\n\n      return undefined;\n    },\n    [t]\n  );\n\n  // ===== VALIDAR TODO EL FORMULARIO =====\n  const validateForm = useCallback((): { isValid: boolean; errors: Record<string, string> } => {\n    const newErrors: Record<string, string> = {};\n    let isValid = true;\n\n    fields\n      .filter((field) => field.config?.visibleInForm !== false)\n      .forEach((field) => {\n        const value = getValue(field.accessorKey as string);\n        const error = validateField(field, value);\n        if (error) {\n          newErrors[field.accessorKey as string] = error;\n          isValid = false;\n        }\n      });\n\n    setFormState((prev) => ({\n      ...prev,\n      errors: newErrors,\n    }));\n\n    return { isValid, errors: newErrors };\n  }, [fields, getValue, validateField]);\n\n  // ===== EFECTO ON MOUNT =====\n  useEffect(() => {\n    visibleFields.forEach(field => {\n      if (field.config?.onMount) {\n        const fieldSetter = (val: any) => setValue(field.accessorKey as string, val);\n        field.config.onMount(fieldSetter, initialData as Record<string, any>);\n      }\n    });\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // ===== MANEJAR ENVÍO =====\n  const handleSubmit = useCallback(\n    (e?: React.FormEvent) => {\n      if (e) {\n        e.preventDefault();\n        e.stopPropagation();\n      }\n\n      if (isSubmittingRef.current || loading) {\n        console.log(\"[MasterCrudForm] Envío bloqueado: ya se está procesando o el formulario está en loading.\");\n        return;\n      }\n\n      isSubmittingRef.current = true;\n      console.log(\"%c[MasterCrudForm] Iniciando proceso de guardado...\", \"color: #22c55e; font-weight: bold; padding: 2px; border: 1px solid #22c55e; border-radius: 4px;\");\n\n      const { isValid, errors } = validateForm();\n\n      if (isValid) {\n        // EXTRAER VALORES ACTUALES DE LA REFERENCIA PARA EVITAR DATOS VIEJOS\n        const currentData = { ...valuesRef.current };\n\n        console.log(\"%c[MasterCrudForm] Envío exitoso. Datos capturados:\", \"color: #22c55e; font-weight: bold;\", currentData);\n\n        setFormState((prev) => ({ ...prev, isSubmitting: true }));\n        if (onSubmit) {\n          const result = onSubmit(currentData);\n          // Si el onSubmit devuelve una promesa, esperamos a que termine para resetear el flag\n          if (result && (result as any) instanceof Promise) {\n            (result as Promise<any>).finally(() => {\n              isSubmittingRef.current = false;\n              setFormState(prev => ({ ...prev, isSubmitting: false }));\n            });\n          } else {\n            // Si no es promesa, damos un pequeño margen para evitar dobles clics accidentales\n            setTimeout(() => {\n              isSubmittingRef.current = false;\n              setFormState(prev => ({ ...prev, isSubmitting: false }));\n            }, 500);\n          }\n        }\n      } else {\n        isSubmittingRef.current = false;\n        console.error(\"[MasterCrudForm] Error de validación. Campos afectados:\", errors);\n        const errorFields = Object.keys(errors).map(key => {\n          const field = fields.find(f => f.accessorKey === key);\n          // Traducimos el nombre del campo usando su accessorKey como llave\n          return field ? t(field.accessorKey as string, field.header) : key;\n        }).join(', ');\n\n        if (showValidationErrorDialog) {\n          setErrorAlert({\n            show: true,\n            title: t('incompleteTitle', 'Información incompleta'),\n            message: `${t('incompleteMessage', 'Para guardar, completa los siguientes campos obligatorios')}: ${errorFields}`\n          });\n        }\n      }\n    },\n    [onSubmit, validateForm, fields, t, showValidationErrorDialog, loading]\n  );\n\n  // Alias para mayor claridad en el renderizado\n  const handleInternalSubmit = (e?: any) => {\n    if (e && e.preventDefault) e.preventDefault();\n    handleSubmit();\n  };\n\n  // ===== MANEJAR BLUR =====\n  const handleBlur = (field: MasterCrudField<T>, value: any) => {\n    if (field.config?.onBlur) {\n      field.config.onBlur(value, field.accessorKey as string, formState.values as Record<string, any>);\n    }\n\n    // Lógica de búsqueda de coincidencias\n    const cleanValue = typeof value === 'string' ? value.trim() : '';\n\n    if (\n      !isEditing &&\n      activeByCompany &&\n      field.config?.checkMatchesOnBlur &&\n      cleanValue.length >= 3 &&\n      cleanValue !== lastSearchedValue.current\n    ) {\n      lastSearchedValue.current = cleanValue;\n      onSearchMatches?.(field, cleanValue);\n    }\n  };\n\n  // Mensaje de validación bajo el campo — estilo pixel-exact del prototipo de detalle:\n  // `flex items-center gap-[3px] text-xs text-[#dc2626]` con icono AlertTriangle de 11px.\n  const renderFieldError = (accessorKey: string): React.ReactNode => {\n    const msg = formState.errors[accessorKey];\n    if (!msg) return null;\n    return (\n      <p className=\"field-error flex items-center gap-[3px] mt-1 text-xs text-[#dc2626]\">\n        <svg className=\"w-[11px] h-[11px] flex-shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" /><path d=\"M12 9v4\" /><path d=\"M12 17h.01\" /></svg>\n        {msg}\n      </p>\n    );\n  };\n\n  // ===== FUNCIÓN DE RENDERIZADO PARA EL WRAPPER (Evita pérdida de foco al no ser un componente) =====\n  const renderFieldWrapper = (\n    field: MasterCrudField<T>,\n    children: React.ReactNode,\n    value: any\n  ) => {\n    const accessorKey = field.accessorKey as string;\n    const isRequired = resolveProp(field.config?.required, formState.values);\n    const companyUuid = String(selectedCompany?.uuid || '000');\n\n    // Reglas de activación del Wrapper\n    const isOverrideActive = !companyRequired &&\n      isEditing &&\n      activeByCompany &&\n      !!field.config?.allowMultiCompanyOverride &&\n      companyUuid !== '000';\n\n    // En contexto de sucursal (edición, compañía no global) todos los campos usan\n    // el label custom del wrapper para mantener consistencia visual, independientemente\n    // de si tienen allowMultiCompanyOverride o no.\n    const isCompanyContext = isEditing && activeByCompany && companyUuid !== '000' && !companyRequired;\n\n    if (!isOverrideActive && !isCompanyContext) return <>{children}{renderFieldError(accessorKey)}</>;\n\n    const globalData = (initialData as any)?._globalValues;\n\n    // Resolución inteligente del valor global para mostrar etiquetas legibles\n    const getResolvedGlobalValue = (): React.ReactNode => {\n      // 1. Prioridad: Función personalizada del desarrollador\n      if (field.config?.getGlobalValue) return field.config.getGlobalValue(initialData);\n\n      const rawValue = globalData?.[accessorKey];\n      if (rawValue === undefined || rawValue === null) return t('undefined', 'Sin definir');\n\n      // 2. Resolución Automática para Lookup (NUEVO)\n      if (field.type === 'lookup' && field.lookupConfig) {\n        return (\n          <GlobalLookupResolver\n            id={rawValue}\n            lookupConfig={field.lookupConfig}\n            t={t}\n          />\n        );\n      }\n\n      // 3. Resolución para Select\n      if (field.type === 'select' && field.options) {\n        const option = field.options.find(opt => String(opt.value) === String(rawValue));\n        return option ? option.label : String(rawValue);\n      }\n\n      // 4. Resolución para Boolean\n      if (field.type === 'boolean') {\n        return !!rawValue ? t('yes', 'Sí') : t('no', 'No');\n      }\n\n      // 5. Default: String\n      return String(rawValue);\n    };\n\n    const globalValueText = getResolvedGlobalValue();\n\n    // Comparación para mostrar botón de revertir\n    const hasOverride = globalData &&\n      globalData[accessorKey] !== undefined &&\n      String(value) !== String(globalData[accessorKey]);\n\n    return (\n      <div className=\"flex flex-col gap-2 w-full mb-2\">\n        <div className=\"flex items-center w-full font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\">\n          <span>\n            {t(field.accessorKey as string, field.header)}\n            {isRequired && <span className=\"ml-1 text-error-content\">*</span>}\n          </span>\n        </div>\n\n        <div className=\"flex flex-col\">\n          <div className=\"flex items-center gap-2 w-full\">\n            <div className=\"flex-1 min-w-0\">\n              {children}\n            </div>\n            {hasOverride && (\n              <div className=\"shrink-0\">\n                <Button\n                  type=\"outline\"\n                  iconOnly\n                  leftIcon={<RevertIcon className=\"w-[12px] h-[12px]\" />}\n                  onClick={() => handleRevertSingleField(field)}\n                  ariaLabel={t('revertToGlobal', 'Revertir a valor global')}\n                  title={t('revertToGlobal', 'Revertir a valor global')}\n                  className=\"\n                    !h-[38px]\n                    !w-[38px]\n                    !bg-[#eff8ff]\n                    !border-[#93d1fd]\n                    !text-[#1355b7]\n                    hover:!bg-[#dbeefe]\n                    dark:!bg-primary-900/30\n                    dark:!border-primary-800\n                    dark:!text-primary-300\n                    transition-all\n                  \"\n                />\n              </div>\n            )}\n          </div>\n          {/* Mensaje de validación pegado al campo (mt-1 = 4px, como el prototipo) */}\n          {renderFieldError(accessorKey)}\n        </div>\n\n        {isOverrideActive && showGlobalValues && (\n          <div className=\"flex items-center gap-1.5 mt-0.5\">\n            <GlobeAltIcon className=\"w-3.5 h-3.5 text-[#1355b7] dark:text-primary-400 shrink-0\" />\n            <p className=\"text-[12px] font-medium leading-4 text-[#1355b7] dark:text-primary-400 italic\">\n              {t('globalValue', 'Valor maestro')}: <span className=\"font-semibold\">{globalValueText}</span>\n            </p>\n          </div>\n        )}\n      </div>\n    );\n  };\n\n  // ===== RENDERIZAR CAMPO POR DEFECTO =====\n  function renderDefaultField(field: MasterCrudField<T>): React.ReactNode {\n    const accessorKey = field.accessorKey as string;\n    const value = getValue(accessorKey);\n    const error = formState.errors[accessorKey];\n\n    // Lógica de deshabilitado base\n    const isConfigDisabled = resolveProp(field.config?.disabled, formState.values);\n\n    // Lógica de sobreescritura multicompañía\n    const companyUuid = String(selectedCompany?.uuid || '000');\n    const isOverrideActive = isEditing &&\n      activeByCompany &&\n      !!field.config?.allowMultiCompanyOverride &&\n      companyUuid !== '000';\n\n    const isRestrictedByCompany = isEditing &&\n      activeByCompany &&\n      companyUuid !== '000' &&\n      !companyRequired &&\n      !field.config?.allowMultiCompanyOverride;\n\n    const isOverrideForbidden = isOverrideActive && !canOverrideMultiCompany;\n\n    const isDisabled = loading ||\n      isReadOnly ||\n      isConfigDisabled ||\n      (isEditing && !!field.config?.disabledOnEdit) ||\n      isRestrictedByCompany ||\n      isOverrideForbidden;\n\n    const isRequired = resolveProp(field.config?.required, formState.values);\n\n    const fieldContent = (() => {\n      if (field.renderInput) {\n        return field.renderInput(\n          value,\n          (newValue) => setValue(accessorKey, newValue),\n          field,\n          formState.values as Record<string, any>\n        );\n      }\n\n      // El label lo gestiona siempre renderFieldWrapper cuando estamos en contexto de compañía\n      // o cuando isOverrideActive es true. En ambos casos ocultamos el label del componente hijo.\n      const isCompanyContext = isEditing && activeByCompany && companyUuid !== '000' && !companyRequired;\n      // En contexto de wrapper (override/compañía) el asterisco de requerido lo pinta la\n      // etiqueta del propio wrapper; el control interno NO debe repetirlo (evita doble \"*\").\n      const inWrapper = isOverrideActive || isCompanyContext;\n      const commonProps = {\n        label: !inWrapper ? t(field.accessorKey as string, field.header) : undefined,\n        error: !!error,\n        disabled: isDisabled,\n        required: inWrapper ? false : isRequired,\n      };\n\n      switch (field.type) {\n        case 'text':\n        case 'email':\n          return (\n            <Input\n              {...commonProps}\n              label={!isOverrideActive ? (commonProps.label as string) : undefined}\n              type={field.type as 'text' | 'email'}\n              value={value ?? ''}\n              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setValue(accessorKey, e.target.value)}\n              onBlur={(e: React.FocusEvent<HTMLInputElement>) => handleBlur(field, e.target.value)}\n              placeholder={field.config?.placeholder}\n              error={!!error}              maxLength={field.config?.maxLength}\n              {...({} as any)}\n            />\n          );\n\n        case 'number':\n          return (\n            <Input\n              {...commonProps}\n              label={!isOverrideActive ? (commonProps.label as string) : undefined}\n              type=\"number\"\n              value={value ?? ''}\n              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setValue(accessorKey, e.target.value ? Number(e.target.value) : '')}\n              onBlur={(e: React.FocusEvent<HTMLInputElement>) => handleBlur(field, e.target.value ? Number(e.target.value) : '')}\n              placeholder={field.config?.placeholder}\n              error={!!error}              min={field.config?.min}\n              max={field.config?.max}\n              step={field.config?.step}\n              {...({} as any)}\n            />\n          );\n\n        case 'date':\n          return (\n            <Input\n              {...commonProps}\n              label={!isOverrideActive ? (commonProps.label as string) : undefined}\n              type=\"date\"\n              value={value ?? ''}\n              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setValue(accessorKey, e.target.value)}\n              onBlur={(e: React.FocusEvent<HTMLInputElement>) => handleBlur(field, e.target.value)}\n              placeholder={field.config?.placeholder}\n              error={!!error}            />\n          );\n\n        case 'boolean': {\n          if (isOverrideActive || isCompanyContext) {\n            // En contexto override o de sucursal: el label lo gestiona renderFieldWrapper\n            return (\n              <div className=\"flex items-center h-10\">\n                <Switch\n                  checked={!!value}\n                  onCheckedChange={(checked) => setValue(accessorKey, checked)}\n                  disabled={isDisabled}\n                />\n              </div>\n            );\n          }\n          return (\n            <div className=\"flex items-center justify-between py-2\">\n              <span className=\"text-sm font-bold leading-5 text-content-primary dark:text-dark-content-primary\">\n                {t(field.accessorKey as string, field.header)}\n                {isRequired && <span className=\"ml-1 text-error-content\">*</span>}\n              </span>\n\n              <Switch\n                checked={!!value}\n                onCheckedChange={(checked) => setValue(accessorKey, checked)}\n                disabled={isDisabled}\n              />\n            </div>\n          );\n        }\n\n        case 'select': {\n          return (\n            <Select\n              {...commonProps}\n              label={!isOverrideActive ? (commonProps.label as string) : undefined}\n              options={\n                field.options?.map((opt) => ({\n                  value: opt.value,\n                  label: opt.label,\n                  icon: opt.icon,\n                  disabled: opt.disabled,\n                })) ?? []\n              }\n              value={value}\n              onChange={(newValue) => setValue(accessorKey, newValue)}\n              onBlur={() => handleBlur(field, value)}\n              placeholder={field.config?.placeholder || `${t('select', 'Seleccionar')}...`}\n              description={field.config?.helperText}              selectSize=\"sm\"\n            />\n          );\n        }\n\n        case 'lookup':\n          if (!field.lookupConfig) return null;\n          return (\n            <LookupField\n              {...commonProps}\n              label={!isOverrideActive ? (commonProps.label as string) : undefined}\n              className={isOverrideActive ? '!gap-0' : ''}\n              entity={field.lookupConfig.entity}\n              fetcher={field.lookupConfig.fetcher}\n              displayFields={field.lookupConfig.displayFields}\n              value={value ? String(value) : null}\n              onChange={(record: any) => {\n                if (!record) {\n                  setValue(accessorKey, null);\n                  handleBlur(field, null);\n                  return;\n                }\n                const valField = field.lookupConfig?.valueField || 'Id';\n                let newValue = record[valField];\n                if (newValue === undefined && valField === 'Id') {\n                  if (record.id !== undefined) newValue = record.id;\n                }\n                setValue(accessorKey, newValue);\n                handleBlur(field, newValue);\n              }}\n              placeholder={field.config?.placeholder || `${t('search', 'Buscar')}...`}\n            />\n          );\n\n        default:\n          return (\n            <Input\n              {...commonProps}\n              label={!isOverrideActive ? (commonProps.label as string) : undefined}\n              type=\"text\"\n              value={value ?? ''}\n              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setValue(accessorKey, e.target.value)}\n              onBlur={(e: React.FocusEvent<HTMLInputElement>) => handleBlur(field, e.target.value)}\n              placeholder={field.config?.placeholder}\n              error={!!error}            />\n          );\n      }\n    })();\n\n    return renderFieldWrapper(field, fieldContent, value);\n  }\n\n  // ===== HELPER PARA RENDERIZADO PERSONALIZADO O POR DEFECTO =====\n  const renderCustomField = useCallback((\n    accessorKey: string,\n    inputRenderer?: (value: any, onChange: (val: any) => void) => React.ReactNode\n  ) => {\n    const field = fields.find(f => f.accessorKey === accessorKey);\n    if (!field) return null;\n\n    // Si no hay inputRenderer, usamos el renderizado por defecto del sistema\n    if (!inputRenderer) {\n      return renderDefaultField(field);\n    }\n\n    const value = getValue(accessorKey);\n    const onChange = (newValue: any) => setValue(accessorKey, newValue);\n\n    return renderFieldWrapper(field, inputRenderer(value, onChange), value);\n  }, [fields, getValue, setValue, showGlobalValues]); // showGlobalValues añadido para reactividad en renderForm\n\n  // ===== FILTRAR CAMPOS VISIBLES =====\n  const visibleFields = fields.filter((field) => {\n    if (isEditing) {\n      if (field.config?.showInEdit !== undefined) return field.config.showInEdit;\n      if (field.config?.visibleInForm !== undefined) return field.config.visibleInForm;\n      return true;\n    }\n    if (field.config?.showInCreate !== undefined) return field.config.showInCreate;\n    if (field.config?.visibleInForm !== undefined) return field.config.visibleInForm;\n    return true;\n  });\n\n  // ===== CLASES DEL CONTENEDOR =====\n  const containerClasses = `\n    flex\n    flex-col\n    bg-white\n    dark:bg-dark-bg-primary\n    max-h-full\n    w-full\n    ${className}\n  `\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== CLASES DEL GRID =====\n  const gridClasses = `\n    grid\n    grid-cols-1\n    ${columns >= 2 ? 'md:grid-cols-2' : ''}\n    ${columns >= 3 ? 'lg:grid-cols-3' : ''}\n    ${columns >= 4 ? 'xl:grid-cols-4' : ''}\n    gap-x-10\n    gap-y-3\n  `\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  // ===== RENDERIZADO DE SKELETON (MÁSCARA DE FORMULARIO) =====\n  const renderSkeleton = () => (\n    <div className={gridClasses}>\n      {visibleFields.map((field, idx) => {\n        const colSpan = field.config?.colSpan;\n        return (\n          <div\n            key={`skeleton-${idx}`}\n            style={{\n              gridColumn: colSpan ? `span ${colSpan} / span ${colSpan}` : undefined\n            }}\n            className=\"flex flex-col gap-2\"\n          >\n            {/* Label Skeleton */}\n            <div className=\"h-4 w-24 bg-border-primary/50 dark:bg-dark-border-primary/30 rounded animate-pulse\" />\n            {/* Input Skeleton */}\n            <div className=\"h-10 w-full bg-border-primary/30 dark:bg-dark-border-primary/20 rounded-lg animate-pulse\" />\n          </div>\n        );\n      })}\n    </div>\n  );\n\n  return (\n    <div className={containerClasses} style={{ maxWidth: width }}>\n      {/* Alerta de Error de Validación (usa el portal del propio AlertDialog: una sola capa,\n          sin backdrop duplicado que bloquee la interacción). */}\n      <AlertDialog\n        isOpen={errorAlert.show}\n        type=\"warning\"\n        hideCancel\n        title={errorAlert.title || t('incompleteTitle', 'Información incompleta')}\n        description={errorAlert.message}\n        onCancel={() => setErrorAlert({ show: false, message: '' })}\n        onConfirm={() => setErrorAlert({ show: false, message: '' })}\n        confirmText={t('accept', 'Entendido')}\n      />\n\n      {/* Advertencia DEV: renderForm sin MasterCrudDynamicEntities */}\n      {process.env.NODE_ENV === 'development' && devDynamicEntitiesWarning && (\n        <div className=\"fixed inset-0 z-[300] flex items-center justify-center bg-black/50 p-4\">\n          <AlertDialog\n            title=\"Error de implementación de maestro\"\n            onConfirm={() => setDevDynamicEntitiesWarning(false)}\n            confirmText=\"Entendido\"\n          >\n            <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n              {`A pesar de que el maestro se encuentra asociado al feature \"${entityName || dynamicFeatureCode}\" no tiene implementado el componente de entidades dinámicas. Para no ver este mensaje de error, proceda a incluir el componente de entidades dinámicas en el RenderForm del maestro.`}\n            </p>\n          </AlertDialog>\n        </div>\n      )}\n\n      {/* Advertencia DEV: renderForm sin MasterCrudFileManager cuando se requiere gestión de archivos */}\n      {process.env.NODE_ENV === 'development' && devFileManagerWarning && (\n        <div className=\"fixed inset-0 z-[300] flex items-center justify-center bg-black/50 p-4\">\n          <AlertDialog\n            title=\"Error de implementación de maestro\"\n            onConfirm={() => setDevFileManagerWarning(false)}\n            confirmText=\"Entendido\"\n          >\n            <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n              {`El maestro tiene habilitada la gestión de archivos (feature \"${featCodeFileManager}\") pero no incluye el componente MasterCrudFileManager en su renderForm. Para no ver este mensaje de error, incluya <MasterCrudFileManager /> dentro del renderForm del maestro.`}\n            </p>\n          </AlertDialog>\n        </div>\n      )}\n\n      {/* Header con botón X */}\n      {!hideHeaderFooter && (\n        <div className=\"flex-none p-5 pb-2 flex items-center justify-between gap-4\">\n          <div className=\"flex flex-col gap-1 min-w-0\">\n            <h2 className=\"text-[16px] font-medium text-primary-600 dark:text-primary-500 truncate\">\n              {isEditing ? `${t('edit', 'Editar')} ${entityName || t('record', 'Registro')}` : `${t('create', 'Nuevo')} ${entityName || t('record', 'Registro')}`}\n            </h2>\n            {/* Selector de Compañía (solo en Modal/Sidebar) */}\n            {activeByCompany && companies.length > 0 && (\n              <div className={loading && isEditing ? 'animate-pulse opacity-50' : ''}>\n                <CompanySelector\n                  companies={companies}\n                  selectedCompany={selectedCompany}\n                  onCompanyChange={(c) => onCompanyChange?.(c, (initialData as any)?.id)}\n                  readOnly={companyRequired}\n                  t={t}\n                />\n              </div>\n            )}\n          </div>\n          <div className=\"flex items-center gap-2 shrink-0 h-6\">\n            {/* Acciones Automáticas y Personalizadas (solo en Modal/Sidebar) */}\n            {headerDropdownItems.length > 0 && (\n              <Dropdown\n                menuClassName=\"w-56\"\n                renderTrigger={() => (\n                  <Button\n                    type=\"outline\"\n                    size=\"xs\"\n                    iconOnly\n                    leftIcon={<Bars3Icon className=\"w-4 h-4\" />}\n                    ariaLabel={t('actions', 'Acciones')}\n                    title={t('actions', 'Acciones')}\n                    disabled={loading}\n                    className=\"flex\" // Forzar comportamiento flex para evitar baseline shifts\n                  />\n                )}\n                items={headerDropdownItems}\n              />\n            )}\n            <Button\n              type=\"outline\"\n              size=\"xs\"\n              iconOnly\n              leftIcon={<XMarkIcon className=\"w-4 h-4\" />}\n              onClick={onCancel}\n              ariaLabel={t('close', 'Cerrar')}\n              className=\"!bg-white dark:!bg-dark-bg-primary flex\"\n            />\n          </div>\n        </div>\n      )}\n\n      {/* Formulario */}\n      <form id={formId} ref={formElementRef} noValidate onSubmit={handleSubmit} className=\"flex flex-col flex-1 min-h-0\">\n        {/* TABS DE NAVEGACIÓN (pestañas de campos formTabs y/o entidades dinámicas / archivos) */}\n        {(hasFieldTabs || (dynamicFeatureCode && dynamicFeature && dynamicFeature.featureEntities?.length && !effectiveHideDynamicTabs) || hasFileManagement) ? (\n          <div className=\"flex-shrink-0 bg-transparent\">\n            <div ref={tabsRowRef} className=\"relative flex items-stretch gap-1 px-3 pt-2\">\n              {hasFieldTabs ? (\n                // Pestañas de campos (formTabs) — cada una con su badge de faltantes\n                fieldTabs.map((ft) => {\n                  const errCount = Object.keys(formState.errors).filter((k) => getFieldTabKey(k) === ft.key).length;\n                  const active = activeGlobalTab === ft.key;\n                  return (\n                    <button\n                      key={ft.key}\n                      type=\"button\"\n                      data-tabkey={ft.key}\n                      onClick={() => setActiveGlobalTab(ft.key)}\n                      className={`tab-btn relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-dark-bg-secondary transition-colors focus:outline-none ${active\n                        ? 'text-[#0c6ade]'\n                        : 'text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-[#eef0f3] dark:hover:bg-white/[0.06]'\n                        }`}\n                    >\n                      {ft.icon && <span className=\"inline-flex items-center justify-center w-3.5 h-3.5\">{ft.icon}</span>}\n                      {ft.label}\n                      {errCount > 0 && (\n                        <span className=\"inline-flex items-center justify-center min-w-4 h-4 px-1 bg-[#dc2626] text-white rounded-full text-[9px] font-bold\">{errCount}</span>\n                      )}\n                    </button>\n                  );\n                })\n              ) : (\n                <button\n                  type=\"button\"\n                  data-tabkey=\"main\"\n                  onClick={() => setActiveGlobalTab('main')}\n                  className={`tab-btn relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-dark-bg-secondary transition-colors focus:outline-none ${activeGlobalTab === 'main'\n                    ? 'text-[#0c6ade]'\n                    : 'text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-[#eef0f3] dark:hover:bg-white/[0.06]'\n                    }`}\n                >\n                  {t('mainInfo', 'Información Principal')}\n                  {Object.keys(formState.errors).length > 0 && (\n                    <span className=\"inline-flex items-center justify-center min-w-4 h-4 px-1 bg-[#dc2626] text-white rounded-full text-[9px] font-bold\">{Object.keys(formState.errors).length}</span>\n                  )}\n                </button>\n              )}\n\n              {hasStandardDynamicEntities && (\n                <button\n                  type=\"button\"\n                  data-tabkey=\"dynamic_entities\"\n                  onClick={() => setActiveGlobalTab('dynamic_entities')}\n                  className={`tab-btn relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-dark-bg-secondary transition-colors focus:outline-none ${activeGlobalTab === 'dynamic_entities'\n                    ? 'text-[#0c6ade]'\n                    : 'text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-[#eef0f3] dark:hover:bg-white/[0.06]'\n                    }`}\n                >\n                  {t('dynamicEntities', 'Datos Adicionales')}\n                </button>\n              )}\n\n              {hasPlansAndCriteriaEntities && (\n                <button\n                  type=\"button\"\n                  data-tabkey=\"plans_and_criteria\"\n                  onClick={() => setActiveGlobalTab('plans_and_criteria')}\n                  className={`tab-btn relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-dark-bg-secondary transition-colors focus:outline-none ${activeGlobalTab === 'plans_and_criteria'\n                    ? 'text-[#0c6ade]'\n                    : 'text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-[#eef0f3] dark:hover:bg-white/[0.06]'\n                    }`}\n                >\n                  {t('plansAndCriteria', 'Planes y Criterios')}\n                </button>\n              )}\n\n              {hasFileManagement && (\n                <button\n                  type=\"button\"\n                  data-tabkey=\"file_management\"\n                  onClick={() => setActiveGlobalTab('file_management')}\n                  className={`tab-btn relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-dark-bg-secondary transition-colors focus:outline-none ${activeGlobalTab === 'file_management'\n                    ? 'text-[#0c6ade]'\n                    : 'text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-[#eef0f3] dark:hover:bg-white/[0.06]'\n                    }`}\n                >\n                  {t('fileManagement', 'Gestión de Archivos')}\n                </button>\n              )}\n              {/* Indicador deslizante con rebote (grosor constante 2.5px) */}\n              <span\n                ref={tabIndicatorRef}\n                aria-hidden=\"true\"\n                className=\"absolute bottom-0 h-[2.5px] rounded-[3px] bg-[#0e79fd] pointer-events-none\"\n                style={{ left: 0, width: 0, transition: 'left .5s cubic-bezier(.34,1.56,.64,1), width .42s cubic-bezier(.22,1,.36,1)' }}\n              />\n            </div>\n          </div>\n        ) : null}\n\n        <div className={`flex-1 min-h-0 overflow-y-auto scrollbar-thin scrollbar-thumb-border-primary dark:scrollbar-thumb-dark-border-primary ${hideHeaderFooter ? 'p-6 md:p-8' : 'p-5 pt-2'}`}>\n          <div className=\"flex flex-col gap-6\">\n            <div className={(hasFieldTabs ? fieldTabs.some(ft => ft.key === activeGlobalTab) : (effectiveHideDynamicTabs || !dynamicFeatureCode || !dynamicFeature || activeGlobalTab === 'main')) ? 'block animate-in fade-in duration-300' : 'hidden'}>\n              {loading && isEditing && !initialData?.[idField as any] ? (\n                renderSkeleton()\n              ) : renderContent ? (\n                <FileGalleryRegistrationContext.Provider value={fileGalleryRegistrationContextValue}>\n                <DynamicEntitiesRegistrationContext.Provider value={registrationContextValue}>\n                  {renderContent({\n                    fields,\n                    entityName,\n                    initialData,\n                    isEditing,\n                    loading,\n                    onSubmit: (e?: any) => {\n                      // Si el componente hijo nos pasa un objeto de datos directamente (no un evento DOM),\n                      // lo relayamos sin pasar por el handleSubmit interno que solo tiene campos overridables.\n                      if (e !== undefined && e !== null && !(e instanceof Event) && typeof e === 'object' && !('nativeEvent' in e) && typeof e.preventDefault !== 'function') {\n                        onSubmit?.(e);\n                        return;\n                      }\n                      if (e && typeof e.preventDefault === 'function') e.preventDefault();\n                      handleSubmit();\n                    },\n                    onCancel,\n                    saveButtonText,\n                    cancelButtonText,\n                    columns,\n                    width,\n                    className,\n                    actions,\n                    hideHeaderFooter,\n                    fullWidthButton,\n                    isReadOnly,\n                    id: formId,\n                    selectedCompany,\n                    t,\n                    activeByCompany,\n                    showGlobalValues,\n                    onSearchMatches,\n                    canOverrideMultiCompany,\n                    companies,\n                    onCompanyChange,\n                    onShowGlobalValuesChange,\n                    onUseGlobalData,\n                    onCreateNew,\n                    onLinkCompanies,\n                    registerDynamicRef,\n                    values: formState.values,\n                    setValue: (name: string, val: any) => setValue(name, val),\n                    errors: formState.errors,\n                    hideDynamicTabs: effectiveHideDynamicTabs,\n                    dynamicFeature,\n                    dynamicFeatureCode,\n                    renderField: renderCustomField\n                  })}\n                </DynamicEntitiesRegistrationContext.Provider>\n                </FileGalleryRegistrationContext.Provider>\n              ) : (\n                <div className={gridClasses}>\n                  {visibleFields\n                    .filter((field) => !hasFieldTabs || getFieldTabKey(field.accessorKey as string) === activeGlobalTab)\n                    .map((field) => {\n                      const colSpan = field.config?.colSpan;\n                      return (\n                        <div\n                          key={field.accessorKey as string}\n                          style={{\n                            gridColumn: colSpan ? `span ${colSpan} / span ${colSpan}` : undefined\n                          }}\n                        >\n                          {renderDefaultField(field)}\n                        </div>\n                      );\n                    })}\n                </div>\n              )}\n            </div>\n\n            {/* Contenedor Unificado de Entidades Dinámicas con soporte interno de Inlines/Tabs */}\n            {dynamicFeatureCode && dynamicFeature && dynamicFeature.featureEntities?.length && !effectiveHideDynamicTabs ? (\n              <>\n                <div className={activeGlobalTab === 'dynamic_entities' ? 'block animate-in fade-in duration-300 space-y-6' : 'hidden'}>\n                  <MasterCrudDynamicEntities\n                    dynamicFeature={dynamicFeature}\n                    dynamicFeatureCode={dynamicFeatureCode}\n                    recordId={(initialData as any)?.id}\n                    registerDynamicRef={(entityCode, el) => { dynamicRefs.current[entityCode] = el; }}\n                    showOnlyPlansAndCriteria={false}\n                  />\n                </div>\n                <div className={activeGlobalTab === 'plans_and_criteria' ? 'block animate-in fade-in duration-300 space-y-6' : 'hidden'}>\n                  <MasterCrudDynamicEntities\n                    dynamicFeature={dynamicFeature}\n                    dynamicFeatureCode={dynamicFeatureCode}\n                    recordId={(initialData as any)?.id}\n                    registerDynamicRef={(entityCode, el) => { dynamicRefs.current[entityCode] = el; }}\n                    showOnlyPlansAndCriteria={true}\n                  />\n                </div>\n              </>\n            ) : null}\n\n            {/* Gestión de Archivos tab content */}\n            {hasFileManagement && (\n              <div className={activeGlobalTab === 'file_management' ? 'block animate-in fade-in duration-300' : 'hidden'}>\n                <FileGalleryRegistrationContext.Provider value={fileGalleryRegistrationContextValue}>\n                  <MasterCrudFileManager\n                    entityId={(initialData as any)?.id}\n                    entityName={entityName || ''}\n                    config={fileManagerConfig!}\n                  />\n                </FileGalleryRegistrationContext.Provider>\n              </div>\n            )}\n          </div>\n        </div>\n\n        {/* Botones de acción - Footer Independiente (Asegura clicabilidad absoluta) */}\n        {!hideHeaderFooter && (\n          <div\n            className=\"flex-none p-5 pt-3 pb-5 bg-white dark:bg-dark-bg-primary border-t border-border-primary/50 dark:border-dark-border-primary/30 relative z-[200] pointer-events-auto shadow-sm\"\n            style={{ position: 'sticky', bottom: 0, marginTop: 'auto' }}\n          >\n            {fullWidthButton ? (\n              <div className=\"flex flex-col gap-3\">\n                <Button\n                  type=\"default\"\n                  size=\"l\"\n                  onClick={(e: any) => {\n                    console.log(\"%c[CLICK-FORCE] Disparando guardado...\", \"background: #22c55e; color: #fff; padding: 2px 5px; border-radius: 4px;\");\n                    if (e && e.preventDefault) e.preventDefault();\n                    if (e && e.stopPropagation) e.stopPropagation();\n                    handleSubmit();\n                  }}\n                  disabled={loading}\n                  fullWidth\n                  className=\"font-bold uppercase tracking-wide\"\n                >\n                  {loading ? t('loading', 'Cargando...') : finalSaveText}\n                </Button>\n              </div>\n            ) : (\n              <div className=\"flex justify-end items-center gap-4\">\n                <Button\n                  type=\"outline\"\n                  size=\"l\"\n                  onClick={onCancel}\n                  disabled={loading}\n                  className=\"font-medium px-6 hover:bg-gray-50 dark:hover:bg-gray-800\"\n                >\n                  {finalCancelText}\n                </Button>\n                <Button\n                  type=\"default\"\n                  size=\"l\"\n                  onClick={(e: any) => {\n                    console.log(\"%c[CLICK-FORCE] Disparando guardado...\", \"background: #22c55e; color: #fff; padding: 2px 5px; border-radius: 4px;\");\n                    if (e && e.preventDefault) e.preventDefault();\n                    if (e && e.stopPropagation) e.stopPropagation();\n                    handleSubmit();\n                  }}\n                  disabled={loading}\n                  className=\"font-bold px-10 uppercase tracking-wide\"\n                >\n                  {loading && !isEditing ? t('saving', 'Guardando...') : loading ? t('loading', 'Cargando...') : finalSaveText}\n                </Button>\n              </div>\n            )}\n          </div>\n        )}\n      </form>\n    </div>\n  );\n\n});\n\nMasterCrudForm.displayName = 'MasterCrudForm';\n","import React, { useState, useRef, useEffect } from 'react';\nimport { Button } from '../Button/Button';\nimport { Switch } from '../Switch/Switch';\nimport { CompanySelector } from './CompanySelector';\nimport type { MasterCrudToolbarProps, ToolbarViewType, MasterCrudCompany } from './MasterCrud.types';\nimport {\n  SearchIcon,\n  FilterIcon,\n  ChevronDownIcon,\n  GridIcon,\n  ListIcon,\n  EllipsisVerticalIcon,\n  DocumentArrowDownIcon,\n  BackIcon,\n} from './icons';\n\n/**\n * MasterCrudToolbar - Barra de herramientas del listado (alineada al prototipo).\n *\n * Izquierda: título + CompanySelector (combobox azul) debajo.\n * Derecha: búsqueda rápida (con toggle de búsqueda avanzada), contenido extra (botón Crear)\n * y menú \"Más opciones\" (kebab vertical) con: alcance multicompañía, modo de visualización y exportar.\n */\nexport const MasterCrudToolbar: React.FC<MasterCrudToolbarProps> = ({\n  title,\n  searchPlaceholder,\n  searchValue = '',\n  onSearchChange,\n  showSearch = true,\n  viewType = 'list',\n  onViewChange,\n  showViewToggle = true,\n  showAdvancedSearch = false,\n  extraContent,\n  className = '',\n  globalActions = [],\n  batchActions = [],\n  hasSelection = false,\n  isAdvancedSearchActive = false,\n  onAdvancedSearchToggle,\n  activeByCompany = false,\n  companyRequired = false,\n  companies = [],\n  selectedCompany,\n  onCompanyChange,\n  showExport = false,\n  onExport,\n  viewScope = 'all',\n  onViewScopeChange,\n  showViewScope = false,\n  onBack,\n  t,\n}) => {\n  // La búsqueda rápida siempre muestra el placeholder \"Buscar\": internamente busca por\n  // todos los campos marcados como buscables, sin importar el campo/estado seleccionado.\n  const finalSearchPlaceholder = searchPlaceholder || t('search', 'Buscar');\n\n  // ===== MENÚ \"MÁS OPCIONES\" =====\n  const [moreOpen, setMoreOpen] = useState(false);\n  const moreRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    if (!moreOpen) return;\n    const onDocClick = (e: MouseEvent) => {\n      if (moreRef.current && !moreRef.current.contains(e.target as Node)) setMoreOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setMoreOpen(false); };\n    document.addEventListener('mousedown', onDocClick);\n    document.addEventListener('keydown', onKey);\n    return () => {\n      document.removeEventListener('mousedown', onDocClick);\n      document.removeEventListener('keydown', onKey);\n    };\n  }, [moreOpen]);\n\n  // ===== ACCIONES =====\n  const currentActions = hasSelection ? batchActions : globalActions;\n  const directActions = currentActions.filter((a) => a.displayType === 'direct');\n  const menuActions = currentActions.filter((a) => a.displayType !== 'direct');\n\n  const handleViewChange = (view: ToolbarViewType) => onViewChange?.(view);\n  const handleCompanySelect = (company: MasterCrudCompany) => onCompanyChange?.(company, undefined);\n\n  const hasMoreMenu = showViewToggle || showExport || (showViewScope && activeByCompany) || menuActions.length > 0;\n\n  return (\n    <div className={`space-y-4 w-full ${className}`}>\n      {/* Barra de navegación: enlace \"Volver\" (prototipo) */}\n      <nav>\n        <button\n          type=\"button\"\n          onClick={() => (onBack ? onBack() : window.history.back())}\n          className=\"inline-flex items-center gap-1 text-sm text-content-tertiary dark:text-dark-content-tertiary hover:text-[#1355b7] transition-colors\"\n        >\n          <BackIcon className=\"w-4 h-4\" />\n          <span>{t('back', 'Volver')}</span>\n        </button>\n      </nav>\n\n      {/* Fila: título + acciones */}\n      <div className=\"flex flex-col md:flex-row md:items-center md:justify-between gap-4 w-full\">\n      {/* Izquierda: título + selector de compañía debajo */}\n      <div className=\"flex flex-col items-start gap-1.5 min-w-0\">\n        <h1 className=\"text-xl font-semibold tracking-tight text-[#1355b7] dark:text-primary-600 truncate max-w-full\">{title}</h1>\n        {activeByCompany && companies.length > 0 && (\n          <CompanySelector\n            companies={companies}\n            selectedCompany={selectedCompany}\n            onCompanyChange={handleCompanySelect}\n            readOnly={companyRequired}\n            t={t}\n          />\n        )}\n      </div>\n\n      {/* Derecha: búsqueda + Crear + kebab */}\n      <div className=\"flex items-center gap-2 flex-shrink-0\">\n        {showSearch && (\n          <div className=\"relative flex items-center\">\n            <span className=\"absolute left-2.5 top-1/2 -translate-y-1/2 text-content-tertiary dark:text-dark-content-tertiary pointer-events-none\">\n              <SearchIcon className=\"w-3.5 h-3.5\" />\n            </span>\n            <input\n              type=\"search\"\n              placeholder={finalSearchPlaceholder}\n              value={searchValue}\n              autoComplete=\"off\"\n              disabled={isAdvancedSearchActive}\n              onChange={(e) => onSearchChange?.(e.target.value)}\n              className=\"pl-8 pr-10 h-9 w-64 text-sm border border-border-primary dark:border-dark-border-primary rounded-md bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary placeholder:text-content-tertiary focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors disabled:opacity-60\"\n            />\n            {showAdvancedSearch && (\n              <button\n                type=\"button\"\n                onClick={onAdvancedSearchToggle}\n                aria-expanded={isAdvancedSearchActive}\n                title={isAdvancedSearchActive ? t('hideAdvancedSearch', 'Ocultar búsqueda avanzada') : t('showAdvancedSearch', 'Mostrar búsqueda avanzada')}\n                className={`absolute right-1.5 inline-flex items-center justify-center w-7 h-7 rounded-md transition-colors ${\n                  isAdvancedSearchActive\n                    ? 'bg-primary-600 text-white'\n                    : 'text-content-tertiary hover:text-primary-600 hover:bg-[#eff8ff] dark:hover:bg-primary-900/20'\n                }`}\n              >\n                {isAdvancedSearchActive\n                  ? <ChevronDownIcon className=\"w-4 h-4 rotate-180\" />\n                  : <FilterIcon className=\"w-4 h-4\" />}\n              </button>\n            )}\n          </div>\n        )}\n\n        {/* Acciones globales directas (poco comunes; el prototipo no las usa por defecto) */}\n        {directActions.map((action) => {\n          const actionName = typeof action.name === 'function' ? action.name(null) : action.name;\n          const actionIcon = typeof action.icon === 'function' ? action.icon(null) : action.icon;\n          return (\n            <Button\n              key={action.id || actionName}\n              type=\"outline\"\n              size=\"base\"\n              leftIcon={actionIcon}\n              onClick={() => action.action?.([])}\n              disabled={typeof action.disabled === 'function' ? action.disabled(null as any) : action.disabled}\n            >\n              {actionName}\n            </Button>\n          );\n        })}\n\n        {/* Botón Crear u otro contenido extra */}\n        {extraContent}\n\n        {/* Menú \"Más opciones\" (kebab vertical, sobre la tabla) */}\n        {hasMoreMenu && (\n          <div className=\"relative\" ref={moreRef}>\n            <button\n              type=\"button\"\n              onClick={() => setMoreOpen((v) => !v)}\n              aria-haspopup=\"menu\"\n              aria-expanded={moreOpen}\n              title={t('moreOptions', 'Más opciones')}\n              className=\"inline-flex items-center justify-center w-9 h-9 border border-border-primary dark:border-dark-border-primary rounded-md bg-background-secondary dark:bg-dark-bg-secondary hover:bg-[#ebebec] dark:hover:bg-dark-bg-primary text-content-tertiary transition-colors\"\n            >\n              <EllipsisVerticalIcon className=\"w-4 h-4\" />\n            </button>\n\n            {moreOpen && (\n              <div role=\"menu\" className=\"absolute right-0 top-full mt-1 w-64 bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-md shadow-md z-50 py-1\">\n                {/* Alcance de filas (multicompañía por sobrescritura).\n                    Un único checkbox: marcado = solo la compañía seleccionada; desmarcado = todos. */}\n                {showViewScope && activeByCompany && (\n                  <div className=\"px-1 py-1 border-b border-border-primary dark:border-dark-border-primary\">\n                    <p className=\"px-2 pt-1 pb-1.5 text-[11px] font-semibold text-content-tertiary tracking-[0.3px]\">{t('recordsToShow', 'Registros a mostrar')}</p>\n                    <button\n                      type=\"button\"\n                      role=\"switch\"\n                      aria-checked={viewScope === 'company'}\n                      onClick={() => onViewScopeChange?.(viewScope === 'company' ? 'all' : 'company')}\n                      className=\"w-full flex items-center justify-between gap-3 px-2 py-2 rounded text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                    >\n                      <span className=\"flex-1 text-left select-none\">\n                        {t('viewCompanyOnly', 'Ver solo registros de la compañía seleccionada')}\n                      </span>\n                      <Switch\n                        size=\"sm\"\n                        checked={viewScope === 'company'}\n                        onChange={() => { }}\n                        className=\"pointer-events-none shrink-0\"\n                      />\n                    </button>\n                  </div>\n                )}\n\n                {/* Modo de visualización (Listado / Tarjetas) */}\n                {showViewToggle && (\n                  <div className=\"px-3 py-2 border-b border-border-primary dark:border-dark-border-primary\">\n                    <p className=\"text-[11px] font-semibold text-content-tertiary tracking-[0.3px] mb-2\">{t('displayMode', 'Modo de visualización')}</p>\n                    <div className=\"inline-flex w-full border border-border-primary dark:border-dark-border-primary rounded-md overflow-hidden text-sm\">\n                      <button\n                        type=\"button\"\n                        onClick={() => handleViewChange('list')}\n                        className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 transition-colors ${viewType === 'list' ? 'bg-primary-600 text-white' : 'bg-white dark:bg-dark-bg-primary text-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'}`}\n                      >\n                        <ListIcon className=\"w-4 h-4\" /><span>{t('listView', 'Listado')}</span>\n                      </button>\n                      <button\n                        type=\"button\"\n                        onClick={() => handleViewChange('grid')}\n                        className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 transition-colors ${viewType === 'grid' ? 'bg-primary-600 text-white' : 'bg-white dark:bg-dark-bg-primary text-content-tertiary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'}`}\n                      >\n                        <GridIcon className=\"w-4 h-4\" /><span>{t('cardView', 'Tarjetas')}</span>\n                      </button>\n                    </div>\n                  </div>\n                )}\n\n                {/* Exportar (solo si showExport) */}\n                {showExport && (\n                  <button\n                    type=\"button\"\n                    role=\"menuitem\"\n                    onClick={() => { onExport?.(); setMoreOpen(false); }}\n                    className=\"w-full flex items-center gap-3 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary text-left transition-colors\"\n                  >\n                    <DocumentArrowDownIcon className=\"w-4 h-4 text-content-tertiary\" />\n                    <span>{t('export', 'Exportar')}</span>\n                  </button>\n                )}\n\n                {/* Acciones de menú personalizadas */}\n                {menuActions.length > 0 && (showViewToggle || showExport || (showViewScope && activeByCompany)) && (\n                  <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n                )}\n                {menuActions.map((action) => {\n                  const actionName = typeof action.name === 'function' ? action.name(null) : action.name;\n                  const actionIcon = typeof action.icon === 'function' ? action.icon(null) : action.icon;\n                  const isDelete = actionName.toLowerCase().includes('eliminar') || actionName.toLowerCase().includes('delete');\n                  return (\n                    <button\n                      key={action.id || actionName}\n                      type=\"button\"\n                      role=\"menuitem\"\n                      disabled={typeof action.disabled === 'function' ? action.disabled(null as any) : action.disabled}\n                      onClick={() => { action.action?.([]); setMoreOpen(false); }}\n                      className={`w-full flex items-center gap-3 px-3 py-2 text-sm text-left transition-colors hover:bg-background-secondary dark:hover:bg-dark-bg-secondary ${isDelete ? 'text-error-content' : 'text-content-primary dark:text-dark-content-primary'}`}\n                    >\n                      {actionIcon && <span className=\"w-4 h-4 flex-shrink-0 text-content-tertiary\">{actionIcon}</span>}\n                      <span>{actionName}</span>\n                    </button>\n                  );\n                })}\n              </div>\n            )}\n          </div>\n        )}\n      </div>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\nimport { Button } from '../Button/Button';\nimport { Badge } from '../Badge/Badge';\nimport { Dropdown } from '../Dropdown/Dropdown';\nimport { Checkbox } from '../Checkbox/Checkbox';\nimport type { DropdownItemProps } from '../Dropdown/Dropdown.types';\nimport type { MasterCrudField, MasterCrudAction } from './MasterCrud.types';\nimport { CalendarIcon, Bars3Icon, LinkIcon } from './icons';\n\ninterface MasterCRUDCardProps<T> {\n  data: T;\n  fields: MasterCrudField<T>[];\n  onEdit?: (record: T) => void;\n  onDelete?: (record: T) => void;\n  rowActions?: (record: T, index: number) => React.ReactNode;\n  index?: number;\n  actions?: MasterCrudAction<T>[];\n  renderCardContent?: (data: T, index: number) => React.ReactNode;\n  /** Habilitar selección múltiple */\n  enableMultiSelect?: boolean;\n  /** Si la tarjeta está seleccionada actualmente      */\n  isSelected?: boolean;\n  /** Callback cuando cambia la selección */\n  onSelect?: (selected: boolean) => void;\n  /** Función de traducción inyectada por el padre       */\n  t: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * MasterCRUDCard - Componente de tarjeta para la vista de grid\n */\nexport const MasterCRUDCard = <T extends Record<string, unknown>>({\n  data,\n  fields,\n  onEdit,\n  onDelete,\n  rowActions,\n  actions = [],\n  renderCardContent,\n  index = 0,\n  enableMultiSelect = false,\n  isSelected = false,\n  onSelect,\n  t,\n}: MasterCRUDCardProps<T>) => {\n  // ===== FILTRAR CAMPOS VISIBLES EN GRID =====\n  const visibleFields = fields.filter(field => {\n    // Sincronización obligatoria con el modo tabla (showInList)\n    if (field.config?.showInList !== undefined) return field.config.showInList;\n    // Fallbacks para retrocompatibilidad\n    if (field.config?.showInGrid !== undefined) return field.config.showInGrid;\n    if (field.config?.visibleInTable !== undefined) return field.config.visibleInTable;\n    return true;\n  });\n\n  // ===== IDENTIFICAR TÍTULO Y FOOTER (Para estructura de Card) =====\n  // El título es el primero marcado como 'title' o el primer campo de texto visible\n  const titleField = visibleFields.find(f => f.config?.cardPosition === 'title') || visibleFields.find(f => f.type === 'text');\n\n  // El footer es el primero marcado como 'footer' o el primer campo de fecha visible\n  const footerField = visibleFields.find(f => f.config?.cardPosition === 'footer') || visibleFields.find(f => f.type === 'date');\n\n  // El resto de los campos que NO son el título principal ni el footer\n  const contentFields = visibleFields.filter(f => f !== titleField && f !== footerField);\n\n  // ===== RENDERIZAR VALOR =====\n  const renderValue = (field: MasterCrudField<T>) => {\n    const value = data[field.accessorKey as string];\n    if (value === null || value === undefined) return null;\n\n    if (field.renderCell) {\n      return field.renderCell(value, data, 0);\n    }\n\n    if (field.type === 'select') {\n      const option = field.options?.find(opt => opt.value === value);\n      return option?.label || value;\n    }\n\n    if (field.type === 'lookup' && field.lookupConfig) {\n      // Si el valor es un objeto (dato populado), intentar mostrar los displayFields\n      if (typeof value === 'object' && value !== null) {\n        const display = field.lookupConfig.displayFields\n          .map(k => (value as any)[k])\n          .filter(v => v !== undefined && v !== null)\n          .join(' - ');\n        return display || String(value);\n      }\n    }\n\n    return String(value);\n  };\n\n  // ===== CONSTRUIR OPCIONES DEL DROPDOWN =====\n  const linkAction = actions.find(a => a.id === 'link');\n  const otherActions = actions.filter(a => a.id !== 'link');\n\n  const dropdownItems: DropdownItemProps[] = otherActions.map((action) => {\n    const isDisabled = typeof action.disabled === 'function' ? action.disabled(data) : action.disabled;\n    const actionName = typeof action.name === 'function' ? action.name(data) : action.name;\n    const actionIcon = typeof action.icon === 'function' ? action.icon(data) : action.icon;\n    \n    return {\n      children: actionName,\n      icon: actionIcon,\n      disabled: isDisabled,\n      onClick: () => action.action?.(data),\n      className: actionName.toLowerCase().includes('eliminar') || actionName.toLowerCase().includes('delete')\n        ? 'text-error-content hover:text-error-content dark:text-error-content'\n        : '',\n    };\n  });\n\n  // Legacy fallback (si no hay actions pero sí onEdit/onDelete, aunque MasterCrud.tsx siempre manda actions)\n  if (dropdownItems.length === 0) {\n    if (onEdit) {\n      dropdownItems.push({\n        children: t('edit', 'Editar'),\n        icon: <span className=\"w-4 h-4\">✎</span>, // Placeholder si no hay icono a mano, pero MasterCrud.tsx manda actions\n        onClick: () => onEdit(data),\n      });\n    }\n\n    if (onDelete) {\n      dropdownItems.push({\n        children: t('delete', 'Eliminar'),\n        icon: <span className=\"w-4 h-4\">🗑️</span>,\n        onClick: () => onDelete(data),\n        className: 'text-error-content hover:text-error-content dark:text-error-content',\n      });\n    }\n  }\n\n  // ===== ESTILOS BASE (Mapeados de Figma a Tailwind/Proyecto) =====\n  // Container: bg-white border border-border-primary rounded-2xl p-5 gap-1\n  const containerClasses = `\n    group\n    relative\n    flex\n    flex-col\n    gap-1\n    p-5\n    rounded-2xl\n    shadow-sm\n    hover:shadow-md\n    transition-all\n    duration-200\n    ${isSelected\n      ? 'bg-[#f7fcff] dark:bg-primary-900/20 border-primary-600 ring-1 ring-primary-600 dark:border-primary-600 dark:ring-primary-600'\n      : 'bg-white dark:bg-dark-bg-primary border-border-primary dark:border-dark-border-primary'}\n  `.replace(/\\s+/g, ' ').trim();\n\n  // ===== RENDERIZAR CHECKBOX DE SELECCIÓN =====\n  const selectionCheckbox = enableMultiSelect && (\n    <div className=\"absolute top-5 left-5 z-10\">\n      <Checkbox\n        checked={isSelected}\n        onChange={(e) => onSelect?.(e.target.checked)}\n        aria-label={t('selectRecord', 'Seleccionar registro')}\n      />\n    </div>\n  );\n\n  // ===== CONTENIDO POR DEFECTO =====\n  const defaultContent = (\n    <>\n      {/* HEADER: Title & Actions */}\n      <div className={`flex items-start justify-between gap-2 w-full ${enableMultiSelect ? 'pl-8' : ''}`}>\n        {/* Title & Code */}\n        <div className=\"flex-1 min-w-0 flex flex-col gap-1\">\n          <h3 className=\"text-[18px] font-medium text-content-primary dark:text-dark-content-primary truncate leading-[20px]\">\n            {titleField ? (renderValue(titleField) as React.ReactNode) : t('noTitle', 'Sin título')}\n          </h3>\n          {/* Si hay un campo de fecha o similar que actúe como código en el header */}\n          {visibleFields.filter(f => f.config?.cardPosition === 'subtitle').length === 0 && footerField && (\n            <p className=\"text-[14px] font-normal italic text-content-secondary dark:text-content-tertiary truncate leading-[18px]\">\n              {renderValue(footerField) as React.ReactNode}\n            </p>\n          )}\n        </div>\n\n        {/* Actions Dropdown */}\n        <div className=\"flex items-center gap-1 absolute top-1 right-1\">\n          {linkAction && (\n            <Button\n              type=\"outline\"\n              size=\"xs\"\n              iconOnly\n              leftIcon={typeof linkAction.icon === 'function' ? linkAction.icon(data) : linkAction.icon}\n              onClick={() => linkAction.action?.(data)}\n              ariaLabel={typeof linkAction.name === 'function' ? linkAction.name(data) : linkAction.name}\n              title={typeof linkAction.name === 'function' ? linkAction.name(data) : linkAction.name}\n              className=\"shrink-0\"\n            />\n          )}\n          {(dropdownItems.length > 0 || rowActions) && (\n            <Dropdown\n              renderTrigger={() => (\n                <button\n                  type=\"button\"\n                  className=\"flex items-center justify-center p-2 rounded-lg text-content-tertiary hover:text-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-inverse/10 transition-all duration-150\"\n                  aria-label={t('moreOptions', 'Más opciones')}\n                >\n                  <Bars3Icon className=\"w-5 h-5\" />\n                </button>\n              )}\n              items={dropdownItems}\n            />\n          )}\n        </div>\n      </div>\n\n      {/* ÁREA DE CONTENIDO (Siguiendo el orden definido en el array fields) */}\n      <div className={`flex flex-col gap-1 w-full ${enableMultiSelect ? 'pl-8' : ''}`}>\n        {contentFields.map(field => {\n          const value = data[field.accessorKey as string];\n          if (value === null || value === undefined) return null;\n\n          // 1. Campos de Estado / Booleanos (Renderizados como Badges)\n          if (field.config?.cardPosition === 'status' || (field.type === 'boolean' && !field.config?.cardPosition)) {\n            const trueLabel = field.config?.trueLabel || t('active', 'Activo');\n            const falseLabel = field.config?.falseLabel || t('inactive', 'Inactivo');\n            return (\n              <div key={field.accessorKey as string} className=\"mt-1\">\n                <Badge\n                  color={field.type === 'boolean' ? (value ? 'green' : 'zinc') : 'blue'}\n                  label={field.type === 'boolean' ? (value ? trueLabel : falseLabel) : String(value)}\n                />\n              </div>\n            );\n          }\n\n          // 2. Subtítulos (Texto resaltado en azul Siesa)\n          if (field.config?.cardPosition === 'subtitle') {\n            return (\n              <p key={field.accessorKey as string} className=\"text-[16px] font-medium text-primary-600 dark:text-primary-500 truncate leading-[20px]\">\n                {renderValue(field) as React.ReactNode}\n              </p>\n            );\n          }\n\n          // 3. Campos de cuerpo estándar (Texto base)\n          return (\n            <p key={field.accessorKey as string} className=\"text-[14px] font-normal text-content-primary dark:text-dark-content-primary truncate leading-[20px]\">\n              {renderValue(field) as React.ReactNode}\n            </p>\n          );\n        })}\n      </div>\n\n      {/* FOOTER */}\n      {footerField && (\n        <div className={`flex items-center gap-2 mt-2 pt-4 border-t border-border-secondary dark:border-dark-border-primary w-full ${enableMultiSelect ? 'pl-8' : ''}`}>\n          <CalendarIcon className=\"w-4 h-4 text-content-secondary dark:text-content-secondary\" />\n          <p className=\"text-[12px] font-medium italic text-content-secondary dark:text-content-secondary truncate leading-[14px]\">\n            {renderValue(footerField) as React.ReactNode}\n          </p>\n        </div>\n      )}\n    </>\n  );\n\n  // ===== CONTENIDO PERSONALIZADO (con dropdown de acciones) =====\n  const customContent = renderCardContent && (\n    <div className={enableMultiSelect ? 'pl-8' : ''}>\n      {/* Actions Dropdown (esquina superior derecha) */}\n      {(dropdownItems.length > 0 || rowActions) && (\n        <div className=\"absolute top-1 right-1 z-10\">\n          <Dropdown\n            renderTrigger={() => (\n              <button\n                type=\"button\"\n                className=\"flex items-center justify-center p-2 rounded-lg text-content-tertiary hover:text-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-inverse/10 transition-all duration-150\"\n                aria-label={t('moreOptions', 'Más opciones')}\n              >\n                <Bars3Icon className=\"w-5 h-5\" />\n              </button>\n            )}\n            items={dropdownItems}\n          />\n        </div>\n      )}\n\n      {/* Contenido personalizado */}\n      {renderCardContent(data, index)}\n    </div>\n  );\n\n  return (\n    <div className={containerClasses}>\n      {selectionCheckbox}\n      {renderCardContent ? customContent : defaultContent}\n    </div>\n  );\n};\n","import React, { useMemo, useState } from 'react';\nimport { CloseIcon as XMarkIcon, PlusIcon, SearchIcon, ChevronDownIcon } from './icons';\nimport type { MasterCrudField, AdvancedFilter } from './MasterCrud.types';\n\ninterface MasterCrudAdvancedSearchProps {\n  fields: MasterCrudField[];\n  onSearch: (filters: AdvancedFilter[]) => void;\n  onClose: () => void;\n  initialSearchTerm?: string;\n  initialSearchField?: string;\n  /**\n   * @deprecated El conector lógico global (Y/O) se muestra siempre en el panel de\n   * filtros avanzados; esta prop ya no controla su visibilidad.\n   */\n  showConnectors?: boolean;\n  maxFilters?: number;\n  /** Lista blanca de columnas filtrables (mismas que muestran el embudo en la tabla). */\n  filterableFields?: string[];\n  columnFilterableFields?: string[];\n  t: (key: string, defaultValue?: string) => string;\n}\n\n// Operadores del selector \"Condición\" del prototipo → operador del filtro server-side.\nconst OPERATORS = [\n  { value: 'equals', labelKey: 'opEquals', label: 'Es igual a' },\n  { value: 'contains', labelKey: 'opContains', label: 'Contiene' },\n  { value: 'startsWith', labelKey: 'opStartsWith', label: 'Empieza con' },\n  { value: 'gt', labelKey: 'opGt', label: 'Es mayor que' },\n  { value: 'lt', labelKey: 'opLt', label: 'Es menor que' },\n] as const;\n\ninterface ConditionRow { id: string; field: string; operator: string; value: string; }\n\nlet rowSeq = 0;\nconst newRow = (field = ''): ConditionRow => ({ id: `cond-${++rowSeq}`, field, operator: 'contains', value: '' });\n\n/**\n * MasterCrudAdvancedSearch — Panel de filtros (prototipo `panel-filtros`).\n *\n * - **Filtros básicos**: un filtro por cada columna marcada como filtrable\n *   (`columnFilterableFields`). Texto = input (contains); enum/boolean = select (equals).\n * - **Filtros avanzados** (`<details>`): condiciones combinadas (Columna/Condición/Valor).\n * - Ambos son **mutuamente excluyentes**: al abrir \"Filtros avanzados\" se deshabilitan los\n *   básicos y, al buscar, se envían solo las condiciones avanzadas; si está cerrado, se envían\n *   los filtros básicos. Todo viaja server-side por el canal `advancedFilters`.\n */\nexport const MasterCrudAdvancedSearch: React.FC<MasterCrudAdvancedSearchProps> = ({\n  fields,\n  onSearch,\n  onClose,\n  filterableFields = [],\n  columnFilterableFields,\n  t,\n}) => {\n  const whitelist = columnFilterableFields ?? (filterableFields.length ? filterableFields : undefined);\n  const filterableCols = useMemo(\n    () => fields.filter((f) =>\n      f.type !== 'lookup' &&\n      (whitelist ? whitelist.includes(f.accessorKey as string) : f.config?.searchable !== false)\n    ),\n    [fields, whitelist]\n  );\n\n  const enumOptionsFor = (field: MasterCrudField): { value: string; label: string }[] | null => {\n    if (field.type === 'boolean') {\n      return [\n        { value: 'true', label: field.config?.trueLabel || t('active', 'Activo') },\n        { value: 'false', label: field.config?.falseLabel || t('inactive', 'Inactivo') },\n      ];\n    }\n    if (field.type === 'select' && field.options?.length) {\n      return field.options.map((o) => ({ value: String(o.value), label: o.label }));\n    }\n    return null;\n  };\n\n  const [basic, setBasic] = useState<Record<string, string>>({});\n  const [advancedOpen, setAdvancedOpen] = useState(false);\n  const [rows, setRows] = useState<ConditionRow[]>([newRow()]);\n  // Conector lógico global que une TODAS las condiciones avanzadas (sin agrupación).\n  // 'AND' (Y) por defecto: se deben cumplir todas; 'OR' (O): basta con una.\n  const [connector, setConnector] = useState<'AND' | 'OR'>('AND');\n\n  const setBasicValue = (key: string, value: string) =>\n    setBasic((prev) => { const next = { ...prev }; if (value === '') delete next[key]; else next[key] = value; return next; });\n\n  const updateRow = (id: string, patch: Partial<ConditionRow>) =>\n    setRows((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));\n  const removeRow = (id: string) => setRows((prev) => (prev.length > 1 ? prev.filter((r) => r.id !== id) : prev));\n  const addRow = () => setRows((prev) => [...prev, newRow()]);\n\n  // Construye los AdvancedFilter según el modo activo (mutuamente excluyente).\n  const buildFilters = (): AdvancedFilter[] => {\n    if (advancedOpen) {\n      const leaves: AdvancedFilter[] = rows\n        .filter((r) => r.field && String(r.value).trim() !== '')\n        .map((r) => ({ id: r.id, field: r.field, connector, operator: r.operator, value: r.value }));\n\n      // Con conector 'O' se envuelven en un único grupo OR para que los consumidores\n      // (y el adaptador MasterPattern) los evalúen como \"al menos una condición\".\n      // Con 'Y' se envían planos: el nivel raíz es un AND implícito.\n      if (connector === 'OR' && leaves.length > 1) {\n        return [{ id: 'adv-or-group', isGroup: true, connector: 'OR', children: leaves }];\n      }\n      return leaves;\n    }\n    return Object.entries(basic).map(([field, value]) => {\n      const f = filterableCols.find((c) => (c.accessorKey as string) === field);\n      const isEnum = !!(f && enumOptionsFor(f));\n      return { id: `basic-${field}`, field, connector: 'AND' as const, operator: isEnum ? 'equals' : 'contains', value };\n    });\n  };\n\n  const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); onSearch(buildFilters()); };\n  const handleClear = () => { setBasic({}); setRows([newRow()]); onSearch([]); };\n\n  const controlCls = 'w-full px-3 py-2 text-sm border border-border-primary dark:border-dark-border-primary rounded-md bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors';\n  const condCtrlCls = 'px-2.5 py-1.5 text-sm border border-border-primary dark:border-dark-border-primary rounded-md bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary focus:outline-none focus:border-[#93d1fd] transition-colors';\n\n  return (\n    <section aria-label={t('filters', 'Filtros')} className=\"bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-lg shadow-sm p-5 flex-shrink-0\">\n      <form className=\"space-y-5\" onSubmit={handleSubmit} onReset={(e) => { e.preventDefault(); handleClear(); }}>\n        {/* ── Filtros básicos (uno por columna filtrable) ── */}\n        <div className={`grid grid-cols-1 md:grid-cols-3 gap-4 transition-opacity duration-200 ${advancedOpen ? 'opacity-50 pointer-events-none' : ''}`} {...(advancedOpen ? { inert: '' as any } : {})}>\n          {filterableCols.map((field) => {\n            const key = field.accessorKey as string;\n            const enumOptions = enumOptionsFor(field);\n            const label = t(key, field.header);\n            return (\n              <div key={key}>\n                <label className=\"block text-[11px] font-semibold text-content-tertiary dark:text-dark-content-tertiary tracking-[0.3px] mb-1\">{label}</label>\n                {enumOptions ? (\n                  <select className={`${controlCls} cursor-pointer`} value={basic[key] ?? ''} onChange={(e) => setBasicValue(key, e.target.value)}>\n                    <option value=\"\">{t('all', 'Todos')}</option>\n                    {enumOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}\n                  </select>\n                ) : (\n                  <input type=\"text\" autoComplete=\"off\" className={controlCls} value={basic[key] ?? ''} onChange={(e) => setBasicValue(key, e.target.value)} />\n                )}\n              </div>\n            );\n          })}\n        </div>\n\n        {/* ── Filtros avanzados (colapsable) ── */}\n        <details className=\"border border-border-primary dark:border-dark-border-primary rounded-lg overflow-hidden\" open={advancedOpen} onToggle={(e) => setAdvancedOpen((e.target as HTMLDetailsElement).open)}>\n          <summary className=\"flex items-center gap-2 cursor-pointer select-none px-4 py-3 bg-white dark:bg-dark-bg-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\" style={{ listStyle: 'none' }}>\n            <ChevronDownIcon className={`w-4 h-4 text-primary-600 flex-shrink-0 transition-transform duration-200 ${advancedOpen ? 'rotate-180' : ''}`} />\n            <span className=\"text-sm font-semibold text-[#1355b7] dark:text-primary-400\">{t('advancedFilters', 'Filtros avanzados')}</span>\n            <span className=\"hidden sm:inline text-xs text-content-tertiary font-normal\">{t('advancedFiltersHint', '— combina varias condiciones personalizadas')}</span>\n          </summary>\n\n          <div className=\"border-t border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-secondary px-4 py-4 flex flex-col gap-4\">\n            {/* ── Conector lógico global (Y / O) que une todas las condiciones ── */}\n            <div className=\"flex flex-wrap items-center gap-x-3 gap-y-2\">\n              <span className=\"text-[11px] font-semibold text-content-secondary tracking-[0.3px] uppercase\">\n                {t('joinConditionsWith', 'Unir condiciones con')}\n              </span>\n              <div role=\"radiogroup\" aria-label={t('joinConditionsWith', 'Unir condiciones con')} className=\"inline-flex rounded-md border border-border-primary dark:border-dark-border-primary overflow-hidden bg-white dark:bg-dark-bg-primary shadow-[0_1px_2px_0_rgba(16,24,40,0.05)]\">\n                {([\n                  { v: 'AND' as const, label: t('connectorAnd', 'Y') },\n                  { v: 'OR' as const, label: t('connectorOr', 'O') },\n                ]).map((opt, i) => {\n                  const active = connector === opt.v;\n                  return (\n                    <button\n                      key={opt.v}\n                      type=\"button\"\n                      role=\"radio\"\n                      aria-checked={active}\n                      onClick={() => setConnector(opt.v)}\n                      className={`px-4 py-1.5 text-sm font-semibold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40 ${i === 1 ? 'border-l border-border-primary dark:border-dark-border-primary' : ''} ${active ? 'bg-primary-600 text-white' : 'bg-white dark:bg-dark-bg-primary text-content-secondary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'}`}\n                    >\n                      {opt.label}\n                    </button>\n                  );\n                })}\n              </div>\n              <span className=\"text-xs text-content-tertiary\">\n                {connector === 'AND'\n                  ? t('connectorAndHint', 'Se deben cumplir todas las condiciones')\n                  : t('connectorOrHint', 'Basta con que se cumpla una condición')}\n              </span>\n            </div>\n\n            {/* Tarjeta de condiciones (blanca, flota) */}\n            <div className=\"rounded-lg bg-white dark:bg-dark-bg-primary overflow-hidden shadow-[0_1px_2px_0_rgba(16,24,40,0.05)] ring-1 ring-black/[0.04]\">\n              {/* Encabezado */}\n              <div className=\"hidden md:flex items-center gap-2 px-3 py-2 bg-white dark:bg-dark-bg-primary border-b border-border-primary dark:border-dark-border-primary text-[11px] font-semibold text-content-secondary tracking-[0.3px] uppercase\">\n                <span className=\"w-5 flex-shrink-0 text-center\">#</span>\n                <span className=\"w-[200px]\">{t('column', 'Columna')}</span>\n                <span className=\"w-[180px]\">{t('condition', 'Condición')}</span>\n                <span className=\"flex-1 min-w-0\">{t('value', 'Valor')}</span>\n                <span className=\"w-8 flex-shrink-0\" />\n              </div>\n\n              {rows.map((row, idx) => (\n                <React.Fragment key={row.id}>\n                <div className=\"flex flex-col md:flex-row md:items-center gap-2 px-3 py-2.5\">\n                  <span className=\"w-5 flex-shrink-0 text-center text-xs font-bold text-content-tertiary select-none\">{idx + 1}</span>\n                  <select aria-label={t('column', 'Columna')} className={`${condCtrlCls} w-full md:w-[200px] cursor-pointer`} value={row.field} onChange={(e) => updateRow(row.id, { field: e.target.value })}>\n                    <option value=\"\">{t('selectColumn', 'Selecciona una columna…')}</option>\n                    {filterableCols.map((f) => <option key={f.accessorKey as string} value={f.accessorKey as string}>{t(f.accessorKey as string, f.header)}</option>)}\n                  </select>\n                  <select aria-label={t('condition', 'Condición')} className={`${condCtrlCls} w-full md:w-[180px] cursor-pointer`} value={row.operator} onChange={(e) => updateRow(row.id, { operator: e.target.value })}>\n                    {OPERATORS.map((op) => <option key={op.value} value={op.value}>{t(op.labelKey, op.label)}</option>)}\n                  </select>\n                  <input type=\"text\" aria-label={t('value', 'Valor')} placeholder={t('writeValue', 'Escribe un valor…')} autoComplete=\"off\" className={`${condCtrlCls} w-full md:flex-1 md:min-w-0`} value={row.value} onChange={(e) => updateRow(row.id, { value: e.target.value })} />\n                  <button type=\"button\" title={t('removeCondition', 'Eliminar condición')} aria-label={t('removeCondition', 'Eliminar condición')} onClick={() => removeRow(row.id)} className=\"flex-shrink-0 inline-flex items-center justify-center w-8 h-8 self-end md:self-auto rounded-md text-content-tertiary hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors\">\n                    <XMarkIcon className=\"w-4 h-4\" />\n                  </button>\n                </div>\n\n                {/* Conector entre condiciones (refleja el selector global Y/O) */}\n                {idx < rows.length - 1 && (\n                  <div className=\"flex items-center gap-2 px-3\">\n                    <span className=\"ml-5 inline-flex items-center justify-center h-5 min-w-[26px] px-2 rounded-full text-[10px] font-bold tracking-wide bg-primary-50 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300 border border-primary-100 dark:border-primary-800 select-none\">\n                      {connector === 'AND' ? t('connectorAnd', 'Y') : t('connectorOr', 'O')}\n                    </span>\n                    <span className=\"h-px flex-1 bg-border-primary/70 dark:bg-dark-border-primary/70\" />\n                  </div>\n                )}\n                </React.Fragment>\n              ))}\n            </div>\n\n            <div>\n              <button type=\"button\" onClick={addRow} className=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold text-primary-600 border border-dashed border-[#93d1fd] hover:bg-[#eff8ff] dark:hover:bg-primary-900/20 transition-colors\">\n                <PlusIcon className=\"w-3.5 h-3.5\" />\n                {t('addCondition', 'Agregar condición')}\n              </button>\n            </div>\n          </div>\n        </details>\n\n        {/* ── Botones ── */}\n        <div className=\"flex justify-end gap-2\">\n          <button type=\"reset\" className=\"inline-flex items-center justify-center gap-2 h-9 px-3 rounded-md text-sm font-medium whitespace-nowrap bg-transparent border border-[#93d1fd] text-primary-600 shadow-sm hover:bg-[#dbeefe] dark:hover:bg-primary-900/20 transition-all duration-150\">\n            <svg className=\"w-4 h-4 shrink-0\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21\" /><path d=\"M22 21H7\" /><path d=\"m5 11 9 9\" /></svg>\n            {t('clear', 'Limpiar')}\n          </button>\n          <button type=\"submit\" className=\"inline-flex items-center justify-center gap-2 h-9 px-3 rounded-md text-sm font-medium whitespace-nowrap bg-primary-600 text-white shadow-inner hover:brightness-110 transition-all duration-150\">\n            <SearchIcon className=\"w-4 h-4 shrink-0\" />\n            {t('search', 'Buscar')}\n          </button>\n        </div>\n      </form>\n    </section>\n  );\n};\n","import React, { useState, useEffect } from 'react';\nimport { Button } from '../Button/Button';\nimport { CloseIcon, LinkIcon, SearchIcon, EnableCompanyIcon } from './icons';\nimport type { MasterCrudCompany, MasterCrudField } from './MasterCrud.types';\n\ninterface LinkModalProps {\n  isOpen: boolean;\n  onClose: () => void;\n  recordId: string | number;\n  record: any;\n  companies: MasterCrudCompany[];\n  fields: MasterCrudField[];\n  onConfirm: (recordId: string | number, companyUuids: (string | number)[]) => void;\n  isLinked: (companyUuid: string | number) => boolean;\n  variant?: 'success' | 'manual';\n  /** Función de traducción inyectada por el padre */\n  t: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * LinkModal - Modal para vinculación de registros a múltiples compañías.\n */\nexport const LinkModal: React.FC<LinkModalProps> = ({\n  isOpen,\n  onClose,\n  recordId,\n  record,\n  companies,\n  fields,\n  onConfirm,\n  isLinked,\n  variant = 'manual',\n  t,\n}) => {\n  // ===== ESTADO LOCAL DE SELECCIÓN =====\n  const [selectedUuids, setSelectedUuids] = useState<(string | number)[]>([]);\n  const [initialUuids, setInitialUuids] = useState<(string | number)[]>([]);\n  // Búsqueda frontend por nombre de compañía\n  const [search, setSearch] = useState('');\n\n  const targetCompanies = companies.filter(c => c.uuid !== '000');\n\n  // El buscador solo aparece cuando la lista es suficientemente larga para justificarlo.\n  const showSearch = targetCompanies.length > 3;\n\n  const normalizedSearch = search.trim().toLowerCase();\n  const filteredCompanies = normalizedSearch\n    ? targetCompanies.filter(c => (c.name || '').toLowerCase().includes(normalizedSearch))\n    : targetCompanies;\n\n  // Inicializar estado con las vinculaciones actuales al abrir\n  useEffect(() => {\n    if (isOpen) {\n      const initialLinks = targetCompanies\n        .filter(c => isLinked(c.uuid))\n        .map(c => c.uuid);\n      setSelectedUuids(initialLinks);\n      setInitialUuids(initialLinks);\n      setSearch('');\n    }\n  }, [isOpen, recordId]);\n\n  if (!isOpen) return null;\n\n  // ===== COMPARACIÓN DE CAMBIOS =====\n  const hasChanges = JSON.stringify([...selectedUuids].sort()) !== JSON.stringify([...initialUuids].sort());\n\n  // ===== MANEJADORES LOCALES =====\n  const handleToggleLink = (uuid: string | number) => {\n    setSelectedUuids(prev => \n      prev.includes(uuid) \n        ? prev.filter(c => c !== uuid) \n        : [...prev, uuid]\n    );\n  };\n\n  const handleLinkAll = () => {\n    setSelectedUuids(targetCompanies.map(c => c.uuid));\n  };\n\n  const handleConfirm = () => {\n    onConfirm(recordId, selectedUuids);\n    onClose();\n  };\n\n  // Construir título dinámico para el modo manual\n  const getDynamicTitle = () => {\n    if (variant === 'success') return t('recordCreatedSuccess', 'Haz creado el registro exitosamente');\n    \n    const titleValues = fields\n      .filter(f => f.config?.showInLinkModalTitle)\n      .map(f => {\n        const val = record[f.accessorKey as string];\n        return val ? String(val) : '';\n      })\n      .filter(v => v !== '');\n\n    const suffix = titleValues.length > 0 ? ` · ${titleValues.join(' - ')}` : '';\n    return `${t('recordLinking', 'Habilitar registro')}${suffix}`;\n  };\n\n  const getDescription = () => {\n    if (variant === 'success') {\n      return t('globalRecordSaved', 'El registro se guardó de forma Global; ahora puedes asignarlo a las compañías de tu elección');\n    }\n    return t('assignRecordToCompanies', 'Puedes asignar este registro a las compañías de tu elección');\n  };\n\n  return (\n    <div className=\"fixed inset-0 z-[70] flex items-center justify-center bg-black/50 p-4 animate-in fade-in duration-200\">\n      <div className=\"bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-2xl flex flex-col w-full max-w-2xl overflow-hidden relative\">\n        \n        {/* Botón Cerrar (X) */}\n        <div className=\"absolute right-4 top-4 z-10\">\n          <Button \n            type=\"outline\" \n            size=\"xs\" \n            iconOnly \n            leftIcon={<CloseIcon className=\"w-4 h-4\" />} \n            onClick={onClose} \n            ariaLabel=\"Cerrar\" \n            className=\"!bg-white dark:!bg-dark-bg-primary\"\n          />\n        </div>\n\n        {/* Header — icono azul de marca (no verde/lima) */}\n        <div className=\"p-[20px] flex gap-5 items-center\">\n          <div className=\"bg-[#dbeefe] dark:bg-primary-900/20 flex items-center justify-center rounded-full shrink-0 size-[40px]\">\n            <LinkIcon className=\"size-6 text-primary-600 dark:text-primary-400\" />\n          </div>\n          <div className=\"flex flex-col justify-center\">\n            <h3 className=\"text-[20px] font-bold leading-[28px] tracking-tight text-content-primary dark:text-dark-content-primary\">\n              {getDynamicTitle()}\n            </h3>\n            <p className=\"text-[14px] font-normal italic leading-[20px] text-content-tertiary dark:text-content-tertiary\">\n              {getDescription()}\n            </p>\n          </div>\n        </div>\n\n        {/* Buscador frontend (fijo, no scrollea con la lista) */}\n        {showSearch && (\n          <div className=\"px-[20px] pb-[12px]\">\n            <div className=\"relative\">\n              <SearchIcon className=\"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-content-tertiary\" />\n              <input\n                type=\"text\"\n                value={search}\n                onChange={(e) => setSearch(e.target.value)}\n                placeholder={t('searchCompanyPlaceholder', 'Buscar compañía…')}\n                aria-label={t('searchCompanyPlaceholder', 'Buscar compañía…')}\n                autoComplete=\"off\"\n                className=\"w-full h-10 pl-9 pr-9 rounded-lg border border-border-primary dark:border-dark-border-primary bg-white dark:bg-dark-bg-primary text-sm text-content-primary dark:text-dark-content-primary placeholder:text-content-tertiary focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors\"\n              />\n              {search && (\n                <button\n                  type=\"button\"\n                  onClick={() => setSearch('')}\n                  aria-label={t('clear', 'Limpiar')}\n                  className=\"absolute right-2 top-1/2 -translate-y-1/2 inline-flex items-center justify-center w-6 h-6 rounded-md text-content-tertiary hover:text-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                >\n                  <CloseIcon className=\"w-3.5 h-3.5\" />\n                </button>\n              )}\n            </div>\n          </div>\n        )}\n\n        {/* Body - Lista de compañías */}\n        <div className=\"px-[20px] pb-[20px] flex flex-col gap-[20px] overflow-y-auto max-h-[400px]\">\n          <div className=\"flex flex-col items-start w-full\">\n            {filteredCompanies.map((company) => {\n              const isCurrentlyLinked = selectedUuids.includes(company.uuid);\n              return (\n                <div\n                  key={company.uuid}\n                  className=\"border border-border-primary dark:border-dark-border-primary h-[64px] px-[8px] flex items-center justify-between rounded-[8px] w-full mb-3 last:mb-0 transition-colors hover:border-[#93d1fd] hover:bg-[#eff8ff]/40 dark:hover:bg-primary-900/10\"\n                >\n                  <div className=\"flex items-center gap-[8px]\">\n                    <div className=\"bg-[#dbeefe] dark:bg-primary-900/20 flex items-center justify-center rounded-[16px] shrink-0 size-[32px]\">\n                      <EnableCompanyIcon className=\"w-[18px] h-[18px]\" />\n                    </div>\n                    <span className=\"text-[16px] font-medium leading-[24px] text-content-primary dark:text-dark-content-primary truncate max-w-[300px]\">\n                      {company.name}\n                    </span>\n                  </div>\n\n                  {isCurrentlyLinked ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => handleToggleLink(company.uuid)}\n                      className=\"inline-flex items-center h-8 px-3 rounded-md text-xs font-semibold border transition-all bg-error/10 text-error-content border-error-border hover:brightness-95 dark:bg-error/20\"\n                    >\n                      {t('unlink', 'Deshabilitar')}\n                    </button>\n                  ) : (\n                    <button\n                      type=\"button\"\n                      onClick={() => handleToggleLink(company.uuid)}\n                      className=\"inline-flex items-center h-8 px-3 rounded-md text-xs font-semibold border transition-all bg-white dark:bg-dark-bg-primary text-primary-600 border-[#93d1fd] hover:bg-[#eff8ff] dark:hover:bg-primary-900/20\"\n                    >\n                      {t('link', 'Habilitar')}\n                    </button>\n                  )}\n                </div>\n              );\n            })}\n\n            {/* Estado vacío del buscador */}\n            {filteredCompanies.length === 0 && (\n              <div className=\"w-full flex flex-col items-center justify-center gap-2 py-10 text-center\">\n                <SearchIcon className=\"w-6 h-6 text-content-tertiary\" />\n                <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary\">\n                  {t('noCompaniesFound', 'No se encontraron compañías')}\n                </p>\n                <p className=\"text-xs text-content-tertiary\">\n                  <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">“{search}”</span>\n                </p>\n              </div>\n            )}\n          </div>\n        </div>\n\n        {/* Footer — botones h-9 px-3 (tamaño del listado, S2.2) */}\n        <div className=\"px-[24px] py-[16px] pb-[20px] flex items-center justify-end gap-3 shrink-0 w-full border-t border-border-secondary dark:border-dark-border-primary\">\n          <Button type=\"plain\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium\" onClick={onClose}>\n            {t('cancelText', 'Cancelar')}\n          </Button>\n          <Button type=\"outline\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium\" onClick={handleLinkAll}>\n            {t('linkAll', 'Habilitar todas')}\n          </Button>\n          <Button type=\"default\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium\" onClick={handleConfirm} disabled={!hasChanges}>\n            {t('confirmText', 'Confirmar')}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\nimport { InformationCircleIcon } from '@heroicons/react/24/outline';\nimport type { InfoProps, InfoColor } from './Info.types';\n\n/**\n * Componente Info del sistema de diseño Siesa\n * \n * Se utiliza para mostrar mensajes informativos, alertas inline o banners de estado.\n * Soporta múltiples esquemas de color y modo oscuro (dark mode).\n * \n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema de tipografía\n * \n * @example\n * ```tsx\n * <Info \n *   title=\"Información de cuenta\" \n *   description=\"Tu suscripción se renovará automáticamente el próximo mes.\" \n *   color=\"blue\" \n * />\n * ```\n */\nexport const Info: React.FC<InfoProps> = ({\n  title,\n  description,\n  color = 'zinc',\n  icon,\n  className = '',\n  children,\n  ...props\n}) => {\n  // ===== CONFIGURACIÓN DE COLORES =====\n  const colorSchemes: Record<InfoColor, string> = {\n    zinc: `\n      bg-[#f4f4f5] border-[#d4d4d8] text-[#3f3f46]\n      dark:bg-[#18181b] dark:border-[#3f3f46] dark:text-[#f4f4f5]\n    `,\n    blue: `\n      bg-[#dbeefe] border-[#93d1fd] text-[#0e79fd]\n      dark:bg-[#112d57] dark:border-[#0f6ae3] dark:text-[#93d1fd]\n    `,\n    red: `\n      bg-[#fef2f2] border-[#fecaca] text-[#b91c1c]\n      dark:bg-[#450a0a] dark:border-[#991b1b] dark:text-[#fecaca]\n    `,\n    green: `\n      bg-[#f0fdf4] border-[#bbf7d0] text-[#15803d]\n      dark:bg-[#064e3b] dark:border-[#065f46] dark:text-[#bbf7d0]\n    `,\n    yellow: `\n      bg-[#fffbeb] border-[#fde68a] text-[#b45309]\n      dark:bg-[#451a03] dark:border-[#78350f] dark:text-[#fde68a]\n    `,\n    orange: `\n      bg-[#fff7ed] border-[#fed7aa] text-[#c2410c]\n      dark:bg-[#431407] dark:border-[#9a3412] dark:text-[#fed7aa]\n    `,\n    purple: `\n      bg-[#faf5ff] border-[#e9d5ff] text-[#7e22ce]\n      dark:bg-[#3b0764] dark:border-[#581c87] dark:text-[#e9d5ff]\n    `,\n    primary: `\n      bg-primary-100 border-primary-300 text-primary-600\n      dark:bg-dark-bg-custom dark:border-dark-border-custom dark:text-dark-content-custom\n    `,\n    secondary: `\n      bg-background-secondary border-border-primary text-content-primary\n      dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary\n    `,\n  };\n\n  // ===== CLASES BASE =====\n  const baseClasses = `\n    flex\n    items-start\n    gap-3\n    p-4\n    rounded-lg\n    border\n    transition-colors\n    duration-150\n    w-full\n  `;\n\n  // ===== COMBINAR CLASES =====\n  const finalClasses = [\n    baseClasses,\n    colorSchemes[color],\n    className,\n  ]\n    .join(' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  return (\n    <div className={finalClasses} {...props}>\n      {/* Icono */}\n      <div className=\"shrink-0 mt-0.5\">\n        {icon || <InformationCircleIcon className=\"w-6 h-6\" />}\n      </div>\n\n      {/* Contenedor de Texto */}\n      <div className=\"flex flex-col gap-1 w-full\">\n        <h3 className=\"text-[18px] font-bold leading-[1.2] tracking-tight\">\n          {title}\n        </h3>\n        {description && (\n          <p className=\"text-sm font-normal leading-[1.4] opacity-90\">\n            {description}\n          </p>\n        )}\n        {children && <div className=\"mt-2\">{children}</div>}\n      </div>\n    </div>\n  );\n};\n","export default \"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='iso-8859-1'?%3e%3c!--%20Generator:%20Adobe%20Illustrator%2027.1.1,%20SVG%20Export%20Plug-In%20.%20SVG%20Version:%206.00%20Build%200)%20--%3e%3csvg%20version='1.1'%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20x='0px'%20y='0px'%20viewBox='0%200%202000%202000'%20style='enable-background:new%200%200%202000%202000;'%20xml:space='preserve'%3e%3cpath%20style='fill:%23313131;'%20d='M1757.6,1550.49H268.703c-0.747,0-1.463-0.3-1.99-0.83c-0.528-0.53-0.825-1.24-0.825-1.99%20c0-0.74,0.297-1.46,0.825-1.99c0.527-0.53,1.243-0.82,1.99-0.82H1757.6c0.75,0,1.46,0.29,1.99,0.82c0.53,0.53,0.82,1.25,0.82,1.99%20c0,0.75-0.29,1.46-0.82,1.99C1759.06,1550.19,1758.35,1550.49,1757.6,1550.49z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1456.99,919.459c0,0,182.17,77.91,208.69,127.761c30.56,57.42-15.76,492.64-138.07,514.21%20c-122.32,21.57-519.71,38.71-519.71,38.71v-52.47l-73.628-52.64l59.356-143.71c0,0-126.503,100.07-183.877-48.01%20c-57.375-148.07-74.623-307.562-74.623-307.562L880.5,951.433l67.147,170.907c0,0,124.323-243.007,182.703-262.305%20c48.26-15.897,190.39,24.972,190.39,24.972l7.07,69.962L1456.99,919.459z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1007.9,1602.95c-0.35,0.01-0.71-0.06-1.04-0.2c-0.34-0.13-0.64-0.33-0.89-0.58%20c-0.28-0.26-0.5-0.58-0.65-0.93c-0.15-0.35-0.23-0.72-0.23-1.1v-51.07l-72.439-51.79c-0.519-0.37-0.898-0.9-1.074-1.51%20c-0.176-0.61-0.139-1.26,0.105-1.85l55.551-134.63c-17.811,11.87-62.103,36.71-105.967,24.77%20c-32.132-8.76-57.104-35.58-74.308-79.73c-56.518-146.41-74.532-306.69-74.532-308.288c-0.07-0.652,0.089-1.308,0.451-1.855%20s0.903-0.95,1.53-1.14l145.35-44.314c0.679-0.203,1.409-0.144,2.046,0.164c0.638,0.309,1.137,0.844,1.399,1.502l64.896,165.141%20c19.342-37.24,126.912-240.147,181.472-258.116c48.52-16.009,186.19,23.261,192.05,24.927c0.54,0.157,1.02,0.473,1.37,0.906%20c0.36,0.434,0.58,0.966,0.63,1.526l6.76,66.629l125.96-34.654c0.61-0.182,1.27-0.134,1.84,0.135%20c7.48,3.197,183.39,78.811,210.07,129.007c22.99,43.21,3.51,304.14-62.6,439.72c-22.99,47.12-49.06,73.58-77.48,78.58%20c-121.17,21.35-516.08,38.57-520.15,38.75H1007.9z%20M937.74,1494.04l71.81,51.34c0.35,0.25,0.65,0.59,0.85,0.98%20c0.2,0.39,0.31,0.83,0.32,1.27v49.54c36.59-1.62,401.12-18.22,516.39-38.53c26.55-4.68,51.23-30.08,73.38-75.5%20c28.62-58.66,51.95-150.24,64.16-251.21c10.4-86.89,9.84-162.3-1.38-183.4c-24.77-46.61-192.52-120.063-206.39-126.098%20l-128.35,35.262c-0.4,0.115-0.81,0.141-1.22,0.076c-0.4-0.065-0.79-0.22-1.13-0.453c-0.33-0.232-0.62-0.538-0.82-0.893%20c-0.21-0.355-0.33-0.752-0.37-1.161l-6.89-68.025c-16.73-4.684-142.91-38.978-186.89-24.499%20c-56.52,18.689-179.802,258.501-181.041,260.891c-0.245,0.48-0.626,0.88-1.095,1.16c-0.47,0.27-1.009,0.4-1.552,0.38%20c-0.543-0.03-1.067-0.21-1.508-0.53c-0.441-0.32-0.781-0.76-0.979-1.26l-66.246-168.5l-140.621,42.783%20c2.387,20.267,21.346,168.407,74.105,304.547c16.415,42.38,40.103,68.07,70.412,76.33c52.713,14.37,108.533-29.07,109.096-29.52%20c0.488-0.38,1.091-0.59,1.712-0.59c0.62,0,1.223,0.21,1.711,0.59c0.498,0.38,0.858,0.9,1.025,1.5s0.131,1.24-0.102,1.81%20L937.74,1494.04z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1252.38,839.048V410.046h-0.41c-86.98-5.899-180.81-9.119-278.608-9.119%20c-82.841,0-162.823,2.251-238.234,6.597h0.495v429.295h-0.27c75.343-4.279,155.235-6.598,238.009-6.598%20c97.948,0,191.918,3.243,279.018,9.142V839.048z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1252.38,842.201h-0.18c-89.26-6.057-183.07-9.187-278.837-9.187%20c-80.883,0-160.775,2.252-237.469,6.575h-0.405c-0.745,0.031-1.473-0.233-2.025-0.735c-0.552-0.501-0.884-1.2-0.925-1.945%20c-0.024-0.473,0.069-0.945,0.27-1.373V409.101c-0.305-0.42-0.489-0.916-0.531-1.434c-0.043-0.517,0.057-1.037,0.29-1.501%20c0.232-0.465,0.587-0.857,1.027-1.133c0.44-0.277,0.947-0.427,1.466-0.435C812.048,400.229,892.255,398,973.453,398%20c95.747,0,189.547,3.062,278.807,9.12h0.43c0.71,0.051,1.37,0.368,1.85,0.886c0.48,0.518,0.74,1.199,0.74,1.906v429.474%20c0.01,0.372-0.06,0.74-0.2,1.084c-0.14,0.345-0.35,0.657-0.61,0.92s-0.58,0.47-0.92,0.609c-0.34,0.139-0.71,0.208-1.08,0.202%20H1252.38z%20M973.363,827.429c94.817,0,187.727,3.018,276.197,9.007V412.681c-88.45-5.944-181.35-9.007-276.197-9.007%20c-79.982,0-158.996,2.252-234.924,6.418v423.755C814.367,829.591,893.403,827.429,973.363,827.429z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1119.73,667.758h-0.19c-43.45-2.95-89.12-4.504-135.73-4.504c-39.383,0-78.293,1.081-115.604,3.198%20h-0.203c-0.734,0.019-1.446-0.247-1.988-0.743c-0.542-0.495-0.87-1.182-0.917-1.914c-0.023-0.262-0.023-0.526,0-0.788V455.689%20c-0.14-0.321-0.224-0.664-0.247-1.013c-0.031-0.742,0.23-1.466,0.726-2.017c0.497-0.552,1.19-0.887,1.931-0.933%20c37.536-2.139,76.559-3.22,116.234-3.22c46.658,0,92.318,1.509,135.918,4.503c0.73,0.038,1.43,0.347,1.95,0.867%20c0.52,0.52,0.82,1.214,0.86,1.948v209.164c0.01,0.384-0.07,0.764-0.22,1.117c-0.15,0.353-0.38,0.67-0.66,0.932%20C1121.08,667.497,1120.42,667.753,1119.73,667.758z%20M983.81,657.67c45.67,0,90.43,1.441,133.1,4.256V458.414%20c-42.78-2.838-87.48-4.279-133.1-4.279c-38.46,0-76.559,1.036-113.015,3.04V660.71c36.569-2.004,74.555-3.04,113.038-3.04H983.81z'%20/%3e%3cpath%20style='fill:%23313131;'%20d='M867.756,660.057l93.582-142.783l52.152,86.918l49.04-41.613l57.22,102.365L867.756,660.057z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1119.73,667.759c-0.5-0.003-0.99-0.138-1.43-0.391c-0.43-0.253-0.78-0.615-1.03-1.05l-55.55-99.37%20l-46.43,39.383c-0.31,0.262-0.67,0.454-1.06,0.563c-0.39,0.108-0.79,0.132-1.19,0.068c-0.4-0.07-0.79-0.225-1.12-0.454%20c-0.34-0.229-0.63-0.527-0.84-0.875l-49.832-83.066L870.12,661.589c-0.198,0.32-0.457,0.598-0.764,0.816%20c-0.306,0.219-0.653,0.374-1.021,0.455c-0.367,0.082-0.747,0.09-1.117,0.022c-0.371-0.067-0.724-0.209-1.038-0.415%20c-0.315-0.206-0.585-0.474-0.795-0.786c-0.209-0.313-0.354-0.664-0.426-1.033c-0.071-0.37-0.068-0.75,0.01-1.118%20c0.078-0.368,0.229-0.717,0.444-1.026l93.583-142.76c0.255-0.406,0.611-0.737,1.034-0.962c0.422-0.226,0.897-0.336,1.375-0.322%20c0.478,0.014,0.944,0.146,1.357,0.386c0.413,0.24,0.759,0.58,1.007,0.988l50.441,84.057l46.5-39.338%20c0.31-0.265,0.69-0.458,1.09-0.564c0.4-0.106,0.82-0.123,1.22-0.05c0.41,0.073,0.8,0.234,1.14,0.473%20c0.34,0.238,0.62,0.548,0.83,0.907l57.21,102.364c0.19,0.322,0.3,0.677,0.35,1.044c0.04,0.367,0.01,0.74-0.09,1.096%20c-0.1,0.357-0.27,0.689-0.5,0.979s-0.51,0.531-0.84,0.709C1120.69,667.715,1120.2,667.801,1119.73,667.759z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1026.53,535.897c10.28,0,18.62-8.337,18.62-18.622c0-10.284-8.34-18.622-18.62-18.622%20c-10.29,0-18.63,8.338-18.63,18.622C1007.9,527.56,1016.24,535.897,1026.53,535.897z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1026.53,538.712c-4.24,0-8.39-1.257-11.91-3.613c-3.53-2.355-6.28-5.703-7.9-9.62%20c-1.62-3.917-2.05-8.227-1.22-12.386c0.83-4.158,2.87-7.978,5.87-10.976c3-2.997,6.82-5.039,10.97-5.866%20c4.16-0.827,8.47-0.403,12.39,1.22c3.92,1.622,7.26,4.37,9.62,7.895s3.61,7.67,3.61,11.909c0,5.684-2.26,11.133-6.28,15.152%20C1037.66,536.446,1032.21,538.706,1026.53,538.712z%20M1026.53,501.468c-3.12,0-6.17,0.925-8.76,2.657%20c-2.59,1.732-4.61,4.193-5.81,7.073c-1.19,2.881-1.5,6.05-0.89,9.107c0.6,3.058,2.11,5.867,4.31,8.071%20c2.2,2.204,5.01,3.706,8.07,4.314c3.06,0.608,6.23,0.296,9.11-0.897c2.88-1.193,5.34-3.214,7.07-5.806s2.66-5.639,2.66-8.757%20c0-4.18-1.66-8.189-4.62-11.145C1034.72,503.129,1030.71,501.468,1026.53,501.468z'/%3e%3cpath%20style='fill:%23313131;'%20d='M800.338,708.717c-0.746,0.018-1.469-0.262-2.01-0.777c-0.54-0.515-0.854-1.224-0.872-1.97%20c-0.018-0.747,0.261-1.47,0.777-2.01c0.515-0.541,1.224-0.855,1.97-0.872c1.329,0,134.812-6.598,386.647,0%20c0.37,0.008,0.73,0.09,1.07,0.239c0.34,0.15,0.64,0.365,0.9,0.632c0.26,0.268,0.46,0.583,0.59,0.928%20c0.13,0.345,0.2,0.713,0.19,1.083c-0.01,0.371-0.08,0.738-0.23,1.079s-0.36,0.649-0.63,0.905c-0.27,0.257-0.59,0.456-0.94,0.587%20c-0.34,0.131-0.71,0.191-1.09,0.176c-251.605-6.575-384.908,0-386.214,0H800.338z'/%3e%3cpath%20style='fill:%23313131;'%20d='M800.542,749.002c-0.747,0.018-1.47-0.261-2.01-0.777c-0.541-0.515-0.855-1.224-0.872-1.97%20c-0.018-0.747,0.261-1.47,0.776-2.01c0.515-0.541,1.224-0.854,1.971-0.872c1.306,0,134.811-6.598,386.643,0%20c0.37,0.008,0.74,0.09,1.07,0.24c0.34,0.15,0.64,0.365,0.9,0.633c0.25,0.268,0.45,0.583,0.58,0.928%20c0.13,0.345,0.19,0.712,0.18,1.081c0,0.372-0.08,0.741-0.22,1.083c-0.15,0.343-0.36,0.652-0.63,0.909%20c-0.27,0.257-0.59,0.456-0.94,0.586s-0.72,0.187-1.09,0.169c-251.592-6.598-384.895,0-386.223,0H800.542z'/%3e%3cpath%20style='fill:%23313131;'%20d='M800.542,789.263c-0.747,0.018-1.47-0.262-2.01-0.777c-0.541-0.515-0.855-1.224-0.872-1.97%20c-0.018-0.747,0.261-1.47,0.776-2.01c0.515-0.541,1.224-0.855,1.971-0.873c1.306,0,134.811-6.597,386.643,0%20c0.37,0.009,0.74,0.091,1.07,0.241c0.34,0.15,0.64,0.365,0.9,0.633c0.25,0.268,0.45,0.583,0.58,0.928%20c0.13,0.345,0.19,0.712,0.18,1.081c0,0.373-0.07,0.743-0.22,1.087c-0.14,0.344-0.36,0.654-0.63,0.912%20c-0.27,0.258-0.59,0.457-0.94,0.586c-0.35,0.128-0.72,0.183-1.09,0.162c-251.592-6.575-384.895,0-386.223,0H800.542z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M151.814,984.759c0-58.14,170.727-108.781,423.057-135.104h-0.225V420.293h-0.675%20c-251.835,26.39-422.157,76.987-422.157,135.104V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M151.815,987.574c-0.747,0-1.463-0.297-1.991-0.824c-0.527-0.528-0.824-1.244-0.824-1.991V555.42%20c0-58.545,158.748-109.975,424.678-137.852h0.698c0.404-0.053,0.814-0.018,1.203,0.102c0.389,0.121,0.747,0.324,1.049,0.596%20c0.29,0.267,0.521,0.591,0.68,0.951c0.159,0.36,0.242,0.75,0.243,1.143v428.191c0.113,0.242,0.181,0.501,0.203,0.766%20c0.076,0.74-0.145,1.48-0.613,2.058c-0.469,0.578-1.147,0.947-1.886,1.027c-125.783,13.128-231.457,32.335-305.584,55.528%20c-75.186,23.53-114.839,50.079-114.839,76.807c0.004,0.389-0.073,0.775-0.225,1.133c-0.153,0.358-0.378,0.68-0.661,0.947%20c-0.284,0.267-0.62,0.472-0.987,0.602C152.593,987.549,152.203,987.602,151.815,987.574z%20M571.832,423.423%20c-124.476,13.15-228.957,32.245-302.544,55.28c-75.028,23.508-114.659,50.034-114.659,76.717v410.447%20c30.286-50.394,181.401-93.898,417.203-118.734V423.423z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M182.754,859.876c0-35.825,79.216-67.011,196.284-83.314l-0.315-268.115%20c-116.843,16.258-195.902,51.07-195.902,86.85L182.754,859.876z'/%3e%3cpath%20style='fill:%23313131;'%20d='M182.753,862.693c-0.37,0.003-0.738-0.068-1.08-0.209c-0.343-0.14-0.655-0.347-0.917-0.609%20c-0.262-0.262-0.469-0.574-0.609-0.916c-0.141-0.343-0.211-0.711-0.208-1.081V595.366c0-37.694,77.842-72.866,198.31-89.642%20c0.398-0.051,0.802-0.017,1.186,0.1s0.739,0.313,1.041,0.577s0.545,0.589,0.712,0.954c0.168,0.364,0.256,0.76,0.259,1.161%20l0.315,267.349v0.338c0.103,0.74-0.089,1.491-0.536,2.089c-0.447,0.599-1.112,0.997-1.851,1.109%20c-117.766,16.347-193.852,47.917-193.852,80.477c0,0.739-0.29,1.448-0.809,1.974C184.196,862.379,183.492,862.681,182.753,862.693z%20M375.818,511.759c-112.182,16.055-190.25,50.281-190.25,83.607v247.286c19.32-29.092,87.48-53.929,190.565-68.475L375.818,511.759z%20'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M151.814,984.759c0,26.211,34.722,50.911,95.992,72.531h-0.248V627.858l0.698,0.248%20c-61.562-21.662-96.442-46.408-96.442-72.686V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M247.806,1060.1c-0.322,0-0.642-0.05-0.945-0.16C181.92,1037.02,149,1011.73,149,984.759v-429.34%20c0-0.746,0.297-1.462,0.824-1.99c0.528-0.528,1.244-0.825,1.991-0.825c0.746,0,1.462,0.297,1.99,0.825%20c0.528,0.528,0.824,1.244,0.824,1.99c0,23.936,32.403,48.03,93.695,69.804h0.18l0.698,0.248c0.701,0.25,1.274,0.766,1.594,1.437%20c0.321,0.671,0.363,1.441,0.118,2.143c-0.126,0.337-0.308,0.649-0.541,0.923v426.186c0.261,0.67,0.261,1.42,0,2.1%20c-0.191,0.53-0.538,0.99-0.997,1.32C248.918,1059.91,248.371,1060.09,247.806,1060.1z%20M154.629,574.446v410.313%20c0,23.461,31.142,47.081,90.07,68.451V629.884C196.512,612.613,166.383,594.059,154.629,574.446z'/%3e%3cpath%20style='fill:%23313131;'%20d='M430.175,770.752c-0.745-0.006-1.457-0.304-1.984-0.831c-0.526-0.526-0.825-1.239-0.831-1.984%20v-88.921c-0.005-0.685,0.243-1.349,0.695-1.864c0.453-0.515,1.079-0.845,1.76-0.928l118.712-15.92%20c0.401-0.053,0.81-0.021,1.198,0.096c0.388,0.116,0.747,0.314,1.053,0.58c0.299,0.265,0.538,0.591,0.701,0.956%20c0.163,0.365,0.247,0.761,0.245,1.16v88.539c-0.004,0.679-0.251,1.335-0.698,1.847c-0.446,0.513-1.061,0.848-1.734,0.945%20l-118.712,16.28L430.175,770.752z%20M432.945,681.471v83.314l113.082-15.514v-82.887L432.945,681.471z'/%3e%3cpath%20style='fill:%23313131;'%20d='M487.28,747.043c-0.4,0.001-0.796-0.082-1.161-0.245c-0.365-0.163-0.691-0.402-0.956-0.701%20l-26.818-30.174c-0.433-0.565-0.635-1.274-0.566-1.983s0.405-1.366,0.939-1.837c0.534-0.471,1.227-0.723,1.939-0.703%20c0.713,0.019,1.391,0.308,1.898,0.808l24.049,27.134l25.647-51.79c0.332-0.672,0.917-1.185,1.626-1.426%20c0.709-0.24,1.485-0.189,2.157,0.142s1.185,0.916,1.425,1.626c0.241,0.709,0.19,1.485-0.141,2.157l-27.517,55.483%20c-0.216,0.423-0.536,0.786-0.93,1.053c-0.393,0.268-0.848,0.432-1.321,0.478L487.28,747.043z'/%3e%3cpath%20style='fill:%23313131;'%20d='M412.003,521.35c-0.686,0.003-1.35-0.244-1.867-0.695c-0.516-0.452-0.85-1.076-0.939-1.757%20c-0.088-0.68,0.075-1.369,0.459-1.938c0.384-0.568,0.962-0.977,1.626-1.149c41.983-10.096,84.624-17.229,127.606-21.347%20c0.369-0.035,0.74,0.002,1.094,0.11s0.682,0.285,0.968,0.52c0.285,0.235,0.522,0.525,0.695,0.851%20c0.174,0.327,0.282,0.684,0.317,1.052c0.036,0.369-0.002,0.74-0.11,1.094c-0.108,0.354-0.285,0.682-0.52,0.968%20c-0.235,0.285-0.524,0.522-0.851,0.695c-0.326,0.174-0.684,0.282-1.052,0.317c-42.694,4.085-85.049,11.166-126.751,21.189%20C412.458,521.318,412.231,521.348,412.003,521.35z'/%3e%3cpath%20style='fill:%23313131;'%20d='M412.003,568.863c-0.686,0.003-1.35-0.244-1.867-0.695c-0.516-0.452-0.85-1.077-0.939-1.757%20c-0.088-0.68,0.075-1.369,0.459-1.938c0.384-0.569,0.962-0.977,1.626-1.15c41.983-10.095,84.624-17.228,127.606-21.346%20c0.744-0.072,1.485,0.155,2.062,0.63c0.576,0.475,0.94,1.16,1.012,1.903c0.072,0.744-0.155,1.485-0.63,2.062%20c-0.475,0.576-1.16,0.94-1.903,1.012c-42.694,4.085-85.049,11.165-126.751,21.189C412.458,568.831,412.231,568.861,412.003,568.863z%20'/%3e%3cpath%20style='fill:%23313131;'%20d='M412.003,617.095c-0.686,0.004-1.35-0.244-1.867-0.695c-0.516-0.452-0.85-1.076-0.939-1.756%20c-0.088-0.681,0.075-1.37,0.459-1.939c0.384-0.568,0.962-0.977,1.626-1.149c41.981-10.109,84.622-17.242,127.606-21.347%20c0.369-0.035,0.74,0.002,1.094,0.11c0.354,0.108,0.682,0.285,0.968,0.52c0.285,0.236,0.522,0.525,0.695,0.851%20c0.174,0.327,0.282,0.684,0.317,1.052c0.036,0.369-0.002,0.74-0.11,1.094c-0.108,0.354-0.285,0.683-0.52,0.968%20c-0.235,0.285-0.524,0.522-0.851,0.695c-0.326,0.174-0.684,0.282-1.052,0.317c-42.696,4.072-85.052,11.153-126.751,21.189%20C412.456,617.053,412.23,617.083,412.003,617.095z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1847.15,984.759c0-58.14-170.73-108.781-423.06-135.104h0.21V420.293h0.67%20c251.84,26.39,422.18,76.987,422.18,135.104V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,987.574c-0.75,0-1.46-0.297-1.99-0.825c-0.53-0.527-0.82-1.243-0.82-1.99%20c0-26.728-39.75-53.276-114.84-76.807c-74.15-23.148-179.69-42.355-305.41-55.505h-0.38c-0.71-0.122-1.36-0.505-1.8-1.076%20c-0.45-0.571-0.66-1.287-0.61-2.009c0-0.158,0-0.315,0-0.45V420.293c0-0.394,0.09-0.783,0.25-1.142c0.16-0.36,0.39-0.681,0.68-0.945%20c0.3-0.263,0.64-0.462,1.02-0.583c0.37-0.122,0.77-0.163,1.16-0.122h0.67c265.93,27.876,424.71,79.396,424.71,137.851v429.407%20c0,0.716-0.27,1.406-0.76,1.929S1847.87,987.528,1847.15,987.574z%20M1427.11,847.11c235.8,24.769,386.92,68.341,417.23,118.734%20V555.42c0-26.683-39.66-53.209-114.69-76.717c-73.47-23.035-178.04-42.13-302.54-55.28V847.11z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,987.574c-0.75,0-1.46-0.297-1.99-0.825c-0.53-0.527-0.82-1.243-0.82-1.99%20c0-26.728-39.75-53.276-114.84-76.807c-74.15-23.148-179.69-42.355-305.41-55.505h-0.38c-0.71-0.122-1.36-0.505-1.8-1.076%20c-0.45-0.571-0.66-1.287-0.61-2.009c0-0.158,0-0.315,0-0.45V420.293c0-0.394,0.09-0.783,0.25-1.142c0.16-0.36,0.39-0.681,0.68-0.945%20c0.3-0.263,0.64-0.462,1.02-0.583c0.37-0.122,0.77-0.163,1.16-0.122h0.67c265.93,27.876,424.71,79.396,424.71,137.851v429.407%20c0,0.716-0.27,1.406-0.76,1.929S1847.87,987.528,1847.15,987.574z%20M1427.11,847.11c235.8,24.769,386.92,68.341,417.23,118.734%20V555.42c0-26.683-39.66-53.209-114.69-76.717c-73.47-23.035-178.04-42.13-302.54-55.28V847.11z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,987.574c-0.75,0-1.46-0.297-1.99-0.825c-0.53-0.527-0.82-1.243-0.82-1.99%20c0-26.728-39.75-53.276-114.84-76.807c-74.15-23.148-179.69-42.355-305.41-55.505h-0.38c-0.71-0.122-1.36-0.505-1.8-1.076%20c-0.45-0.571-0.66-1.287-0.61-2.009c0-0.158,0-0.315,0-0.45V420.293c0-0.394,0.09-0.783,0.25-1.142c0.16-0.36,0.39-0.681,0.68-0.945%20c0.3-0.263,0.64-0.462,1.02-0.583c0.37-0.122,0.77-0.163,1.16-0.122h0.67c265.93,27.876,424.71,79.396,424.71,137.851v429.407%20c0,0.716-0.27,1.406-0.76,1.929S1847.87,987.528,1847.15,987.574z%20M1427.11,847.11c235.8,24.769,386.92,68.341,417.23,118.734%20V555.42c0-26.683-39.66-53.209-114.69-76.717c-73.47-23.035-178.04-42.13-302.54-55.28V847.11z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,951.433c0-43.503-62.8-81.423-155.62-101.148V529.029h0.25%20c92.64,19.748,155.37,57.622,155.37,101.081V951.433z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1847.15,954.247c-0.75,0-1.46-0.296-1.99-0.824c-0.53-0.528-0.83-1.244-0.83-1.99%20c0-40.532-58.7-78.226-153.11-98.356h-0.14c-0.72-0.143-1.35-0.557-1.77-1.157c-0.42-0.601-0.59-1.34-0.48-2.063V529.029%20c-0.01-0.43,0.07-0.857,0.25-1.247c0.18-0.391,0.45-0.735,0.79-1.005c0.32-0.264,0.7-0.454,1.11-0.555s0.84-0.111,1.25-0.031h0.25%20c97.16,20.716,157.62,60.505,157.62,103.828v321.414c0,0.381-0.08,0.758-0.23,1.109s-0.37,0.667-0.64,0.93%20c-0.28,0.264-0.6,0.468-0.96,0.601S1847.53,954.266,1847.15,954.247z%20M1694.41,848.033c78.81,17.091,132.99,46.769,149.92,80.635%20V630.087c0-40.059-57.35-77.347-149.92-97.636V848.033z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1847.15,984.759c0,26.211-34.72,50.911-95.99,72.531h0.25V627.858l-0.7,0.248%20c61.54-21.662,96.44-46.408,96.44-72.686V984.759z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1751.16,1060.1c-0.58,0.01-1.14-0.17-1.61-0.5c-0.48-0.33-0.83-0.8-1.03-1.34%20c-0.14-0.34-0.21-0.69-0.21-1.05s0.07-0.72,0.21-1.05V629.974c-0.24-0.268-0.42-0.582-0.54-0.923c-0.24-0.699-0.2-1.467,0.11-2.137%20c0.32-0.67,0.89-1.189,1.58-1.443l0.72-0.248h0.16c61.31-21.707,93.72-45.8,93.72-69.804c0-0.746,0.29-1.462,0.82-1.99%20c0.53-0.528,1.25-0.825,1.99-0.825c0.75,0,1.46,0.297,1.99,0.825c0.53,0.528,0.83,1.244,0.83,1.99v429.34%20c0,27.021-32.92,52.261-97.86,75.181C1751.75,1060.04,1751.46,1060.1,1751.16,1060.1z%20M1754.22,629.862v423.328%20c58.97-21.37,90.07-45.04,90.07-68.454v-410.29C1832.56,594.059,1802.41,612.613,1754.22,629.862z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,531.777c-0.25-0.006-0.51-0.044-0.76-0.113c-100.97-28.664-207.16-38.122-208.27-38.279%20c-0.73-0.077-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.039c0.07-0.736,0.42-1.417,0.98-1.895%20c0.56-0.479,1.29-0.718,2.03-0.664c1.06,0,107.81,9.615,209.3,38.415c0.67,0.172,1.25,0.585,1.63,1.158%20c0.39,0.574,0.55,1.268,0.45,1.952c-0.09,0.684-0.43,1.31-0.96,1.757c-0.52,0.448-1.2,0.687-1.89,0.672V531.777z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,583.363c-0.26,0.007-0.51-0.031-0.76-0.113c-100.97-28.642-207.16-38.122-208.27-38.279%20c-0.73-0.077-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.303-0.63-2.039c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.478,1.29-0.717,2.03-0.663c1.06,0,107.81,9.592,209.3,38.415c0.65,0.189,1.21,0.605,1.57,1.172%20c0.37,0.567,0.52,1.247,0.43,1.917c-0.09,0.669-0.42,1.282-0.93,1.728s-1.16,0.694-1.84,0.699V583.363z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,634.86c-0.25,0.031-0.51,0.031-0.76,0c-100.97-28.665-207.16-38.145-208.27-38.28%20c-0.73-0.076-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.038c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.479,1.29-0.717,2.03-0.664c1.06,0,107.81,9.615,209.3,38.415c0.65,0.189,1.21,0.605,1.57,1.172%20c0.37,0.567,0.52,1.248,0.43,1.917s-0.42,1.283-0.93,1.728c-0.51,0.446-1.16,0.694-1.84,0.7V634.86z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,686.651c-0.25,0.031-0.51,0.031-0.76,0c-100.97-28.664-207.16-38.122-208.27-38.279%20c-0.74-0.066-1.43-0.426-1.91-1c-0.49-0.574-0.72-1.316-0.65-2.063c0.06-0.746,0.42-1.436,1-1.917c0.57-0.482,1.31-0.715,2.06-0.65%20c1.06,0.113,107.81,9.615,209.3,38.438c0.65,0.189,1.21,0.605,1.57,1.172c0.37,0.567,0.52,1.247,0.43,1.917%20c-0.09,0.669-0.42,1.282-0.93,1.728s-1.16,0.694-1.84,0.699V686.651z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1665.68,738.149c-0.26,0.007-0.52-0.031-0.76-0.113c-100.97-28.642-207.16-38.122-208.27-38.279%20c-0.37-0.027-0.73-0.128-1.07-0.297c-0.33-0.169-0.62-0.402-0.87-0.686c-0.24-0.285-0.42-0.614-0.53-0.97%20c-0.12-0.356-0.16-0.73-0.13-1.102c0.04-0.372,0.14-0.734,0.32-1.064c0.17-0.33,0.41-0.623,0.7-0.86%20c0.28-0.238,0.62-0.415,0.97-0.523c0.36-0.108,0.74-0.144,1.11-0.105c1.06,0,107.81,9.592,209.3,38.415%20c0.65,0.189,1.21,0.605,1.57,1.172c0.37,0.567,0.52,1.247,0.43,1.917c-0.09,0.669-0.43,1.282-0.93,1.728%20c-0.51,0.446-1.16,0.694-1.84,0.699V738.149z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,789.757c-0.25-0.006-0.51-0.043-0.76-0.112c-100.97-28.665-207.16-38.145-208.27-38.28%20c-0.73-0.076-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.038c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.479,1.29-0.717,2.03-0.664c1.06,0,107.81,9.615,209.3,38.415c0.67,0.173,1.25,0.585,1.63,1.159%20c0.39,0.573,0.55,1.268,0.45,1.952c-0.09,0.684-0.43,1.309-0.96,1.757c-0.52,0.447-1.2,0.687-1.89,0.671V789.757z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1663.99,841.345c-0.25-0.006-0.51-0.043-0.76-0.112c-100.97-28.665-207.16-38.122-208.27-38.28%20c-0.73-0.076-1.41-0.439-1.88-1.009c-0.47-0.57-0.69-1.302-0.63-2.038c0.07-0.736,0.42-1.417,0.98-1.896%20c0.56-0.479,1.29-0.717,2.03-0.664c1.06,0,107.81,9.593,209.3,38.415c0.65,0.189,1.21,0.605,1.57,1.172%20c0.37,0.568,0.52,1.248,0.43,1.917c-0.09,0.669-0.42,1.283-0.93,1.729c-0.51,0.445-1.16,0.693-1.84,0.699V841.345z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1353.64,725.516c11.45,0,20.73-14.174,20.73-31.659s-9.28-31.66-20.73-31.66%20c-11.46,0-20.74,14.175-20.74,31.66S1342.18,725.516,1353.64,725.516z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1353.66,728.308c-12.99,0-23.55-15.447-23.58-34.452c0-19.005,10.56-34.474,23.56-34.474%20c12.99,0,23.55,15.469,23.55,34.451c0.16,8.439-2.11,16.746-6.53,23.936C1366.16,724.525,1360.17,728.308,1353.66,728.308z%20M1335.64,693.856c0,15.627,8.22,28.822,18.02,28.822c4.5,0,9.01-2.837,12.29-7.993c3.83-6.262,5.78-13.492,5.61-20.829%20c0-15.65-8.22-28.845-18.01-28.845c-9.71,0-18.02,13.218-18.02,28.845H1335.64z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1320.74,885.051l7.07,69.961l129.18-35.555l52.08-176.244l-137.08-38.392L1320.74,885.051z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1327.81,957.828c-0.57-0.005-1.13-0.177-1.6-0.495c-0.34-0.233-0.62-0.538-0.82-0.892%20c-0.21-0.354-0.34-0.749-0.37-1.158l-7.14-69.939c-0.08-0.348-0.08-0.71,0-1.058l51.25-180.139c0.2-0.716,0.68-1.321,1.33-1.684%20c0.65-0.363,1.42-0.454,2.14-0.253l137.08,38.393c0.36,0.095,0.7,0.263,0.99,0.492c0.3,0.229,0.54,0.515,0.72,0.841%20c0.18,0.326,0.3,0.685,0.34,1.055c0.03,0.371,0,0.746-0.11,1.102l-51.88,176.176c-0.14,0.458-0.39,0.874-0.73,1.209%20c-0.35,0.335-0.77,0.577-1.23,0.705l-129.18,35.532C1328.34,957.79,1328.08,957.828,1327.81,957.828z%20M1323.6,885.322l6.75,66.088%20l124.46-34.248l50.75-171.966l-131.61-36.906L1323.6,885.322z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1344,804.822c0,0,27.24-14.501,75.32,0c26.52,8.017-0.9-54.379-0.9-54.379l-54.9-15.357%20L1344,804.822z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1423.53,808.357c-1.71-0.027-3.4-0.308-5.02-0.833c-46.23-13.96-72.93-0.36-73.2-0.225%20c-0.49,0.264-1.04,0.378-1.59,0.326c-0.55-0.053-1.07-0.268-1.5-0.618c-0.42-0.348-0.74-0.813-0.9-1.337%20c-0.17-0.524-0.17-1.085-0.02-1.613l19.52-69.804c0.1-0.357,0.27-0.69,0.49-0.982c0.23-0.291,0.52-0.535,0.84-0.717%20c0.32-0.181,0.67-0.298,1.04-0.343c0.37-0.045,0.74-0.017,1.1,0.083l54.92,15.469c0.4,0.113,0.77,0.313,1.08,0.585%20c0.32,0.272,0.57,0.611,0.74,0.991c3.29,7.476,19.19,45.283,9.66,56.046c-0.9,0.998-2,1.782-3.24,2.296%20C1426.21,808.195,1424.87,808.426,1423.53,808.357z%20M1378.29,795.523c14.2,0.141,28.29,2.372,41.84,6.62%20c3.06,0.923,5.18,0.765,6.31-0.496c5.13-5.809-2.66-31.524-10.07-48.817l-50.89-14.254l-17.23,61.473%20C1357.95,796.905,1368.1,795.376,1378.29,795.523z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1354.22,667.691l-9.32,41.905c-2.22,9.824-2.49,19.99-0.78,29.917%20c1.72,9.926,5.37,19.416,10.76,27.928c5.38,8.511,12.4,15.876,20.63,21.673c8.24,5.796,17.54,9.91,27.37,12.105l13.76,3.108%20c9.82,2.208,19.99,2.46,29.91,0.74c9.92-1.72,19.41-5.378,27.92-10.764c8.5-5.387,15.87-12.396,21.67-20.629%20c5.8-8.233,9.92-17.527,12.12-27.352l9.44-41.928c4.7-20.967,0.89-42.943-10.61-61.099c-11.49-18.156-29.72-31.006-50.68-35.725%20l-5.3-1.194c-10.38-2.338-21.13-2.607-31.62-0.791c-10.5,1.816-20.53,5.682-29.52,11.376c-9,5.694-16.79,13.105-22.92,21.809%20C1360.91,647.474,1356.56,657.302,1354.22,667.691z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1432.56,808.786c-5.97,0.002-11.92-0.662-17.74-1.982l-11.51-2.589%20c-10.33-2.319-20.11-6.65-28.77-12.748c-8.66-6.098-16.03-13.842-21.69-22.789c-5.67-8.948-9.52-18.925-11.32-29.36%20c-1.81-10.434-1.54-21.123,0.78-31.455l9.16-40.802c4.88-21.689,18.17-40.553,36.95-52.444c18.79-11.891,41.52-15.835,63.21-10.965%20l5.32,1.194c21.67,4.902,40.52,18.201,52.41,36.981c11.89,18.78,15.84,41.508,10.99,63.199l-9.16,40.778%20c-4.25,18.894-15.15,35.629-30.71,47.152c-0.6,0.385-1.33,0.529-2.03,0.401c-0.7-0.127-1.33-0.516-1.75-1.088%20c-0.43-0.571-0.62-1.283-0.54-1.991c0.08-0.709,0.42-1.361,0.96-1.826c14.48-10.716,24.63-26.286,28.58-43.863l9.16-40.779%20c4.52-20.235,0.84-41.437-10.25-58.955c-11.09-17.519-28.68-29.923-48.9-34.493l-5.29-1.193c-10.02-2.252-20.39-2.508-30.51-0.754%20c-10.12,1.754-19.79,5.484-28.47,10.977c-8.68,5.493-16.19,12.641-22.1,21.036c-5.92,8.396-10.12,17.874-12.37,27.894l-9.17,40.847%20c-2.16,9.612-2.4,19.555-0.72,29.263c1.68,9.707,5.26,18.988,10.53,27.313c5.27,8.324,12.12,15.529,20.18,21.202%20c8.05,5.674,17.15,9.705,26.76,11.863l11.5,2.568c13.56,3.061,27.69,2.281,40.83-2.252c0.35-0.137,0.73-0.201,1.11-0.19%20c0.37,0.012,0.74,0.1,1.09,0.259c0.34,0.159,0.65,0.385,0.9,0.665c0.26,0.28,0.45,0.609,0.58,0.966%20c0.12,0.357,0.17,0.736,0.15,1.113c-0.03,0.377-0.13,0.745-0.3,1.083c-0.17,0.337-0.41,0.636-0.7,0.88%20c-0.29,0.244-0.62,0.427-0.99,0.538C1450.31,807.335,1441.46,808.803,1432.56,808.786z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1354.22,667.69c0,0,11.91-19.636,23.37-26.751c11.47-7.116,92.87,13.308,99.55,18.802%20c5.77,4.751,9.89,13.195,12.5,29.881c2.86,18.351,25.45,25.985,25.45,25.985l2.52-11.259l19.41-80.838%20c0.12-0.513,0.14-1.046,0.05-1.566c-0.08-0.521-0.27-1.02-0.55-1.466c-0.28-0.447-0.65-0.833-1.08-1.136%20c-0.44-0.303-0.92-0.516-1.44-0.628l-153.07-33.393c-0.99-0.215-2.03-0.043-2.89,0.48c-0.87,0.523-1.5,1.359-1.77,2.335%20L1354.22,667.69z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1515.09,718.422c-0.31,0.001-0.61-0.045-0.9-0.135c-0.99-0.338-24.23-8.422-27.34-28.237%20c-2.25-14.816-5.85-23.486-11.51-28.147c-6.05-4.976-86.46-24.634-96.28-18.554c-10.76,6.755-22.32,25.602-22.52,25.782%20c-0.34,0.615-0.89,1.081-1.56,1.306c-0.66,0.225-1.39,0.194-2.03-0.088c-0.65-0.282-1.16-0.794-1.45-1.436%20c-0.28-0.642-0.31-1.367-0.09-2.033l22.06-79.554c0.46-1.678,1.55-3.115,3.04-4.012c1.48-0.898,3.26-1.187,4.96-0.807l153.12,33.461%20c0.88,0.19,1.72,0.556,2.46,1.076c0.73,0.519,1.36,1.182,1.84,1.948s0.8,1.621,0.94,2.513c0.14,0.892,0.11,1.804-0.11,2.682%20l-19.41,80.815l-2.5,11.258c-0.09,0.383-0.26,0.744-0.49,1.058c-0.24,0.314-0.54,0.575-0.88,0.766%20C1516.02,718.312,1515.56,718.428,1515.09,718.422z%20M1386.38,636.819c26.3,0,87.25,16.392,92.54,20.738%20c6.76,5.607,10.97,15.357,13.51,31.637c1.99,12.655,14.8,19.861,20.65,22.518l1.8-7.949l19.41-80.882%20c0.04-0.148,0.05-0.302,0.03-0.453c-0.03-0.151-0.08-0.296-0.16-0.426c-0.08-0.127-0.19-0.237-0.31-0.322s-0.26-0.144-0.41-0.173%20l-153.12-33.483c-0.29-0.057-0.59-0.002-0.84,0.152c-0.25,0.155-0.43,0.398-0.51,0.681l-17.72,64.017%20c4.16-5.516,9.18-10.334,14.86-14.276C1379.33,637.169,1382.86,636.558,1386.38,636.819z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1418.49,711.871h-0.61l-23.26-5.224c-0.49-0.107-0.93-0.34-1.3-0.676%20c-0.36-0.337-0.63-0.764-0.77-1.238c-0.32-0.968-1.26-3.941,10.13-32.02c0.28-0.693,0.82-1.246,1.51-1.537%20c0.69-0.291,1.47-0.297,2.16-0.017c0.69,0.281,1.25,0.825,1.54,1.514c0.29,0.688,0.29,1.464,0.01,2.157%20c-3.68,8.778-6.9,17.745-9.63,26.863l20.85,4.684c0.67,0.151,1.27,0.547,1.68,1.113c0.4,0.566,0.58,1.261,0.5,1.951%20c-0.08,0.69-0.41,1.327-0.93,1.788s-1.19,0.714-1.88,0.709V711.871z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1448.86,687.056c-0.63-0.005-1.24-0.217-1.73-0.603c-0.5-0.387-0.86-0.927-1.01-1.536%20c-3.72-14.907-20.27-16.46-21.08-16.506c-0.74-0.063-1.43-0.418-1.91-0.988c-0.49-0.57-0.72-1.308-0.66-2.051%20c0.03-0.369,0.13-0.728,0.29-1.057c0.17-0.33,0.4-0.623,0.68-0.862c0.28-0.239,0.61-0.42,0.96-0.531s0.72-0.151,1.09-0.117%20c0.22,0,21.39,1.869,26.1,20.738c0.09,0.359,0.11,0.733,0.05,1.1c-0.05,0.367-0.18,0.719-0.37,1.037%20c-0.19,0.318-0.44,0.595-0.74,0.816c-0.29,0.221-0.63,0.38-0.99,0.47C1449.32,687.018,1449.09,687.048,1448.86,687.056z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1379.31,671.97c-0.53,0-1.04-0.146-1.48-0.421c-0.45-0.274-0.81-0.667-1.04-1.135%20c-0.24-0.468-0.33-0.991-0.29-1.512c0.05-0.52,0.24-1.017,0.55-1.436c9.01-11.889,26.06-9.322,26.78-9.209%20c0.36,0.057,0.71,0.186,1.03,0.379c0.31,0.193,0.59,0.447,0.81,0.746c0.21,0.299,0.37,0.638,0.46,0.997%20c0.08,0.36,0.1,0.733,0.04,1.098c-0.06,0.365-0.19,0.715-0.38,1.031c-0.19,0.315-0.45,0.589-0.75,0.807%20c-0.29,0.217-0.63,0.373-0.99,0.46c-0.36,0.086-0.74,0.101-1.1,0.044c-0.14,0-14.41-2.117-21.41,7.07%20c-0.27,0.338-0.61,0.612-0.99,0.799C1380.16,671.875,1379.74,671.972,1379.31,671.97z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1428.35,692.641c2.01,0,3.65-1.633,3.65-3.647c0-2.015-1.64-3.648-3.65-3.648%20c-2.02,0-3.65,1.633-3.65,3.648C1424.7,691.008,1426.33,692.641,1428.35,692.641z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1390.36,685.727c2.02,0,3.65-1.633,3.65-3.648c0-2.014-1.63-3.647-3.65-3.647%20c-2.01,0-3.65,1.633-3.65,3.647C1386.71,684.094,1388.35,685.727,1390.36,685.727z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1523.27,735.838c7.49-15.802,5.16-32.587-5.19-37.49c-10.35-4.904-24.81,3.93-32.29,19.731%20c-7.49,15.802-5.17,32.587,5.18,37.491C1501.33,760.473,1515.78,751.639,1523.27,735.838z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1497.07,759.653h-1.3c-0.75-0.051-1.45-0.396-1.94-0.96c-0.49-0.564-0.74-1.3-0.69-2.047%20c0.05-0.746,0.4-1.442,0.96-1.934c0.57-0.492,1.3-0.74,2.05-0.689c8.56,0.563,18.82-7.588,24.43-19.432%20c6.76-14.141,4.93-29.588-3.85-33.776c-6.24-2.95-14.82,0.247-21.87,8.196c-0.49,0.558-1.19,0.897-1.93,0.941%20c-0.75,0.045-1.48-0.209-2.04-0.705c-0.56-0.495-0.9-1.193-0.94-1.938c-0.05-0.745,0.21-1.478,0.7-2.036%20c8.74-9.863,19.93-13.51,28.49-9.547c11.73,5.561,14.66,24.048,6.53,41.229C1519.34,750.533,1507.7,759.653,1497.07,759.653z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1509.39,729.974h-0.25l-5.83-0.518c-0.54-0.048-1.05-0.251-1.48-0.584%20c-0.43-0.333-0.75-0.781-0.93-1.292c-0.17-0.511-0.2-1.062-0.07-1.588c0.12-0.526,0.4-1.004,0.79-1.377l11.51-11.011%20c0.26-0.279,0.57-0.501,0.92-0.654c0.35-0.153,0.73-0.234,1.11-0.236s0.76,0.073,1.12,0.221c0.35,0.149,0.67,0.368,0.93,0.643%20c0.26,0.276,0.47,0.602,0.61,0.96c0.13,0.357,0.19,0.738,0.17,1.12c-0.02,0.382-0.11,0.756-0.28,1.099%20c-0.16,0.344-0.4,0.65-0.69,0.9l-7.05,6.755c0.7,0.125,1.33,0.51,1.76,1.079c0.43,0.569,0.62,1.278,0.55,1.986%20c-0.07,0.708-0.41,1.361-0.95,1.829c-0.54,0.467-1.23,0.714-1.94,0.691V729.974z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1349.9,689.691c-0.51,0-1-0.139-1.44-0.401c-0.43-0.262-0.78-0.637-1.02-1.086l-4.5-8.331%20c-0.2-0.325-0.33-0.687-0.38-1.064c-0.06-0.377-0.04-0.761,0.06-1.129s0.27-0.712,0.51-1.011c0.23-0.3,0.53-0.549,0.86-0.732%20s0.7-0.296,1.08-0.333s0.76,0.004,1.12,0.119c0.37,0.115,0.7,0.303,0.99,0.552c0.29,0.249,0.52,0.554,0.69,0.896l4.5,8.354%20c0.18,0.323,0.29,0.679,0.33,1.046c0.04,0.366,0.01,0.737-0.09,1.091c-0.11,0.354-0.28,0.684-0.52,0.97%20c-0.23,0.286-0.52,0.524-0.84,0.698C1350.84,689.57,1350.37,689.694,1349.9,689.691z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1429.07,743.8c-8.87,0-15.76-7.318-18.44-12.092c-0.3-0.511-0.43-1.103-0.37-1.692%20c0.05-0.589,0.3-1.145,0.69-1.589c0.39-0.444,0.91-0.753,1.49-0.883c0.58-0.131,1.18-0.076,1.72,0.156%20c2.77,1.076,5.73,1.543,8.69,1.368c2.96-0.175,5.85-0.987,8.47-2.381c4.51-2.252,7.86-5.652,8.65-8.715%20c0.13-0.647,0.48-1.228,0.99-1.64c0.52-0.413,1.16-0.629,1.82-0.611c0.64,0.021,1.25,0.255,1.73,0.663%20c0.49,0.408,0.82,0.968,0.95,1.588c0.14,0.766,3.22,18.712-9.57,24.184C1433.76,743.174,1431.43,743.734,1429.07,743.8z%20M1420.54,734.793c1.71,1.64,3.87,2.745,6.21,3.181c2.33,0.435,4.74,0.183,6.94-0.727c1.78-0.917,3.3-2.28,4.4-3.957%20s1.75-3.611,1.88-5.613c-1.86,1.638-3.93,3.024-6.15,4.121c-4.12,2.065-8.68,3.071-13.28,2.927V734.793z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1013.69,1586.72c-1.42,8.19-3.22,12.97-5.27,13.01c-2.05,0.05-3.92-4.3-5.63-11.89%20c-3.263-14.23-5.807-39.97-6.438-69.37c-0.643-20.29,0.049-40.6,2.072-60.8c1.531-12.99,3.786-20.92,6.416-20.96%20c2.64-0.05,5.36,8.19,7.48,21.72c2.75,19.73,4.25,39.61,4.5,59.52C1017.56,1546.82,1016.14,1572.17,1013.69,1586.72z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1008.35,1602.52c-3.46,0-7.11-3.28-10.511-26.09c-4.906-38.45-5.767-77.31-2.567-115.95%20c2.409-23.21,5.988-26.48,9.498-26.54c3.52-0.07,7.21,3.01,10.63,26.09c2.61,19.2,4.05,38.54,4.33,57.92%20c0.57,19.36-0.01,38.74-1.76,58.03c-2.41,23.21-5.99,26.48-9.48,26.54H1008.35z%20M1004.91,1440.4c-3.22,5.99-6.756,34.25-5.765,78.11%20c0.995,43.87,5.715,71.92,9.205,77.78c3.2-5.99,6.76-34.27,5.75-78.12c-0.97-43.95-5.72-72.03-9.21-77.88L1004.91,1440.4z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1016.91,1517.99c-0.25-19.91-1.75-39.79-4.5-59.51l-5.2-0.27l-4.82-0.27l-3.875-0.22l-3.603-0.21%20l-4.751-0.24l-5.742-0.34l-4.954-0.25l-11.552-0.61l-11.258-0.52l-10.809-0.45l-4.323-0.15c-3.333-0.14-6.755-0.25-10.088-0.34%20c-4.098-0.14-8.241-0.23-12.362-0.32h-2.251c-52.128-0.92-104.954,1.8-140.847,15.95c-2.094,0.83-4.278,1.71-6.485,2.67%20c-2.207,0.97-4.503,1.96-6.868,3.02l-3.535,1.62l-7.183,3.45l-3.648,1.82l-3.648,1.87c-19.477,10.11-38.752,22.14-48.727,31.93%20l-1.734,1.8c-0.811,0.9-1.554,1.76-2.252,2.59c-2.544,3.4-3.58,6.4-2.567,8.78c0.171,0.41,0.374,0.8,0.608,1.17%20c4.143,6.4,15.425,1.49,17.113,0.75l-0.18,0.11c-4.03,2.45-32.38,20.15-25.85,34.02c0.073,0.2,0.156,0.38,0.248,0.57%20c5.607,10.45,28.575-3.76,37.469-9.8c-6.553,4.91-19.568,16.35-15.289,26.75l0.202,0.43c0.233,0.43,0.555,0.81,0.946,1.1%20c7.633,6.08,41.387-7,47.467-9.41l0.36-0.13h-0.293h-0.135c-4.503,1.93-22.517,10.53-20.266,19.99c0.12,0.53,0.301,1.05,0.541,1.53%20c0.13,0.27,0.297,0.52,0.495,0.75c6.08,6.98,43.211-3.83,88.111-9.6c3.603-0.45,7.25-0.9,10.921-1.26%20c16.955-1.78,45.71,7.64,86.534,6.76c6.68-0.14,13.285-0.37,19.815-0.7l2.252-0.11l3.693-0.21c6.125-0.36,12.129-0.76,18.014-1.21%20c5.164-0.41,10.238-0.84,15.222-1.31l5.044-0.45l9.975-0.97l5.472-0.54l4.823-0.49c3.71-0.36,7.34-0.74,10.89-1.13%20C1016.15,1572.17,1017.56,1546.82,1016.91,1517.99z'/%3e%3cpath%20style='fill:%23313131;'%20d='M741.186,1602.77c-5.247,0-8.58-0.92-10.494-2.99c-0.39-0.45-0.716-0.95-0.968-1.49%20c-0.341-0.67-0.591-1.38-0.743-2.12c-0.332-1.88-0.21-3.82,0.358-5.65c0.568-1.83,1.565-3.5,2.907-4.86%20c-11.799,3.53-24.274,5.74-29.475,1.6l-0.338-0.27c-0.551-0.5-1.029-1.06-1.419-1.69c-0.028-0.07-0.066-0.14-0.112-0.2l-0.203-0.43%20c-1.016-2.35-1.466-4.9-1.313-7.45c0.152-2.55,0.903-5.03,2.191-7.23c-6.89,3.06-12.429,4.05-16.55,2.95%20c-1.394-0.35-2.697-0.99-3.817-1.89c-1.12-0.9-2.031-2.03-2.668-3.32c-0.157-0.29-0.27-0.54-0.383-0.78%20c-4.503-10.47,6.756-22.34,16.461-30c-1.467-0.16-2.878-0.64-4.129-1.42c-1.252-0.78-2.311-1.83-3.1-3.08%20c-0.322-0.5-0.601-1.03-0.833-1.58c-1.351-3.24-0.36-7.11,2.928-11.55c0.69-0.93,1.443-1.81,2.251-2.63%20c0.086-0.12,0.184-0.22,0.293-0.32l1.666-1.73c9.3-9.21,27.291-21.01,49.404-32.45h0.225l3.445-1.78l3.603-1.78%20c2.544-1.26,4.954-2.43,7.34-3.53l3.581-1.65c2.364-1.08,4.661-2.09,6.912-3.04c2.252-0.94,4.504-1.86,6.553-2.7%20c30.894-12.16,75.996-17.29,141.86-16.14c0.698,0,1.531,0,2.251,0c4.121,0,8.264,0.18,12.385,0.31c3.378,0,6.755,0.2,10.11,0.34%20l4.346,0.16l10.854,0.45c3.783,0.16,7.565,0.34,11.258,0.54l12.227,0.63c1.441,0,2.837,0.16,4.279,0.2l28.011,1.56%20c0.64,0.03,1.25,0.29,1.73,0.72c0.48,0.43,0.8,1.01,0.9,1.64c2.78,19.86,4.28,39.87,4.51,59.92c0.63,27.99-0.61,53.88-3.27,69.26%20c-0.12,0.59-0.43,1.13-0.88,1.54c-0.45,0.4-1.01,0.65-1.62,0.71l-21.185,2.26l-6.237,0.6l-8.827,0.81%20c-4.954,0.45-10.043,0.9-15.222,1.29c-6.62,0.52-12.565,0.92-18.172,1.24l-3.738,0.2h-0.72c-0.54,0-1.081,0-1.644,0%20c-6.44,0.34-13.127,0.56-19.838,0.72c-19.27,0.14-38.518-1.36-57.532-4.5c-12.069-1.72-21.594-3.09-28.754-2.26%20c-3.671,0.39-7.274,0.81-10.854,1.26c-15.402,1.96-29.835,4.51-42.58,6.76C760.866,1600.86,748.932,1602.77,741.186,1602.77z%20M753.232,1578h-0.157c-10.133,4.62-19.816,11.6-18.6,16.78c0.064,0.32,0.17,0.63,0.316,0.92c2.904,3.22,23.238-0.29,42.895-3.69%20c12.813-2.25,27.314-4.73,42.783-6.76c3.603-0.45,7.273-0.9,10.989-1.28c7.836-0.81,17.676,0.61,30.128,2.39%20c18.707,3.1,37.646,4.61,56.609,4.5c6.755-0.14,13.285-0.38,19.748-0.7h1.531h0.788l3.648-0.2c5.584-0.32,11.506-0.72,18.014-1.22%20c5.134-0.4,10.193-0.83,15.176-1.28l8.76-0.81l6.215-0.61l19.045-1.94c2.37-15.24,3.43-39.67,2.86-66.08%20c-0.27-18.99-1.64-37.94-4.09-56.77l-25.719-1.42l-4.278-0.22l-12.205-0.63l-11.259-0.52l-10.605-0.45l-4.504-0.18l-10.11-0.32%20c-4.121-0.13-8.219-0.25-12.34-0.31h-2.251c-65.301-1.15-109.638,3.87-139.811,15.76c-2.072,0.81-4.233,1.69-6.417,2.63%20c-2.185,0.95-4.504,1.94-6.756,3l-3.535,1.62c-2.252,1.08-4.706,2.25-7.093,3.4l-3.648,1.8l-3.602,1.87h-0.203%20c-21.234,11.01-39.113,22.72-47.85,31.34l-1.531,1.58c-0.04,0.07-0.093,0.13-0.157,0.18c-0.7,0.72-1.361,1.47-1.982,2.25%20c-1.959,2.64-2.747,4.75-2.252,5.99c0.101,0.26,0.229,0.51,0.383,0.74c2.252,3.72,9.863,1.45,13.511-0.27h0.247%20c0.689-0.25,1.449-0.23,2.124,0.06c0.675,0.29,1.212,0.82,1.502,1.5c0.211,0.52,0.262,1.09,0.146,1.64%20c-0.117,0.55-0.395,1.05-0.799,1.44c-0.151,0.15-0.317,0.28-0.496,0.39l-0.338,0.22c-10.38,6.49-28.822,21.12-24.769,30.44%20c0.054,0.15,0.122,0.28,0.203,0.41c0.283,0.57,0.688,1.06,1.187,1.45c0.498,0.39,1.078,0.66,1.695,0.8%20c4.886,1.29,14.524-2.48,26.481-10.33c0.599-0.34,1.302-0.45,1.975-0.31c0.673,0.15,1.269,0.54,1.677,1.09%20c0.407,0.55,0.598,1.24,0.535,1.92c-0.063,0.69-0.375,1.33-0.877,1.8c-5.382,4.37-13.871,12.83-10.448,20.56v0.18%20c0.07,0.11,0.153,0.2,0.247,0.29h0.113c4.008,3.36,22.765-0.79,44.584-9.86l0.406-0.14c0.377-0.09,0.771-0.11,1.155-0.05%20c0.385,0.07,0.752,0.21,1.08,0.42c0.327,0.21,0.608,0.49,0.824,0.81c0.216,0.33,0.362,0.69,0.431,1.07%20c0.166,0.61,0.126,1.25-0.115,1.83c-0.24,0.58-0.668,1.06-1.214,1.37V1578z'/%3e%3cpath%20style='fill:%23313131;'%20d='M752.85,1578c-0.644,0-1.267-0.22-1.767-0.63c-0.5-0.4-0.846-0.97-0.98-1.6%20c-0.134-0.63-0.049-1.28,0.242-1.86c0.291-0.57,0.769-1.03,1.356-1.29c29.701-13.51,69.804-24.14,87.976-27.72%20c0.734-0.14,1.496,0.01,2.116,0.43c0.621,0.42,1.05,1.06,1.194,1.8c0.143,0.73-0.011,1.49-0.429,2.12%20c-0.418,0.62-1.066,1.05-1.801,1.19c-18.013,3.51-57.464,14.05-86.737,27.31C753.65,1577.91,753.252,1578,752.85,1578z'/%3e%3cpath%20style='fill:%23313131;'%20d='M714.412,1562.33c-0.442,0-0.877-0.11-1.268-0.31c-0.392-0.21-0.729-0.5-0.984-0.86%20c-0.218-0.3-0.375-0.64-0.462-1c-0.086-0.36-0.101-0.74-0.042-1.1c0.059-0.37,0.189-0.72,0.384-1.03%20c0.194-0.32,0.449-0.59,0.75-0.81c25.985-18.58,90.07-43.8,113.871-48.48c0.37-0.09,0.756-0.11,1.133-0.05%20c0.377,0.06,0.738,0.2,1.061,0.4c0.322,0.21,0.599,0.48,0.815,0.79c0.215,0.32,0.364,0.67,0.438,1.05%20c0.073,0.37,0.07,0.76-0.011,1.13c-0.08,0.38-0.236,0.73-0.457,1.04c-0.222,0.31-0.504,0.57-0.831,0.77%20c-0.326,0.2-0.689,0.33-1.067,0.39c-22.878,4.5-86.692,29.67-111.664,47.55C715.589,1562.15,715.007,1562.33,714.412,1562.33z'/%3e%3cpath%20style='fill:%23313131;'%20d='M707.14,1534.38c-0.43,0.02-0.857-0.07-1.247-0.25c-0.391-0.18-0.735-0.45-1.005-0.78%20c-0.233-0.29-0.406-0.62-0.511-0.98c-0.104-0.35-0.137-0.72-0.098-1.09c0.04-0.37,0.152-0.73,0.33-1.05%20c0.178-0.33,0.418-0.61,0.707-0.84c19.162-15.52,73.001-40.81,108.511-48.21c0.372-0.11,0.763-0.14,1.148-0.09%20c0.384,0.05,0.754,0.18,1.086,0.38c0.333,0.2,0.62,0.46,0.845,0.78c0.224,0.31,0.381,0.67,0.46,1.05c0.08,0.38,0.08,0.77,0.001,1.15%20c-0.08,0.38-0.236,0.74-0.461,1.06c-0.224,0.31-0.512,0.58-0.844,0.78c-0.332,0.2-0.702,0.33-1.086,0.38%20c-34.182,7.14-87.818,32.29-106.125,47.11C708.362,1534.16,707.761,1534.37,707.14,1534.38z'/%3e%3cpath%20style='fill:%23313131;'%20d='M956.023,1029.28c-57.982,76.8-226.727,80.7-226.727,80.7s-39.653-256.115-58.05-279.218%20c-18.397-23.103-101.328,0.923-103.22-30.624c-1.891-31.547,86.625-25.58,84.778-42.175%20c-1.846-16.595-174.622-24.026-165.188-48.052c9.435-24.026,87.188-22.72,87.188-22.72c-3.31-29.093,41.094-31.682,41.094-31.682%20c0-15.92,42.4-17.271,42.4-17.271c0.924-8.286,83.855-28.732,179.667,88.246c58.703,71.605,88.561,156.608,103.58,218.283%20c2.409,9.886,4.503,19.163,6.102,27.674C951.537,991.208,954.334,1010.18,956.023,1029.28z'/%3e%3cpath%20style='fill:%23313131;'%20d='M729.297,1112.86c-0.673,0-1.324-0.24-1.835-0.68c-0.511-0.44-0.851-1.04-0.958-1.71%20c-13.668-88.31-43.256-260.117-57.464-277.861c-7.633-9.548-29.07-10.223-49.808-10.899c-25.986-0.81-52.871-1.666-54.042-21.324%20c-1.216-20.716,29.835-26.773,54.762-31.659c12.88-2.522,30.534-5.967,30.038-10.381c-1.914-5.449-41.387-11.821-70.209-16.46%20c-52.826-8.534-87.818-14.951-94.28-26.12c-0.616-1.025-0.985-2.179-1.079-3.37c-0.094-1.192,0.091-2.389,0.538-3.498%20c9.007-23.17,70.772-24.589,86.872-24.566c-0.111-5.878,1.941-11.591,5.765-16.055c9.75-11.597,29.07-14.636,35.803-15.38%20c3.377-14.433,34.766-16.978,43.188-17.406c2.332-2.232,5.228-3.789,8.376-4.503c3.243-0.946,80.297-22.09,175.208,93.762%20c59.671,72.822,89.529,159.514,104.098,219.41c2.252,9.3,4.301,18.644,6.125,27.809c3.882,18.891,6.694,37.991,8.422,57.191%20c0.042,0.68-0.157,1.35-0.563,1.89c-58.14,77.01-221.977,81.72-228.912,81.88L729.297,1112.86z%20M571.675,689.961%20c-23.103,0-74.533,3.625-81.356,20.986c-0.131,0.329-0.183,0.683-0.152,1.035c0.032,0.352,0.145,0.692,0.332,0.992%20c5.517,9.66,52.511,17.248,90.273,23.35c52.488,8.467,73.969,12.768,74.915,21.392c1.081,9.57-14.636,12.655-34.542,16.528%20c-22.787,4.503-51.137,10.02-50.213,25.805c0.833,14.523,24.026,15.266,48.57,16.055c22.022,0.698,44.787,1.418,54.041,12.97%20c18.014,22.382,53.885,250.076,58.253,278.066c20.896-0.9,168.183-9.66,221.459-78.81c-1.75-18.61-4.501-37.105-8.242-55.415%20c-1.801-9.007-3.85-18.374-6.079-27.584c-14.412-59.333-43.977-145.17-102.972-217.158%20c-73.993-90.317-138.077-94.731-155.979-93.943c-12.001,0.541-17.811,3.446-18.802,4.504c-0.128,0.614-0.456,1.167-0.933,1.575%20c-0.477,0.407-1.075,0.645-1.701,0.677c-10.291,0.337-39.676,3.693-39.676,14.456c0.001,0.714-0.271,1.401-0.761,1.921%20c-0.49,0.519-1.16,0.831-1.873,0.871c-0.248,0-24.094,1.576-34.204,13.51c-1.737,2.044-3.018,4.435-3.756,7.014%20c-0.737,2.578-0.916,5.285-0.523,7.938c0.055,0.404,0.021,0.814-0.099,1.203c-0.121,0.389-0.325,0.747-0.599,1.049%20c-0.271,0.296-0.601,0.532-0.97,0.691s-0.767,0.238-1.169,0.232L571.675,689.961z'/%3e%3cpath%20style='fill:%23313131;'%20d='M625.265,691.56h-0.157c-0.338,0-34.407-1.801-50.214-1.576c-0.37,0.012-0.739-0.051-1.084-0.185%20c-0.346-0.134-0.66-0.336-0.925-0.595c-0.265-0.259-0.475-0.569-0.617-0.91c-0.143-0.342-0.214-0.71-0.211-1.08%20c0-0.735,0.287-1.441,0.8-1.967s1.212-0.83,1.947-0.848c15.987-0.225,50.236,1.577,50.574,1.599c0.7,0.078,1.346,0.415,1.81,0.945%20c0.463,0.531,0.711,1.216,0.694,1.92c-0.017,0.705-0.297,1.377-0.786,1.885c-0.489,0.507-1.15,0.813-1.853,0.857L625.265,691.56z'/%3e%3cpath%20style='fill:%23313131;'%20d='M661.564,663.908h-0.608c-0.316,0-31.525-6.755-44.743-5.539c-0.366,0.037-0.737,0.001-1.09-0.106%20c-0.353-0.106-0.682-0.282-0.967-0.517c-0.284-0.234-0.52-0.523-0.692-0.849c-0.173-0.326-0.279-0.683-0.313-1.05%20c-0.037-0.368-0.002-0.74,0.105-1.095c0.107-0.354,0.282-0.684,0.516-0.971c0.234-0.286,0.523-0.524,0.849-0.699%20c0.326-0.175,0.684-0.283,1.052-0.32c14.073-1.396,45.17,5.359,46.498,5.629c0.662,0.17,1.241,0.572,1.629,1.133%20c0.389,0.561,0.563,1.244,0.489,1.923c-0.074,0.679-0.39,1.309-0.891,1.773c-0.501,0.465-1.152,0.733-1.834,0.756V663.908z'/%3e%3cpath%20style='fill:%23313131;'%20d='M696.871,648.37c-0.267,0.01-0.534-0.028-0.788-0.112c-0.248,0-24.544-7.138-37.672-7.138%20c-0.746,0-1.462-0.297-1.99-0.825c-0.528-0.528-0.824-1.244-0.824-1.99c-0.003-0.369,0.067-0.734,0.206-1.076%20c0.139-0.341,0.344-0.651,0.604-0.913c0.259-0.262,0.568-0.469,0.908-0.611c0.34-0.142,0.705-0.215,1.074-0.215%20c13.938,0,38.279,7.071,39.248,7.363c0.715,0.219,1.315,0.71,1.673,1.366c0.358,0.657,0.444,1.428,0.241,2.147%20c-0.174,0.577-0.528,1.083-1.01,1.444C698.059,648.17,697.473,648.367,696.871,648.37z'/%3e%3cpath%20style='fill:%23313131;'%20d='M725.243,897.684c-0.642-0.011-1.261-0.24-1.756-0.649c-0.494-0.409-0.836-0.974-0.968-1.603%20l-4.616-19.297c-0.143-0.714-0.003-1.456,0.39-2.069c0.393-0.613,1.008-1.05,1.716-1.22c0.709-0.169,1.455-0.057,2.083,0.313%20c0.627,0.37,1.087,0.968,1.282,1.67l4.504,19.275c0.087,0.361,0.102,0.735,0.043,1.102c-0.058,0.366-0.188,0.718-0.383,1.034%20c-0.194,0.316-0.45,0.59-0.751,0.807c-0.301,0.217-0.642,0.372-1.003,0.457C725.61,897.581,725.429,897.641,725.243,897.684z'/%3e%3cpath%20style='fill:%23313131;'%20d='M736.659,945.466c-0.641-0.011-1.26-0.24-1.755-0.65c-0.495-0.409-0.837-0.973-0.969-1.602%20l-4.616-19.274c-0.173-0.729-0.05-1.497,0.343-2.134c0.392-0.638,1.022-1.093,1.751-1.267c0.728-0.173,1.496-0.049,2.134,0.343%20c0.637,0.393,1.093,1.023,1.266,1.752l4.503,19.274c0.088,0.358,0.103,0.73,0.046,1.094c-0.057,0.363-0.186,0.712-0.378,1.026%20c-0.193,0.314-0.446,0.587-0.744,0.803c-0.299,0.216-0.637,0.37-0.995,0.455C737.059,945.372,736.862,945.433,736.659,945.466z'/%3e%3cpath%20style='fill:%23313131;'%20d='M748.188,993.248c-0.647-0.003-1.273-0.228-1.773-0.638c-0.501-0.41-0.844-0.98-0.974-1.614%20l-4.503-19.275c-0.143-0.714-0.003-1.456,0.39-2.069c0.393-0.613,1.008-1.051,1.717-1.22c0.708-0.169,1.454-0.057,2.082,0.313%20c0.627,0.37,1.087,0.968,1.282,1.67l4.504,19.275c0.087,0.359,0.103,0.732,0.046,1.097c-0.057,0.366-0.185,0.716-0.377,1.032%20c-0.193,0.316-0.445,0.591-0.744,0.809s-0.637,0.375-0.997,0.462L748.188,993.248z'/%3e%3cpath%20style='fill:%23313131;'%20d='M759.447,1041.05c-0.646-0.01-1.27-0.23-1.77-0.64c-0.499-0.41-0.844-0.98-0.978-1.61l-4.503-19.28%20c-0.102-0.36-0.129-0.74-0.079-1.12c0.049-0.37,0.173-0.73,0.365-1.06c0.193-0.33,0.448-0.61,0.753-0.83%20c0.304-0.23,0.651-0.39,1.019-0.48c0.368-0.09,0.75-0.1,1.123-0.04c0.373,0.07,0.73,0.21,1.049,0.41%20c0.318,0.2,0.593,0.47,0.806,0.78c0.213,0.32,0.362,0.67,0.436,1.04l4.616,19.27c0.169,0.73,0.043,1.49-0.349,2.13%20c-0.393,0.63-1.02,1.08-1.745,1.25C759.954,1040.97,759.703,1041.03,759.447,1041.05z'/%3e%3cpath%20style='fill:%23313131;'%20d='M770.931,1088.83c-0.646,0-1.271-0.22-1.769-0.63c-0.497-0.41-0.835-0.98-0.956-1.62l-4.616-19.27%20c-0.102-0.37-0.129-0.75-0.079-1.13c0.049-0.37,0.173-0.73,0.365-1.06c0.193-0.32,0.448-0.61,0.753-0.83%20c0.304-0.23,0.651-0.39,1.019-0.48c0.368-0.08,0.75-0.1,1.123-0.03c0.374,0.06,0.73,0.2,1.049,0.4c0.318,0.21,0.593,0.47,0.806,0.78%20c0.214,0.32,0.362,0.67,0.436,1.04l4.616,19.28c0.169,0.72,0.044,1.49-0.348,2.13c-0.392,0.63-1.02,1.09-1.746,1.27%20C771.372,1088.75,771.153,1088.8,770.931,1088.83z'/%3e%3cpath%20style='fill:%23313131;'%20d='M895.43,998.562c-3.514,0-6.949-1.042-9.871-2.994c-2.921-1.953-5.198-4.727-6.543-7.974%20c-1.345-3.246-1.697-6.818-1.011-10.264c0.685-3.447,2.377-6.612,4.862-9.097c2.485-2.485,5.65-4.177,9.097-4.862%20c3.446-0.686,7.018-0.334,10.265,1.011c3.246,1.344,6.021,3.622,7.973,6.543c1.952,2.922,2.994,6.357,2.994,9.871%20c0,4.711-1.872,9.23-5.204,12.562C904.661,996.69,900.142,998.562,895.43,998.562z%20M895.43,968.681%20c-2.402,0-4.749,0.713-6.745,2.047c-1.997,1.335-3.552,3.232-4.47,5.451c-0.918,2.219-1.157,4.66-0.687,7.015%20c0.47,2.355,1.628,4.518,3.328,6.214c1.699,1.697,3.864,2.851,6.22,3.316c2.356,0.466,4.797,0.223,7.014-0.699%20c2.217-0.922,4.111-2.482,5.442-4.48c1.331-1.999,2.039-4.348,2.035-6.749c0-1.593-0.314-3.17-0.925-4.642%20c-0.61-1.471-1.504-2.807-2.631-3.933c-1.128-1.125-2.466-2.017-3.938-2.624C898.6,968.989,897.023,968.678,895.43,968.681z'/%3e%3cpath%20style='fill:%23313131;'%20d='M839.676,1021.78c-3.514,0-6.951-1.04-9.876-2.98c-2.925-1.95-5.205-4.73-6.553-7.97%20c-1.349-3.25-1.704-6.82-1.021-10.27c0.683-3.448,2.374-6.615,4.857-9.102c2.484-2.487,5.65-4.182,9.097-4.869%20s7.02-0.337,10.268,1.007c3.247,1.344,6.023,3.621,7.976,6.544c1.954,2.922,2.996,6.36,2.996,9.87%20c-0.006,4.71-1.876,9.22-5.202,12.55S844.383,1021.77,839.676,1021.78z%20M839.676,991.898c-2.402-0.004-4.752,0.704-6.751,2.036%20c-1.999,1.332-3.558,3.227-4.48,5.446c-0.921,2.22-1.163,4.66-0.696,7.02c0.468,2.35,1.624,4.52,3.323,6.22%20c1.699,1.7,3.863,2.85,6.22,3.32c2.356,0.47,4.798,0.22,7.017-0.7s4.114-2.48,5.446-4.48c1.332-2,2.04-4.35,2.036-6.75%20c-0.006-3.21-1.284-6.287-3.555-8.557C845.965,993.182,842.888,991.904,839.676,991.898z'/%3e%3cpath%20style='fill:%23313131;'%20d='M947.647,975.257h-0.293c-3.71-0.383-7.205-1.926-9.988-4.409c-2.784-2.482-4.714-5.779-5.517-9.422%20c-0.802-3.642-0.437-7.445,1.045-10.868c1.482-3.422,4.004-6.291,7.21-8.199c0.373-0.233,0.799-0.372,1.238-0.403%20c0.44-0.031,0.88,0.045,1.283,0.223c0.408,0.168,0.77,0.428,1.06,0.761c0.289,0.332,0.497,0.727,0.607,1.153%20c2.251,9.3,4.301,18.645,6.124,27.809c0.08,0.408,0.069,0.829-0.034,1.233c-0.102,0.403-0.292,0.779-0.557,1.099%20c-0.265,0.321-0.598,0.579-0.974,0.756C948.474,975.167,948.063,975.258,947.647,975.257z%20M939.878,949.858%20c-1.176,1.421-2.013,3.092-2.446,4.886c-0.434,1.793-0.452,3.662-0.055,5.464c0.397,1.802,1.2,3.49,2.348,4.935%20c1.147,1.445,2.609,2.609,4.274,3.404C942.716,962.355,941.342,956.095,939.878,949.858z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M873.52,931.212c-2.967-0.005-5.852-0.977-8.216-2.769c-2.365-1.792-4.082-4.306-4.889-7.161%20c-38.505-135.51-105.72-189.146-106.395-189.754c-2.709-2.264-4.434-5.489-4.815-8.998c-0.381-3.509,0.612-7.029,2.772-9.821%20c2.16-2.792,5.317-4.638,8.809-5.152c3.492-0.513,7.048,0.347,9.919,2.399c3.018,2.252,74.758,58.951,115.942,203.895%20c0.979,3.476,0.54,7.198-1.22,10.35c-1.759,3.153-4.697,5.48-8.169,6.471C876.043,931.026,874.785,931.208,873.52,931.212z'/%3e%3cpath%20style='fill:%23313131;'%20d='M873.52,934.027c-3.566-0.026-7.027-1.204-9.868-3.359c-2.841-2.155-4.908-5.171-5.894-8.597%20c-38.1-134.114-104.774-187.795-105.427-188.336c-3.449-2.669-5.696-6.6-6.247-10.926c-0.551-4.326,0.639-8.694,3.308-12.143%20c2.67-3.449,6.6-5.696,10.926-6.247c4.327-0.551,8.695,0.639,12.144,3.308c3.062,2.365,75.5,59.536,116.932,205.337%20c1.17,4.18,0.644,8.652-1.464,12.446c-2.108,3.795-5.627,6.604-9.794,7.819C876.637,933.775,875.083,934.01,873.52,934.027z%20M762.396,709.957c-2.253-0.002-4.451,0.7-6.286,2.008c-1.834,1.309-3.214,3.158-3.946,5.289c-0.732,2.132-0.78,4.439-0.136,6.598%20c0.644,2.16,1.946,4.064,3.726,5.447c0.675,0.541,68.633,54.853,107.363,191.218c0.651,2.26,2.016,4.249,3.891,5.67%20c1.875,1.42,4.159,2.196,6.512,2.211c1.005-0.009,2.005-0.153,2.972-0.428c2.756-0.786,5.089-2.633,6.486-5.136%20c1.397-2.503,1.745-5.458,0.967-8.217c-40.936-144.111-111.956-200.112-114.974-202.431%20C767.089,710.732,764.775,709.948,762.396,709.957z'/%3e%3cpath%20style='fill:%23313131;'%20d='M993.627,1354.13c-0.458,0-0.91-0.11-1.315-0.33c-0.405-0.21-0.751-0.52-1.009-0.9%20c-0.257-0.38-0.418-0.82-0.468-1.27c-0.05-0.46,0.012-0.92,0.18-1.35l101.895-255.93c0.13-0.35,0.33-0.67,0.59-0.94%20c0.25-0.28,0.56-0.49,0.91-0.64c0.34-0.16,0.71-0.24,1.08-0.24c0.38-0.01,0.75,0.06,1.1,0.2s0.66,0.35,0.93,0.61%20c0.26,0.26,0.48,0.58,0.62,0.92c0.14,0.35,0.22,0.72,0.22,1.09c-0.01,0.38-0.08,0.75-0.23,1.09l-101.958,255.94%20c-0.207,0.51-0.558,0.94-1.01,1.26C994.71,1353.95,994.177,1354.12,993.627,1354.13z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1007.9,1602.95c-0.52,0-1.03-0.14-1.48-0.42c-0.44-0.27-0.8-0.67-1.03-1.13%20c-0.24-0.47-0.34-1-0.29-1.52c0.05-0.52,0.24-1.01,0.55-1.43c0.25-0.34,12.75-18.29,8.6-86.76c-3.62-59.65-12.47-73.39-12.56-73.52%20c-0.27-0.39-0.44-0.84-0.49-1.3c-0.05-0.47,0.02-0.95,0.2-1.38c0.18-0.43,0.46-0.82,0.83-1.11c0.36-0.3,0.8-0.5,1.26-0.58%20l455.12-81.9c0.37-0.07,0.75-0.07,1.12,0c0.37,0.07,0.72,0.22,1.03,0.43c0.31,0.21,0.58,0.48,0.78,0.8%20c0.21,0.31,0.35,0.66,0.41,1.03c0.07,0.38,0.06,0.75-0.02,1.12c-0.08,0.37-0.24,0.72-0.46,1.02c-0.22,0.31-0.5,0.57-0.82,0.76%20c-0.32,0.2-0.68,0.33-1.05,0.38l-451.4,81.29c3.04,7.27,9,26.77,11.68,72.69c4.35,71.72-9.18,89.82-9.77,90.54%20c-0.27,0.32-0.61,0.58-0.99,0.75C1008.74,1602.88,1008.32,1602.97,1007.9,1602.95z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1432.02,1360.75h-0.61c-0.73-0.16-1.36-0.6-1.76-1.23s-0.54-1.39-0.38-2.12l37.09-166.16%20c0.16-0.72,0.61-1.36,1.24-1.76s1.4-0.53,2.12-0.36c0.73,0.16,1.37,0.61,1.77,1.24s0.53,1.39,0.36,2.12l-37.08,166.14%20c-0.16,0.61-0.51,1.15-1.01,1.54C1433.26,1360.54,1432.65,1360.75,1432.02,1360.75z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1464.26,894.848l10.61,32.537L1370.5,1028.6l-42.69-73.586L1464.26,894.848z'/%3e%3cpath%20style='fill:%23FFFFFF;'%20d='M1327.81,955.013l-7.07-69.961l4.07-14.322l-28.62,7.791l-50.44,104.008L1327.81,955.013z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1370.5,1031.42h-0.38c-0.42-0.07-0.83-0.23-1.18-0.47c-0.36-0.24-0.65-0.56-0.87-0.93l-42.78-73.565%20c-0.21-0.344-0.33-0.726-0.37-1.123c-0.05-0.396-0.01-0.796,0.12-1.175c0.12-0.379,0.32-0.728,0.59-1.022%20c0.27-0.295,0.6-0.53,0.96-0.688l136.46-60.144c0.36-0.162,0.75-0.245,1.14-0.244c0.4,0,0.79,0.084,1.15,0.245%20c0.35,0.162,0.68,0.398,0.94,0.693c0.26,0.294,0.46,0.641,0.57,1.017l10.61,32.538c0.17,0.499,0.19,1.036,0.06,1.547%20s-0.4,0.974-0.78,1.335l-104.37,101.196C1371.87,1031.12,1371.2,1031.4,1370.5,1031.42z%20M1331.82,956.32l39.31,67.75l100.52-97.473%20l-9.01-27.899L1331.82,956.32z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1245.82,985.344c-0.47-0.001-0.94-0.123-1.36-0.355c-0.42-0.233-0.77-0.567-1.02-0.972%20c-0.25-0.406-0.4-0.869-0.42-1.345c-0.03-0.477,0.07-0.952,0.28-1.381l50.44-103.985c0.16-0.346,0.38-0.658,0.66-0.917%20c0.28-0.259,0.6-0.46,0.96-0.592l28.62-7.769c0.48-0.131,0.99-0.131,1.47-0.001c0.48,0.129,0.92,0.385,1.27,0.74%20c0.35,0.355,0.6,0.797,0.73,1.281c0.12,0.483,0.11,0.991-0.02,1.471l-3.92,13.803l7,69.398c0.07,0.634-0.08,1.272-0.42,1.809%20c-0.35,0.537-0.87,0.939-1.47,1.141l-82.05,27.516C1246.33,985.276,1246.08,985.329,1245.82,985.344z%20M1298.24,880.908%20l-46.97,96.825l73.59-24.769l-6.76-67.71c-0.08-0.348-0.08-0.71,0-1.058l2.71-9.525L1298.24,880.908z'/%3e%3cpath%20style='fill:%23313131;'%20d='M976.898,1205.36c-0.576,0-1.139-0.17-1.61-0.51c-0.472-0.33-0.83-0.79-1.025-1.34l-29.273-80.2%20c-0.256-0.7-0.224-1.48,0.091-2.16c0.314-0.68,0.885-1.2,1.587-1.46c0.702-0.25,1.477-0.22,2.154,0.09%20c0.678,0.32,1.203,0.89,1.46,1.59l29.273,80.23c0.157,0.43,0.208,0.88,0.149,1.33c-0.059,0.45-0.226,0.88-0.488,1.25%20c-0.261,0.37-0.609,0.67-1.013,0.88C977.799,1205.26,977.351,1205.37,976.898,1205.36z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1156.81,1411.87c-0.36,0.01-0.72-0.05-1.06-0.16c-0.69-0.27-1.25-0.8-1.56-1.48%20c-0.31-0.67-0.34-1.45-0.08-2.14l171-454.045c0.13-0.346,0.32-0.663,0.58-0.933c0.25-0.27,0.55-0.487,0.89-0.64%20c0.34-0.153,0.7-0.238,1.07-0.25c0.37-0.012,0.74,0.049,1.08,0.179c0.35,0.13,0.67,0.327,0.94,0.58%20c0.26,0.252,0.48,0.555,0.63,0.892c0.16,0.337,0.24,0.7,0.25,1.07c0.02,0.369-0.04,0.737-0.17,1.083l-170.93,454.014%20c-0.21,0.54-0.57,1-1.04,1.33C1157.94,1411.69,1157.38,1411.87,1156.81,1411.87z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1331.14,1015.11c-2.19,0-4.34-0.65-6.17-1.87c-1.82-1.22-3.24-2.95-4.08-4.98%20c-0.84-2.03-1.06-4.26-0.64-6.41c0.43-2.158,1.49-4.136,3.04-5.688c1.55-1.553,3.53-2.61,5.69-3.039%20c2.15-0.428,4.38-0.208,6.41,0.632c2.03,0.84,3.76,2.263,4.98,4.089c1.22,1.825,1.87,3.976,1.87,6.166c0,2.95-1.17,5.77-3.25,7.85%20C1336.91,1013.94,1334.09,1015.11,1331.14,1015.11z%20M1331.14,998.562c-1.08,0-2.14,0.322-3.04,0.924%20c-0.9,0.604-1.6,1.454-2.02,2.464c-0.41,1-0.52,2.1-0.3,3.16c0.21,1.06,0.73,2.04,1.5,2.8c0.77,0.77,1.75,1.28,2.81,1.49%20c1.06,0.21,2.16,0.1,3.16-0.32c1-0.42,1.85-1.12,2.45-2.02c0.6-0.91,0.92-1.97,0.91-3.05c0-1.45-0.58-2.83-1.61-3.85%20C1333.98,999.135,1332.59,998.562,1331.14,998.562z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1275.66,1161.21c-2.2,0-4.35-0.65-6.18-1.87c-1.83-1.21-3.25-2.95-4.1-4.98%20c-0.84-2.03-1.06-4.26-0.63-6.42c0.42-2.15,1.48-4.13,3.04-5.68c1.55-1.56,3.53-2.62,5.69-3.04c2.15-0.43,4.39-0.21,6.41,0.63%20c2.03,0.85,3.77,2.27,4.99,4.1c1.21,1.83,1.86,3.98,1.86,6.18c-0.01,2.93-1.18,5.75-3.25,7.82%20C1281.41,1160.03,1278.6,1161.2,1275.66,1161.21z%20M1275.66,1144.66c-1.08-0.01-2.14,0.31-3.05,0.91c-0.9,0.6-1.6,1.45-2.02,2.45%20c-0.42,1-0.53,2.1-0.32,3.16c0.21,1.06,0.72,2.04,1.49,2.81c0.76,0.77,1.74,1.29,2.8,1.5c1.06,0.22,2.16,0.11,3.16-0.31%20c1.01-0.41,1.86-1.11,2.46-2.01c0.61-0.9,0.93-1.96,0.93-3.04c0-1.45-0.58-2.84-1.6-3.86%20C1278.49,1145.24,1277.11,1144.66,1275.66,1144.66z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1220.11,1311.87c-2.2,0-4.35-0.64-6.18-1.86c-1.83-1.22-3.25-2.95-4.1-4.98%20c-0.84-2.03-1.06-4.27-0.63-6.42c0.42-2.16,1.48-4.14,3.04-5.69c1.55-1.55,3.53-2.61,5.69-3.04c2.15-0.43,4.39-0.21,6.41,0.64%20c2.03,0.84,3.77,2.27,4.99,4.1c1.21,1.82,1.86,3.97,1.86,6.17c-0.01,2.94-1.18,5.75-3.25,7.83%20C1225.86,1310.7,1223.04,1311.86,1220.11,1311.87z%20M1220.11,1295.32c-1.08,0-2.14,0.31-3.05,0.91c-0.9,0.6-1.61,1.45-2.02,2.45%20c-0.42,1-0.53,2.1-0.32,3.17c0.21,1.06,0.72,2.04,1.49,2.8c0.76,0.77,1.74,1.29,2.8,1.51c1.06,0.21,2.16,0.1,3.16-0.31%20c1.01-0.41,1.86-1.12,2.46-2.02c0.61-0.9,0.93-1.96,0.93-3.04c0-1.45-0.58-2.83-1.6-3.86%20C1222.94,1295.9,1221.56,1295.33,1220.11,1295.32z'/%3e%3cpath%20style='fill:%23313131;'%20d='M753.84,1108.49l2.567,12.14c0,0,108.399-10.58,168.182-56.95l-1.643-4.23%20C922.946,1059.45,866.562,1100.84,753.84,1108.49z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1093.74,1099.69l-121.549,265.34l21.369-13.71L1093.74,1099.69z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1466.7,1202.55l-35.06,157.06l-21.91,3.67L1466.7,1202.55z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1245.75,982.53l82.06-27.516l3.89,6.71L1245.75,982.53z'/%3e%3cpath%20style='fill:%23313131;'%20d='M1370.5,1028.6l-42.69-73.586l-9.05,3.04L1370.5,1028.6z'/%3e%3c/svg%3e\"","import React, { useState, useCallback, useEffect, useRef } from 'react';\nimport { Button } from '../Button/Button';\nimport { AlertDialog } from '../AlertDialog/AlertDialog';\nimport { Toast, toast } from '../Toast';\nimport { MasterCrudTable } from './MasterCrudTable';\nimport { MasterCrudForm } from './MasterCrudForm';\nimport { PlusIcon, PencilIcon, TrashIcon } from './icons';\nimport type { MasterCrudDetailConfig, MasterCrudAction } from './MasterCrud.types';\nimport type { ToastColor } from '../Toast/Toast.types';\n\n// ============================================\n// TIPOS INTERNOS\n// ============================================\n\ninterface MasterCrudDetailSectionProps<D = any> {\n  /** ID del registro maestro al que pertenecen estos detalles */\n  masterId: string | number;\n  /** Configuración completa del detalle */\n  config: MasterCrudDetailConfig<D>;\n  /** Función de traducción inyectada por el padre */\n  t: (key: string, defaultValue?: string) => string;\n  /** Idioma para formatos (ISO 639-1) */\n  locale?: string;\n  /**\n   * Si este componente se renderiza dentro de un modal padre.\n   * Afecta el z-index de los modales internos para evitar solapamiento.\n   * @default false\n   */\n  isInsideModal?: boolean;\n}\n\n// ============================================\n// COMPONENTE PRINCIPAL\n// ============================================\n\n/**\n * MasterCrudDetailSection — Sección embebida de registros de detalle.\n *\n * Se renderiza dentro del formulario del maestro (modo página o modal expandido)\n * y permite gestionar los registros hijos sin salir de la pantalla actual.\n *\n * Características:\n * - Carga y muestra los detalles del maestro activo\n * - Permite crear, editar y eliminar detalles desde modales internos\n * - Auto-inyecta el foreignKey al crear nuevos registros\n * - Completamente auto-contenido (no depende del estado del padre)\n *\n * @see MasterCrudDetailConfig para la configuración completa\n */\nexport const MasterCrudDetailSection = <D extends Record<string, any>>({\n  masterId,\n  config,\n  t,\n  locale = 'es',\n  isInsideModal = false,\n}: MasterCrudDetailSectionProps<D>) => {\n  const {\n    title,\n    entityName = '',\n    fields,\n    service,\n    foreignKey,\n    idField = 'id',\n    showCreateButton = true,\n    pageSize = 5,\n    emptyMessage,\n    allowEdit = true,\n    allowDelete = true,\n    permissions,\n    actions: customActions = [],\n    formWidth = '600px',\n    formColumns = 2,\n    createButtonText,\n    saveButtonText,\n    cancelButtonText,\n    onDetailCreateSuccess,\n    onDetailUpdateSuccess,\n    onDetailDeleteSuccess,\n  } = config;\n\n  const canCreate = permissions?.canCreate ?? showCreateButton;\n  const canUpdate = permissions?.canUpdate ?? allowEdit;\n  const canDelete  = permissions?.canDelete ?? allowDelete;\n\n  // ===== ESTADO =====\n  const [data, setData] = useState<D[]>([]);\n  const [total, setTotal] = useState(0);\n  const [loading, setLoading] = useState(false);\n  const [currentPage, setCurrentPage] = useState(1);\n\n  const [detailViewState, setDetailViewState] = useState<'LIST' | 'CREATE' | 'EDIT'>('LIST');\n  const [selectedDetail, setSelectedDetail] = useState<D | null>(null);\n  const [formLoading, setFormLoading] = useState(false);\n  const [deleteConfirm, setDeleteConfirm] = useState<{ show: boolean; record: D | null }>({\n    show: false,\n    record: null,\n  });\n  const [toastConfig, setToastConfig] = useState<{ show: boolean; message: string; color: ToastColor }>({\n    show: false,\n    message: '',\n    color: 'green',\n  });\n\n  const formRef = useRef<any>(null);\n\n  // ===== HELPERS =====\n  const showToast = useCallback((message: string, color: ToastColor = 'green') => {\n    setToastConfig({ show: true, message, color });\n    setTimeout(() => setToastConfig(prev => ({ ...prev, show: false })), 4000);\n  }, []);\n\n  // ===== CARGA DE DATOS =====\n  const loadData = useCallback(async () => {\n    setLoading(true);\n    try {\n      const response = await service.getAll({\n        page: currentPage,\n        limit: pageSize,\n        filters: { [foreignKey]: masterId },\n      });\n      setData(response.data);\n      setTotal(response.total);\n    } catch (err: any) {\n      const msg = err?.msgError || err?.detail || err?.message\n        || t('errorDataLoad', 'Error al cargar los registros');\n      showToast(msg, 'red');\n    } finally {\n      setLoading(false);\n    }\n  }, [masterId, currentPage, pageSize, foreignKey, service, showToast, t]);\n\n  useEffect(() => {\n    loadData();\n  }, [loadData]);\n\n  // ===== HANDLERS CRUD =====\n  const handleCreate = useCallback(() => {\n    setSelectedDetail(null);\n    setDetailViewState('CREATE');\n  }, []);\n\n  const handleEdit = useCallback((record: D) => {\n    setSelectedDetail(record);\n    setDetailViewState('EDIT');\n  }, []);\n\n  const handleCancel = useCallback(() => {\n    setDetailViewState('LIST');\n    setSelectedDetail(null);\n  }, []);\n\n  const handleSubmit = useCallback(async (formData: Partial<D>) => {\n    setFormLoading(true);\n    try {\n      if (detailViewState === 'CREATE') {\n        // Inyectar automáticamente el foreignKey con el ID del maestro\n        const dataWithFk = { ...formData, [foreignKey]: masterId } as Partial<D>;\n        const created = await service.create(dataWithFk);\n        onDetailCreateSuccess?.(created);\n        showToast(t('successCreate', 'Registro creado correctamente'), 'green');\n      } else if (detailViewState === 'EDIT' && selectedDetail) {\n        const recordId = (selectedDetail as any)[idField];\n        const updated = await service.update(recordId, formData);\n        onDetailUpdateSuccess?.(updated);\n        showToast(t('successUpdate', 'Registro actualizado correctamente'), 'green');\n      }\n      await loadData();\n      setDetailViewState('LIST');\n      setSelectedDetail(null);\n    } catch (err: any) {\n      const msg = err?.msgError || err?.detail || err?.message\n        || t('defaultError', 'Ha ocurrido un error inesperado');\n      showToast(msg, 'red');\n    } finally {\n      setFormLoading(false);\n    }\n  }, [\n    detailViewState, selectedDetail, idField, foreignKey, masterId,\n    service, loadData, showToast, t, onDetailCreateSuccess, onDetailUpdateSuccess,\n  ]);\n\n  const handleDeleteClick = useCallback((record: D) => {\n    setDeleteConfirm({ show: true, record });\n  }, []);\n\n  const handleDeleteConfirm = useCallback(async () => {\n    if (!deleteConfirm.record) return;\n    const recordId = (deleteConfirm.record as any)[idField];\n    try {\n      await service.delete(recordId);\n      onDetailDeleteSuccess?.(recordId);\n      showToast(t('successDelete', 'Registro eliminado correctamente'), 'green');\n      setDeleteConfirm({ show: false, record: null });\n      await loadData();\n    } catch (err: any) {\n      const msg = err?.msgError || err?.detail || err?.message\n        || t('defaultError', 'Ha ocurrido un error inesperado');\n      showToast(msg, 'red');\n    }\n  }, [deleteConfirm.record, idField, service, loadData, showToast, t, onDetailDeleteSuccess]);\n\n  // ===== ACCIONES DE LA TABLA =====\n  const actionsList: MasterCrudAction<D>[] = [\n    ...(canUpdate ? [{\n      id: 'edit',\n      name: t('edit', 'Editar'),\n      icon: <PencilIcon className=\"w-4 h-4\" />,\n      action: (r: D | D[]) => handleEdit(r as D),\n      order: 100,\n    }] : []),\n    ...(canDelete ? [{\n      id: 'delete',\n      name: t('delete', 'Eliminar'),\n      icon: <TrashIcon className=\"w-4 h-4\" />,\n      action: (r: D | D[]) => handleDeleteClick(r as D),\n      order: 200,\n    }] : []),\n    ...customActions,\n  ].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n  const totalPages = Math.ceil(total / pageSize);\n\n  // z-index de los modales internos: más alto cuando estamos dentro de un modal padre\n  const innerModalZ = isInsideModal ? 'z-[70]' : 'z-[60]';\n\n  // Título resuelto\n  const sectionTitle = title || t('details', 'Detalles');\n  const addLabel = createButtonText\n    || `${t('add', 'Agregar')}${entityName ? ` ${entityName}` : ''}`;\n\n  // ===== RENDER =====\n  return (\n    <>\n      {/* Toast de operaciones del detalle (posición distinta al toast del maestro) */}\n      {toastConfig.show && (() => {\n        const { message, color } = toastConfig;\n        const toastType = color === 'red' ? 'error' : color === 'green' ? 'success' : color === 'orange' ? 'warning' : 'info';\n\n        setTimeout(() => {\n          if (toastType === 'error') {\n            toast.error('Error', { description: message });\n          } else if (toastType === 'success') {\n            toast.success('Correcto', { description: message });\n          } else if (toastType === 'warning') {\n            toast.warning('Advertencia', { description: message });\n          } else {\n            toast('Información', { description: message });\n          }\n          setToastConfig(prev => ({ ...prev, show: false }));\n        }, 0);\n\n        return null;\n      })()\n      }\n\n      {/* ─── Sección de Detalle ──────────────────────────────────────────── */}\n      <div className=\"mt-6\">\n\n        {/* Separador visual con título flotante */}\n        <div className=\"relative flex items-center mb-5\">\n          <div className=\"flex-grow border-t border-border-primary dark:border-dark-border-primary\" />\n          <span className=\"mx-3 text-xs font-semibold uppercase tracking-widest text-content-secondary dark:text-content-secondary select-none\">\n            {sectionTitle}\n          </span>\n          <div className=\"flex-grow border-t border-border-primary dark:border-dark-border-primary\" />\n        </div>\n\n        {/* Header: título con badge de total + botón agregar */}\n        <div className=\"flex items-center justify-between mb-4\">\n          <div className=\"flex items-center gap-2\">\n            <h3 className=\"text-base font-semibold text-content-primary dark:text-dark-content-primary\">\n              {sectionTitle}\n            </h3>\n            {total > 0 && (\n              <span className={[\n                'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold',\n                'bg-primary-custom-50 text-primary-custom-600',\n                'dark:bg-dark-bg-inverse/20 dark:text-primary-custom-400',\n              ].join(' ')}>\n                {total}\n              </span>\n            )}\n          </div>\n\n          {canCreate && (\n            <Button\n              type=\"outline\"\n              size=\"sm\"\n              leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n              onClick={handleCreate}\n            >\n              {addLabel}\n            </Button>\n          )}\n        </div>\n\n        {/* Tabla de detalles */}\n        <div className=\"rounded-xl overflow-hidden border border-border-primary dark:border-dark-border-primary\">\n          <MasterCrudTable\n            fields={fields}\n            data={data}\n            loading={loading}\n            emptyMessage={emptyMessage || t('empty', 'No hay registros disponibles')}\n            showRowActions={canUpdate || canDelete || customActions.length > 0}\n            actions={actionsList}\n            pagination={totalPages > 1 ? {\n              currentPage,\n              totalPages,\n              onPageChange: setCurrentPage,\n              pageSize,\n              totalRecords: total,\n              previousLabel: t('previous', 'Anterior'),\n              nextLabel: t('next', 'Siguiente'),\n              perPageLabel: t('perPage', 'por pág.'),\n              recordsLabel: t('records', 'registros'),\n              goToPageLabel: t('goToPage', 'Pág.'),\n            } : undefined}\n            t={t}\n            locale={locale}\n          />\n        </div>\n      </div>\n\n      {/* ─── Modal de Crear / Editar Detalle ───────────────────────────────── */}\n      {(detailViewState === 'CREATE' || detailViewState === 'EDIT') && (\n        <div\n          className={`fixed inset-0 ${innerModalZ} flex items-center justify-center bg-black/50 p-4 animate-in fade-in duration-200`}\n          role=\"dialog\"\n          aria-modal=\"true\"\n        >\n          <div\n            className=\"w-full bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col overflow-hidden max-h-[90vh] animate-in zoom-in-95 duration-200\"\n            style={{ maxWidth: formWidth }}\n          >\n            <MasterCrudForm\n              ref={formRef}\n              fields={fields as any}\n              entityName={entityName}\n              initialData={selectedDetail || undefined}\n              isEditing={detailViewState === 'EDIT'}\n              loading={formLoading}\n              onSubmit={handleSubmit as any}\n              onCancel={handleCancel}\n              saveButtonText={saveButtonText || t('save', 'Guardar')}\n              cancelButtonText={cancelButtonText || t('cancel', 'Cancelar')}\n              columns={formColumns}\n              width=\"100%\"\n              idField={idField}\n              className=\"flex-1 min-h-0\"\n              t={t}\n            />\n          </div>\n        </div>\n      )}\n\n      {/* ─── Confirmación de Eliminación ───────────────────────────────────── */}\n      {deleteConfirm.show && (\n        <div className={`fixed inset-0 ${innerModalZ} flex items-center justify-center bg-black/50`}>\n          <AlertDialog\n            title={t('confirmDeleteTitle', '¿Estás seguro de eliminar este registro?')}\n            onCancel={() => setDeleteConfirm({ show: false, record: null })}\n            onConfirm={handleDeleteConfirm}\n            cancelText={t('cancelText', 'Cancelar')}\n            confirmText={t('confirmDeleteText', 'Eliminar')}\n          >\n            <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n              {t('confirmDeleteDesc', 'Esta acción no se puede deshacer.')}\n            </p>\n          </AlertDialog>\n        </div>\n      )}\n    </>\n  );\n};\n","/**\n * MasterPatternAdapter\n *\n * Implementa la interfaz CrudService<T> consumiendo los endpoints estándar\n * generados por la librería Siesa.MasterPattern (.NET).\n *\n * Endpoints asumidos:\n *   POST   /{resourcePath}/search  → SearchResponse (getAll)\n *   GET    /{resourcePath}/{id}    → T              (getById)\n *   POST   /{resourcePath}         → T              (create)\n *   PUT    /{resourcePath}/{id}    → T              (update)\n *   DELETE /{resourcePath}/{id}    → 204            (delete / deactivate)\n *\n * Normalización de claves:\n *   C# serializa en PascalCase (System.Text.Json) → convertimos a camelCase JS.\n *   Ej: \"ExchangeRate\" → \"exchangeRate\", \"ID\" → \"id\", \"UUID\" → \"uuid\".\n */\n\nimport type {\n  CrudService,\n  GetAllParams,\n  GetAllResponse,\n  MasterPatternConfig,\n  MasterCrudOperationType,\n  AdvancedFilter,\n  MasterCrudField,\n} from './MasterCrud.types';\n\n// ============================================================\n// Utilidades de normalización de claves\n// ============================================================\n\n/** PascalCase/ALL_CAPS → camelCase */\nconst toCamelCase = (key: string): string => {\n  if (!key) return key;\n  // Palabras completamente en mayúsculas (ID, UUID, CODE, etc.) → minúsculas\n  if (/^[A-Z0-9]+$/.test(key)) return key.toLowerCase();\n  // Primer carácter a minúscula\n  return key.charAt(0).toLowerCase() + key.slice(1);\n};\n\n/** camelCase → PascalCase (para enviar en SearchRequest) */\nconst toPascalCase = (key: string): string => {\n  if (!key) return key;\n  return key.charAt(0).toUpperCase() + key.slice(1);\n};\n\n/** Convierte todas las claves de un objeto plano a camelCase */\nconst normalizeResponseKeys = <T>(raw: Record<string, any>): T => {\n  const result: Record<string, any> = {};\n  for (const key of Object.keys(raw)) {\n    result[toCamelCase(key)] = raw[key];\n  }\n  return result as T;\n};\n\n// ============================================================\n// Error helper\n// ============================================================\n\nasync function throwIfNotOk(response: Response): Promise<never> {\n  let message = `HTTP ${response.status}`;\n  try {\n    const body = await response.json();\n    // Prioridad: message → detail (RFC 7807) → title → string literal\n    // `detail` contiene el mensaje legible (\"El código debe ser único\")\n    // `title` contiene el código técnico (\"validation.validation_failed\")\n    if (body?.message) message = body.message;\n    else if (body?.detail) message = body.detail;\n    else if (body?.title) message = body.title;\n    else if (typeof body === 'string') message = body;\n  } catch {\n    // ignore parse error\n  }\n  throw new Error(message);\n}\n\n// ============================================================\n// Conversión de filtros avanzados → JsonElement[][] (AND of OR groups)\n// ============================================================\n\n/**\n * Convierte la estructura de AdvancedFilter del frontend al formato\n * JsonElement[][] que espera SearchRequest.filters en el backend.\n *\n * Regla de conversión:\n *   - Un nodo hoja { field, operator, value } → elemento simple  { field, operator, value }\n *   - Grupos raíces con connector \"OR\" se agrupan en el mismo array interno\n *   - Grupos con connector \"AND\" generan un array separado (nueva dimensión)\n *\n * Formato resultante: [[filter1, filter2], [filter3]] donde el AND está entre\n * arrays y el OR está dentro del mismo array.\n */\nfunction convertAdvancedFilters(filters: AdvancedFilter[]): Record<string, any>[][] {\n  const andGroups: Record<string, any>[][] = [];\n\n  const toLeaf = (f: AdvancedFilter) => ({\n    field: toPascalCase(f.field as string),\n    operator: f.operator,\n    value: f.value,\n  });\n\n  for (const filter of filters) {\n    if (filter.isGroup && filter.children?.length) {\n      if (filter.connector === 'OR') {\n        // OR entre hijos → todos en el MISMO array interno (una sola dimensión).\n        const orLeaves = filter.children\n          .filter((c) => c.field && c.operator !== undefined)\n          .map(toLeaf);\n        if (orLeaves.length) andGroups.push(orLeaves);\n      } else {\n        // AND entre hijos → cada uno en su propio array (nueva dimensión).\n        const group = convertAdvancedFilters(filter.children);\n        andGroups.push(...group);\n      }\n    } else if (filter.field && filter.operator !== undefined) {\n      andGroups.push([toLeaf(filter)]);\n    }\n  }\n\n  return andGroups;\n}\n\n// ============================================================\n// Adaptador principal\n// ============================================================\n\nexport class MasterPatternCrudAdapter<T extends Record<string, any>>\n  implements CrudService<T>\n{\n  private readonly config: MasterPatternConfig;\n  private readonly fields: MasterCrudField<T>[];\n\n  constructor(config: MasterPatternConfig, fields: MasterCrudField<T>[] = []) {\n    this.config = config;\n    this.fields = fields;\n  }\n\n  // ----------------------------------------------------------\n  // URL helpers\n  // ----------------------------------------------------------\n\n  private getBaseUrl(): string {\n    const base = this.config.baseUrl.replace(/\\/$/, '');\n    const path = this.config.resourcePath.replace(/^\\//, '').replace(/\\/$/, '');\n    return `${base}/${path}`;\n  }\n\n  private getSearchUrl(): string {\n    return `${this.getBaseUrl()}/search`;\n  }\n\n  private getItemUrl(id: string | number): string {\n    return `${this.getBaseUrl()}/${id}`;\n  }\n\n  // ----------------------------------------------------------\n  // Header builder (incluye X-Company-ID cuando corresponde)\n  // ----------------------------------------------------------\n\n  private async buildHeaders(companyData?: any): Promise<Record<string, string>> {\n    const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\n    if (this.config.getHeaders) {\n      const custom = await this.config.getHeaders();\n      Object.assign(headers, custom);\n    }\n\n    // X-Company-ID: se omite si uuid es '000' (Global) o no está definido\n    const uuid = companyData?.uuid;\n    if (uuid && String(uuid) !== '000') {\n      headers['X-Company-ID'] = String(uuid);\n    }\n\n    return headers;\n  }\n\n  // ----------------------------------------------------------\n  // Campos a solicitar en SearchRequest.fields\n  // ----------------------------------------------------------\n\n  private getRequestFields(): string[] | undefined {\n    if (this.config.requestFields?.length) {\n      return this.config.requestFields;\n    }\n    // Auto-deriva desde la definición de campos del MasterCrud\n    const keys = this.fields\n      .map((f) => f.accessorKey as string)\n      .filter(Boolean)\n      .map(toPascalCase);\n    return keys.length ? keys : undefined;\n  }\n\n  // ----------------------------------------------------------\n  // SearchRequest builder\n  // ----------------------------------------------------------\n\n  private buildSearchBody(params: GetAllParams, companyData?: any): Record<string, any> {\n    if (this.config.mapSearchRequest) {\n      return this.config.mapSearchRequest(params, companyData);\n    }\n\n    const body: Record<string, any> = {\n      page: params.page,\n      pageSize: params.limit,\n    };\n\n    const fields = this.getRequestFields();\n    if (fields?.length) body.fields = fields;\n\n    if (params.search) {\n      body.search = params.search;\n      if (params.searchField) {\n        body.searchFields = [toPascalCase(params.searchField as string)];\n      }\n    }\n\n    if (params.sortBy) {\n      body.orderBy = {\n        field: toPascalCase(params.sortBy as string),\n        direction: params.sortDirection ?? 'asc',\n      };\n    }\n\n    const advancedFilters = params.filters?.advancedFilters;\n    if (Array.isArray(advancedFilters) && advancedFilters.length > 0) {\n      const converted = convertAdvancedFilters(advancedFilters);\n      if (converted.length > 0) body.filters = converted;\n    }\n\n    // Alcance de filas en modo sobrescritura multicompañía (aditivo). El backend\n    // Siesa.MasterPattern puede usarlo para acotar a habilitados en la compañía.\n    if (params.filters?.viewScope) {\n      body.viewScope = params.filters.viewScope;\n    }\n\n    return body;\n  }\n\n  // ----------------------------------------------------------\n  // CrudService implementation\n  // ----------------------------------------------------------\n\n  async getAll(params: GetAllParams, companyData?: any): Promise<GetAllResponse<T>> {\n    const headers = await this.buildHeaders(companyData);\n    const body = this.buildSearchBody(params, companyData);\n\n    const response = await fetch(this.getSearchUrl(), {\n      method: 'POST',\n      headers,\n      body: JSON.stringify(body),\n    });\n\n    if (!response.ok) await throwIfNotOk(response);\n\n    const json = await response.json();\n    // SearchResponse: { data: Dictionary<string, object?>[], page, pageSize }\n    const rawItems: Record<string, any>[] = json.data ?? json.Data ?? [];\n\n    // Normaliza claves PascalCase → camelCase\n    const normalizedData = rawItems.map((item) => normalizeResponseKeys<T>(item));\n\n    // Heurística hasMore: si llegaron pageSize registros, podrían haber más\n    const limit = params.limit;\n    const knownMin = (params.page - 1) * limit + normalizedData.length;\n    const mightHaveMore = normalizedData.length >= limit;\n    const total = mightHaveMore ? knownMin + 1 : knownMin;\n\n    return { data: normalizedData, total };\n  }\n\n  async getById(id: string | number, companyData?: any): Promise<T> {\n    const headers = await this.buildHeaders(companyData);\n    const response = await fetch(this.getItemUrl(id), { method: 'GET', headers });\n    if (!response.ok) await throwIfNotOk(response);\n    const raw: Record<string, any> = await response.json();\n    return normalizeResponseKeys<T>(raw);\n  }\n\n  async create(data: Partial<T>, companyData?: any): Promise<T> {\n    const headers = await this.buildHeaders(companyData);\n    const response = await fetch(this.getBaseUrl(), {\n      method: 'POST',\n      headers,\n      body: JSON.stringify(data),\n    });\n    if (!response.ok) await throwIfNotOk(response);\n    const raw: Record<string, any> = await response.json();\n    return normalizeResponseKeys<T>(raw);\n  }\n\n  async update(id: string | number, data: Partial<T>, companyData?: any): Promise<T> {\n    const headers = await this.buildHeaders(companyData);\n    const response = await fetch(this.getItemUrl(id), {\n      method: 'PUT',\n      headers,\n      body: JSON.stringify(data),\n    });\n    if (!response.ok) await throwIfNotOk(response);\n    const raw: Record<string, any> = await response.json();\n    return normalizeResponseKeys<T>(raw);\n  }\n\n  /**\n   * DELETE /{resourcePath}/{id}\n   *\n   * En modo MasterPattern el endpoint DELETE solo desactiva (soft-delete).\n   * La operación 'activate' no existe → se ignora silenciosamente.\n   * MasterCrud.tsx fuerza effectiveAllowStatusReversion=false para que el\n   * botón de activación nunca aparezca.\n   */\n  async delete(\n    id: string | number,\n    companyData?: any,\n    operation?: MasterCrudOperationType,\n  ): Promise<void> {\n    // 'activate' no tiene endpoint — no-op (el botón no debería aparecer en UI)\n    if (operation === 'activate') return;\n\n    const headers = await this.buildHeaders(companyData);\n    const response = await fetch(this.getItemUrl(id), {\n      method: 'DELETE',\n      headers,\n    });\n\n    // 204 No Content = éxito\n    if (response.status === 204 || response.ok) return;\n    await throwIfNotOk(response);\n  }\n}\n","import type { DynamicEntitiesFetcher } from '../../DynamicEntities/core/api/fetcher';\nimport { resolveFetcher } from '../../DynamicEntities/core/api/fetcher';\n\nexport interface BulkUpdatePayload {\n  recordIds: string[];\n  entityPatches: Array<{\n    entityCode: string;\n    fieldValues: Record<string, unknown>;\n  }>;\n}\n\nexport interface BulkProgressEvent {\n  processed: number;\n  total: number;\n  succeeded: number;\n  failed: number;\n  isComplete: boolean;\n  errors?: Array<{ recordId: string; reason: string }>;\n}\n\nexport class BulkDynamicEditService {\n  private baseUrl: string;\n  private http: DynamicEntitiesFetcher;\n\n  /**\n   * @param baseUrl Raíz de la API.\n   * @param fetcher Transporte del anfitrión (con `Authorization` y demás\n   * cabeceras). Ausente → `fetch` global, igual que antes.\n   */\n  constructor(baseUrl: string, fetcher?: DynamicEntitiesFetcher) {\n    this.baseUrl = baseUrl;\n    this.http = resolveFetcher(fetcher);\n  }\n\n  async bulkUpdate(\n    featureCode: string,\n    payload: BulkUpdatePayload,\n    onProgress: (event: BulkProgressEvent) => void,\n    signal?: AbortSignal\n  ): Promise<void> {\n    const url = `${this.baseUrl}/dynamic-entities/${featureCode}/bulk-update`;\n\n    const response = await this.http(url, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        'Accept': 'text/event-stream',\n      },\n      body: JSON.stringify(payload),\n      signal,\n    });\n\n    if (!response.ok) {\n      throw new Error(`Error al iniciar la operación: ${response.status} ${response.statusText}`);\n    }\n\n    const reader = response.body?.getReader();\n    if (!reader) throw new Error('No se pudo obtener el stream de respuesta');\n\n    const decoder = new TextDecoder();\n    let buffer = '';\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        buffer += decoder.decode(value, { stream: true });\n        const lines = buffer.split('\\n');\n        buffer = lines.pop() ?? '';\n\n        let eventType = '';\n        let dataLine = '';\n\n        for (const line of lines) {\n          if (line.startsWith('event:')) {\n            eventType = line.slice(6).trim();\n          } else if (line.startsWith('data:')) {\n            dataLine = line.slice(5).trim();\n          } else if (line === '' && dataLine) {\n            try {\n              const parsed: BulkProgressEvent = JSON.parse(dataLine);\n              onProgress(parsed);\n            } catch {\n              // linea SSE malformada, ignorar\n            }\n            eventType = '';\n            dataLine = '';\n          }\n        }\n\n        // Si llega data sin event separador (solo data:)\n        if (dataLine) {\n          try {\n            const parsed: BulkProgressEvent = JSON.parse(dataLine);\n            onProgress(parsed);\n          } catch {\n            // ignorar\n          }\n        }\n      }\n    } finally {\n      reader.releaseLock();\n    }\n  }\n}\n","import type { DynamicEntitiesFetcher } from '../DynamicEntities/core/api/fetcher';\n\nimport { useState, useCallback, useRef } from 'react';\nimport { BulkDynamicEditService } from './services/BulkDynamicEditService';\nimport type { BulkProgressEvent } from './services/BulkDynamicEditService';\nimport type { EditorPhase, BulkProgressState, BulkUpdateResult } from './MasterCrud.types';\n\nexport interface UseBulkDynamicEditOptions {\n  baseUrl: string;\n  /** Transporte del anfitrión; ausente → `fetch` global. */\n  fetcher?: DynamicEntitiesFetcher;\n  featureCode: string;\n  recordIds: string[];\n  onComplete?: (result: BulkUpdateResult) => void;\n}\n\nexport interface UseBulkDynamicEditReturn {\n  phase: EditorPhase;\n  progress: BulkProgressState;\n  result: BulkUpdateResult | null;\n  start: (payload: {\n    entityPatches: Array<{ entityCode: string; fieldValues: Record<string, unknown> }>;\n  }) => Promise<void>;\n  cancel: () => void;\n  reset: () => void;\n}\n\nconst initialProgress: BulkProgressState = {\n  processed: 0,\n  total: 0,\n  succeeded: 0,\n  failed: 0,\n  isComplete: false,\n};\n\nexport function useBulkDynamicEdit({\n  baseUrl,\n  fetcher,\n  featureCode,\n  recordIds,\n  onComplete,\n}: UseBulkDynamicEditOptions): UseBulkDynamicEditReturn {\n  const [phase, setPhase] = useState<EditorPhase>('editing');\n  const [progress, setProgress] = useState<BulkProgressState>(initialProgress);\n  const [result, setResult] = useState<BulkUpdateResult | null>(null);\n  const abortControllerRef = useRef<AbortController | null>(null);\n\n  const start = useCallback(\n    async (payload: {\n      entityPatches: Array<{ entityCode: string; fieldValues: Record<string, unknown> }>;\n    }) => {\n      abortControllerRef.current = new AbortController();\n      const service = new BulkDynamicEditService(baseUrl, fetcher);\n\n      setPhase('processing');\n      setProgress({ ...initialProgress, total: recordIds.length });\n      setResult(null);\n\n      try {\n        await service.bulkUpdate(\n          featureCode,\n          { recordIds, entityPatches: payload.entityPatches },\n          (event: BulkProgressEvent) => {\n            setProgress({\n              processed: event.processed,\n              total: event.total,\n              succeeded: event.succeeded,\n              failed: event.failed,\n              isComplete: event.isComplete,\n            });\n\n            if (event.isComplete) {\n              const finalResult: BulkUpdateResult = {\n                processed: event.processed,\n                total: event.total,\n                succeeded: event.succeeded,\n                failed: event.failed,\n                errors: event.errors ?? [],\n              };\n              setResult(finalResult);\n              setPhase('completed');\n              onComplete?.(finalResult);\n            }\n          },\n          abortControllerRef.current.signal\n        );\n      } catch (error: any) {\n        if (error?.name === 'AbortError') {\n          // Cancelación silenciosa\n          setPhase('editing');\n          setProgress(initialProgress);\n          return;\n        }\n        throw error;\n      }\n    },\n    [baseUrl, fetcher, featureCode, recordIds, onComplete]\n  );\n\n  const cancel = useCallback(() => {\n    abortControllerRef.current?.abort();\n    abortControllerRef.current = null;\n    setPhase('editing');\n    setProgress(initialProgress);\n  }, []);\n\n  const reset = useCallback(() => {\n    abortControllerRef.current?.abort();\n    abortControllerRef.current = null;\n    setPhase('editing');\n    setProgress(initialProgress);\n    setResult(null);\n  }, []);\n\n  return { phase, progress, result, start, cancel, reset };\n}\n","import React, { useState, useEffect, useCallback, useMemo } from 'react';\nimport { FeatureService } from '../DynamicEntities/admin/services/FeatureService';\nimport { DynamicFieldRenderer } from '../DynamicEntities/ui/DynamicFieldRenderer';\nimport { DynamicEntitiesApi } from '../DynamicEntities/core/api/DynamicEntitiesApi';\nimport { useOptionalDynamicEntitiesContext } from '../DynamicEntities/core/DynamicEntitiesProvider';\nimport { useBulkDynamicEdit } from './useBulkDynamicEdit';\nimport type { BulkUpdateResult, EditorPhase } from './MasterCrud.types';\nimport type { Feature, FeatureEntity } from '../DynamicEntities/admin/services/FeatureService';\nimport type { DynamicField } from '../DynamicEntities/core/types/DynamicField.types';\nimport type { GenericList } from '../DynamicEntities/core/types/DynamicEntity.types';\n\ninterface EntityWithFields {\n  featureEntity: FeatureEntity;\n  fields: DynamicField[];\n  lists: GenericList[];\n}\n\ninterface MasterCrudBulkDynamicEditorProps {\n  featureCode: string;\n  recordIds: string[];\n  onClose: () => void;\n  onComplete: (result: BulkUpdateResult) => void;\n  /**\n   * Función de traducción inyectada por el padre (MasterCrud). Si no se provee,\n   * se usan los textos por defecto en español.\n   */\n  t?: (key: string, defaultValue?: string) => string;\n}\n\nexport const MasterCrudBulkDynamicEditor: React.FC<MasterCrudBulkDynamicEditorProps> = ({\n  featureCode,\n  recordIds,\n  onClose,\n  onComplete,\n  t = (_key: string, defaultValue?: string) => defaultValue ?? _key,\n}) => {\n  const ctx = useOptionalDynamicEntitiesContext();\n  const baseUrl = ctx?.baseUrl ?? '';\n  const fetcher = ctx?.fetcher;\n\n  const [loadingFeature, setLoadingFeature] = useState(true);\n  const [loadError, setLoadError] = useState<string | null>(null);\n  const [entitiesWithFields, setEntitiesWithFields] = useState<EntityWithFields[]>([]);\n\n  // fieldValues: { entityCode -> { fieldCode -> value } }\n  const [fieldValues, setFieldValues] = useState<Record<string, Record<string, unknown>>>({});\n\n  const [modalPhase, setModalPhase] = useState<EditorPhase>('loading');\n\n  const [typedConfirmationValue, setTypedConfirmationValue] = useState('');\n  const [isTypedConfirmModalOpen, setIsTypedConfirmModalOpen] = useState(false);\n  const expectedConfirmationKeyword = useMemo(() => `update-bulk-${featureCode}`, [featureCode]);\n  const isTypedConfirmationValid = typedConfirmationValue === expectedConfirmationKeyword;\n\n  const handleBulkComplete = useCallback(\n    (result: BulkUpdateResult) => {\n      onComplete(result);\n    },\n    [onComplete]\n  );\n\n  const { phase, progress, result, start, cancel } = useBulkDynamicEdit({\n    baseUrl,\n    fetcher,\n    featureCode,\n    recordIds,\n    onComplete: handleBulkComplete,\n  });\n\n  // Sync useBulkDynamicEdit phase into local modalPhase (except loading)\n  useEffect(() => {\n    if (modalPhase !== 'loading' && modalPhase !== 'confirming') {\n      setModalPhase(phase);\n    }\n  }, [phase]);\n\n  // Load feature + entity definitions\n  useEffect(() => {\n    if (!baseUrl) return;\n\n    const load = async () => {\n      setLoadingFeature(true);\n      setLoadError(null);\n      try {\n        const featureService = new FeatureService(baseUrl, fetcher);\n        const feature: Feature = await featureService.getByPath(featureCode);\n\n        if (!feature.featureEntities?.length) {\n          setEntitiesWithFields([]);\n          setModalPhase('editing');\n          return;\n        }\n\n        // Load definition for each entity (to get fields + lists)\n        const entities: EntityWithFields[] = [];\n        for (const fe of feature.featureEntities) {\n          if (!fe.dynamicEntity) continue;\n          // Filter: exclude inactive\n          if (fe.dynamicEntity.isDisabled) continue;\n\n          try {\n            const def = await DynamicEntitiesApi.getDefinition(baseUrl, featureCode, fe.dynamicEntity.code, fetcher);\n            entities.push({\n              featureEntity: fe,\n              fields: def.fields.filter(f => f.visible),\n              lists: def.lists,\n            });\n          } catch {\n            // skip entities that fail to load\n          }\n        }\n\n        setEntitiesWithFields(entities);\n        setModalPhase('editing');\n      } catch (err: any) {\n        setLoadError(err?.message ?? t('bulkLoadError', 'Error al cargar las entidades dinámicas'));\n        setModalPhase('loading');\n      } finally {\n        setLoadingFeature(false);\n      }\n    };\n\n    load();\n  }, [baseUrl, fetcher, featureCode]);\n\n  const handleFieldChange = useCallback(\n    (entityCode: string, fieldCode: string, value: unknown) => {\n      setFieldValues(prev => ({\n        ...prev,\n        [entityCode]: {\n          ...(prev[entityCode] ?? {}),\n          [fieldCode]: value,\n        },\n      }));\n    },\n    []\n  );\n\n  const buildPatches = useCallback(() => {\n    return Object.entries(fieldValues)\n      .map(([entityCode, fv]) => {\n        const defined = Object.fromEntries(\n          Object.entries(fv).filter(([, v]) => v !== undefined)\n        );\n        return { entityCode, fieldValues: defined };\n      })\n      .filter(patch => Object.keys(patch.fieldValues).length > 0);\n  }, [fieldValues]);\n\n  const countFilledFields = useCallback(() => {\n    let count = 0;\n    for (const fv of Object.values(fieldValues)) {\n      for (const v of Object.values(fv)) {\n        if (v !== undefined && v !== '') count++;\n      }\n    }\n    return count;\n  }, [fieldValues]);\n\n  const handlePreview = useCallback(() => {\n    if (countFilledFields() === 0) return;\n    setModalPhase('confirming');\n  }, [countFilledFields]);\n\n  const handleConfirm = useCallback(async () => {\n    const patches = buildPatches();\n    setModalPhase('processing');\n    await start({ entityPatches: patches });\n  }, [buildPatches, start]);\n\n  const handleBackToEdit = useCallback(() => {\n    setModalPhase('editing');\n    setTypedConfirmationValue('');\n    setIsTypedConfirmModalOpen(false);\n  }, []);\n\n  const handleOpenTypedConfirm = useCallback(() => {\n    setTypedConfirmationValue('');\n    setIsTypedConfirmModalOpen(true);\n  }, []);\n\n  const handleCancelTypedConfirm = useCallback(() => {\n    setIsTypedConfirmModalOpen(false);\n    setTypedConfirmationValue('');\n  }, []);\n\n  const handleConfirmTypedConfirm = useCallback(async () => {\n    if (!isTypedConfirmationValid) return;\n    setIsTypedConfirmModalOpen(false);\n    await handleConfirm();\n  }, [isTypedConfirmationValid, handleConfirm]);\n\n  const handleCancel = useCallback(() => {\n    cancel();\n    onClose();\n  }, [cancel, onClose]);\n\n  const exportErrors = useCallback(() => {\n    if (!result?.errors?.length) return;\n    const lines = [`${t('recordIdCsv', 'ID del Registro')},${t('reasonCsv', 'Motivo')}`, ...result.errors.map(e => `${e.recordId},\"${e.reason.replace(/\"/g, '\"\"')}\"`).join('\\n')];\n    const csv = lines.join('\\n');\n    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });\n    const url = URL.createObjectURL(blob);\n    const a = document.createElement('a');\n    a.href = url;\n    a.download = `errores_edicion_masiva_${new Date().toISOString().slice(0, 10)}.csv`;\n    document.body.appendChild(a);\n    a.click();\n    document.body.removeChild(a);\n    URL.revokeObjectURL(url);\n  }, [result]);\n\n  const progressPercent =\n    progress.total > 0 ? Math.round((progress.processed / progress.total) * 100) : 0;\n\n  return (\n    <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4\">\n      <div className=\"w-full max-w-2xl bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col max-h-[90vh] overflow-hidden\">\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0\">\n          <h2 className=\"text-lg font-semibold text-gray-900 dark:text-gray-100\">\n            {t('bulkEditTitle', 'Editar campos dinámicos')}\n          </h2>\n          {modalPhase !== 'processing' && (\n            <button\n              type=\"button\"\n              onClick={handleCancel}\n              className=\"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors\"\n              aria-label={t('close', 'Cerrar')}\n            >\n              <svg className=\"w-5 h-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n                <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" />\n              </svg>\n            </button>\n          )}\n        </div>\n\n        {/* Body */}\n        <div className=\"flex-1 overflow-y-auto p-6\">\n\n          {/* FASE: loading */}\n          {modalPhase === 'loading' && (\n            <div className=\"flex flex-col items-center justify-center py-16 gap-4\">\n              {loadingFeature && (\n                <>\n                  <div className=\"w-8 h-8 border-4 border-primary-600 border-t-transparent rounded-full animate-spin\" />\n                  <p className=\"text-sm text-gray-500 dark:text-gray-400\">{t('bulkLoadingFields', 'Cargando campos dinámicos...')}</p>\n                </>\n              )}\n              {loadError && (\n                <div className=\"text-sm text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 text-center\">\n                  {loadError}\n                </div>\n              )}\n            </div>\n          )}\n\n          {/* FASE: editing */}\n          {modalPhase === 'editing' && (\n            <div className=\"space-y-6\">\n              <p className=\"text-sm text-gray-500 dark:text-gray-400\">\n                {t('bulkEditingIntroPrefix', 'Se aplicarán cambios a')} <strong>{recordIds.length}</strong>{' '}\n                {t('bulkEditingIntroSuffix', 'registros seleccionados. Llena solo los campos que deseas modificar; los campos vacíos no se alterarán.')}\n              </p>\n\n              {entitiesWithFields.length === 0 && (\n                <div className=\"text-sm text-gray-400 italic text-center py-8\">\n                  {t('bulkNoDynamicEntities', 'No hay entidades dinámicas configuradas para este módulo.')}\n                </div>\n              )}\n\n              {entitiesWithFields.map(({ featureEntity, fields, lists }) => {\n                const entity = featureEntity.dynamicEntity!;\n                const isReadonlyOrDisabled = entity.isReadonly || entity.isDisabled;\n\n                return (\n                  <div key={entity.code} className=\"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden\">\n                    <div className=\"bg-gray-50 dark:bg-gray-800 px-4 py-3 border-b border-gray-200 dark:border-gray-700\">\n                      <h3 className=\"text-sm font-semibold text-gray-700 dark:text-gray-300\">\n                        {entity.description || entity.code}\n                      </h3>\n                      {entity.multiRecord && (\n                        <p className=\"text-xs text-amber-600 dark:text-amber-400 mt-0.5\">\n                          {t('bulkMultiRecordNote', 'Solo se actualizará la fila principal de cada registro')}\n                        </p>\n                      )}\n                      {isReadonlyOrDisabled && (\n                        <p className=\"text-xs text-gray-400 dark:text-gray-500 mt-0.5\">\n                          {t('bulkReadonlyEntity', 'Esta entidad es de solo lectura')}\n                        </p>\n                      )}\n                    </div>\n                    <div className=\"p-4 grid grid-cols-1 sm:grid-cols-2 gap-x-4\">\n                      {fields.map(field => {\n                        const entityCode = entity.code;\n                        const value = fieldValues[entityCode]?.[field.code];\n                        const listOptions = field.genericListId\n                          ? (lists.find(l => l.id === field.genericListId)?.items ?? []).map(i => ({\n                            label: i.label || i.value,\n                            value: i.value,\n                          }))\n                          : [];\n\n                        return (\n                          <DynamicFieldRenderer\n                            key={field.code}\n                            field={{\n                              ...field,\n                              disabled: isReadonlyOrDisabled || field.disabled || field.readonly,\n                            }}\n                            value={value}\n                            onChange={v => handleFieldChange(entityCode, field.code, v)}\n                            options={listOptions}\n                          />\n                        );\n                      })}\n                    </div>\n                  </div>\n                );\n              })}\n            </div>\n          )}\n\n          {/* FASE: confirming */}\n          {modalPhase === 'confirming' && (\n            <div className=\"space-y-4\">\n              <div className=\"bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4\">\n                <p className=\"text-sm font-medium text-amber-800 dark:text-amber-200\">\n                  {t('bulkChangesSummary', 'Resumen de cambios')}\n                </p>\n                <p className=\"text-sm text-amber-700 dark:text-amber-300 mt-1\">\n                  {t('bulkWillApply', 'Se aplicarán')}{' '}\n                  <strong>{countFilledFields()} {t('bulkFieldsLabel', 'campo(s)')}</strong> {t('bulkToLabel', 'a')}{' '}\n                  <strong>{recordIds.length} {t('bulkRecordsLabel', 'registro(s)')}</strong>.\n                </p>\n              </div>\n\n              <div className=\"space-y-3\">\n                {buildPatches().map(patch => (\n                  <div key={patch.entityCode} className=\"border border-gray-200 dark:border-gray-700 rounded-lg p-3\">\n                    <p className=\"text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2\">\n                      {entitiesWithFields.find(e => e.featureEntity.dynamicEntity?.code === patch.entityCode)?.featureEntity.dynamicEntity?.description || patch.entityCode}\n                    </p>\n                    <ul className=\"space-y-1\">\n                      {Object.entries(patch.fieldValues).map(([fCode, fVal]) => {\n                        const entityDef = entitiesWithFields.find(e => e.featureEntity.dynamicEntity?.code === patch.entityCode);\n                        const fieldDef = entityDef?.fields.find(f => f.code === fCode);\n                        const label = fieldDef?.labels['es'] || fCode;\n                        return (\n                          <li key={fCode} className=\"text-sm text-gray-700 dark:text-gray-300 flex gap-2\">\n                            <span className=\"font-medium\">{label}:</span>\n                            <span className=\"text-gray-500 dark:text-gray-400 truncate\">\n                              {fVal === null ? `(${t('emptyValue', 'vacío')})` : String(fVal)}\n                            </span>\n                          </li>\n                        );\n                      })}\n                    </ul>\n                  </div>\n                ))}\n              </div>\n\n            </div>\n          )}\n\n          {/* FASE: processing */}\n          {modalPhase === 'processing' && (\n            <div className=\"flex flex-col items-center justify-center py-8 gap-6\">\n              <div className=\"w-full\">\n                <div className=\"flex justify-between text-sm text-gray-600 dark:text-gray-400 mb-2\">\n                  <span>{t('bulkProcessing', 'Procesando registros...')}</span>\n                  <span>{progress.processed} / {progress.total}</span>\n                </div>\n                <div className=\"w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3 overflow-hidden\">\n                  <div\n                    className=\"bg-primary-600 h-3 rounded-full transition-all duration-300\"\n                    style={{ width: `${progressPercent}%` }}\n                  />\n                </div>\n                <div className=\"flex justify-between text-xs text-gray-500 dark:text-gray-400 mt-1\">\n                  <span className=\"text-green-600 dark:text-green-400\">{progress.succeeded} {t('bulkSucceededLabel', 'exitosos')}</span>\n                  {progress.failed > 0 && (\n                    <span className=\"text-red-600 dark:text-red-400\">{progress.failed} {t('bulkFailedLabel', 'fallidos')}</span>\n                  )}\n                </div>\n              </div>\n            </div>\n          )}\n\n          {/* FASE: completed */}\n          {modalPhase === 'completed' && result && (\n            <div className=\"space-y-4\">\n              <div className={`rounded-lg p-4 border ${result.failed === 0\n                ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'\n                : 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800'\n                }`}>\n                <p className=\"text-sm font-semibold text-gray-800 dark:text-gray-200 mb-1\">\n                  {t('bulkOperationCompleted', 'Operación completada')}\n                </p>\n                <div className=\"flex gap-6 text-sm\">\n                  <span className=\"text-green-700 dark:text-green-300 font-medium\">\n                    {result.succeeded} {t('bulkSucceededLabel', 'exitosos')}\n                  </span>\n                  {result.failed > 0 && (\n                    <span className=\"text-red-700 dark:text-red-300 font-medium\">\n                      {result.failed} {t('bulkFailedLabel', 'fallidos')}\n                    </span>\n                  )}\n                  <span className=\"text-gray-500 dark:text-gray-400\">\n                    {t('bulkOfLabel', 'de')} {result.total} {t('bulkRecordsPlural', 'registros')}\n                  </span>\n                </div>\n              </div>\n\n              {result.errors && result.errors.length > 0 && (\n                <div className=\"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden\">\n                  <div className=\"bg-gray-50 dark:bg-gray-800 px-4 py-2 border-b border-gray-200 dark:border-gray-700\">\n                    <p className=\"text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider\">\n                      {t('bulkRecordsWithError', 'Registros con error')}\n                    </p>\n                  </div>\n                  <div className=\"max-h-40 overflow-y-auto divide-y divide-gray-100 dark:divide-gray-800\">\n                    {result.errors.map(err => (\n                      <div key={err.recordId} className=\"px-4 py-2 text-sm\">\n                        <span className=\"font-mono text-xs text-gray-500 dark:text-gray-400 mr-2\">{err.recordId}</span>\n                        <span className=\"text-red-600 dark:text-red-400\">{err.reason}</span>\n                      </div>\n                    ))}\n                  </div>\n                </div>\n              )}\n            </div>\n          )}\n\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex-shrink-0\">\n\n          {modalPhase === 'editing' && (\n            <>\n              <button\n                type=\"button\"\n                onClick={handleCancel}\n                className=\"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors\"\n              >\n                {t('cancel', 'Cancelar')}\n              </button>\n              <button\n                type=\"button\"\n                onClick={handlePreview}\n                disabled={countFilledFields() === 0}\n                className=\"px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors\"\n              >\n                {t('bulkPreview', 'Previsualizar')}\n              </button>\n            </>\n          )}\n\n          {modalPhase === 'confirming' && (\n            <>\n              <button\n                type=\"button\"\n                onClick={handleBackToEdit}\n                className=\"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors\"\n              >\n                {t('back', 'Volver')}\n              </button>\n              <button\n                type=\"button\"\n                onClick={handleOpenTypedConfirm}\n                className=\"px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors\"\n              >\n                {t('bulkApplyTo', 'Aplicar a')} {recordIds.length} {t('bulkRecordsPlural', 'registros')}\n              </button>\n            </>\n          )}\n\n          {modalPhase === 'processing' && (\n            <button\n              type=\"button\"\n              onClick={cancel}\n              className=\"px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition-colors\"\n            >\n              {t('bulkCancelOperation', 'Cancelar operación')}\n            </button>\n          )}\n\n          {modalPhase === 'completed' && (\n            <>\n              {result && result.errors && result.errors.length > 0 && (\n                <button\n                  type=\"button\"\n                  onClick={exportErrors}\n                  className=\"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors\"\n                >\n                  {t('bulkExportErrorsCsv', 'Exportar errores CSV')}\n                </button>\n              )}\n              <button\n                type=\"button\"\n                onClick={onClose}\n                className=\"px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors\"\n              >\n                {t('close', 'Cerrar')}\n              </button>\n            </>\n          )}\n\n        </div>\n      </div>\n\n      {/* Modal de confirmación tipeada (overlay encima del editor) */}\n      {isTypedConfirmModalOpen && (\n        <div className=\"fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4\">\n          <div className=\"w-full max-w-md bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col overflow-hidden\">\n            <div className=\"px-6 py-4 border-b border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20\">\n              <h3 className=\"text-base font-semibold text-red-800 dark:text-red-200\">\n                {t('bulkConfirmTitle', 'Confirmar modificación masiva')}\n              </h3>\n            </div>\n            <div className=\"px-6 py-5 space-y-3\">\n              <p className=\"text-sm text-gray-700 dark:text-gray-300\">\n                {t('bulkConfirmLine1Prefix', 'Vas a modificar')} <strong>{recordIds.length}</strong>{' '}\n                {t('bulkConfirmLine1Suffix', 'registro(s). Esta acción no se puede deshacer.')}\n              </p>\n              <p className=\"text-sm text-gray-700 dark:text-gray-300\">\n                {t('bulkConfirmTypePrompt', 'Para confirmar, escribe')}{' '}\n                <code className=\"font-mono text-xs bg-red-100 dark:bg-red-900/40 text-red-800 dark:text-red-200 px-1.5 py-0.5 rounded select-all\">\n                  {expectedConfirmationKeyword}\n                </code>\n              </p>\n              <input\n                type=\"text\"\n                value={typedConfirmationValue}\n                onChange={e => setTypedConfirmationValue(e.target.value)}\n                autoComplete=\"off\"\n                autoFocus\n                spellCheck={false}\n                aria-label={t('bulkConfirmAriaLabel', 'Confirmación de modificación masiva')}\n                className=\"w-full px-3 py-2 text-sm font-mono bg-white dark:bg-dark-bg-primary border border-red-300 dark:border-red-700 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500 text-gray-900 dark:text-gray-100\"\n              />\n            </div>\n            <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700\">\n              <button\n                type=\"button\"\n                onClick={handleCancelTypedConfirm}\n                className=\"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors\"\n              >\n                {t('cancel', 'Cancelar')}\n              </button>\n              <button\n                type=\"button\"\n                onClick={handleConfirmTypedConfirm}\n                disabled={!isTypedConfirmationValid}\n                className=\"px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors\"\n              >\n                {t('confirmText', 'Confirmar')}\n              </button>\n            </div>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n};\n","import { useCallback, useMemo } from 'react';\nimport { useTranslation } from '../LanguageManagement/hooks/useTranslation';\n\ninterface UseMasterCrudTranslationProps {\n  locale?: string;\n  uiPrefix?: string;\n  fieldsPrefix?: string;\n  externalTranslations?: Record<string, string>;\n  internalTranslations: Record<string, any>;\n  tProp?: (key: string, defaultValue?: string) => string;\n}\n\n/**\n * Hook interno para gestionar la traducción en MasterCrud con retrocompatibilidad y agnosticismo.\n * \n * Prioridad de resolución:\n * 1. tProp (Función inyectada por el usuario - Agnosticismo Total)\n * 2. externalTranslations (Mapeo estático por props)\n * 3. Sistema global del proyecto (LanguageManagement / Contexto)\n * 4. Diccionario interno estático (Fallback de seguridad)\n */\nexport const useMasterCrudTranslation = ({\n  locale = 'es',\n  uiPrefix = 'mastercrud',\n  fieldsPrefix,\n  externalTranslations,\n  internalTranslations,\n  tProp,\n}: UseMasterCrudTranslationProps) => {\n  let globalI18n: any = null;\n  try {\n    // Intentar usar el sistema del proyecto si no se provee una función externa\n    if (!tProp) {\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      globalI18n = useTranslation();\n    }\n  } catch (e) {\n    globalI18n = null;\n  }\n\n  const { t: globalT, isReady } = globalI18n || {};\n  const activeT = tProp || globalT;\n\n  const t = useCallback((key: string, defaultValue?: string): string => {\n    // 1. Prioridad: Función inyectada o Global\n    if (activeT && (tProp || isReady)) {\n      // Intentar resolver con prefijo de UI\n      const uiKey = `${uiPrefix}.${key}`;\n      const translated = activeT(uiKey, '__NOT_FOUND__');\n      \n      if (translated !== '__NOT_FOUND__' && translated !== uiKey) {\n        return translated;\n      }\n\n      // Si no se encontró y es una llave de campo, intentar con prefijo de campos\n      if (fieldsPrefix) {\n        const fieldKey = `${fieldsPrefix}.${key}`;\n        const fieldTranslated = activeT(fieldKey, '__NOT_FOUND__');\n        if (fieldTranslated !== '__NOT_FOUND__' && fieldTranslated !== fieldKey) {\n          return fieldTranslated;\n        }\n      }\n    }\n\n    // 2. Prioridad: Diccionario estático externo\n    if (externalTranslations && externalTranslations[key]) {\n      return externalTranslations[key];\n    }\n\n    // 3. Prioridad: Diccionario interno estático\n    const internalSet = internalTranslations[locale] || internalTranslations.es;\n    if (internalSet && internalSet[key]) {\n      return internalSet[key];\n    }\n\n    // 4. Fallback final\n    return defaultValue || key;\n  }, [activeT, tProp, isReady, uiPrefix, fieldsPrefix, externalTranslations, internalTranslations, locale]);\n\n  return { t, isReady: isReady ?? true };\n};\n","import React, { useState, useCallback, useEffect, useRef } from 'react';\nimport { Switch } from '../Switch/Switch';\nimport { Button } from '../Button/Button';\nimport { AlertDialog } from '../AlertDialog/AlertDialog';\nimport { MasterCrudTable } from './MasterCrudTable';\nimport { MasterCrudForm } from './MasterCrudForm';\nimport { MasterCrudToolbar } from './MasterCrudToolbar';\nimport { MasterCRUDCard } from './MasterCRUDCard';\nimport { MasterCrudAdvancedSearch } from './MasterCrudAdvancedSearch';\nimport { CompanySelector } from './CompanySelector';\nimport { LinkModal } from './LinkModal';\nimport { MatchModal } from '../MatchModal';\nimport { Toast } from '../Toast';\nimport { Badge } from '../Badge/Badge';\nimport { Info } from '../Info/Info';\nimport { Dropdown } from '../Dropdown/Dropdown';\nimport noDataImage from '../../assets/nodata.svg';\nimport type { ToastColor } from '../Toast/Toast.types';\nimport type {\n  MasterCrudProps,\n  ViewState,\n  GetAllParams,\n  ToolbarViewType,\n  MasterCrudAction,\n  AdvancedFilter,\n  MasterCrudCompany,\n  MatchResult,\n  MasterCrudField,\n  MasterCrudOperationType,\n  BulkUpdateResult,\n  FileManagerConfig,\n  CrudService,\n  MasterCrudDetailConfig,\n} from './MasterCrud.types';\nimport { MasterCrudDetailSection } from './MasterCrudDetailSection';\nimport { MasterPatternCrudAdapter } from './MasterPatternAdapter';\nimport type { GalleryResource } from '../FileUploaderGallery/FileUploaderGallery.types';\nimport { MasterCrudBulkDynamicEditor } from './MasterCrudBulkDynamicEditor';\nimport { PlusIcon, CloseIcon as XMarkIcon, PencilIcon, TrashIcon, BackIcon, Bars3Icon, ChevronDownIcon, GlobeAltIcon, LinkIcon, MinusCircleIcon, CheckCircleIcon, ClockIcon, EllipsisVerticalIcon, NoSymbolIcon } from './icons';\nimport { AuditHistoryPanel } from '../../audit/components/AuditHistoryPanel';\n\nimport { useMasterCrudTranslation } from './useMasterCrudTranslation';\n\n// ===== TRADUCCIONES INTERNAS (FALLBACK) =====\nconst internalTranslations: Record<string, any> = {\n  es: {\n    save: 'Guardar',\n    cancel: 'Cancelar',\n    create: 'Crear',\n    edit: 'Editar',\n    delete: 'Eliminar',\n    activate: 'Activar',\n    deactivate: 'Desactivar',\n    search: 'Buscar',\n    searchBy: 'Buscar por',\n    filterBy: 'Filtrar por',\n    sortBy: 'Ordenar por',\n    all: 'Todos',\n    noSort: 'Sin orden',\n    empty: 'No hay registros disponibles',\n    confirmDeleteTitle: '¿Estás seguro de eliminar este registro?',\n    confirmDeleteDesc: 'Esta acción no se puede deshacer.',\n    confirmDeleteText: 'Eliminar',\n    confirmText: 'Confirmar',\n    cancelText: 'Cancelar',\n    errorTitle: 'Error',\n    incompleteTitle: 'Información incompleta',\n    incompleteMessage: 'Para guardar, completa los siguientes campos obligatorios',\n    successTitle: 'Éxito',\n    defaultError: 'Ha ocurrido un error inesperado',\n    noPermission: 'No tienes permiso de lectura para ver estos registros',\n    loading: 'Cargando...',\n    preview: 'Vista Previa',\n    advancedSearch: 'Búsqueda Avanzada',\n    globalValues: 'Valores Globales',\n    useGlobalData: 'Usar datos globales',\n    linkCompanies: 'Habilitar compañías',\n    createNew: 'Crear nuevo registro',\n    revertToGlobal: 'Restaurar a valores globales',\n    showGlobalValues: 'Mostrar valores globales',\n    confirmGlobalResetTitle: '¿Restaurar campos?',\n    confirmGlobalResetDesc: 'Se perderán los cambios locales y se usarán los valores maestros.',\n    confirmCreateTitle: '¿Crear nuevo registro?',\n    confirmCreateDesc: 'Se perderán los cambios no guardados.',\n    isRequired: 'es requerido',\n    back: 'Volver',\n    saving: 'Guardando...',\n    successCreate: 'Registro creado correctamente',\n    successUpdate: 'Registro actualizado correctamente',\n    successDelete: 'Registro eliminado correctamente',\n    successDeactivate: 'Registro desactivado correctamente',\n    successActivate: 'Registro activado correctamente',\n    successUnlink: 'Registro deshabilitado correctamente',\n    successLink: 'Registro habilitado correctamente',\n    successRevert: 'Campos restaurados a valores globales',\n    confirmDeactivateTitle: '¿Estás seguro de desactivar este registro?',\n    confirmDeactivateDesc: 'El registro dejará de estar disponible.',\n    confirmDeactivateCompanyDesc: 'El registro dejará de estar disponible en esta compañía.',\n    confirmUnlinkTitle: '¿Estás seguro de deshabilitar este registro?',\n    confirmUnlinkDesc: 'El registro ya no estará habilitado en esta sucursal.',\n    confirmActivateTitle: '¿Estás seguro de activar este registro?',\n    confirmActivateDesc: 'El registro volverá a estar disponible.',\n    confirmActivateCompanyDesc: 'El registro volverá a estar disponible en esta compañía.',\n    confirmLinkTitle: '¿Estás seguro de habilitar este registro?',\n    confirmLinkDesc: 'El registro quedará habilitado en esta sucursal.',\n    errorDetailLoad: 'Error al cargar el detalle del registro',\n    errorDataLoad: 'Error al cargar los datos del registro',\n    errorRecordNotFound: 'No se encontró el registro seleccionado',\n    errorLinkDynamic: 'Error al habilitar dinámicamente',\n    successLinkDynamic: 'Registro habilitado y cargado',\n    previous: 'Anterior',\n    next: 'Siguiente',\n    perPage: 'por página',\n    records: 'registros',\n    goToPage: 'Página',\n    // Alineación con el prototipo (listado + detalle)\n    moreOptions: 'Más opciones',\n    moreActions: 'Más acciones',\n    auditChanges: 'Auditoría de Cambios',\n    export: 'Exportar',\n    displayMode: 'Modo de visualización',\n    listView: 'Listado',\n    cardView: 'Tarjetas',\n    recordsToShow: 'Registros a mostrar',\n    viewAll: 'Ver todos los registros',\n    viewCompany: 'Ver registros de la compañía seleccionada',\n    viewCompanyOnly: 'Ver solo registros de la compañía seleccionada',\n    // Modal de habilitación por compañía (LinkModal)\n    searchCompanyPlaceholder: 'Buscar compañía…',\n    noCompaniesFound: 'No se encontraron compañías',\n    // Conector lógico de búsqueda avanzada\n    joinConditionsWith: 'Unir condiciones con',\n    connectorAnd: 'Y',\n    connectorOr: 'O',\n    connectorAndHint: 'Se deben cumplir todas las condiciones',\n    connectorOrHint: 'Basta con que se cumpla una condición',\n    // Editor de edición masiva de campos dinámicos (MasterCrudBulkDynamicEditor)\n    close: 'Cerrar',\n    bulkEditTitle: 'Editar campos dinámicos',\n    bulkLoadingFields: 'Cargando campos dinámicos...',\n    bulkLoadError: 'Error al cargar las entidades dinámicas',\n    bulkEditingIntroPrefix: 'Se aplicarán cambios a',\n    bulkEditingIntroSuffix: 'registros seleccionados. Llena solo los campos que deseas modificar; los campos vacíos no se alterarán.',\n    bulkNoDynamicEntities: 'No hay entidades dinámicas configuradas para este módulo.',\n    bulkMultiRecordNote: 'Solo se actualizará la fila principal de cada registro',\n    bulkReadonlyEntity: 'Esta entidad es de solo lectura',\n    bulkChangesSummary: 'Resumen de cambios',\n    bulkWillApply: 'Se aplicarán',\n    bulkFieldsLabel: 'campo(s)',\n    bulkToLabel: 'a',\n    bulkRecordsLabel: 'registro(s)',\n    bulkProcessing: 'Procesando registros...',\n    bulkSucceededLabel: 'exitosos',\n    bulkFailedLabel: 'fallidos',\n    bulkOperationCompleted: 'Operación completada',\n    bulkOfLabel: 'de',\n    bulkRecordsPlural: 'registros',\n    bulkRecordsWithError: 'Registros con error',\n    recordIdCsv: 'ID del Registro',\n    reasonCsv: 'Motivo',\n    bulkPreview: 'Previsualizar',\n    bulkApplyTo: 'Aplicar a',\n    bulkCancelOperation: 'Cancelar operación',\n    bulkExportErrorsCsv: 'Exportar errores CSV',\n    bulkConfirmTitle: 'Confirmar modificación masiva',\n    bulkConfirmLine1Prefix: 'Vas a modificar',\n    bulkConfirmLine1Suffix: 'registro(s). Esta acción no se puede deshacer.',\n    bulkConfirmTypePrompt: 'Para confirmar, escribe',\n    bulkConfirmAriaLabel: 'Confirmación de modificación masiva',\n    showAdvancedSearch: 'Mostrar búsqueda avanzada',\n    hideAdvancedSearch: 'Ocultar búsqueda avanzada',\n    filter: 'Filtrar',\n    hideFilter: 'Ocultar filtro',\n    editing: 'Edición',\n    creating: 'Creación',\n    companyStatus: 'Habilitación en la compañía seleccionada',\n    enabledInCompany: 'Habilitado en la compañía seleccionada',\n    notEnabledInCompany: 'No habilitado en la compañía seleccionada',\n    enabled: 'Habilitado',\n    notEnabled: 'No habilitado',\n    masterRecord: 'Registro maestro',\n    unsavedTitle: 'Tienes cambios sin guardar',\n    unsavedDesc: 'Si sales ahora perderás los siguientes cambios. ¿Deseas guardarlos antes de volver al listado?',\n    modifiedFields: 'Campos modificados',\n    emptyValue: 'vacío',\n    keepEditing: 'Seguir editando',\n    discardExit: 'Descartar y salir',\n    saveExit: 'Guardar y salir',\n  },\n  en: {\n    save: 'Save',\n    cancel: 'Cancel',\n    cancelText: 'Cancel',\n    confirmText: 'Confirm',\n    create: 'Create',\n    edit: 'Edit',\n    delete: 'Delete',\n    activate: 'Activate',\n    deactivate: 'Deactivate',\n    search: 'Search',\n    searchBy: 'Search by',\n    filterBy: 'Filter by',\n    sortBy: 'Sort by',\n    all: 'All',\n    noSort: 'No sort',\n    empty: 'No records available',\n    confirmDeleteTitle: 'Are you sure you want to delete this record?',\n    confirmDeleteDesc: 'This action cannot be undone.',\n    confirmDeleteText: 'Delete',\n    confirmDeactivateTitle: 'Are you sure you want to deactivate this record?',\n    confirmDeactivateDesc: 'The record will no longer be available.',\n    confirmActivateTitle: 'Are you sure you want to activate this record?',\n    confirmActivateDesc: 'The record will be available again.',\n    confirmDeactivateCompanyDesc: 'The record will no longer be available in this company.',\n    confirmActivateCompanyDesc: 'The record will be available again in this company.',\n    errorTitle: 'Error',\n    incompleteTitle: 'Incomplete information',\n    incompleteMessage: 'To save, complete the following required fields',\n    successTitle: 'Success',\n    defaultError: 'An unexpected error occurred',\n    noPermission: 'You do not have read permission to view these records',\n    loading: 'Loading...',\n    preview: 'Preview',\n    advancedSearch: 'Advanced Search',\n    globalValues: 'Global Values',\n    useGlobalData: 'Use global data',\n    linkCompanies: 'Enable companies',\n    createNew: 'Create new record',\n    revertToGlobal: 'Restore to global values',\n    showGlobalValues: 'Show global values',\n    confirmGlobalResetTitle: 'Restore fields?',\n    confirmGlobalResetDesc: 'Local changes will be lost and master values will be used.',\n    confirmCreateTitle: 'Create new record?',\n    confirmCreateDesc: 'Unsaved changes will be lost.',\n    isRequired: 'is required',\n    back: 'Back',\n    saving: 'Saving...',\n    successCreate: 'Record created successfully',\n    successUpdate: 'Record updated successfully',\n    successDelete: 'Record deleted successfully',\n    successDeactivate: 'Record deactivated successfully',\n    successActivate: 'Record activated successfully',\n    successRevert: 'Fields restored to master values',\n    errorDetailLoad: 'Error loading record details',\n    errorDataLoad: 'Error loading record data',\n    errorRecordNotFound: 'Selected record not found',\n    errorLinkDynamic: 'Error enabling dynamically',\n    successLinkDynamic: 'Record enabled and loaded',\n    previous: 'Previous',\n    next: 'Next',\n    perPage: 'per page',\n    records: 'records',\n    goToPage: 'Page',\n    moreOptions: 'More options',\n    moreActions: 'More actions',\n    auditChanges: 'Change audit',\n    export: 'Export',\n    displayMode: 'Display mode',\n    listView: 'List',\n    cardView: 'Cards',\n    recordsToShow: 'Records to show',\n    viewAll: 'View all records',\n    viewCompany: 'View records for the selected company',\n    viewCompanyOnly: 'Show only records for the selected company',\n    // Company enablement modal (LinkModal)\n    searchCompanyPlaceholder: 'Search company…',\n    noCompaniesFound: 'No companies found',\n    // Advanced search logical connector\n    joinConditionsWith: 'Join conditions with',\n    connectorAnd: 'AND',\n    connectorOr: 'OR',\n    connectorAndHint: 'All conditions must be met',\n    connectorOrHint: 'At least one condition must be met',\n    // Bulk dynamic fields editor (MasterCrudBulkDynamicEditor)\n    close: 'Close',\n    bulkEditTitle: 'Edit dynamic fields',\n    bulkLoadingFields: 'Loading dynamic fields...',\n    bulkLoadError: 'Error loading dynamic entities',\n    bulkEditingIntroPrefix: 'Changes will be applied to',\n    bulkEditingIntroSuffix: 'selected records. Fill in only the fields you want to modify; empty fields will not be changed.',\n    bulkNoDynamicEntities: 'There are no dynamic entities configured for this module.',\n    bulkMultiRecordNote: 'Only the main row of each record will be updated',\n    bulkReadonlyEntity: 'This entity is read-only',\n    bulkChangesSummary: 'Summary of changes',\n    bulkWillApply: 'Will apply',\n    bulkFieldsLabel: 'field(s)',\n    bulkToLabel: 'to',\n    bulkRecordsLabel: 'record(s)',\n    bulkProcessing: 'Processing records...',\n    bulkSucceededLabel: 'successful',\n    bulkFailedLabel: 'failed',\n    bulkOperationCompleted: 'Operation completed',\n    bulkOfLabel: 'of',\n    bulkRecordsPlural: 'records',\n    bulkRecordsWithError: 'Records with errors',\n    recordIdCsv: 'Record ID',\n    reasonCsv: 'Reason',\n    bulkPreview: 'Preview',\n    bulkApplyTo: 'Apply to',\n    bulkCancelOperation: 'Cancel operation',\n    bulkExportErrorsCsv: 'Export errors CSV',\n    bulkConfirmTitle: 'Confirm bulk modification',\n    bulkConfirmLine1Prefix: 'You are about to modify',\n    bulkConfirmLine1Suffix: 'record(s). This action cannot be undone.',\n    bulkConfirmTypePrompt: 'To confirm, type',\n    bulkConfirmAriaLabel: 'Bulk modification confirmation',\n    showAdvancedSearch: 'Show advanced search',\n    hideAdvancedSearch: 'Hide advanced search',\n    filter: 'Filter',\n    hideFilter: 'Hide filter',\n    editing: 'Editing',\n    creating: 'Creating',\n    companyStatus: 'Enablement in the selected company',\n    enabledInCompany: 'Enabled in the selected company',\n    notEnabledInCompany: 'Not enabled in the selected company',\n    enabled: 'Enabled',\n    notEnabled: 'Not enabled',\n    masterRecord: 'Master record',\n    unsavedTitle: 'You have unsaved changes',\n    unsavedDesc: 'If you leave now you will lose the following changes. Do you want to save them before returning to the list?',\n    modifiedFields: 'Modified fields',\n    emptyValue: 'empty',\n    keepEditing: 'Keep editing',\n    discardExit: 'Discard and exit',\n    saveExit: 'Save and exit',\n  }\n};\n\n/**\n * MasterCrud - Componente genérico para gestión de entidades (CRUD)\n */\nexport const MasterCrud = <T extends Record<string, any>>({\n  title,\n  entityName,\n  fields,\n  service: serviceProp,\n  masterPattern,\n  idField = 'id',\n  pageSize = 10,\n  showCreateButton = true,\n  showSearch = true,\n  showRowActions = true,\n  allowDelete = true,\n  softDelete = true,\n  onCreateSuccess,\n  onUpdateSuccess,\n  onDeleteSuccess,\n  onError,\n  createButtonText,\n  saveButtonText,\n  cancelButtonText,\n  emptyMessage,\n  className = '',\n  id,\n  renderToolbar,\n  rowActions,\n  formWidth = '600px',\n  formColumns = 2,\n  showViewToggle = true,\n  showAdvancedSearch = true,\n  showExport = false,\n  onExport,\n  onBack,\n  formTabs,\n  showValidationErrorDialog = true,\n  columnFilterableFields,\n  defaultViewScope = 'all',\n  filterableFields,\n  useToolbar = true,\n  onViewChange,\n  enableGridInfiniteScroll = true,\n  onBeforeCreate,\n  onBeforeUpdate,\n  onBeforeDelete,\n  locale = 'es',\n  uiPrefix = 'mastercrud',\n  fieldsPrefix,\n  externalTranslations,\n  t: tProp,\n  permissions,\n  internalErrorHandling = true,\n  actions = [],\n  globalActions = [],\n  batchActions: batchActionsProp = [],\n  emptyStateConfig,\n  renderCardContent,\n  renderForm,\n  showDefaultEditAction = true,\n  maximizeEditModal = false,\n  maximizeCustomModal = true,\n  fetchDetailOnEdit = true,\n  navigationType: navigationTypeProp,\n  enableMultiSelect = false,\n  showAdvancedSearchConnectors = false,\n  maxAdvancedFilters = 4,\n  initialFiltersVisible = true,\n  headerBadges,\n  renderHeaderExtra,\n  activeByCompany = false,\n  companyRequired = false,\n  companies = [],\n  onCompanyChange,\n  onConfirmLinking,\n  isCompanyLinked,\n  showGlobalValues: showGlobalValuesProp,\n  onSearchMatches,\n  dynamicFeatureCode,\n  hideDynamicTabs = false,\n  allowStatusReversion = true,\n  statusField = 'isActive',\n  deactivateTooltip,\n  activateTooltip,\n  onBulkUpdateComplete,\n  auditHistory,\n  featCodeFileManager,\n  fileManagerConfig,\n  fileAcceptedExtensions,\n  fileMaxSizeMB,\n  fileTotalMaxSizeMB,\n  fileMultiple,\n  detailConfig,\n}: MasterCrudProps<T>) => {\n  // ===== MOTOR DE TRADUCCIÓN =====\n  const { t } = useMasterCrudTranslation({\n    locale,\n    uiPrefix,\n    fieldsPrefix,\n    externalTranslations,\n    internalTranslations,\n    tProp: tProp,\n  });\n\n  // ===== RESOLUCIÓN DE SERVICIO (service | masterPattern) =====\n  // Usamos las propiedades primitivas de masterPattern como deps (no el objeto completo)\n  // para que un masterPattern inline no cause una nueva instancia del adapter en cada render.\n  // getHeaders y mapSearchRequest deben ser referencias estables (definidas fuera del JSX).\n  const _resolvedService = React.useMemo((): CrudService<T> => {\n    if (serviceProp) return serviceProp;\n    if (masterPattern) return new MasterPatternCrudAdapter<T>(masterPattern, fields);\n    throw new Error('[MasterCrud] Debes proporcionar \"service\" o \"masterPattern\".');\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [serviceProp, masterPattern?.baseUrl, masterPattern?.resourcePath, masterPattern?.masterType, masterPattern?.getHeaders, masterPattern?.mapSearchRequest]);\n  // Sombrea la prop para que todo el código existente del componente funcione sin cambios\n  const service = _resolvedService;\n\n  // Dev warning: ambas props definidas (service tiene precedencia; masterPattern será ignorado)\n  if (process.env.NODE_ENV !== 'production' && serviceProp && masterPattern) {\n    console.warn('[MasterCrud] Se definieron \"service\" y \"masterPattern\" simultáneamente. \"service\" tiene precedencia y \"masterPattern\" será ignorado.');\n  }\n\n  // ===== CALLBACKS ESTABILIZADOS (Definidos pronto para evitar TDZ) =====\n  const getErrorMessage = useCallback((error: unknown): string => {\n    // Formato: string directo\n    if (typeof error === 'string' && error) return error;\n\n    if (typeof error === 'object' && error !== null) {\n      const errObj = error as any;\n\n      // PRIORIDAD 1 — Campos de alta prioridad directamente en el error.\n      // Se comprueban ANTES de `message` para no capturar el texto genérico de Axios\n      // (\"Request failed with status code 4xx\") cuando el servidor ya envió un mensaje específico.\n      //   - msgError  → formato interno Siesa\n      //   - detail    → RFC 7807 Problem Details (APIs .NET, Python, etc.)\n      if (errObj.msgError) return String(errObj.msgError);\n      if (errObj.detail) return String(errObj.detail);\n\n      // PRIORIDAD 2 — Cuerpo del servidor en response.data (error envuelto por Axios/Fetch).\n      // Cubre el caso en que el servicio NO re-lanza response.data sino el AxiosError completo.\n      const responseData = errObj.response?.data;\n      if (responseData && typeof responseData === 'object') {\n        const fromData = responseData.msgError || responseData.detail || responseData.message || responseData.title;\n        if (fromData) return String(fromData);\n      }\n      if (typeof responseData === 'string' && responseData) return responseData;\n\n      // PRIORIDAD 3 — message estándar de JS Error.\n      // También está presente en AxiosError, pero como mensaje genérico (\"Request failed...\"),\n      // por eso se evalúa solo después de verificar response.data.\n      if (errObj.message) return String(errObj.message);\n\n      // PRIORIDAD 4 — title como último recurso descriptivo (RFC 7807)\n      if (errObj.title) return String(errObj.title);\n    }\n\n    return t('defaultError');\n  }, [t]);\n\n  // ===== REFS PARA ESTABILIZAR CALLBACKS (Evitar bucles infinitos en loadData) =====\n  const serviceRef = useRef(service);\n  const getErrorMessageRef = useRef(getErrorMessage);\n\n  useEffect(() => { serviceRef.current = service; }, [service]);\n  useEffect(() => { getErrorMessageRef.current = getErrorMessage; }, [getErrorMessage]);\n  const canRead = permissions?.canRead ?? true;\n  const canCreate = permissions?.canCreate ?? showCreateButton;\n  const canUpdate = permissions?.canUpdate ?? showRowActions;\n  const canDelete = permissions?.canDelete ?? allowDelete;\n  const canChangeStatus = permissions?.canChangeStatus ?? true;\n  const canOverrideMultiCompany = permissions?.canOverrideMultiCompany ?? true;\n  const canBulkUpdate = permissions?.canBulkUpdate ?? false;\n\n  // En modo MasterPattern, DELETE no soporta reactivación → forzar false\n  const effectiveAllowStatusReversion = masterPattern ? false : allowStatusReversion;\n\n  // ===== RESOLUCIÓN DINÁMICA DE TÍTULOS =====\n  const finalTitle = t('title', title);\n  const finalEntityName = t('entityName', entityName);\n\n  // ===== CONFIGURACIÓN DE NAVEGACIÓN =====\n  // Por defecto la navegación al detalle es 'page' (del listado a la página de edición),\n  // no modal ni sidebar. El consumidor puede sobrescribirlo con la prop navigationType.\n  const navigationType = navigationTypeProp ?? 'page';\n\n  // ===== LÓGICA DE COMPAÑÍAS AUTOMÁTICAS =====\n  const globalCompany = React.useMemo(() => ({ uuid: '000', code: '000', name: 'Global' }), []);\n\n  const allCompanies = React.useMemo(() => {\n    if (!activeByCompany) return [];\n    if (companyRequired) return [...companies];\n    return [globalCompany, ...companies];\n  }, [activeByCompany, companyRequired, companies, globalCompany]);\n\n  // ===== ESTADOS =====\n  const [viewState, setViewState] = useState<ViewState>('LIST');\n  const [selectedRecord, setSelectedRecord] = useState<T | null>(null);\n  const [globalRecordId, setGlobalRecordId] = useState<string | number | null>(null);\n  const [selectedCompany, setSelectedCompany] = useState<MasterCrudCompany | undefined>(() => {\n    if (!activeByCompany) return undefined;\n\n    // 1. Si hay una compañía seleccionada por defecto, usarla\n    const defaultCompany = companies.find(c => c.isSelectedByDefault);\n    if (defaultCompany) return defaultCompany;\n\n    // 2. Si companyRequired es true y hay compañías, seleccionar la primera\n    if (companyRequired && companies.length > 0) return companies[0];\n\n    // 3. Fallback: Global (solo si no es obligatoria una compañía específica)\n    return companyRequired ? undefined : allCompanies[0];\n  });\n  const [toastConfig, setToastConfig] = useState<{ show: boolean; message: string; color: ToastColor; }>({ show: false, message: '', color: 'zinc', });\n  const showToast = useCallback((message: string, color: ToastColor = 'zinc') => { setToastConfig({ show: true, message, color }); setTimeout(() => { setToastConfig((prev) => ({ ...prev, show: false })); }, 5000); }, []);\n  const hideToast = useCallback(() => { setToastConfig((prev) => ({ ...prev, show: false })); }, []);\n\n  const [linkConfirmState, setLinkConfirmState] = useState<{ show: boolean; company: MasterCrudCompany | null }>({ show: false, company: null });\n\n  const [selectedRecords, setSelectedRecords] = useState<T[]>([]);\n  const selectedIds = React.useMemo(() => selectedRecords.map(r => (r as any)[idField]), [selectedRecords, idField]);\n\n  const [isAdvancedSearchActive, setIsAdvancedSearchActive] = useState(false);\n  const [advancedFilters, setAdvancedFilters] = useState<AdvancedFilter[]>([]);\n\n  const [data, setData] = useState<T[]>([]);\n  const [total, setTotal] = useState(0);\n  const [loading, setLoading] = useState(false);\n  const [formLoading, setFormLoading] = useState(false);\n  const [hasMore, setHasMore] = useState(true);\n\n  const [searchTerm, setSearchTerm] = useState('');\n  const [searchField, setSearchField] = useState<string>('all');\n  const searchFieldRef = useRef<string>('all');\n  const [currentPage, setCurrentPage] = useState(1);\n  const [internalPageSize, setInternalPageSize] = useState(pageSize);\n  const [sortColumn, setSortColumn] = useState<string | undefined>();\n  const [sortDirection, setSortDirection] = useState<'asc' | 'desc' | null>(null);\n  const [viewType, setViewType] = useState<ToolbarViewType>('list');\n  // Filtros por columna (server-side, viajan por el canal advancedFilters — retrocompatible).\n  const [columnFilters, setColumnFilters] = useState<Record<string, { value: string; operator: 'contains' | 'equals' }>>({});\n  // Alcance de filas en modo sobrescritura multicompañía (Global + compañía).\n  const [viewScope, setViewScope] = useState<'all' | 'company'>(defaultViewScope);\n  // Modal de cambios sin guardar (dirty state) al Volver (S2.8).\n  const [dirtyModal, setDirtyModal] = useState<{ show: boolean; changes: { label: string; from: any; to: any }[] }>({ show: false, changes: [] });\n  // Menú \"Más acciones\" del detalle (desplegable a la izquierda, como el listado).\n  const [detailActionsOpen, setDetailActionsOpen] = useState(false);\n  const detailActionsRef = useRef<HTMLDivElement>(null);\n  useEffect(() => {\n    if (!detailActionsOpen) return;\n    const onDocClick = (e: MouseEvent) => { if (detailActionsRef.current && !detailActionsRef.current.contains(e.target as Node)) setDetailActionsOpen(false); };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setDetailActionsOpen(false); };\n    document.addEventListener('mousedown', onDocClick);\n    document.addEventListener('keydown', onKey);\n    return () => { document.removeEventListener('mousedown', onDocClick); document.removeEventListener('keydown', onKey); };\n  }, [detailActionsOpen]);\n\n  const [customModalState, setCustomModalState] = useState<{ show: boolean; content: React.ReactNode | null; title: string; }>({ show: false, content: null, title: '', });\n  const [linkModalState, setLinkModalState] = useState<{ show: boolean; record: T | null; variant: 'success' | 'manual' }>({ show: false, record: null, variant: 'manual' });\n  const [showGlobalResetConfirm, setShowGlobalResetConfirm] = useState(false);\n  const [showCreateConfirm, setShowCreateConfirm] = useState(false);\n  const [showGlobalValues, setShowGlobalValues] = useState(showGlobalValuesProp ?? false);\n  const [matchModalState, setMatchModalState] = useState<{ show: boolean; matches: MatchResult[]; fieldName: string }>({ show: false, matches: [], fieldName: '' });\n  const [previewModalState, setPreviewModalState] = useState<{ show: boolean; record: T | null; loading: boolean }>({ show: false, record: null, loading: false });\n  const [auditModalState, setAuditModalState] = useState<{ show: boolean; record: T | null }>({ show: false, record: null });\n  const [showBulkDynamicEditor, setShowBulkDynamicEditor] = useState(false);\n  const formRef = useRef<any>(null);\n\n  // ===== ESTADO DE GESTIÓN DE ARCHIVOS (modo automático via service) =====\n  const [fileResources, setFileResources] = useState<GalleryResource[]>([]);\n  const [fileResourcesLoading, setFileResourcesLoading] = useState(false);\n\n  // ===== EFECTO DE AUTO-SELECCIÓN DE COMPAÑÍA (Carga asíncrona) =====\n  useEffect(() => {\n    if (activeByCompany && companies.length > 0 && !selectedCompany) {\n      // 1. Prioridad: Compañía marcada como default\n      const defaultCompany = companies.find(c => c.isSelectedByDefault);\n      if (defaultCompany) {\n        setSelectedCompany(defaultCompany);\n        return;\n      }\n\n      // 2. Prioridad: Si es requerida, forzar la primera disponible\n      if (companyRequired) {\n        setSelectedCompany(companies[0]);\n        return;\n      }\n\n      // 3. Fallback: Global (si no es requerida una específica)\n      if (!companyRequired) {\n        setSelectedCompany(allCompanies[0]);\n      }\n    }\n  }, [activeByCompany, companyRequired, companies, selectedCompany, allCompanies]);\n\n  // ===== CARGA AUTOMÁTICA DE ARCHIVOS AL SELECCIONAR REGISTRO =====\n  useEffect(() => {\n    if (!featCodeFileManager || !service.getFiles) return;\n    const recordId = selectedRecord ? (selectedRecord as any)[idField] : null;\n    if (!recordId) { setFileResources([]); return; }\n\n    setFileResourcesLoading(true);\n    service.getFiles(recordId, selectedCompany)\n      .then(files => setFileResources(files))\n      .catch(() => setFileResources([]))\n      .finally(() => setFileResourcesLoading(false));\n  }, [selectedRecord, idField, featCodeFileManager, selectedCompany]);\n\n  // ===== HELPERS BÁSICOS =====\n  const getCompanyPrimaryData = useCallback(() => selectedCompany, [selectedCompany]);\n\n  // ===== LÓGICA DE VINCULACIÓN AUTOMÁTICA (Retrocompatible) =====\n  const checkLinkStatus = useCallback((recordId: string | number, companyUuid: string | number): boolean => {\n    // 1. Si es la compañía seleccionada actualmente en el toolbar, se considera vinculada (contexto activo)\n    if (selectedCompany && String(selectedCompany.uuid) === String(companyUuid)) {\n      return true;\n    }\n\n    // 2. Prioridad: Callback explícito del usuario\n    if (isCompanyLinked) {\n      return isCompanyLinked(recordId, companyUuid);\n    }\n\n    // 3. Fallback: Buscar en el registro seleccionado (Modo Edición/Detalle)\n    const currentRecordId = selectedRecord ? (selectedRecord as any)[idField] : null;\n    if (selectedRecord && String(currentRecordId) === String(recordId)) {\n      const linked = (selectedRecord as any)._linkedCompanies;\n      if (Array.isArray(linked)) {\n        return linked.some(uuid => String(uuid) === String(companyUuid));\n      }\n    }\n\n    // 3. Fallback: Buscar en el listado general (Modo Tabla/Grid)\n    const recordInList = data.find(r => String((r as any)[idField]) === String(recordId));\n    if (recordInList) {\n      const linked = (recordInList as any)._linkedCompanies;\n      if (Array.isArray(linked)) {\n        return linked.some(uuid => String(uuid) === String(companyUuid));\n      }\n    }\n\n    return false;\n  }, [isCompanyLinked, selectedRecord, idField, data]);\n\n  // Predicado por fila para la columna de estado por compañía del listado (N9).\n  // A diferencia de checkLinkStatus, NO asume que la compañía activa está siempre habilitada:\n  // refleja el estado real del registro en esa compañía.\n  const isRecordCompanyEnabled = useCallback((row: any): boolean => {\n    if (!selectedCompany || String(selectedCompany.uuid) === '000') return true;\n    const rid = row?.[idField];\n    if (isCompanyLinked) return isCompanyLinked(rid, selectedCompany.uuid);\n    const linked = row?._linkedCompanies;\n    if (Array.isArray(linked)) return linked.some((u: any) => String(u) === String(selectedCompany.uuid));\n    if (typeof row?._enabled === 'boolean') return row._enabled;\n    if (typeof row?.enabled === 'boolean') return row.enabled;\n    return true;\n  }, [selectedCompany, idField, isCompanyLinked]);\n\n  // Filtros por columna activos por defecto: si el consumidor no especifica columnas,\n  // se habilita el embudo en todos los campos visibles filtrables (no lookup). Retrocompatible.\n  const effectiveColumnFilterableFields = React.useMemo(() => {\n    if (columnFilterableFields) return columnFilterableFields;\n    if (filterableFields) return filterableFields;\n    return fields\n      .filter(f => f.type !== 'lookup' && f.config?.searchable !== false)\n      .map(f => f.accessorKey as string);\n  }, [columnFilterableFields, filterableFields, fields]);\n\n  // Mapa uuid → habilitado para el CompanySelector del detalle (S2.7): muestra por compañía\n  // si el registro está Habilitado / No habilitado.\n  const detailCompanyEnabledMap = React.useMemo(() => {\n    const map: Record<string, boolean> = {};\n    const rid = globalRecordId ?? (selectedRecord as any)?.[idField];\n    if (rid == null) return map;\n    allCompanies.forEach((c) => {\n      if (String(c.uuid) !== '000') map[String(c.uuid)] = checkLinkStatus(rid, c.uuid);\n    });\n    return map;\n  }, [allCompanies, checkLinkStatus, globalRecordId, selectedRecord, idField]);\n\n  const handleCompanyChange = useCallback(async (company: MasterCrudCompany, recordId?: string | number) => {\n    const isGlobal = String(company.uuid) === '000';\n    const currentId = recordId || (selectedRecord as any)?.[idField];\n\n    if (viewState === 'EDIT' && currentId && activeByCompany && !isGlobal) {\n      const linked = checkLinkStatus(globalRecordId || currentId, company.uuid);\n      if (!linked) { setLinkConfirmState({ show: true, company }); return; }\n    }\n\n    setSelectedCompany(company);\n    // Al cambiar de compañía, el alcance de filas se reinicia a su valor por defecto (N9).\n    setViewScope(defaultViewScope);\n    onCompanyChange?.(company, currentId);\n\n    if (viewState === 'EDIT' && currentId) {\n      setFormLoading(true);\n      try {\n        let record: T;\n        const targetId = globalRecordId || currentId;\n        if (service.getById) { record = await service.getById(targetId, company); }\n        else {\n          const response = await service.getAll({ page: 1, limit: 1, filters: { [idField]: targetId } }, company);\n          record = response.data[0];\n        }\n        if (record) setSelectedRecord(record);\n      } catch {\n        showToast(t('errorReload', 'Error al recargar el registro'), 'red');\n      } finally { setFormLoading(false); }\n    }\n\n    if (!recordId && viewState === 'LIST') { setCurrentPage(1); setHasMore(true); }\n  }, [onCompanyChange, viewState, activeByCompany, checkLinkStatus, globalRecordId, selectedRecord, idField, service, showToast, t]);\n\n  const handleConfirmDynamicLink = useCallback(async () => {\n    if (!linkConfirmState.company || !selectedRecord) return;\n    const company = linkConfirmState.company;\n    const currentId = (selectedRecord as any)[idField];\n    const targetId = globalRecordId || currentId;\n\n    setFormLoading(true);\n    setLinkConfirmState({ show: false, company: null });\n\n    try {\n      // Obtener vinculaciones actuales y agregar la nueva para no perder las anteriores\n      const currentLinks = (selectedRecord as any)._linkedCompanies || [];\n      const newLinks = Array.from(new Set([...currentLinks, company.uuid]));\n\n      await onConfirmLinking?.(targetId, newLinks);\n      setSelectedCompany(company);\n      onCompanyChange?.(company, targetId);\n\n      let record: T;\n      if (service.getById) { record = await service.getById(targetId, company); }\n      else {\n        const response = await service.getAll({ page: 1, limit: 1, filters: { [idField]: targetId } }, company);\n        record = response.data[0];\n      }\n\n      if (record) {\n        setSelectedRecord(record);\n\n        // Sincronizar también en el listado general (data)\n        setData(prev => prev.map(item => {\n          if (String((item as any)[idField]) === String(targetId)) {\n            return { ...item, _linkedCompanies: newLinks, ...(record || {}) };\n          }\n          return item;\n        }));\n\n        showToast(t('successLinkDynamic', 'Registro habilitado y cargado'), 'green');\n      }\n    } catch (error) {\n      showToast(getErrorMessage(error), 'red');\n    } finally { setFormLoading(false); }\n  }, [linkConfirmState.company, selectedRecord, idField, globalRecordId, onConfirmLinking, onCompanyChange, service, showToast, getErrorMessage, t]);\n\n  const handleLinkRecords = useCallback(async (recordId: string | number, companyUuids: (string | number)[]) => {\n    try {\n      await onConfirmLinking?.(recordId, companyUuids);\n\n      // Actualizar en el listado general\n      setData(prev => prev.map(item => {\n        if (String((item as any)[idField]) === String(recordId)) {\n          return { ...item, _linkedCompanies: companyUuids };\n        }\n        return item;\n      }));\n\n      // Actualizar el registro seleccionado si es el mismo que se está vinculando\n      if (selectedRecord && String((selectedRecord as any)[idField]) === String(recordId)) {\n        setSelectedRecord(prev => prev ? { ...prev, _linkedCompanies: companyUuids } : null);\n      }\n\n      showToast(t('successLink', 'Habilitaciones actualizadas correctamente'), 'green');\n    } catch (error) {\n      showToast(getErrorMessage(error), 'red');\n      // El backend puede haber guardado vinculaciones parciales antes del error.\n      // Se cede al event loop para que React procese actualizaciones de estado pendientes,\n      // luego se re-lee el registro para reflejar el estado real.\n      setTimeout(async () => {\n        try {\n          const company = getCompanyPrimaryData();\n          const svc = serviceRef.current;\n          const refreshed = svc.getById\n            ? await svc.getById(recordId, company)\n            : (await svc.getAll({ page: 1, limit: 1, filters: { [idField]: recordId } }, company)).data[0];\n          if (refreshed) {\n            const actualLinks = (refreshed as any)._linkedCompanies;\n            if (Array.isArray(actualLinks)) {\n              setData(prev => prev.map(item =>\n                String((item as any)[idField]) === String(recordId)\n                  ? { ...item, _linkedCompanies: actualLinks }\n                  : item\n              ));\n              if (selectedRecord && String((selectedRecord as any)[idField]) === String(recordId)) {\n                setSelectedRecord(prev => prev ? { ...prev, _linkedCompanies: actualLinks } : null);\n              }\n            }\n          }\n        } catch { /* Silencioso: no altera el mensaje de error principal */ }\n      }, 0);\n    }\n  }, [onConfirmLinking, idField, selectedRecord, getCompanyPrimaryData, showToast, getErrorMessage, t]);\n\n  const handleSearchMatches = useCallback(async (field: MasterCrudField<T>, value: string) => {\n    if (!onSearchMatches) return;\n    try {\n      const results = await onSearchMatches(field, value);\n      if (results && results.length > 0) {\n        // `header` es obligatorio en el contrato, pero lo define la configuración\n        // del consumidor: TypeScript no garantiza que llegue en runtime. Se\n        // normaliza aquí para no guardar un `undefined` en un estado tipado como\n        // `string`; el MatchModal degrada solo a su título genérico.\n        const fieldName = typeof field.header === 'string' ? field.header : '';\n        setMatchModalState({ show: true, matches: results, fieldName });\n      }\n    } catch (error) {\n      console.error('Error searching matches:', error);\n    }\n  }, [onSearchMatches]);\n\n  const handleViewMatch = useCallback(async (match: MatchResult) => {\n    setPreviewModalState({ show: true, record: null, loading: true });\n    try {\n      let record: T;\n      if (service.getById) { record = await service.getById(match.id, getCompanyPrimaryData()); }\n      else {\n        const response = await service.getAll({ page: 1, limit: 1, filters: { [idField]: match.id } }, getCompanyPrimaryData());\n        record = response.data[0];\n      }\n\n      if (record) { setPreviewModalState({ show: true, record, loading: false }); }\n      else {\n        showToast(t('errorRecordNotFound', 'No se pudo encontrar el registro seleccionado'), 'red');\n        setPreviewModalState(prev => ({ ...prev, show: false, loading: false }));\n      }\n    } catch (error) {\n      showToast(t('errorDataLoad', 'Error al cargar los datos del registro'), 'red');\n      setPreviewModalState(prev => ({ ...prev, show: false, loading: false }));\n    }\n  }, [service, getCompanyPrimaryData, idField, showToast, t]);\n\n  useEffect(() => {\n    const mediaQuery = window.matchMedia('(max-width: 1024px)');\n    const handleDeviceChange = (e: MediaQueryListEvent | MediaQueryList) => { setViewType(e.matches ? 'grid' : 'list'); };\n    handleDeviceChange(mediaQuery);\n    mediaQuery.addEventListener('change', handleDeviceChange);\n    return () => mediaQuery.removeEventListener('change', handleDeviceChange);\n  }, []);\n\n  const handleConfirmGlobalReset = useCallback(() => {\n    formRef.current?.revertAllToGlobal();\n    setShowGlobalResetConfirm(false);\n    showToast(t('successRevert', 'Campos restaurados a valores globales'), 'zinc');\n  }, [showToast, t]);\n\n  const searchFieldOptions = React.useMemo(() => {\n    let targetFields = fields;\n    if (filterableFields && filterableFields.length > 0) {\n      targetFields = fields.filter(f => filterableFields.includes(f.accessorKey as string));\n    } else {\n      targetFields = fields.filter(f => f.config?.searchable !== false);\n    }\n    const options = targetFields.map(f => ({\n      value: f.accessorKey as string,\n      label: t(f.accessorKey as string, f.header)\n    }));\n    return [{ value: 'all', label: t('all') }, ...options];\n  }, [fields, filterableFields, t]);\n\n  useEffect(() => {\n    if (searchField === 'all' && fields.length > 0) {\n      const targetFields = filterableFields && filterableFields.length > 0\n        ? fields.filter(f => filterableFields.includes(f.accessorKey as string))\n        : fields.filter(f => f.config?.searchable !== false);\n\n      if (targetFields.length > 0) {\n        const firstField = targetFields[0].accessorKey as string;\n        setSearchField(firstField);\n        searchFieldRef.current = firstField;\n      }\n    }\n  }, [fields, filterableFields]);\n\n  const sortFieldOptions = React.useMemo(() => {\n    const targetFields = fields.filter(f => f.config?.sortable === true);\n    const options = targetFields.map(f => ({\n      value: f.accessorKey as string,\n      label: t(f.accessorKey as string, f.header),\n      field: f.accessorKey as string,\n      direction: 'asc' as const,\n    }));\n    return [{ value: '', label: t('noSort'), field: '', direction: 'asc' as const }, ...options];\n  }, [fields, t]);\n\n  const observer = useRef<IntersectionObserver | null>(null);\n  const lastElementRef = useCallback((node: HTMLDivElement) => {\n    if (loading) return;\n    if (observer.current) observer.current.disconnect();\n    observer.current = new IntersectionObserver(entries => { if (entries[0].isIntersecting && hasMore) { setCurrentPage(prevPage => prevPage + 1); } });\n    if (node) observer.current.observe(node);\n  }, [loading, hasMore]);\n\n  const loadData = useCallback(async () => {\n    if (!canRead) return;\n    if (activeByCompany && companyRequired && !selectedCompany) return;\n    if (viewType === 'grid' && enableGridInfiniteScroll && currentPage > 1 && !hasMore) return;\n\n    setLoading(true);\n    try {\n      const currentSearchField = searchFieldRef.current;\n\n      // Filtros por columna → AdvancedFilter[] (viajan por el canal de búsqueda avanzada\n      // existente, retrocompatible con endpoints que ya soportan advancedFilters).\n      const columnAdvancedFilters: AdvancedFilter[] = Object.entries(columnFilters).map(([field, { value, operator }]) => ({\n        id: `col_${field}`,\n        field,\n        connector: 'AND' as const,\n        operator,\n        value,\n      }));\n      const mergedAdvancedFilters = [\n        ...(isAdvancedSearchActive ? advancedFilters : []),\n        ...columnAdvancedFilters,\n      ];\n\n      // Alcance de filas (multicompañía por sobrescritura), aditivo y server-side.\n      const isCompanyScope = activeByCompany && selectedCompany && String(selectedCompany.uuid) !== '000';\n      const scopeFilter = isCompanyScope ? { viewScope } : undefined;\n\n      const hasFilters = mergedAdvancedFilters.length > 0 || !!scopeFilter;\n      const params: GetAllParams = {\n        page: currentPage,\n        limit: internalPageSize,\n        search: isAdvancedSearchActive ? undefined : (searchTerm || undefined),\n        searchField: isAdvancedSearchActive ? undefined : (currentSearchField !== 'all' ? currentSearchField : undefined),\n        sortBy: sortColumn,\n        sortDirection: sortDirection || undefined,\n        filters: hasFilters\n          ? {\n              ...(mergedAdvancedFilters.length > 0 ? { advancedFilters: mergedAdvancedFilters } : {}),\n              ...(scopeFilter || {}),\n            }\n          : undefined,\n      };\n\n      const response = await serviceRef.current.getAll(params, getCompanyPrimaryData());\n\n      if (viewType === 'grid' && enableGridInfiniteScroll && currentPage > 1) { setData(prev => [...prev, ...response.data]); }\n      else { setData(response.data); }\n\n      setTotal(response.total);\n      const loadedCount = (currentPage - 1) * internalPageSize + response.data.length;\n      setHasMore(loadedCount < response.total);\n\n    } catch (error) {\n      if (internalErrorHandling) showToast(getErrorMessageRef.current(error), 'red');\n      onError?.(error as Error, 'fetch');\n    } finally { setLoading(false); }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [currentPage, internalPageSize, searchTerm, sortColumn, sortDirection, viewType, enableGridInfiniteScroll, isAdvancedSearchActive, advancedFilters, columnFilters, viewScope, activeByCompany, selectedCompany, getCompanyPrimaryData, canRead]);\n\n  useEffect(() => { loadData(); }, [loadData]);\n\n  // Cambio de un filtro por columna (server-side): actualiza estado y recarga desde la página 1.\n  const handleColumnFilterChange = useCallback((field: string, value: string, operator: 'contains' | 'equals') => {\n    setColumnFilters((prev) => {\n      const next = { ...prev };\n      if (value === '' || value == null) delete next[field];\n      else next[field] = { value, operator };\n      return next;\n    });\n    setCurrentPage(1);\n    setHasMore(true);\n  }, []);\n\n  // Cambio de alcance de filas (multicompañía por sobrescritura), server-side.\n  const handleViewScopeChange = useCallback((scope: 'all' | 'company') => {\n    setViewScope(scope);\n    setCurrentPage(1);\n    setHasMore(true);\n  }, []);\n\n  // Detección del modo sobrescritura multicompañía con compañía específica seleccionada.\n  // En modo \"compañía requerida\" no aplica el modelo de sobreescritura Global→Sucursal:\n  // los registros son propios de la compañía, por lo que NO se muestran la columna de estado\n  // por compañía ni los switches de alcance (\"Registros a mostrar\").\n  const isCompanyScopeActive = !!(activeByCompany && !companyRequired && selectedCompany && String(selectedCompany.uuid) !== '000');\n\n  const handleSearch = useCallback((term: string) => { setSearchTerm(term); setCurrentPage(1); setHasMore(true); }, []);\n  const handleSort = useCallback((column: string, direction: 'asc' | 'desc' | null) => { setSortColumn(direction ? column : undefined); setSortDirection(direction); }, []);\n  const handleSortChange = useCallback((value: string) => { const newSortColumn = value || undefined; setSortColumn(newSortColumn); if (newSortColumn && !sortDirection) setSortDirection('asc'); setCurrentPage(1); setHasMore(true); }, [sortDirection]);\n  const handleSortDirectionChange = useCallback((direction: 'asc' | 'desc') => { setSortDirection(direction); if (sortColumn) { setCurrentPage(1); setHasMore(true); } }, [sortColumn]);\n  const handleFilterChange = useCallback((value: string) => { setSearchField(value); searchFieldRef.current = value; setSearchTerm(''); if (searchTerm !== '') { setCurrentPage(1); setHasMore(true); } }, [searchTerm]);\n  const handleViewChange = useCallback((view: ToolbarViewType) => { setViewType(view); setCurrentPage(1); setHasMore(true); onViewChange?.(view); }, [onViewChange]);\n  const handlePageChange = useCallback((page: number) => { setCurrentPage(page); }, []);\n  const handlePageSizeChange = useCallback((size: number) => { setInternalPageSize(size); setCurrentPage(1); setHasMore(true); }, []);\n  const handleCreate = useCallback(() => { setSelectedRecord(null); setGlobalRecordId(null); setViewState('CREATE'); }, []);\n  const handleEdit = useCallback(async (record: T) => {\n    const id = (record as any)[idField];\n    setGlobalRecordId(id);\n    setViewState('EDIT');\n\n    if (fetchDetailOnEdit) {\n      setSelectedRecord(null);\n      setFormLoading(true);\n      try {\n        let detailedRecord: T;\n        if (service.getById) { detailedRecord = await service.getById(id, getCompanyPrimaryData()); }\n        else {\n          const response = await service.getAll({ page: 1, limit: 1, filters: { [idField]: id } }, getCompanyPrimaryData());\n          detailedRecord = response.data[0];\n        }\n        if (detailedRecord) { setSelectedRecord(detailedRecord); }\n        else { setSelectedRecord(record); }\n      } catch (error) {\n        if (internalErrorHandling) showToast(t('errorDetailLoad', 'Error al cargar el detalle del registro'), 'red');\n        setSelectedRecord(record);\n      } finally { setFormLoading(false); }\n    } else { setSelectedRecord(record); }\n  }, [idField, fetchDetailOnEdit, service, getCompanyPrimaryData, internalErrorHandling, showToast, t]);\n  const handleFormCancel = useCallback(() => { setViewState('LIST'); setSelectedRecord(null); setGlobalRecordId(null); }, []);\n  // Volver con guardia de cambios sin guardar (S2.8): si el formulario está \"sucio\", pide confirmación.\n  const handleBackGuarded = useCallback(() => {\n    const changes = (formRef.current?.getChanges?.() ?? []) as { label: string; from: any; to: any }[];\n    if (changes.length > 0) setDirtyModal({ show: true, changes });\n    else handleFormCancel();\n  }, [handleFormCancel]);\n\n  const handleSelectionChange = useCallback((newIds: (string | number)[]) => {\n    setSelectedRecords(prev => {\n      const currentDataIds = data.map(r => (r as any)[idField]);\n      const idsToUnselect = currentDataIds.filter(id => !newIds.includes(id));\n      let updated = prev.filter(r => !idsToUnselect.includes((r as any)[idField]));\n      const idsToAdd = newIds.filter(id => !prev.some(r => (r as any)[idField] === id));\n      const recordsToAdd = data.filter(r => idsToAdd.includes((r as any)[idField]));\n      return [...updated, ...recordsToAdd];\n    });\n  }, [data, idField]);\n\n  const toggleAdvancedSearch = useCallback(() => {\n    setIsAdvancedSearchActive(prev => { if (prev) { setAdvancedFilters([]); setCurrentPage(1); } return !prev; });\n  }, []);\n\n  const handleAdvancedSearch = useCallback((filters: AdvancedFilter[]) => { setAdvancedFilters(filters); setCurrentPage(1); setHasMore(true); }, []);\n\n  const [deleteConfirm, setDeleteConfirm] = useState<{ show: boolean; record: T | null }>({ show: false, record: null });\n  const handleDeleteClick = useCallback(async (record: T) => { if (onBeforeDelete && !(await onBeforeDelete(record))) return; setDeleteConfirm({ show: true, record }); }, [onBeforeDelete]);\n  const handleDeleteConfirm = useCallback(async () => {\n    if (!deleteConfirm.record) return;\n    setLoading(true);\n    try {\n      const recordId = (deleteConfirm.record as any)[idField];\n      const companyData = getCompanyPrimaryData();\n      const isActive = !!((deleteConfirm.record as any)[statusField] ?? true);\n\n      let operation: MasterCrudOperationType = 'delete';\n      if (softDelete) {\n        operation = isActive ? 'deactivate' : 'activate';\n      }\n\n      // Enviar contexto de compañía y estado actual al fetch de eliminación\n      // El tercer parámetro indica el tipo de operación (física o cambio de estado)\n      await service.delete(recordId, { ...companyData, isActive, record: deleteConfirm.record, companyRequired }, operation);\n      onDeleteSuccess?.(recordId);\n\n      const isBranchContext = activeByCompany && !companyRequired && selectedCompany && String(selectedCompany.uuid) !== '000';\n      let successMsg = t('successDelete', 'Registro eliminado correctamente');\n\n      if (softDelete && isBranchContext) {\n        if (isActive) {\n          successMsg = t('successUnlink', 'Registro deshabilitado correctamente');\n        } else {\n          successMsg = t('successLink', 'Registro habilitado correctamente');\n        }\n      } else if (softDelete && !isBranchContext) {\n        successMsg = isActive\n          ? t('successDeactivate', 'Registro desactivado correctamente')\n          : t('successActivate', 'Registro activado correctamente');\n      }\n\n      showToast(successMsg, 'green');\n      setDeleteConfirm({ show: false, record: null });\n\n      if (operation === 'delete') {\n        // En contexto de eliminación física: Quitar el registro de la tabla/card\n        setTotal(prev => Math.max(0, prev - 1));\n        setData(prevData => {\n          const newData = prevData.filter(item => (item as any)[idField] !== recordId);\n          if (viewType === 'list' && newData.length === 0 && currentPage > 1) { setCurrentPage(prev => prev - 1); }\n          return newData;\n        });\n        setSelectedRecords(prev => prev.filter(r => (r as any)[idField] !== recordId));\n      } else {\n        // En contexto de cambio de estado: Solo refrescar para reflejar cambio\n        loadData();\n      }\n    } catch (error) {\n      if (internalErrorHandling) showToast(getErrorMessage(error), 'red');\n      onError?.(error as Error, 'delete');\n    } finally { setLoading(false); }\n  }, [deleteConfirm.record, idField, service, onDeleteSuccess, onError, showToast, getErrorMessage, internalErrorHandling, viewType, currentPage, getCompanyPrimaryData, t, loadData, softDelete, statusField, activeByCompany, companyRequired, selectedCompany]);\n\n  const handleCustomAction = useCallback((action: MasterCrudAction<T>, record: T) => {\n    const actionName = typeof action.name === 'function' ? action.name(record) : action.name;\n    if (action.modalContent) { const content = typeof action.modalContent === 'function' ? action.modalContent(record) : action.modalContent; setCustomModalState({ show: true, content, title: actionName }); }\n    else if (action.action) { action.action(record, getCompanyPrimaryData()); }\n  }, [getCompanyPrimaryData]);\n\n  const handleCloseCustomModal = useCallback(() => { setCustomModalState({ show: false, content: null, title: '' }); }, []);\n\n  const getActionsDefinition = useCallback((): MasterCrudAction<T>[] => {\n    const defaultActions: MasterCrudAction<T>[] = [];\n    if (canRead && canUpdate && showDefaultEditAction) defaultActions.push({ id: 'edit', name: t('edit'), icon: <PencilIcon className=\"w-4 h-4\" />, action: (r: T | T[]) => handleEdit(r as T), order: 100 });\n    if (activeByCompany && !companyRequired) {\n      defaultActions.push({\n        id: 'link', name: t('link', 'Habilitar'), icon: <LinkIcon className=\"w-4 h-4\" />,\n        action: (r: T | T[]) => { setLinkModalState({ show: true, record: Array.isArray(r) ? r[0] : r, variant: 'manual' }); },\n        order: 110\n      });\n    }\n\n    const showSoftDelete = softDelete && canChangeStatus;\n    const showHardDelete = !softDelete && canDelete;\n\n    if (showSoftDelete || showHardDelete) {\n      const isBranchContext = activeByCompany && selectedCompany && String(selectedCompany.uuid) !== '000';\n\n      defaultActions.push({\n        id: 'delete',\n        name: (r) => {\n          if (!r) return t('delete');\n          const isActive = !!((r as any)[statusField] ?? true);\n          const isBranchContext = activeByCompany && !companyRequired && selectedCompany && String(selectedCompany.uuid) !== '000';\n\n          if (isActive) {\n            // El botón de estado usa siempre terminología de Desactivar (Global y Sucursal).\n            // La \"habilitación por compañía\" (Habilitar/Deshabilitar) es un concepto aparte\n            // gestionado por la acción 'link' y el modal de habilitación.\n            if (!isBranchContext) return softDelete ? t('deactivateRecord', 'Desactivar registro') : t('delete', 'Eliminar');\n            // En Sucursal, respetamos el tooltip personalizado si existe; si no, 'Desactivar registro'.\n            if (deactivateTooltip) return deactivateTooltip;\n            return t('deactivateRecord', 'Desactivar registro');\n          } else {\n            // Si el registro está inactivo, mostramos siempre Activar\n            if (!isBranchContext) return t('activate', 'Activar');\n            if (activateTooltip) return activateTooltip;\n            return t('activate', 'Activar');\n          }\n        },\n        icon: (r) => {\n          if (!softDelete) return <TrashIcon className=\"w-4 h-4\" />;\n          if (!r) return <TrashIcon className=\"w-4 h-4\" />;\n          const isActive = !!((r as any)[statusField] ?? true);\n          const isBranchContext = activeByCompany && !companyRequired && selectedCompany && String(selectedCompany.uuid) !== '000';\n\n          // 1. Si el registro está inactivo, mostramos siempre el icono de activación (Círculo con Check)\n          if (!isActive) return <CheckCircleIcon className=\"w-4 h-4\" />;\n\n          // 2. Si el registro está activo y es softDelete:\n          // En Global (!isBranchContext) o Sucursal, usamos MinusCircleIcon para representar 'Desactivar/Desvincular'\n          // Reservamos TrashIcon solo para cuando softDelete es FALSE (borrado físico)\n          return isBranchContext ? <NoSymbolIcon className=\"w-4 h-4\" /> : (softDelete ? <NoSymbolIcon className=\"w-4 h-4\" /> : <TrashIcon className=\"w-4 h-4\" />);\n        },\n        action: (r: T | T[]) => handleDeleteClick(r as T),\n        disabled: (r) => {\n          if (!r) return false;\n          const isActive = !!((r as any)[statusField] ?? true);\n          // Si no se permite reversión y el registro ya está inactivo/desvinculado, deshabilitamos.\n          if (effectiveAllowStatusReversion === false && !isActive) return true;\n          return false;\n        },\n        visible: (r) => {\n          if (!r) return true;\n          const isActive = !!((r as any)[statusField] ?? true);\n          // Si no se permite reversión y el registro ya está inactivo, OCULTAMOS el botón.\n          if (effectiveAllowStatusReversion === false && !isActive) return false;\n          return true;\n        },\n        order: 200\n      });\n    }\n    if (auditHistory?.enabled) {\n      defaultActions.push({\n        id: 'audit',\n        name: t('auditChanges', 'Auditoría de Cambios'),\n        icon: <ClockIcon className=\"w-4 h-4\" />,\n        order: 150,\n        displayType: 'menu',\n        visible: (r: T) => !!(r as any).id || !!(r as any).uuid,\n        action: (r: T | T[]) => setAuditModalState({ show: true, record: r as T }),\n      });\n    }\n\n    const customActions = actions.map(action => ({ ...action, order: action.order ?? 0, action: (r: T | T[]) => handleCustomAction(action, r as T) }));\n\n    return [...defaultActions, ...customActions].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n  }, [canRead, canUpdate, showDefaultEditAction, canDelete, canChangeStatus, softDelete, actions, t, handleEdit, handleDeleteClick, handleCustomAction, activeByCompany, companyRequired, selectedCompany, deactivateTooltip, activateTooltip, effectiveAllowStatusReversion, statusField, auditHistory]);\n\n  const actionsList = React.useMemo(() => getActionsDefinition(), [getActionsDefinition]);\n\n  const combinedBatchActions = React.useMemo(() => {\n    const explicitBatchActions = batchActionsProp.map(a => ({ ...a, action: () => { a.action?.(selectedRecords); setSelectedRecords([]); } }));\n    const inferredBatchActions = actions.filter(a => a.isGroupAction).map(a => ({ ...a, action: () => { a.action?.(selectedRecords); setSelectedRecords([]); } }));\n    return [...explicitBatchActions, ...inferredBatchActions];\n  }, [batchActionsProp, actions, selectedRecords]);\n\n  const handleBulkUpdateComplete = useCallback((result: BulkUpdateResult) => {\n    loadData();\n    setSelectedRecords([]);\n    setShowBulkDynamicEditor(false);\n    onBulkUpdateComplete?.(result);\n  }, [loadData, onBulkUpdateComplete]);\n\n  const handleFormSubmit = useCallback(async (formData: Partial<T>) => {\n    setFormLoading(true);\n    try {\n      if (viewState === 'CREATE') {\n        if (onBeforeCreate && !(await onBeforeCreate(formData))) { setFormLoading(false); return; }\n        let dataToCreate = { ...formData };\n        if (activeByCompany && selectedCompany && String(selectedCompany.uuid) !== '000') { (dataToCreate as any)._createInGlobal = true; }\n        const created = await service.create(dataToCreate, getCompanyPrimaryData());\n        console.log(\"%c[MASTER-CRUD] Registro base creado exitosamente con ID:\", \"color: #22c55e;\", (created as any)[idField]);\n\n        // Guardar entidades dinámicas si existen\n        console.log(\"%c[MASTER-CRUD] Evaluando guardado de entidades dinámicas. FeatureCode:\", \"color: blue;\", dynamicFeatureCode);\n        if (dynamicFeatureCode && formRef.current?.saveDynamicEntities) {\n          const dynamicSuccess = await formRef.current.saveDynamicEntities((created as any)[idField]);\n          if (!dynamicSuccess) {\n            showToast('Registro base creado, pero hubo un error con los datos dinámicos', 'red');\n          }\n        }\n\n        // Guardar gestión de archivos si está habilitada\n        if (featCodeFileManager && formRef.current?.saveFileManagement) {\n          const fileSuccess = await formRef.current.saveFileManagement((created as any)[idField]);\n          if (!fileSuccess) {\n            showToast('Registro creado, pero hubo errores al gestionar los archivos', 'red');\n          }\n        }\n\n        onCreateSuccess?.(created);\n        showToast(t('successCreate', 'Registro creado correctamente'), 'green');\n        loadData();\n        if (activeByCompany && (!selectedCompany || String(selectedCompany.uuid) === '000')) {\n          setSelectedRecord(created);\n          setGlobalRecordId((created as any)[idField]);\n          setViewState('EDIT');\n          setLinkModalState({ show: true, record: created, variant: 'success' });\n        } else if (detailConfig) {\n          // Maestro-Detalle: quedarse en EDIT para que aparezca la sección de detalles\n          setSelectedRecord(created);\n          setGlobalRecordId((created as any)[idField]);\n          setViewState('EDIT');\n        } else { setViewState('LIST'); setSelectedRecord(null); setGlobalRecordId(null); }\n      } else if (viewState === 'EDIT' && selectedRecord) {\n        const recordId = (selectedRecord as any)[idField];\n        let dataToUpdate: Partial<T> = { ...formData };\n        if (activeByCompany && selectedCompany && String(selectedCompany.uuid) !== '000') {\n          const overriddenFields = fields.filter(f => f.config?.allowMultiCompanyOverride).map(f => f.accessorKey as string);\n          (dataToUpdate as any)._multicompanyMetadata = { isOverride: true, companyUuid: selectedCompany.uuid, overriddenFields };\n        }\n        if (onBeforeUpdate && !(await onBeforeUpdate(recordId, dataToUpdate))) { setFormLoading(false); return; }\n        const updated = await service.update(recordId, dataToUpdate, getCompanyPrimaryData());\n        console.log(\"%c[MASTER-CRUD] Registro base actualizado exitosamente. ID:\", \"color: #22c55e;\", recordId);\n\n        // Guardar entidades dinámicas si existen\n        console.log(\"%c[MASTER-CRUD] Evaluando guardado de entidades dinámicas (EDIT). FeatureCode:\", \"color: blue;\", dynamicFeatureCode);\n        if (dynamicFeatureCode && formRef.current?.saveDynamicEntities) {\n          const dynamicSuccess = await formRef.current.saveDynamicEntities(recordId);\n          if (!dynamicSuccess) {\n            showToast('Registro base actualizado, pero hubo un error con los datos dinámicos', 'red');\n          }\n        }\n\n        // Guardar gestión de archivos si está habilitada\n        if (featCodeFileManager && formRef.current?.saveFileManagement) {\n          const fileSuccess = await formRef.current.saveFileManagement(recordId);\n          if (!fileSuccess) {\n            showToast('Registro actualizado, pero hubo errores al gestionar los archivos', 'red');\n          }\n        }\n\n        if (!detailConfig) {\n          setViewState('LIST');\n          setSelectedRecord(null);\n        } else {\n          // Maestro-Detalle: actualizar selectedRecord con la respuesta del servidor\n          // para que el formulario refleje los datos actualizados sin datos stale\n          setSelectedRecord(updated ?? ({ ...selectedRecord, ...dataToUpdate } as T));\n        }\n        setData(prevData => prevData.map(item => (item as any)[idField] === recordId ? { ...item, ...dataToUpdate, ...(updated || {}) } : item));\n        onUpdateSuccess?.(updated);\n        showToast(t('successUpdate', 'Registro actualizado correctamente'), 'green');\n      }\n    } catch (error) {\n      if (internalErrorHandling) showToast(getErrorMessage(error), 'red');\n      onError?.(error as Error, viewState === 'CREATE' ? 'create' : 'update');\n    } finally { setFormLoading(false); }\n  }, [viewState, selectedRecord, idField, service, onCreateSuccess, onUpdateSuccess, onError, loadData, onBeforeCreate, onBeforeUpdate, showToast, getErrorMessage, internalErrorHandling, activeByCompany, selectedCompany, fields, getCompanyPrimaryData, t, detailConfig]);\n\n  const totalPages = Math.ceil(total / internalPageSize);\n  // Llena la altura disponible tanto en un contenedor flex-col (flex-1) como en uno de altura\n  // explícita (h-full). Con un padre flex-col + hermanos (p. ej. un panel informativo en una\n  // story), `flex-1` gana y respeta a los hermanos; con un padre de altura explícita, aplica\n  // `h-full`. En ambos casos el header/footer de la tabla quedan fijos con scroll interno. Si el\n  // contenedor no acota la altura, degrada a scroll de página (sin romper).\n  const containerClasses = `flex flex-col w-full relative flex-1 min-h-0 h-full ${className}`.trim();\n\n  // ===== CONFIGURACIÓN EFECTIVA DE GESTIÓN DE ARCHIVOS =====\n  // Si el consumidor pasa fileManagerConfig manual, se usa tal cual (modo manual).\n  // Si el servicio implementa los métodos de archivos, se construye automáticamente (modo automático).\n  const effectiveFileManagerConfig = React.useMemo((): FileManagerConfig | undefined => {\n    if (!featCodeFileManager) return undefined;\n    if (fileManagerConfig) return fileManagerConfig;\n    if (!service.getFiles) return undefined;\n\n    return {\n      resources: fileResources,\n      isLoading: fileResourcesLoading,\n      allowDeletion: !!service.deleteFile,\n      showFileUploader: !!service.uploadFile,\n      acceptedExtensions: fileAcceptedExtensions,\n      maxFileSizeMB: fileMaxSizeMB,\n      maxTotalSizeMB: fileTotalMaxSizeMB,\n      multipleFiles: fileMultiple,\n      onUpload: service.uploadFile\n        ? async (file: File, recId: string | number) => {\n          await service.uploadFile!(recId, file, getCompanyPrimaryData());\n          const updated = await service.getFiles!(recId, getCompanyPrimaryData());\n          setFileResources(updated);\n        }\n        : undefined,\n      onDelete: service.deleteFile\n        ? async (uuid: string, recId: string | number) => {\n          await service.deleteFile!(recId, uuid, getCompanyPrimaryData());\n          setFileResources(prev => prev.filter(r => r.uuid !== uuid));\n        }\n        : undefined,\n      onAccept: service.saveFiles\n        ? async (selected: GalleryResource[], recId: string | number) => {\n          await service.saveFiles!(recId, selected, getCompanyPrimaryData());\n        }\n        : undefined,\n    };\n  }, [featCodeFileManager, fileManagerConfig, service, fileResources, fileResourcesLoading, getCompanyPrimaryData]);\n\n  const defaultToolbar = useToolbar ? (\n    <MasterCrudToolbar\n      title={finalTitle}\n      searchPlaceholder={t('search', 'Buscar')}\n      searchValue={searchTerm}\n      onSearchChange={handleSearch}\n      showSearch={showSearch}\n      filterOptions={searchFieldOptions}\n      selectedFilter={searchField}\n      onFilterChange={handleFilterChange}\n      showFilter={showSearch && searchFieldOptions.length > 0}\n      filterButtonText={t('searchBy')}\n      sortOptions={sortFieldOptions}\n      selectedSort={sortColumn}\n      onSortChange={handleSortChange}\n      sortDirection={sortDirection || 'asc'}\n      onSortDirectionChange={handleSortDirectionChange}\n      showSort={sortFieldOptions.length > 0}\n      sortButtonText={t('sortBy')}\n      viewType={viewType}\n      onViewChange={handleViewChange}\n      showViewToggle={showViewToggle}\n      showAdvancedSearch={showAdvancedSearch}\n      globalActions={globalActions}\n      batchActions={combinedBatchActions}\n      hasSelection={selectedRecords.length > 0}\n      isAdvancedSearchActive={isAdvancedSearchActive}\n      onAdvancedSearchToggle={toggleAdvancedSearch}\n      initialFiltersVisible={initialFiltersVisible}\n      activeByCompany={activeByCompany}\n      companies={allCompanies}\n      selectedCompany={selectedCompany}\n      onCompanyChange={handleCompanyChange}\n      showExport={showExport}\n      onExport={onExport}\n      showViewScope={isCompanyScopeActive}\n      viewScope={viewScope}\n      onViewScopeChange={handleViewScopeChange}\n      onBack={onBack}\n      t={t}\n      extraContent={\n        <div className=\"flex items-center gap-2\">\n          {dynamicFeatureCode && enableMultiSelect && canBulkUpdate && selectedRecords.length > 0 && (\n            <Button\n              type=\"plain\"\n              size=\"base\"\n              onClick={() => setShowBulkDynamicEditor(true)}\n            >\n              Editar campos dinamicos\n            </Button>\n          )}\n          {canCreate && (\n            <Button type=\"default\" size=\"base\" className=\"!text-sm font-medium\" leftIcon={<PlusIcon className=\"w-4 h-4\" />} onClick={handleCreate}>\n              {createButtonText || t('create')}\n            </Button>\n          )}\n        </div>\n      }\n    />\n  ) : (\n    <div className=\"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4\">\n      <h1 className=\"text-xl font-semibold text-[#1355b7] dark:text-primary-custom-600\">{finalTitle}</h1>\n      {canCreate && (\n        <Button type=\"default\" size=\"base\" className=\"!text-sm font-medium\" leftIcon={<PlusIcon className=\"w-4 h-4\" />} onClick={handleCreate}>\n          {createButtonText || t('create')}\n        </Button>\n      )}\n    </div>\n  );\n\n  return (\n    <div className={containerClasses} id={id} style={{ width: '100%', minWidth: '100%' }}>\n      <Toast\n        isVisible={toastConfig.show}\n        message={toastConfig.message}\n        color={toastConfig.color}\n        onClose={hideToast}\n        position=\"top-right\"\n        className=\"z-[9999]\"\n      />\n\n      {/* Solo renderizamos el listado principal si NO estamos en modo página de creación/edición */}\n      {!(navigationType === 'page' && (viewState === 'CREATE' || viewState === 'EDIT')) ? (\n        <div className=\"flex-1 flex flex-col min-h-0 transition-all duration-300 overflow-hidden\">\n          {/* Contenedor centrado — ancho ideal max-w-7xl (1280px); alinea header y resultados (S2.0) */}\n          <div className=\"flex-1 min-h-0 flex flex-col w-full max-w-7xl mx-auto px-4 md:px-6 py-4 md:py-6 gap-4 md:gap-6\">\n            <div className=\"flex-shrink-0\">\n              {renderToolbar ? renderToolbar({ onSearch: handleSearch, onCreate: handleCreate, searchTerm }) : defaultToolbar}\n            </div>\n\n            <div className=\"flex-1 min-h-0 flex overflow-hidden gap-4\">\n              <div className=\"flex-1 min-h-0 flex flex-col overflow-hidden\">\n              {!canRead ? (\n                <div className=\"flex flex-col items-center justify-center py-20 px-4 text-center\">\n                  <div className=\"w-full max-w-md\">\n                    <Info title={t('errorTitle')} description={t('noPermission')} color=\"red\" />\n                  </div>\n                </div>\n              ) : (\n                <>\n                  {isAdvancedSearchActive && (\n                    <div className=\"mb-4 flex-shrink-0\">\n                      <MasterCrudAdvancedSearch fields={fields} onSearch={handleAdvancedSearch} onClose={toggleAdvancedSearch} initialSearchTerm={searchTerm} initialSearchField={searchField} showConnectors={showAdvancedSearchConnectors} maxFilters={maxAdvancedFilters} filterableFields={filterableFields} columnFilterableFields={effectiveColumnFilterableFields} t={t} />\n                    </div>\n                  )}\n\n                  {viewType === 'list' ? (\n                    data.length > 0 || loading ? (\n                      <div className=\"flex flex-col flex-1 min-h-0 bg-white dark:bg-dark-bg-primary rounded-xl border border-border-primary dark:border-dark-border-primary overflow-hidden w-full\">\n                        <MasterCrudTable fields={fields} data={data} loading={loading} stickyHeader emptyMessage={emptyMessage || t('empty')} onSort={handleSort} sortColumn={sortColumn} sortDirection={sortDirection} pagination={{ currentPage, totalPages, onPageChange: handlePageChange, pageSize: internalPageSize, pageSizeOptions: [10, 25, 50, 100], onPageSizeChange: handlePageSizeChange, totalRecords: total, previousLabel: t('previous', 'Anterior'), nextLabel: t('next', 'Siguiente'), perPageLabel: t('perPage', 'por página'), recordsLabel: t('records', 'registros'), goToPageLabel: t('goToPage', 'Página') }} showRowActions={showRowActions} actions={actionsList} onEdit={canUpdate ? handleEdit : undefined} onDelete={canDelete ? handleDeleteClick : undefined} rowActions={rowActions} locale={locale} enableMultiSelect={enableMultiSelect} selectedIds={selectedIds} onSelectionChange={handleSelectionChange} columnFilterableFields={effectiveColumnFilterableFields} columnFilters={Object.fromEntries(Object.entries(columnFilters).map(([k, v]) => [k, v.value]))} onColumnFilterChange={handleColumnFilterChange} showCompanyStatusColumn={isCompanyScopeActive} isRecordCompanyEnabled={isRecordCompanyEnabled} onCompanyStatusClick={(row) => setLinkModalState({ show: true, record: row as T, variant: 'manual' })} t={t} />\n                      </div>\n                    ) : (\n                      <div className=\"flex flex-1 min-h-0 flex-col items-center justify-center py-20 px-4 text-center\">\n                        {emptyStateConfig?.image ? (typeof emptyStateConfig.image === 'string' ? <img src={emptyStateConfig.image} alt=\"Empty\" className=\"w-48 h-48 mb-6 opacity-50\" /> : <div className=\"mb-6 opacity-50\">{emptyStateConfig.image}</div>) : <div className=\"mb-6 flex items-center justify-center\"><img src={noDataImage} alt=\"No hay registros\" className=\"w-64 h-64 mb-4 object-contain\" /></div>}\n                        <div className=\"w-full max-w-md text-left\">\n                          <Info title={emptyStateConfig?.title || t('emptyTitle', 'Aún no tienes registros')} description={emptyStateConfig?.description || t('emptyDesc', 'Dale click en el botón nuevo para iniciar')} color=\"blue\" />\n                        </div>\n                      </div >\n                    )\n                  ) : (\n                    <div className=\"flex-1 min-h-0 overflow-auto -mx-1 px-1\">\n                    <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4\">\n                      {data.length > 0 ? data.map((record, index) => (\n                        <div key={(record as any)[idField] || index} ref={index === data.length - 1 && viewType === 'grid' && enableGridInfiniteScroll ? lastElementRef : null}>\n                          <MasterCRUDCard data={record} fields={fields} actions={actionsList} onEdit={canUpdate ? handleEdit : undefined} onDelete={canDelete ? handleDeleteClick : undefined} rowActions={rowActions} index={index} renderCardContent={renderCardContent} enableMultiSelect={enableMultiSelect} isSelected={selectedIds.includes((record as any)[idField])} onSelect={(selected) => { if (selected) { setSelectedRecords(prev => [...prev, record]); } else { const id = (record as any)[idField]; setSelectedRecords(prev => prev.filter(item => (item as any)[idField] !== id)); } }} t={t} />\n                        </div>\n                      )) : !loading && (\n                        <div className=\"col-span-full flex flex-col items-center justify-center py-20 px-4 text-center\">\n                          {emptyStateConfig?.image ? (typeof emptyStateConfig.image === 'string' ? <img src={emptyStateConfig.image} alt=\"Empty\" className=\"w-48 h-48 mb-6 opacity-50\" /> : <div className=\"mb-6 opacity-50\">{emptyStateConfig.image}</div>) : <div className=\"mb-6 flex items-center justify-center\"><img src={noDataImage} alt=\"No hay registros\" className=\"w-64 h-64 mb-4 object-contain\" /></div>}\n                          <div className=\"w-full max-w-md text-left\">\n                            <Info title={emptyStateConfig?.title || t('emptyTitle', 'Aún no tienes registros')} description={emptyStateConfig?.description || t('emptyDesc', 'Dale click en el botón nuevo para iniciar')} color=\"blue\" />\n                          </div>\n                        </div >\n                      )}\n                      {loading && Array.from({ length: 4 }).map((_, i) => <div key={i} className=\"h-48 bg-gray-100 dark:bg-gray-800 rounded-2xl animate-pulse\" />)}\n                    </div >\n                    </div >\n                  )}\n                </>\n              )}\n            </div >\n\n            {/* Sidebar Interior (Desplaza al listado) */}\n            {\n              navigationType === 'sidebar' && (viewState === 'CREATE' || viewState === 'EDIT') && (\n                <div className=\"w-[450px] flex-none p-5 pl-0 animate-in slide-in-from-right duration-300 flex flex-col overflow-hidden\">\n                  <div className=\"max-h-full h-fit bg-white dark:bg-dark-bg-primary rounded-2xl overflow-hidden border border-border-secondary dark:border-dark-border-primary flex flex-col shadow-sm\">\n                    <MasterCrudForm\n                      ref={formRef}\n                      fields={fields as any}\n                      entityName={entityName}\n                      initialData={selectedRecord || undefined}\n                      isEditing={viewState === 'EDIT'}\n                      dynamicFeatureCode={dynamicFeatureCode}\n                      hideDynamicTabs={hideDynamicTabs}\n                      loading={formLoading}\n                      onSubmit={handleFormSubmit as any}\n                      onCancel={handleFormCancel}\n                      saveButtonText={saveButtonText || t('save')}\n                      cancelButtonText={cancelButtonText || t('cancel')}\n                      columns={1}\n                      width=\"100%\"\n                      idField={idField as string}\n                      className=\"max-h-full h-fit border-none rounded-none shadow-none\"\n                      actions={(viewState === 'EDIT' ? actionsList : undefined) as any}\n                      selectedCompany={selectedCompany}\n                      activeByCompany={activeByCompany}\n                      companyRequired={companyRequired}\n                      fullWidthButton={true}\n                      showGlobalValues={showGlobalValues}\n                      onSearchMatches={handleSearchMatches as any}\n                      canOverrideMultiCompany={canOverrideMultiCompany}\n                      companies={allCompanies}\n                      onCompanyChange={handleCompanyChange}\n                      onShowGlobalValuesChange={setShowGlobalValues}\n                      onUseGlobalData={() => setShowGlobalResetConfirm(true)}\n                      onCreateNew={handleCreate}\n                      onLinkCompanies={() => setLinkModalState({ show: true, record: selectedRecord, variant: 'manual' })}\n                      renderContent={renderForm as any}\n                      featCodeFileManager={featCodeFileManager}\n                      fileManagerConfig={effectiveFileManagerConfig}\n                      formTabs={formTabs}\n                      t={t}\n                    />\n                  </div>\n                </div>\n              )\n            }\n              </div >\n            </div >\n          </div >\n      ) : (\n        /* Formulario en Modo Página */\n        <div className=\"flex-1 flex flex-col min-h-0 w-full animate-in fade-in duration-300 overflow-hidden\" style={{ width: '100%', minWidth: '100%' }}>\n          {/* Header del detalle: transparente, centrado (max-w-7xl), alineado como el listado (S2.1) */}\n          <div className=\"flex-shrink-0\">\n            <div className=\"max-w-7xl w-full mx-auto px-4 md:px-6 pt-4 md:pt-5 pb-6 space-y-3\">\n              <nav>\n                <button type=\"button\" onClick={handleBackGuarded} className=\"inline-flex items-center gap-1 text-sm text-content-tertiary dark:text-dark-content-tertiary hover:text-[#1355b7] transition-colors\">\n                  <BackIcon className=\"w-4 h-4\" /><span>{t('back', 'Volver')}</span>\n                </button>\n              </nav>\n              <div className=\"flex flex-col md:flex-row md:items-start md:justify-between gap-4\">\n                <div className=\"flex flex-col gap-2 min-w-0\">\n                  {/* Título = solo el nombre del maestro */}\n                  <h1 className=\"text-xl font-semibold tracking-tight text-[#1355b7] dark:text-primary-600 truncate\">{finalTitle}</h1>\n                  {/* CompanySelector (combobox azul) + badges Activo/Edición a su lado (S2.1b) */}\n                  <div className=\"flex items-center gap-2 flex-wrap\">\n                    {activeByCompany && allCompanies.length > 0 && <CompanySelector companies={allCompanies} selectedCompany={selectedCompany} onCompanyChange={(company) => handleCompanyChange(company, (selectedRecord as any)?.[idField])} readOnly={companyRequired} companyEnabledMap={detailCompanyEnabledMap} t={t} />}\n                    {(() => {\n                      const recordActive = (selectedRecord as any)?.[statusField] ?? true;\n                      return (\n                        <span className={`inline-flex items-center h-[18px] px-1.5 text-[10px] font-semibold leading-none rounded ${recordActive ? 'bg-[#ecfccb] text-[#4d7c0f] dark:bg-lime-900/30 dark:text-lime-400' : 'bg-background-secondary text-content-tertiary dark:bg-dark-bg-secondary dark:text-dark-content-tertiary'}`}>\n                          {recordActive ? t('active', 'Activo') : t('inactive', 'Inactivo')}\n                        </span>\n                      );\n                    })()}\n                    <span className=\"inline-flex items-center gap-1 h-[18px] px-1.5 text-[10px] font-semibold leading-none rounded bg-[#fef9c3] text-[#a16207] dark:bg-yellow-900/20 dark:text-yellow-500\">\n                      <PencilIcon className=\"w-3 h-3\" />{viewState === 'EDIT' ? t('editing', 'Edición') : t('creating', 'Creación')}\n                    </span>\n                    {((typeof headerBadges === 'function' ? headerBadges(selectedRecord) : headerBadges || []).length > 0) && (typeof headerBadges === 'function' ? headerBadges(selectedRecord) : headerBadges || []).map((badge, idx) => <Badge key={idx} label={badge.label} color={badge.color} className=\"text-[10px] px-1.5 py-0\" />)}\n                  </div>\n                  {renderHeaderExtra && <div className=\"mt-1\">{renderHeaderExtra(selectedRecord)}</div>}\n                </div>\n                {/* Acciones: Cancelar · Guardar · kebab (h-9, S2.2) */}\n                <div className=\"flex items-center gap-2 flex-shrink-0\">\n                  <Button\n                    type=\"outline\"\n                    size=\"base\"\n                    className=\"!h-9 !px-3 !text-sm font-medium\"\n                    leftIcon={<XMarkIcon className=\"w-4 h-4\" />}\n                    onClick={handleBackGuarded}\n                  >\n                    {cancelButtonText || t('cancel', 'Cancelar')}\n                  </Button>\n                  <Button\n                    type=\"default\"\n                    size=\"base\"\n                    className=\"!h-9 !px-3 !text-sm font-medium\"\n                    leftIcon={\n                      <svg className=\"w-4 h-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z\" /><path d=\"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7\" /><path d=\"M7 3v4a1 1 0 0 0 1 1h7\" /></svg>\n                    }\n                    disabled={formLoading}\n                    onClick={() => { if (formRef.current) formRef.current.submit(); }}\n                  >\n                    {formLoading ? '...' : (saveButtonText || t('save'))}\n                  </Button>\n                  {(viewState === 'EDIT' || (viewState === 'CREATE' && activeByCompany)) && (() => {\n                    const extraActions = actionsList.filter(a => a.id !== 'edit' && a.id !== 'link');\n                    const isGlobal = !selectedCompany || String(selectedCompany.uuid) === '000';\n                    const showMasterData = activeByCompany && viewState === 'EDIT' && !isGlobal && !companyRequired;\n                    const showLinkCreate = activeByCompany && viewState === 'EDIT' && !companyRequired;\n                    const menuItemCls = 'w-full flex items-center gap-2.5 px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors text-left';\n                    const close = () => setDetailActionsOpen(false);\n                    if (!showMasterData && !showLinkCreate && extraActions.length === 0) return null;\n                    return (\n                      <div className=\"relative\" ref={detailActionsRef}>\n                        <button\n                          type=\"button\"\n                          aria-haspopup=\"menu\"\n                          aria-expanded={detailActionsOpen}\n                          title={t('moreActions', 'Más acciones')}\n                          aria-label={t('moreActions', 'Más acciones')}\n                          onClick={() => setDetailActionsOpen(v => !v)}\n                          className=\"inline-flex items-center justify-center w-9 h-9 border border-border-primary dark:border-dark-border-primary rounded-md bg-background-secondary dark:bg-dark-bg-secondary hover:bg-[#ebebec] dark:hover:bg-dark-bg-primary text-content-tertiary transition-colors\"\n                        >\n                          <EllipsisVerticalIcon className=\"w-4 h-4\" />\n                        </button>\n                        {detailActionsOpen && (\n                          <div role=\"menu\" className=\"absolute right-0 top-full mt-1 z-50 min-w-[260px] bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-md shadow-md py-1\">\n                            {showMasterData && (\n                              <>\n                                <button type=\"button\" role=\"menuitem\" className={menuItemCls} onClick={() => { close(); setShowGlobalResetConfirm(true); }}>\n                                  <GlobeAltIcon className=\"w-4 h-4 text-[#1355b7] dark:text-primary-400 flex-shrink-0\" />\n                                  {t('useGlobalData', 'Usar datos maestros')}\n                                </button>\n                                <button type=\"button\" role=\"menuitem\" className={`${menuItemCls} justify-between`} onClick={() => setShowGlobalValues(!showGlobalValues)}>\n                                  <span className=\"flex items-center gap-2.5\"><GlobeAltIcon className=\"w-4 h-4 text-[#1355b7] dark:text-primary-400 flex-shrink-0\" />{t('showGlobalValues', 'Mostrar valores maestros')}</span>\n                                  <span className={`w-7 h-4 rounded-full relative inline-block flex-shrink-0 transition-colors ${showGlobalValues ? 'bg-[#1355b7]' : 'bg-border-primary dark:bg-dark-border-primary'}`}>\n                                    <span className=\"absolute top-0.5 w-3 h-3 rounded-full bg-white shadow transition-all\" style={{ left: showGlobalValues ? '14px' : '2px' }} />\n                                  </span>\n                                </button>\n                              </>\n                            )}\n                            {showLinkCreate && (\n                              <>\n                                {showMasterData && <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />}\n                                <button type=\"button\" role=\"menuitem\" className={menuItemCls} onClick={() => { close(); setLinkModalState({ show: true, record: selectedRecord, variant: 'manual' }); }}>\n                                  <LinkIcon className=\"w-4 h-4 text-content-tertiary flex-shrink-0\" />\n                                  {t('linkCompanies', 'Habilitar compañías')}\n                                </button>\n                                <button type=\"button\" role=\"menuitem\" className={menuItemCls} onClick={() => { close(); setShowCreateConfirm(true); }}>\n                                  <PlusIcon className=\"w-4 h-4 text-content-tertiary flex-shrink-0\" />\n                                  {t('createNew', 'Crear nuevo registro')}\n                                </button>\n                              </>\n                            )}\n                            {extraActions.length > 0 && (showMasterData || showLinkCreate) && <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />}\n                            {extraActions.map(action => {\n                              const actionName = typeof action.name === 'function' ? action.name(selectedRecord!) : action.name;\n                              const actionIcon = typeof action.icon === 'function' ? action.icon(selectedRecord!) : action.icon;\n                              const isDestructive = actionName.toLowerCase().includes('eliminar') || actionName.toLowerCase().includes('desactivar') || actionName.toLowerCase().includes('delete');\n                              const disabled = typeof action.disabled === 'function' ? action.disabled(selectedRecord!) : action.disabled;\n                              return (\n                                <button\n                                  key={action.id || actionName}\n                                  type=\"button\"\n                                  role=\"menuitem\"\n                                  disabled={disabled}\n                                  onClick={() => { close(); action.action?.(selectedRecord!); }}\n                                  className={`w-full flex items-center gap-2.5 px-3 py-2 text-sm text-left transition-colors disabled:opacity-40 ${isDestructive ? 'text-error-content hover:bg-error/10' : 'text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary'}`}\n                                >\n                                  {actionIcon && <span className=\"w-4 h-4 flex-shrink-0 inline-flex items-center justify-center\">{actionIcon}</span>}\n                                  {actionName}\n                                </button>\n                              );\n                            })}\n                          </div>\n                        )}\n                      </div>\n                    );\n                  })()}\n                </div>\n              </div>\n            </div>\n          </div >\n          <div className={`w-full max-w-7xl mx-auto px-4 md:px-6 pb-4 ${detailConfig ? 'flex-1 min-h-0 overflow-auto py-1' : 'flex-1 min-h-0 flex flex-col'}`}>\n            <div className={`w-full bg-white dark:bg-dark-bg-primary rounded-2xl border border-border-primary dark:border-dark-border-primary overflow-hidden ${detailConfig ? 'p-8 min-h-[400px] shadow-xs' : 'flex flex-col flex-1 min-h-0 shadow-sm'}`}>\n              <MasterCrudForm\n                key={`form-page-${viewState}-${(selectedRecord as any)?.[idField] || 'new'}`}\n                ref={formRef}\n                fields={fields as any}\n                entityName={entityName}\n                initialData={selectedRecord || undefined}\n                isEditing={viewState === 'EDIT'}\n                dynamicFeatureCode={dynamicFeatureCode}\n                hideDynamicTabs={hideDynamicTabs}\n                loading={formLoading}\n                onSubmit={handleFormSubmit as any}\n                onCancel={handleFormCancel}\n                saveButtonText={saveButtonText || t('save')}\n                cancelButtonText={cancelButtonText || t('cancel')}\n                columns={formColumns}\n                width=\"100%\"\n                idField={idField as string}\n                className=\"flex-1 min-h-0\"\n                actions={(viewState === 'EDIT' ? actionsList : undefined) as any}\n                selectedCompany={selectedCompany}\n                activeByCompany={activeByCompany}\n                companyRequired={companyRequired}\n                fullWidthButton={false}\n                showGlobalValues={showGlobalValues}\n                onSearchMatches={handleSearchMatches as any}\n                canOverrideMultiCompany={canOverrideMultiCompany}\n                companies={allCompanies}\n                onCompanyChange={handleCompanyChange}\n                onShowGlobalValuesChange={setShowGlobalValues}\n                onUseGlobalData={() => setShowGlobalResetConfirm(true)}\n                onCreateNew={handleCreate}\n                onLinkCompanies={() => setLinkModalState({ show: true, record: selectedRecord, variant: 'manual' })}\n                renderContent={renderForm as any}\n                featCodeFileManager={featCodeFileManager}\n                fileManagerConfig={effectiveFileManagerConfig}\n                showValidationErrorDialog={showValidationErrorDialog}\n                formTabs={formTabs}\n                t={t}\n                hideHeaderFooter={true}\n              />\n            </div >\n\n            {/* ─── Sección de Detalle embebida ─── */}\n            {detailConfig && (\n              viewState === 'EDIT' && globalRecordId != null ? (\n                <MasterCrudDetailSection\n                  masterId={globalRecordId}\n                  config={detailConfig as MasterCrudDetailConfig<any>}\n                  t={t}\n                  locale={locale}\n                  isInsideModal={false}\n                />\n              ) : viewState === 'CREATE' ? (\n                /* Placeholder en CREATE: reserva el mismo espacio visual que ocupará el detalle,\n                   garantizando consistencia de ancho entre CREATE y EDIT. */\n                <div className=\"mt-6 w-full\">\n                  <div className=\"relative flex items-center mb-5\">\n                    <div className=\"flex-grow border-t border-border-primary dark:border-dark-border-primary\" />\n                    <span className=\"mx-3 text-xs font-semibold uppercase tracking-widest text-content-secondary dark:text-content-secondary select-none\">\n                      {(detailConfig as MasterCrudDetailConfig<any>).title || t('details', 'Detalles')}\n                    </span>\n                    <div className=\"flex-grow border-t border-border-primary dark:border-dark-border-primary\" />\n                  </div>\n                  <div className=\"rounded-xl border border-dashed border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-secondary/30 flex items-center justify-center py-10 px-6 text-center\">\n                    <p className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary\">\n                      {t('detailAvailableAfterSave', 'Guarda el registro para gestionar los detalles.')}\n                    </p>\n                  </div>\n                </div>\n              ) : null\n            )}\n          </div >\n        </div >\n      )}\n\n      {(viewState === 'CREATE' || viewState === 'EDIT') && navigationType === 'modal' && (\n        <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4\">\n          {/* Cuando hay detailConfig en modo EDIT, expandir a pantalla casi completa para mostrar la sección de detalle */}\n          <div\n            className={`w-full bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col overflow-hidden ${\n              (detailConfig && viewState === 'EDIT') || maximizeEditModal ? 'h-[95vh]' : 'max-h-[90vh]'\n            }`}\n            style={{ maxWidth: (detailConfig && viewState === 'EDIT') || maximizeEditModal ? '95vw' : formWidth }}\n          >\n            {detailConfig && viewState === 'EDIT' ? (\n              /* Modo Maestro-Detalle: formulario con header/footer propio + detalle scrollable */\n              <>\n                <MasterCrudForm\n                  ref={formRef}\n                  fields={fields as any}\n                  entityName={entityName}\n                  initialData={selectedRecord || undefined}\n                  isEditing={true}\n                  dynamicFeatureCode={dynamicFeatureCode}\n                  hideDynamicTabs={hideDynamicTabs}\n                  loading={formLoading}\n                  onSubmit={handleFormSubmit as any}\n                  onCancel={handleFormCancel}\n                  saveButtonText={saveButtonText || t('save')}\n                  cancelButtonText={cancelButtonText || t('cancel')}\n                  columns={formColumns}\n                  width=\"100%\"\n                  idField={idField as string}\n                  className=\"flex-shrink-0\"\n                  actions={actionsList as any}\n                  selectedCompany={selectedCompany}\n                  activeByCompany={activeByCompany}\n                  companyRequired={companyRequired}\n                  fullWidthButton={false}\n                  showGlobalValues={showGlobalValues}\n                  onSearchMatches={handleSearchMatches as any}\n                  canOverrideMultiCompany={canOverrideMultiCompany}\n                  companies={allCompanies}\n                  onCompanyChange={handleCompanyChange}\n                  onShowGlobalValuesChange={setShowGlobalValues}\n                  onUseGlobalData={() => setShowGlobalResetConfirm(true)}\n                  onCreateNew={handleCreate}\n                  onLinkCompanies={() => setLinkModalState({ show: true, record: selectedRecord, variant: 'manual' })}\n                  renderContent={renderForm as any}\n                  featCodeFileManager={featCodeFileManager}\n                  fileManagerConfig={effectiveFileManagerConfig}\n                  formTabs={formTabs}\n                  t={t}\n                />\n                {/* Sección de detalles con scroll propio, separada visualmente del formulario */}\n                {globalRecordId != null && (\n                  <div className=\"flex-1 overflow-auto px-6 pb-6\">\n                    <MasterCrudDetailSection\n                      masterId={globalRecordId}\n                      config={detailConfig as MasterCrudDetailConfig<any>}\n                      t={t}\n                      locale={locale}\n                      isInsideModal={true}\n                    />\n                  </div>\n                )}\n              </>\n            ) : (\n              /* Modo normal sin detailConfig */\n              <MasterCrudForm\n                ref={formRef}\n                fields={fields as any}\n                entityName={entityName}\n                initialData={selectedRecord || undefined}\n                isEditing={viewState === 'EDIT'}\n                dynamicFeatureCode={dynamicFeatureCode}\n                hideDynamicTabs={hideDynamicTabs}\n                loading={formLoading}\n                onSubmit={handleFormSubmit as any}\n                onCancel={handleFormCancel}\n                saveButtonText={saveButtonText || t('save')}\n                cancelButtonText={cancelButtonText || t('cancel')}\n                columns={formColumns}\n                width=\"100%\"\n                idField={idField as string}\n                className=\"flex-1 min-h-0\"\n                actions={(viewState === 'EDIT' ? actionsList : undefined) as any}\n                selectedCompany={selectedCompany}\n                activeByCompany={activeByCompany}\n                companyRequired={companyRequired}\n                fullWidthButton={false}\n                showGlobalValues={showGlobalValues}\n                onSearchMatches={handleSearchMatches as any}\n                canOverrideMultiCompany={canOverrideMultiCompany}\n                companies={allCompanies}\n                onCompanyChange={handleCompanyChange}\n                onShowGlobalValuesChange={setShowGlobalValues}\n                onUseGlobalData={() => setShowGlobalResetConfirm(true)}\n                onCreateNew={handleCreate}\n                onLinkCompanies={() => setLinkModalState({ show: true, record: selectedRecord, variant: 'manual' })}\n                renderContent={renderForm as any}\n                featCodeFileManager={featCodeFileManager}\n                fileManagerConfig={effectiveFileManagerConfig}\n                formTabs={formTabs}\n                t={t}\n              />\n            )}\n          </div >\n        </div >\n      )}\n\n      <AlertDialog\n        isOpen={showGlobalResetConfirm}\n        type=\"warning\"\n        title={t('confirmGlobalResetTitle', '¿Restaurar a los valores maestros?')}\n        description={t('confirmGlobalResetDesc', 'Se descartarán los cambios locales de esta compañía y los campos volverán a tomar los valores del registro maestro (Global). Esta acción no afecta a otras compañías.')}\n        onCancel={() => setShowGlobalResetConfirm(false)}\n        onConfirm={handleConfirmGlobalReset}\n        cancelText={t('cancelText', 'Cancelar')}\n        confirmText={t('confirmRestore', 'Restaurar valores')}\n      />\n\n      <AlertDialog\n        isOpen={showCreateConfirm}\n        type=\"warning\"\n        title={t('confirmCreateTitle', '¿Crear un nuevo registro?')}\n        description={t('confirmCreateDesc', 'Se descartarán los cambios no guardados del registro actual y se abrirá un formulario en blanco para crear uno nuevo.')}\n        onCancel={() => setShowCreateConfirm(false)}\n        onConfirm={() => { setShowCreateConfirm(false); handleCreate(); }}\n        cancelText={t('cancelText', 'Cancelar')}\n        confirmText={t('confirmCreateBtn', 'Crear nuevo')}\n      />\n\n      <AlertDialog\n        isOpen={linkConfirmState.show && !!linkConfirmState.company}\n        type=\"info\"\n        title={t('linkConfirmTitle', 'Registro no disponible en esta compañía')}\n        onCancel={() => setLinkConfirmState({ show: false, company: null })}\n        onConfirm={handleConfirmDynamicLink}\n        cancelText={t('cancelText', 'Cancelar')}\n        confirmText={t('confirmLink', 'Habilitar y continuar')}\n        description={\n          <div className=\"flex flex-col gap-2\">\n            <p className=\"text-sm leading-5 text-content-secondary dark:text-dark-content-secondary\">\n              {t('linkConfirmLine1', 'Para editar este registro en')}\n              {' '}\n              <span className=\"font-semibold text-content-primary dark:text-dark-content-primary\">\n                {linkConfirmState.company?.name}\n              </span>\n              {t('linkConfirmLine2', ', primero debe estar habilitado en esta compañía.')}\n            </p>\n            <p className=\"text-sm leading-5 text-content-tertiary dark:text-dark-content-tertiary\">\n              {t('linkConfirmLine3', 'Se creará una sobrescritura a partir de los valores del registro maestro (Global). ¿Deseas habilitarlo ahora y continuar?')}\n            </p>\n          </div>\n        }\n      />\n\n      {deleteConfirm.show && (() => {\n        const isActive = !!((deleteConfirm.record as any)[statusField] ?? true);\n        const isBranchContext = activeByCompany && !companyRequired && selectedCompany && String(selectedCompany.uuid) !== '000';\n\n        let title = isActive ? t('confirmDeleteTitle') : t('confirmActivateTitle');\n        let description = isActive ? t('confirmDeleteDesc') : t('confirmActivateDesc');\n        let confirmText = isActive ? t('confirmDeleteText') : t('activate');\n\n        if (softDelete) {\n          // El botón de estado siempre usa terminología de Desactivar/Activar (nunca 'Deshabilitar').\n          // En Sucursal, la descripción aclara que el alcance es la compañía seleccionada.\n          if (isBranchContext) {\n            title = isActive ? t('confirmDeactivateTitle', '¿Estás seguro de desactivar este registro?') : t('confirmActivateTitle', '¿Estás seguro de activar este registro?');\n            description = isActive ? t('confirmDeactivateCompanyDesc', 'El registro dejará de estar disponible en esta compañía.') : t('confirmActivateCompanyDesc', 'El registro volverá a estar disponible en esta compañía.');\n            confirmText = isActive ? t('deactivate', 'Desactivar') : t('activate', 'Activar');\n          } else {\n            // Contexto Global con softDelete: Usar terminología de Desactivar\n            title = isActive ? t('confirmDeactivateTitle', '¿Estás seguro de desactivar este registro?') : t('confirmActivateTitle');\n            description = isActive ? t('confirmDeactivateDesc', 'El registro dejará de estar disponible.') : t('confirmActivateDesc');\n            confirmText = isActive ? t('deactivate', 'Desactivar') : t('activate', 'Activar');\n          }\n        }\n\n        return (\n          <AlertDialog\n            isOpen\n            type={isActive ? 'danger' : 'success'}\n            title={title}\n            description={description}\n            onCancel={() => setDeleteConfirm({ show: false, record: null })}\n            onConfirm={handleDeleteConfirm}\n            cancelText={t('cancelText')}\n            confirmText={confirmText}\n          />\n        );\n      })()}\n\n      {activeByCompany && linkModalState.show && linkModalState.record && (\n        <LinkModal\n          isOpen={linkModalState.show}\n          onClose={() => {\n            const wasSuccess = linkModalState.variant === 'success';\n            setLinkModalState(prev => ({ ...prev, show: false, record: null }));\n            if (wasSuccess) { setViewState('LIST'); setSelectedRecord(null); setGlobalRecordId(null); }\n          }}\n          recordId={(linkModalState.record as any)[idField]}\n          record={linkModalState.record}\n          companies={allCompanies}\n          fields={fields}\n          variant={linkModalState.variant}\n          onConfirm={handleLinkRecords}\n          isLinked={(companyUuid) => checkLinkStatus((linkModalState.record as any)[idField], companyUuid)}\n          t={t}\n        />\n      )}\n\n      {matchModalState.show && (\n        <MatchModal isOpen={matchModalState.show} onClose={() => setMatchModalState(prev => ({ ...prev, show: false }))} matches={matchModalState.matches} fieldName={matchModalState.fieldName} onView={handleViewMatch} onContinue={() => setMatchModalState(prev => ({ ...prev, show: false }))} />\n      )}\n\n      {/* Modal de cambios sin guardar (dirty state) al Volver (S2.8) */}\n      {dirtyModal.show && (\n        <div className=\"fixed inset-0 z-[75] flex items-center justify-center p-4\">\n          <div className=\"absolute inset-0 bg-black/50\" onClick={() => setDirtyModal({ show: false, changes: [] })} />\n          <div className=\"relative w-full max-w-[560px] bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl shadow-2xl overflow-hidden\">\n            <div className=\"p-6\">\n              <div className=\"flex items-start gap-4\">\n                <div className=\"w-10 h-10 flex-shrink-0 rounded-full bg-[#fef9c3] dark:bg-yellow-900/20 flex items-center justify-center\">\n                  <svg className=\"w-6 h-6 text-[#a16207]\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" /><path d=\"M12 9v4\" /><path d=\"M12 17h.01\" /></svg>\n                </div>\n                <div className=\"min-w-0 flex-1\">\n                  <h3 className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\">{t('unsavedTitle', 'Tienes cambios sin guardar')}</h3>\n                  <p className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary mt-1 leading-5\">{t('unsavedDesc', 'Si sales ahora perderás los siguientes cambios. ¿Deseas guardarlos antes de volver al listado?')}</p>\n                  <div className=\"mt-3 rounded-lg border border-border-primary dark:border-dark-border-primary overflow-hidden\">\n                    <p className=\"px-3 py-1.5 bg-background-secondary dark:bg-dark-bg-secondary text-[11px] font-semibold uppercase tracking-[0.3px] text-content-secondary border-b border-border-primary dark:border-dark-border-primary\">{t('modifiedFields', 'Campos modificados')}</p>\n                    <ul className=\"max-h-[180px] overflow-y-auto divide-y divide-border-secondary dark:divide-dark-border-primary\">\n                      {dirtyModal.changes.map((c, i) => (\n                        <li key={i} className=\"px-3 py-2 text-xs\">\n                          <p className=\"font-semibold text-content-primary dark:text-dark-content-primary\">{c.label}</p>\n                          <p className=\"mt-0.5 text-content-tertiary flex items-center gap-1.5 flex-wrap\">\n                            {String(c.from) === '' ? <span className=\"italic text-content-secondary\">({t('emptyValue', 'vacío')})</span> : <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">{String(c.from)}</span>}\n                            <svg className=\"w-3 h-3 text-content-secondary\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M5 12h14\" /><path d=\"m12 5 7 7-7 7\" /></svg>\n                            {String(c.to) === '' ? <span className=\"italic text-content-secondary\">({t('emptyValue', 'vacío')})</span> : <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">{String(c.to)}</span>}\n                          </p>\n                        </li>\n                      ))}\n                    </ul>\n                  </div>\n                </div>\n              </div>\n            </div>\n            <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-border-primary dark:border-dark-border-primary\">\n              <Button type=\"plain\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap\" onClick={() => setDirtyModal({ show: false, changes: [] })}>{t('keepEditing', 'Seguir editando')}</Button>\n              <Button type=\"outline\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap !text-error-content !border-error-content\" onClick={() => { setDirtyModal({ show: false, changes: [] }); handleFormCancel(); }}>{t('discardExit', 'Descartar y salir')}</Button>\n              <Button type=\"default\" size=\"base\" className=\"!h-9 !px-3 !text-sm font-medium whitespace-nowrap\" onClick={() => { setDirtyModal({ show: false, changes: [] }); if (formRef.current) formRef.current.submit(); }}>{t('saveExit', 'Guardar y salir')}</Button>\n            </div>\n          </div>\n        </div>\n      )}\n\n      {previewModalState.show && (\n        <div className=\"fixed inset-0 z-[90] flex items-center justify-center bg-black/50 p-4 animate-in fade-in duration-200\">\n          <div className=\"bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col w-[95vw] h-[95vh] overflow-hidden relative\">\n            <div className=\"flex items-center justify-between p-4 border-b border-border-secondary dark:border-dark-border-primary shrink-0\">\n              <div className=\"flex items-center gap-4\"><h3 className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\">{t('preview', 'Vista Previa')}</h3></div>\n              <Button type=\"outline\" size=\"xs\" iconOnly leftIcon={<XMarkIcon className=\"w-4 h-4\" />} onClick={() => setPreviewModalState(prev => ({ ...prev, show: false }))} ariaLabel={t('close', 'Cerrar')} className=\"!bg-white dark:!bg-dark-bg-primary\" />\n            </div>\n            <div className=\"flex-1 overflow-auto bg-background-secondary dark:bg-dark-bg-primary p-5\">\n              <div className=\"bg-white dark:bg-dark-bg-primary rounded-2xl p-8 w-full min-h-[400px] shadow-xs\">\n                {previewModalState.loading ? (\n                  <div className=\"flex items-center justify-center h-full py-20\">\n                    <div className=\"animate-spin rounded-full h-12 w-12 border-b-2 border-primary-custom-600\"></div>\n                  </div>\n                ) : previewModalState.record && (\n                  renderForm ? renderForm({\n                    fields, entityName, initialData: previewModalState.record,\n                    isEditing: true, loading: false, isReadOnly: true,\n                    onSubmit: () => { }, onCancel: () => { },\n                    columns: formColumns, width: \"100%\", className: \"w-full\",\n                    hideHeaderFooter: true,\n                    selectedCompany: globalCompany,\n                    activeByCompany,\n                    canOverrideMultiCompany,\n                    t\n                  }) :\n                    <MasterCrudForm\n                      fields={fields as any}\n                      entityName={entityName}\n                      initialData={previewModalState.record}\n                      isEditing={true}\n                      loading={false}\n                      isReadOnly={true}\n                      dynamicFeatureCode={dynamicFeatureCode}\n                      hideDynamicTabs={hideDynamicTabs}\n                      onSubmit={() => { }}\n                      onCancel={() => { }}\n                      columns={formColumns}\n                      width=\"100%\"\n                      className=\"w-full\"\n                      hideHeaderFooter={true}\n                      selectedCompany={globalCompany}\n                      activeByCompany={activeByCompany}\n                      companyRequired={companyRequired}\n                      canOverrideMultiCompany={canOverrideMultiCompany}\n                      t={t}\n                    />\n                )}\n              </div>\n            </div>\n            <div className=\"px-[24px] py-[16px] pb-[24px] flex items-center justify-end gap-[12px] shrink-0 w-full border-t border-border-secondary dark:border-dark-border-primary bg-white dark:bg-dark-bg-primary\">\n              <Button type=\"outline\" size=\"l\" onClick={() => setPreviewModalState(prev => ({ ...prev, show: false }))} className=\"font-medium px-6\">{t('cancelText', 'Cancelar')}</Button>\n              <Button type=\"default\" size=\"l\" onClick={() => { const record = previewModalState.record; setPreviewModalState({ show: false, record: null, loading: false }); setMatchModalState(prev => ({ ...prev, show: false })); if (record) handleEdit(record); }} className=\"font-bold px-8\">{t('edit', 'Editar')}</Button>\n            </div>\n          </div>\n        </div>\n      )}\n\n      {showBulkDynamicEditor && dynamicFeatureCode && selectedRecords.length > 0 && (\n        <MasterCrudBulkDynamicEditor\n          featureCode={dynamicFeatureCode}\n          recordIds={selectedRecords.map(r => String((r as any)[idField]))}\n          onClose={() => setShowBulkDynamicEditor(false)}\n          onComplete={handleBulkUpdateComplete}\n          t={t}\n        />\n      )}\n\n      {customModalState.show && (\n        <div className=\"fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4\">\n          <div className={`bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col relative ${maximizeCustomModal ? 'w-[95vw] h-[95vh]' : 'w-full max-w-4xl max-h-[90vh]'}`}>\n            <div className=\"flex items-center justify-between p-4 border-b border-border-secondary dark:border-dark-border-primary\">\n              <div className=\"flex items-center gap-4\">\n                <Button type=\"plain\" size=\"sm\" iconOnly leftIcon={<BackIcon className=\"w-5 h-5\" />} onClick={handleCloseCustomModal} ariaLabel={t('back', 'Volver')} />\n                <h3 className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\">{customModalState.title}</h3>\n              </div>\n              <Button type=\"outline\" size=\"xs\" iconOnly leftIcon={<XMarkIcon className=\"w-4 h-4\" />} onClick={handleCloseCustomModal} ariaLabel={t('close', 'Cerrar')} className=\"!bg-white dark:!bg-dark-bg-primary\" />\n            </div>\n            <div className=\"flex-1 overflow-auto p-4\">{customModalState.content}</div>\n          </div>\n        </div>\n      )}\n\n      {auditModalState.show && auditHistory && auditModalState.record && (\n        <div className=\"fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4\">\n          <div className=\"bg-white dark:bg-dark-bg-primary rounded-xl shadow-2xl flex flex-col relative w-full max-w-3xl max-h-[90vh]\">\n            <div className=\"flex items-center justify-between p-4 border-b border-border-secondary dark:border-dark-border-primary\">\n              <h3 className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\">\n                {t('auditHistory', 'Historial de cambios')}\n              </h3>\n              <Button type=\"outline\" size=\"xs\" iconOnly leftIcon={<XMarkIcon className=\"w-4 h-4\" />}\n                onClick={() => setAuditModalState({ show: false, record: null })}\n                ariaLabel={t('close', 'Cerrar')} className=\"!bg-white dark:!bg-dark-bg-primary\" />\n            </div>\n            <div className=\"flex-1 overflow-hidden\">\n              <AuditHistoryPanel\n                fetchFn={auditHistory.fetchFn}\n                entityId={String((auditModalState.record as any).id ?? (auditModalState.record as any).uuid ?? '')}\n              />\n            </div>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono de sobre (envelope) para el input de email\n */\nexport const EnvelopeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n\n/**\n * Icono de candado cerrado (lock) para el input de contraseña\n */\nexport const LockClosedIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V7A1.5 1.5 0 0 0 3 8.5v5A1.5 1.5 0 0 0 4.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 11.5 7V4.5A3.5 3.5 0 0 0 8 1Zm2 6V4.5a2 2 0 1 0-4 0V7h4Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono de ojo (eye) para mostrar/ocultar contraseña\n */\nexport const EyeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z\" />\n    <path\n      fillRule=\"evenodd\"\n      d=\"M1.38 8.28a.87.87 0 0 1 0-.566 7.003 7.003 0 0 1 13.238.006.87.87 0 0 1 0 .56A7.003 7.003 0 0 1 1.379 8.28ZM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Logo de Siesa\n */\nexport const SiesaLogo: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    width=\"200\"\n    height=\"50\"\n    viewBox=\"0 0 200 50\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    {...props}\n  >\n    {/* Símbolo de Siesa (cuadrados azules) */}\n    <rect x=\"0\" y=\"0\" width=\"15\" height=\"20\" fill=\"#0e79fd\" />\n    <rect x=\"0\" y=\"30\" width=\"10\" height=\"20\" fill=\"#0e79fd\" />\n    <rect x=\"20\" y=\"0\" width=\"15\" height=\"20\" fill=\"#0e79fd\" />\n    <rect x=\"30\" y=\"30\" width=\"10\" height=\"20\" fill=\"#0e79fd\" />\n\n    {/* Texto \"Siesa\" */}\n    <text\n      x=\"68\"\n      y=\"35\"\n      fontFamily=\"Inter, sans-serif\"\n      fontSize=\"32\"\n      fontWeight=\"400\"\n      fill=\"#0e79fd\"\n    >\n      Siesa\n    </text>\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type { FormEvent } from 'react';\nimport type { LoginViewProps } from './LoginView.types';\nimport { EnvelopeIcon, LockClosedIcon, EyeIcon } from './icons';\n\n/**\n * LoginView - Vista de inicio de sesión del sistema Siesa\n *\n * Vista completa de login con formulario de autenticación que incluye:\n * - Logo de Siesa\n * - Campos de email y contraseña\n * - Opción de \"olvidé mi contraseña\"\n * - Link para crear cuenta nueva\n * - Fondo decorativo opcional\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels y manejo de formulario semántico\n * - Validación de email básica\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * <LoginView\n *   onSubmit={(email, password) => console.log('Login', email, password)}\n *   onForgotPassword={() => console.log('Forgot password')}\n *   onSignUp={() => console.log('Sign up')}\n * />\n * ```\n */\nexport const LoginView: React.FC<LoginViewProps> = ({\n  onSubmit,\n  onForgotPassword,\n  onSignUp,\n  isLoading = false,\n  errorMessage,\n  className = '',\n  showBackground = true,\n  variant = 'responsive',\n}) => {\n  // ===== ESTADO LOCAL =====\n  const [email, setEmail] = useState('');\n  const [password, setPassword] = useState('');\n  const [showPassword, setShowPassword] = useState(false);\n  const [emailError, setEmailError] = useState('');\n\n  // ===== HANDLERS =====\n  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n\n    // Validación básica de email\n    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n    if (!emailRegex.test(email)) {\n      setEmailError('Por favor ingresa un email válido');\n      return;\n    }\n\n    setEmailError('');\n    onSubmit?.(email, password);\n  };\n\n  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n    if (emailError) setEmailError('');\n  };\n\n  const togglePasswordVisibility = () => {\n    setShowPassword(!showPassword);\n  };\n\n  return (\n    <div\n      className={[\n        'relative',\n        'min-h-screen',\n        'w-full',\n        'flex',\n        'flex-col',\n        'items-center',\n        'justify-center',\n        'box-border',\n        // Mobile: sin padding en el wrapper (el padding está en el contenedor)\n        'p-0',\n        // Desktop: padding para centrar el card\n        'md:p-4',\n        className,\n      ].join(' ')}\n    >\n      {/* ===== FONDO DECORATIVO ===== */}\n      {showBackground && (\n        <div className=\"absolute inset-0 pointer-events-none\" aria-hidden=\"true\">\n          <div className=\"absolute inset-0 bg-primary-100 dark:bg-dark-bg-custom\" />\n          <img\n            src=\"/bg_siesa.png\"\n            alt=\"\"\n            className=\"absolute inset-0 w-full h-full object-cover opacity-10\"\n          />\n        </div>\n      )}\n\n      {/* ===== CONTENEDOR PRINCIPAL ===== */}\n      <div\n        className={[\n          // Clases base comunes\n          'relative',\n          'box-border',\n          'flex',\n          'flex-col',\n          'items-center',\n          'justify-center',\n          'gap-4',\n          'p-16',\n          'shrink-0',\n          'bg-bg-primary',\n          'dark:bg-dark-bg-primary',\n\n          // Clases específicas según variant\n          ...(variant === 'mobile' ? [\n            // Forzar mobile: sin efectos de card\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n          ] : variant === 'desktop' ? [\n            // Forzar desktop: con efectos de card\n            'w-[400px]',\n            'h-auto',\n            'rounded-2xl',\n            'shadow-lg',\n            'dark:shadow-2xl',\n            'overflow-clip',\n            'border',\n            'border-transparent',\n            'dark:border-dark-border-primary',\n          ] : [\n            // Responsive: cambia según viewport\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n            'md:w-[400px]',\n            'md:h-auto',\n            'md:rounded-2xl',\n            'md:shadow-lg',\n            'md:dark:shadow-2xl',\n            'md:overflow-clip',\n            'md:border',\n            'md:border-transparent',\n            'md:dark:border-dark-border-primary',\n          ]),\n        ].join(' ')}\n      >\n        {/* ===== LOGO ===== */}\n        <div className=\"w-full flex flex-col items-center pb-4\">\n          <img\n            src=\"/.Siesa Logo.png\"\n            alt=\"Siesa\"\n            className=\"w-[200px] h-[50px] object-contain\"\n          />\n        </div>\n\n        {/* ===== HEADING ===== */}\n        <div className=\"w-full text-center\">\n          <h1\n            className={[\n              'text-[20px]',\n              'leading-[28px]',\n              'font-bold',\n              'tracking-[-0.5px]',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Iniciar Sesión\n          </h1>\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Inicia sesión ingresando con tu correo electrónico y contraseña.\n          </p>\n        </div>\n\n        {/* ===== MENSAJE DE ERROR GENERAL ===== */}\n        {errorMessage && (\n          <div\n            className={[\n              'w-full',\n              'p-3',\n              'bg-error-bg',\n              'dark:bg-error-bg',\n              'border',\n              'border-error-border',\n              'dark:border-error-border',\n              'rounded-md',\n              'text-error-content',\n              'dark:text-error-content',\n              'text-sm',\n            ].join(' ')}\n            role=\"alert\"\n          >\n            {errorMessage}\n          </div>\n        )}\n\n        {/* ===== FORMULARIO ===== */}\n        <form onSubmit={handleSubmit} className=\"w-full flex flex-col gap-2\">\n          {/* Email Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"email-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Correo Electrónico <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <EnvelopeIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"email-input\"\n                type=\"email\"\n                placeholder=\"ejemplo@miempresa.com\"\n                value={email}\n                onChange={handleEmailChange}\n                disabled={isLoading}\n                required\n                autoComplete=\"email\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                  emailError ? 'border-error-border!' : '',\n                ].filter(Boolean).join(' ')}\n              />\n            </div>\n            {emailError && (\n              <p className=\"text-xs text-error-content dark:text-error-content\">\n                {emailError}\n              </p>\n            )}\n          </div>\n\n          {/* Password Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <div className=\"flex items-center justify-between\">\n              <label\n                htmlFor=\"password-input\"\n                className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n              >\n                Contraseña <span className=\"text-red-600\">*</span>\n              </label>\n              <button\n                type=\"button\"\n                onClick={onForgotPassword}\n                className=\"text-[12px] leading-4 font-bold text-primary-600 dark:text-[#93d1fd] hover:underline transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-[#93d1fd] rounded-sm px-1\"\n              >\n                Olvidé mi Contraseña\n              </button>\n            </div>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <LockClosedIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"password-input\"\n                type={showPassword ? 'text' : 'password'}\n                placeholder=\"••••••••\"\n                value={password}\n                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}\n                disabled={isLoading}\n                required\n                autoComplete=\"current-password\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-10',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                ].join(' ')}\n              />\n              <button\n                type=\"button\"\n                onClick={togglePasswordVisibility}\n                className=\"absolute right-3 top-1/2 -translate-y-1/2 opacity-50 hover:opacity-100 text-content-tertiary dark:text-dark-content-tertiary transition-opacity duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-dark-border-custom rounded-sm p-1\"\n                aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}\n              >\n                <EyeIcon className=\"w-4 h-4\" />\n              </button>\n            </div>\n          </div>\n\n          {/* Submit Button */}\n          <button\n            type=\"submit\"\n            disabled={isLoading || !email || !password}\n            className={[\n              'relative',\n              'w-full',\n              'px-2.5',\n              'py-1.5',\n              'flex',\n              'items-center',\n              'justify-center',\n              'gap-2',\n              'font-bold',\n              'text-sm',\n              'leading-5',\n              'text-primary-inverse-content',\n              'dark:text-[#0e79fd]',\n              'bg-[#0e79fd]',\n              'dark:bg-dark-bg-inverse',\n              'border',\n              'border-[#3c9bf6]',\n              'dark:border-[#93d1fd]',\n              'rounded-md',\n              'shadow-button-inset',\n              'hover:bg-primary-500',\n              'dark:hover:bg-[#93d1fd]',\n              'active:scale-95',\n              'transition-all',\n              'duration-150',\n              'focus:outline-hidden',\n              'focus:ring-2',\n              'focus:ring-primary-400',\n              'dark:focus:ring-[#93d1fd]',\n              'focus:ring-offset-2',\n              'dark:focus:ring-offset-[#3f3f46]',\n              'disabled:opacity-50',\n              'disabled:cursor-not-allowed',\n            ].join(' ')}\n          >\n            {isLoading ? 'Iniciando sesión...' : 'Iniciar Sesión'}\n          </button>\n        </form>\n\n        {/* ===== SIGN UP LINK ===== */}\n        <button\n          type=\"button\"\n          onClick={onSignUp}\n          className={[\n            'w-full',\n            'px-2.5',\n            'py-1.5',\n            'flex',\n            'items-center',\n            'justify-center',\n            'gap-2',\n            'font-bold',\n            'text-sm',\n            'leading-5',\n            'text-[#0e79fd]',\n            'dark:text-[#93d1fd]',\n            'hover:bg-primary-100',\n            'dark:hover:bg-[#93d1fd]/10',\n            'rounded-md',\n            'transition-all',\n            'duration-150',\n            'focus:outline-hidden',\n            'focus:ring-2',\n            'focus:ring-primary-400',\n            'dark:focus:ring-[#93d1fd]',\n            'focus:ring-offset-2',\n            'dark:focus:ring-offset-[#3f3f46]',\n          ].join(' ')}\n        >\n          ¿No tienes una cuenta?\n        </button>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono de círculo de usuario para el input de nombre\n */\nexport const UserCircleIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M15 8A7 7 0 1 1 1 8a7 7 0 0 1 14 0Zm-5-2a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM8 9c-1.825 0-3.422.977-4.295 2.437A5.49 5.49 0 0 0 8 13.5a5.49 5.49 0 0 0 4.294-2.063A4.997 4.997 0 0 0 8 9Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono de sobre (envelope) para el input de email\n */\nexport const EnvelopeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n\n/**\n * Icono de candado cerrado (lock) para el input de contraseña\n */\nexport const LockClosedIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V7A1.5 1.5 0 0 0 3 8.5v5A1.5 1.5 0 0 0 4.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 11.5 7V4.5A3.5 3.5 0 0 0 8 1Zm2 6V4.5a2 2 0 1 0-4 0V7h4Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono de ojo (eye) para mostrar/ocultar contraseña\n */\nexport const EyeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z\" />\n    <path\n      fillRule=\"evenodd\"\n      d=\"M1.38 8.28a.87.87 0 0 1 0-.566 7.003 7.003 0 0 1 13.238.006.87.87 0 0 1 0 .56A7.003 7.003 0 0 1 1.379 8.28ZM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type { FormEvent } from 'react';\nimport type { SignUpViewProps } from './SignUpView.types';\nimport { UserCircleIcon, EnvelopeIcon, LockClosedIcon, EyeIcon } from './icons';\n\n/**\n * SignUpView - Vista de registro del sistema Siesa\n *\n * Vista completa de registro con formulario que incluye:\n * - Logo de Siesa\n * - Campos de nombre, email y contraseña\n * - Botón de registro\n * - Link para iniciar sesión\n * - Texto de términos y condiciones\n * - Fondo decorativo opcional\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels y manejo de formulario semántico\n * - Validación de email básica\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * <SignUpView\n *   onSubmit={(name, email, password) => console.log('Sign up', name, email, password)}\n *   onSignIn={() => console.log('Go to sign in')}\n *   onTermsClick={() => console.log('View terms')}\n *   onPrivacyClick={() => console.log('View privacy')}\n * />\n * ```\n */\nexport const SignUpView: React.FC<SignUpViewProps> = ({\n  onSubmit,\n  onSignIn,\n  onTermsClick,\n  onPrivacyClick,\n  isLoading = false,\n  errorMessage,\n  className = '',\n  showBackground = true,\n  variant = 'responsive',\n}) => {\n  // ===== ESTADO LOCAL =====\n  const [name, setName] = useState('');\n  const [email, setEmail] = useState('');\n  const [password, setPassword] = useState('');\n  const [showPassword, setShowPassword] = useState(false);\n  const [emailError, setEmailError] = useState('');\n\n  // ===== HANDLERS =====\n  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n\n    // Validación básica de email\n    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n    if (!emailRegex.test(email)) {\n      setEmailError('Por favor ingresa un email válido');\n      return;\n    }\n\n    setEmailError('');\n    onSubmit?.(name, email, password);\n  };\n\n  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n    if (emailError) setEmailError('');\n  };\n\n  const togglePasswordVisibility = () => {\n    setShowPassword(!showPassword);\n  };\n\n  return (\n    <div\n      className={[\n        'relative',\n        'min-h-screen',\n        'w-full',\n        'flex',\n        'flex-col',\n        'items-center',\n        'justify-center',\n        'box-border',\n        // Mobile: sin padding en el wrapper\n        'p-0',\n        // Desktop: padding para centrar el card\n        'md:p-4',\n        className,\n      ].join(' ')}\n    >\n      {/* ===== FONDO DECORATIVO ===== */}\n      {showBackground && (\n        <div className=\"absolute inset-0 pointer-events-none\" aria-hidden=\"true\">\n          <div className=\"absolute inset-0 bg-primary-100 dark:bg-dark-bg-custom\" />\n          <img\n            src=\"/bg_siesa.png\"\n            alt=\"\"\n            className=\"absolute inset-0 w-full h-full object-cover opacity-10\"\n          />\n        </div>\n      )}\n\n      {/* ===== CONTENEDOR PRINCIPAL ===== */}\n      <div\n        className={[\n          // Clases base comunes\n          'relative',\n          'box-border',\n          'flex',\n          'flex-col',\n          'items-center',\n          'justify-center',\n          'gap-4',\n          'p-16',\n          'shrink-0',\n          'bg-bg-primary',\n          'dark:bg-dark-bg-primary',\n\n          // Clases específicas según variant\n          ...(variant === 'mobile' ? [\n            // Forzar mobile: sin efectos de card\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n          ] : variant === 'desktop' ? [\n            // Forzar desktop: con efectos de card\n            'w-[400px]',\n            'h-auto',\n            'rounded-2xl',\n            'shadow-lg',\n            'dark:shadow-2xl',\n            'overflow-clip',\n            'border',\n            'border-transparent',\n            'dark:border-dark-border-primary',\n          ] : [\n            // Responsive: cambia según viewport\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n            'md:w-[400px]',\n            'md:h-auto',\n            'md:rounded-2xl',\n            'md:shadow-lg',\n            'md:dark:shadow-2xl',\n            'md:overflow-clip',\n            'md:border',\n            'md:border-transparent',\n            'md:dark:border-dark-border-primary',\n          ]),\n        ].join(' ')}\n      >\n        {/* ===== LOGO ===== */}\n        <div className=\"w-full flex flex-col items-center pb-4\">\n          <img\n            src=\"/.Siesa Logo.png\"\n            alt=\"Siesa\"\n            className=\"w-[200px] h-[50px] object-contain\"\n          />\n        </div>\n\n        {/* ===== HEADING ===== */}\n        <div className=\"w-full text-center\">\n          <h1\n            className={[\n              'text-[20px]',\n              'leading-[28px]',\n              'font-bold',\n              'tracking-[-0.5px]',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Crear Cuenta\n          </h1>\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Ingresa todos los datos para crear tu cuenta.\n          </p>\n        </div>\n\n        {/* ===== MENSAJE DE ERROR GENERAL ===== */}\n        {errorMessage && (\n          <div\n            className={[\n              'w-full',\n              'p-3',\n              'bg-error-bg',\n              'dark:bg-error-bg',\n              'border',\n              'border-error-border',\n              'dark:border-error-border',\n              'rounded-md',\n              'text-error-content',\n              'dark:text-error-content',\n              'text-sm',\n            ].join(' ')}\n            role=\"alert\"\n          >\n            {errorMessage}\n          </div>\n        )}\n\n        {/* ===== FORMULARIO ===== */}\n        <form onSubmit={handleSubmit} className=\"w-full flex flex-col gap-2\">\n          {/* Name Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"name-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Nombre <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <UserCircleIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"name-input\"\n                type=\"text\"\n                placeholder=\"Juan Pérez\"\n                value={name}\n                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}\n                disabled={isLoading}\n                required\n                autoComplete=\"name\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                ].join(' ')}\n              />\n            </div>\n          </div>\n\n          {/* Email Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"email-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Correo Electrónico <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <EnvelopeIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"email-input\"\n                type=\"email\"\n                placeholder=\"ejemplo@miempresa.com\"\n                value={email}\n                onChange={handleEmailChange}\n                disabled={isLoading}\n                required\n                autoComplete=\"email\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                  emailError ? 'border-error-border!' : '',\n                ].filter(Boolean).join(' ')}\n              />\n            </div>\n            {emailError && (\n              <p className=\"text-xs text-error-content dark:text-error-content\">\n                {emailError}\n              </p>\n            )}\n          </div>\n\n          {/* Password Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"password-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Contraseña <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <LockClosedIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"password-input\"\n                type={showPassword ? 'text' : 'password'}\n                placeholder=\"••••••••\"\n                value={password}\n                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}\n                disabled={isLoading}\n                required\n                autoComplete=\"new-password\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-10',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                ].join(' ')}\n              />\n              <button\n                type=\"button\"\n                onClick={togglePasswordVisibility}\n                className=\"absolute right-3 top-1/2 -translate-y-1/2 opacity-50 hover:opacity-100 text-content-tertiary dark:text-dark-content-tertiary transition-opacity duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-dark-border-custom rounded-sm p-1\"\n                aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}\n              >\n                <EyeIcon className=\"w-4 h-4\" />\n              </button>\n            </div>\n          </div>\n\n          {/* Submit Button */}\n          <button\n            type=\"submit\"\n            disabled={isLoading || !name || !email || !password}\n            className={[\n              'relative',\n              'w-full',\n              'px-2.5',\n              'py-1.5',\n              'flex',\n              'items-center',\n              'justify-center',\n              'gap-2',\n              'font-bold',\n              'text-sm',\n              'leading-5',\n              'text-primary-inverse-content',\n              'dark:text-[#0e79fd]',\n              'bg-[#0e79fd]',\n              'dark:bg-dark-bg-inverse',\n              'border',\n              'border-[#3c9bf6]',\n              'dark:border-[#93d1fd]',\n              'rounded-md',\n              'shadow-button-inset',\n              'hover:bg-primary-500',\n              'dark:hover:bg-[#93d1fd]',\n              'active:scale-95',\n              'transition-all',\n              'duration-150',\n              'focus:outline-hidden',\n              'focus:ring-2',\n              'focus:ring-primary-400',\n              'dark:focus:ring-[#93d1fd]',\n              'focus:ring-offset-2',\n              'dark:focus:ring-offset-[#3f3f46]',\n              'disabled:opacity-50',\n              'disabled:cursor-not-allowed',\n            ].join(' ')}\n          >\n            {isLoading ? 'Registrando...' : 'Registrarse'}\n          </button>\n        </form>\n\n        {/* ===== SIGN IN LINK ===== */}\n        <button\n          type=\"button\"\n          onClick={onSignIn}\n          className={[\n            'w-full',\n            'px-2.5',\n            'py-1.5',\n            'flex',\n            'items-center',\n            'justify-center',\n            'gap-2',\n            'font-bold',\n            'text-sm',\n            'leading-5',\n            'text-[#0e79fd]',\n            'dark:text-[#93d1fd]',\n            'hover:bg-primary-100',\n            'dark:hover:bg-[#93d1fd]/10',\n            'rounded-md',\n            'transition-all',\n            'duration-150',\n            'focus:outline-hidden',\n            'focus:ring-2',\n            'focus:ring-primary-400',\n            'dark:focus:ring-[#93d1fd]',\n            'focus:ring-offset-2',\n            'dark:focus:ring-offset-[#3f3f46]',\n          ].join(' ')}\n        >\n          Ya tengo una cuenta\n        </button>\n\n        {/* ===== TÉRMINOS Y CONDICIONES ===== */}\n        <div className=\"w-full text-center\">\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Al registrarse, estás aceptando nuestras{' '}\n            <button\n              type=\"button\"\n              onClick={onTermsClick}\n              className=\"text-[#0e79fd] dark:text-[#93d1fd] underline hover:no-underline focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-[#93d1fd] rounded-sm\"\n            >\n              Condiciones de Uso\n            </button>\n            {' '}y nuestras{' '}\n            <button\n              type=\"button\"\n              onClick={onPrivacyClick}\n              className=\"text-[#0e79fd] dark:text-[#93d1fd] underline hover:no-underline focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-[#93d1fd] rounded-sm\"\n            >\n              Políticas de Privacidad\n            </button>\n            .\n          </p>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React, { useRef, useCallback, useEffect } from 'react';\nimport { Input } from '../Input/Input';\n\ninterface ParameterEditorSearchBarProps {\n  value: string;\n  onChange: (value: string) => void;\n  placeholder?: string;\n}\n\nconst SearchIcon = (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 20 20\"\n    fill=\"currentColor\"\n    className=\"w-4 h-4\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M9 3.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11ZM2 9a7 7 0 1 1 12.452 4.391l3.328 3.329a.75.75 0 1 1-1.06 1.06l-3.329-3.328A7 7 0 0 1 2 9Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const ParameterEditorSearchBar: React.FC<ParameterEditorSearchBarProps> = ({\n  value,\n  onChange,\n  placeholder = 'Buscar campo a configurar',\n}) => {\n  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(() => {\n    return () => {\n      if (debounceRef.current) clearTimeout(debounceRef.current);\n    };\n  }, []);\n\n  const handleChange = useCallback(\n    (e: React.ChangeEvent<HTMLInputElement>) => {\n      const newValue = e.target.value;\n\n      if (debounceRef.current) {\n        clearTimeout(debounceRef.current);\n      }\n\n      debounceRef.current = setTimeout(() => {\n        onChange(newValue);\n      }, 300);\n    },\n    [onChange]\n  );\n\n  return (\n    <Input\n      startIcon={SearchIcon as React.ReactElement}\n      placeholder={placeholder}\n      defaultValue={value}\n      onChange={handleChange}\n    />\n  );\n};\n","import React, { useRef, useState, useEffect, useCallback } from 'react';\nimport { Tab } from '../Tabs/Tabs';\nimport { Button } from '../Button/Button';\n\ninterface ScrollableTabItem {\n  id: string;\n  label: string;\n  badge?: number;\n}\n\ninterface ParameterEditorScrollableTabsProps {\n  tabs: ScrollableTabItem[];\n  activeId: string;\n  onChange: (id: string) => void;\n}\n\nexport const ParameterEditorScrollableTabs: React.FC<ParameterEditorScrollableTabsProps> = ({\n  tabs,\n  activeId,\n  onChange,\n}) => {\n  const scrollRef = useRef<HTMLDivElement>(null);\n  const [showLeftArrow, setShowLeftArrow] = useState(false);\n  const [showRightArrow, setShowRightArrow] = useState(false);\n\n  const updateArrows = useCallback(() => {\n    const el = scrollRef.current;\n    if (!el) return;\n    setShowLeftArrow(el.scrollLeft > 0);\n    setShowRightArrow(el.scrollLeft + el.clientWidth < el.scrollWidth - 1);\n  }, []);\n\n  useEffect(() => {\n    const el = scrollRef.current;\n    if (!el) return;\n\n    updateArrows();\n\n    el.addEventListener('scroll', updateArrows, { passive: true });\n\n    const observer = new ResizeObserver(updateArrows);\n    observer.observe(el);\n\n    return () => {\n      el.removeEventListener('scroll', updateArrows);\n      observer.disconnect();\n    };\n  }, [updateArrows, tabs]);\n\n  const scroll = (direction: 'left' | 'right') => {\n    const el = scrollRef.current;\n    if (!el) return;\n    el.scrollBy({\n      left: direction === 'left' ? -200 : 200,\n      behavior: 'smooth',\n    });\n  };\n\n  // Arrow icons as inline SVGs\n  const ChevronLeft = (\n    <svg\n      xmlns=\"http://www.w3.org/2000/svg\"\n      viewBox=\"0 0 20 20\"\n      fill=\"currentColor\"\n      className=\"w-4 h-4\"\n    >\n      <path\n        fillRule=\"evenodd\"\n        d=\"M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z\"\n        clipRule=\"evenodd\"\n      />\n    </svg>\n  );\n\n  const ChevronRight = (\n    <svg\n      xmlns=\"http://www.w3.org/2000/svg\"\n      viewBox=\"0 0 20 20\"\n      fill=\"currentColor\"\n      className=\"w-4 h-4\"\n    >\n      <path\n        fillRule=\"evenodd\"\n        d=\"M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 1 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z\"\n        clipRule=\"evenodd\"\n      />\n    </svg>\n  );\n\n  return (\n    <div className=\"relative flex items-center border-b border-border-primary dark:border-dark-border-primary px-4 pt-2\">\n      {showLeftArrow && (\n        <Button\n          type=\"plain\"\n          size=\"sm\"\n          iconOnly\n          leftIcon={ChevronLeft}\n          onClick={() => scroll('left')}\n          ariaLabel=\"Desplazar tabs a la izquierda\"\n          className=\"shrink-0 z-10\"\n        />\n      )}\n\n      <div\n        ref={scrollRef}\n        className=\"flex overflow-x-auto overflow-y-hidden scroll-smooth scrollbar-hide flex-1\"\n        style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}\n      >\n        <div className=\"flex items-end pb-2.5 gap-2\">\n          {tabs.map((tab) => (\n            <Tab\n              key={tab.id}\n              label={tab.label}\n              active={tab.id === activeId}\n              badge={tab.badge}\n              onClick={() => onChange(tab.id)}\n            />\n          ))}\n        </div>\n      </div>\n\n      {showRightArrow && (\n        <Button\n          type=\"plain\"\n          size=\"sm\"\n          iconOnly\n          leftIcon={ChevronRight}\n          onClick={() => scroll('right')}\n          ariaLabel=\"Desplazar tabs a la derecha\"\n          className=\"shrink-0 z-10\"\n        />\n      )}\n    </div>\n  );\n};\n","import type {\n  ParameterCategory,\n  ParameterDefinition,\n  ParameterChange,\n  ParameterSavePayload,\n} from './ParameterEditor.types';\n\n/**\n * Strips diacritics (tildes, accents) for accent-insensitive comparison.\n * Only used at comparison time — never mutates the original data.\n */\nfunction stripDiacritics(text: string): string {\n  return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '');\n}\n\n/**\n * Returns all parameters from a category (direct + from sections).\n */\nexport function getAllCategoryParameters(\n  category: ParameterCategory\n): ParameterDefinition[] {\n  const direct = category.parameters ?? [];\n  const fromSections = (category.sections ?? []).flatMap((s) => s.parameters);\n  return [...direct, ...fromSections];\n}\n\n/**\n * Builds the initial values map from dataSource.\n * Maps parameterId -> resolvedValue\n */\nexport function buildOriginalValues(\n  dataSource: ParameterCategory[]\n): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const cat of dataSource) {\n    for (const param of getAllCategoryParameters(cat)) {\n      map.set(param.id, param.resolvedValue);\n    }\n  }\n  return map;\n}\n\n/**\n * Validates a parameter value against its validation rules.\n * Returns an error message if invalid, or empty string if valid.\n */\nexport function validateParameter(\n  param: ParameterDefinition,\n  value: string\n): string {\n  if (!param.validations || param.validations.length === 0) return '';\n\n  for (const rule of param.validations) {\n    switch (rule.ruleType) {\n      case 'REGEX':\n      case 'FORMAT': {\n        try {\n          const regex = new RegExp(rule.ruleValue);\n          if (!regex.test(value)) return rule.errorMessage;\n        } catch {\n          // Invalid regex, skip validation\n        }\n        break;\n      }\n      case 'MIN': {\n        const numVal = parseFloat(value);\n        const minVal = parseFloat(rule.ruleValue);\n        if (!isNaN(numVal) && !isNaN(minVal) && numVal < minVal) {\n          return rule.errorMessage;\n        }\n        break;\n      }\n      case 'MAX': {\n        const numVal = parseFloat(value);\n        const maxVal = parseFloat(rule.ruleValue);\n        if (!isNaN(numVal) && !isNaN(maxVal) && numVal > maxVal) {\n          return rule.errorMessage;\n        }\n        break;\n      }\n      case 'MAX_LENGTH': {\n        const maxLen = parseInt(rule.ruleValue, 10);\n        if (!isNaN(maxLen) && value.length > maxLen) {\n          return rule.errorMessage;\n        }\n        break;\n      }\n    }\n  }\n\n  return '';\n}\n\n/**\n * Filters parameters by search term.\n * Matches against name, code, and description (case-insensitive).\n */\nexport function filterParameters(\n  parameters: ParameterDefinition[],\n  searchTerm: string\n): ParameterDefinition[] {\n  if (!searchTerm.trim()) return parameters;\n  const term = stripDiacritics(searchTerm.toLowerCase());\n  return parameters.filter(\n    (p) =>\n      stripDiacritics(p.name.toLowerCase()).includes(term) ||\n      stripDiacritics(p.code.toLowerCase()).includes(term) ||\n      stripDiacritics(p.description.toLowerCase()).includes(term)\n  );\n}\n\n/**\n * Returns visible parameters sorted by sortOrder.\n */\nexport function getVisibleParameters(\n  parameters: ParameterDefinition[]\n): ParameterDefinition[] {\n  return parameters\n    .filter((p) => p.isVisible !== false)\n    .sort((a, b) => a.sortOrder - b.sortOrder);\n}\n\n/**\n * Gets the count of changes for a specific category.\n */\nexport function getCategoryChangeCount(\n  category: ParameterCategory,\n  editedValues: Map<string, string>,\n  originalValues: Map<string, string>\n): number {\n  let count = 0;\n  for (const param of getAllCategoryParameters(category)) {\n    const edited = editedValues.get(param.id);\n    const original = originalValues.get(param.id);\n    if (edited !== undefined && edited !== original) {\n      count++;\n    }\n  }\n  return count;\n}\n\n/**\n * Gets the total count of all changes across dataSource.\n */\nexport function getTotalChangeCount(\n  editedValues: Map<string, string>,\n  originalValues: Map<string, string>\n): number {\n  let count = 0;\n  for (const [id, value] of editedValues) {\n    if (value !== originalValues.get(id)) {\n      count++;\n    }\n  }\n  return count;\n}\n\n/**\n * Builds the list of changes for the confirm panel.\n */\nexport function buildChangeList(\n  dataSource: ParameterCategory[],\n  editedValues: Map<string, string>,\n  originalValues: Map<string, string>,\n  entityDisplayLabels?: Map<string, string>\n): ParameterChange[] {\n  const changes: ParameterChange[] = [];\n\n  const pushChange = (\n    param: ParameterDefinition,\n    catName: string,\n    catId: string,\n    sectionName?: string,\n    sectionId?: string\n  ) => {\n    const edited = editedValues.get(param.id);\n    const original = originalValues.get(param.id);\n    if (edited !== undefined && edited !== original) {\n      changes.push({\n        parameterId: param.id,\n        parameterCode: param.code,\n        parameterName: param.name,\n        categoryName: catName,\n        categoryId: catId,\n        sectionName,\n        sectionId,\n        dataType: param.dataType,\n        oldValue: original ?? '',\n        newValue: edited,\n        isSensitive: param.isSensitive,\n        listOptions: param.listOptions,\n        oldEntityDisplayLabel: entityDisplayLabels?.get(original ?? ''),\n        newEntityDisplayLabel: entityDisplayLabels?.get(edited),\n        rowVersion: param.rowVersion,\n      });\n    }\n  };\n\n  for (const cat of dataSource) {\n    for (const param of cat.parameters ?? []) {\n      pushChange(param, cat.name, cat.id);\n    }\n    for (const section of cat.sections ?? []) {\n      for (const param of section.parameters) {\n        pushChange(param, cat.name, cat.id, section.name, section.id);\n      }\n    }\n  }\n\n  return changes;\n}\n\n/**\n * Filters a category by search term, including sections.\n * Returns null if no parameters match.\n */\nexport function filterCategoryBySearch(\n  category: ParameterCategory,\n  searchTerm: string\n): ParameterCategory | null {\n  if (!searchTerm.trim()) return category;\n\n  const filteredParams = filterParameters(category.parameters ?? [], searchTerm);\n  const filteredSections = (category.sections ?? [])\n    .map((section) => ({\n      ...section,\n      parameters: filterParameters(section.parameters, searchTerm),\n    }))\n    .filter((section) => section.parameters.length > 0);\n\n  if (filteredParams.length === 0 && filteredSections.length === 0) return null;\n\n  return {\n    ...category,\n    parameters: filteredParams,\n    sections: filteredSections,\n  };\n}\n\n/**\n * Builds the save payload from the change list.\n */\nexport function buildSavePayload(\n  changes: ParameterChange[]\n): ParameterSavePayload[] {\n  return changes.map((c) => ({\n    parameterId: c.parameterId,\n    parameterCode: c.parameterCode,\n    value: c.newValue,\n    rowVersion: c.rowVersion,\n  }));\n}\n\n/**\n * Returns the display label for a value.\n * For BOOLEAN returns \"Sí\"/\"No\", for LIST returns the option label, for sensitive returns masked.\n */\nexport function getDisplayValue(\n  value: string,\n  dataType: string,\n  isSensitive: boolean,\n  listOptions?: Array<{ value: string; label: string }> | null,\n  entityDisplayLabel?: string\n): string {\n  if (isSensitive) return '••••••••';\n\n  if (dataType === 'BOOLEAN') {\n    return value === 'true' ? 'Sí' : 'No';\n  }\n\n  if (dataType === 'LIST' && listOptions) {\n    const option = listOptions.find((o) => String(o.value) === String(value));\n    return option ? option.label : value;\n  }\n\n  if (dataType === 'ENTITY' && entityDisplayLabel) {\n    return entityDisplayLabel;\n  }\n\n  return value;\n}\n\n/**\n * Gets the current value for a parameter (edited or original).\n */\nexport function getCurrentValue(\n  paramId: string,\n  editedValues: Map<string, string>,\n  originalValues: Map<string, string>\n): string {\n  return editedValues.has(paramId)\n    ? editedValues.get(paramId)!\n    : originalValues.get(paramId) ?? '';\n}\n\n/**\n * Extracts min/max values from validation rules.\n */\nexport function getMinMaxFromValidations(\n  validations: ParameterDefinition['validations']\n): { min?: number; max?: number; maxLength?: number } {\n  const result: { min?: number; max?: number; maxLength?: number } = {};\n\n  for (const rule of validations) {\n    if (rule.ruleType === 'MIN') {\n      result.min = parseFloat(rule.ruleValue);\n    } else if (rule.ruleType === 'MAX') {\n      result.max = parseFloat(rule.ruleValue);\n    } else if (rule.ruleType === 'MAX_LENGTH') {\n      result.maxLength = parseInt(rule.ruleValue, 10);\n    }\n  }\n\n  return result;\n}\n","import React, { useMemo, useRef, useState } from 'react';\nimport { Input } from '../Input/Input';\nimport { Select } from '../Select/Select';\nimport { Switch } from '../Switch/Switch';\nimport { LookupField } from '../LookupField';\nimport { Badge } from '../Badge/Badge';\nimport { AlertDialog } from '../AlertDialog/AlertDialog';\nimport { Button } from '../Button/Button';\nimport { ArrowUturnLeftIcon } from '@heroicons/react/24/outline';\nimport type { Fetcher } from '../LookupField';\nimport type { ParameterDefinition } from './ParameterEditor.types';\nimport { getMinMaxFromValidations, validateParameter } from './ParameterEditor.utils';\n\ninterface ParameterEditorDynamicFieldProps {\n  parameter: ParameterDefinition;\n  value: string;\n  originalValue: string;\n  onChange: (parameterId: string, value: string) => void;\n  onValidationError: (parameterId: string, error: string) => void;\n  onEntityDisplayLabel?: (parameterId: string, label: string) => void;\n  validationError?: string;\n  fetcher: Fetcher;\n  readOnly?: boolean;\n  onResetToDefault?: (parameterId: string, parameterCode: string) => Promise<void>;\n}\n\nexport const ParameterEditorDynamicField: React.FC<ParameterEditorDynamicFieldProps> = ({\n  parameter,\n  value,\n  originalValue,\n  onChange,\n  onValidationError,\n  onEntityDisplayLabel,\n  validationError,\n  fetcher,\n  readOnly = false,\n  onResetToDefault,\n}) => {\n  const isModified = value !== originalValue;\n  const { min, max, maxLength } = getMinMaxFromValidations(parameter.validations);\n\n  const [isResetting, setIsResetting] = useState(false);\n  const [showResetConfirm, setShowResetConfirm] = useState(false);\n\n  // Track the last ID selected by the user in ENTITY fields to prevent\n  // LookupField from re-fetching when the parent re-renders with the same ID.\n  const lastEntitySelectionRef = useRef<string>('');\n\n  // Wrap fetcher for ENTITY fields to inject whereClause (Section 11.5 doc técnico)\n  const entityFetcher: Fetcher = useMemo(() => {\n    const whereClause = parameter.entityMapping?.whereClause;\n    if (!whereClause) return fetcher;\n    return (entity, request) =>\n      fetcher(entity, { ...request, rawSqlClause: whereClause } as typeof request);\n  }, [fetcher, parameter.entityMapping?.whereClause]);\n\n  const handleBlur = (currentValue: string) => {\n    const error = validateParameter(parameter, currentValue);\n    onValidationError(parameter.id, error);\n  };\n\n  const handleResetToDefault = async () => {\n    if (!onResetToDefault) return;\n    setIsResetting(true);\n    try {\n      await onResetToDefault(parameter.id, parameter.code);\n      setShowResetConfirm(false);\n    } finally {\n      setIsResetting(false);\n    }\n  };\n\n  const renderResetButton = () => {\n    if (readOnly || !onResetToDefault || !parameter.isOverridden) return null;\n    return (\n      <div className=\"pt-6 shrink-0\">\n        <Button\n          type=\"outline\"\n          className=\"p-2 h-10 w-10 flex items-center justify-center border-border-primary dark:border-dark-border-primary !px-0\"\n          onClick={() => setShowResetConfirm(true)}\n          disabled={isResetting}\n          ariaLabel=\"Restaurar a valor predeterminado\"\n        >\n          <ArrowUturnLeftIcon className={`size-5 text-content-secondary dark:text-dark-content-secondary ${isResetting ? 'animate-spin' : ''}`} aria-hidden=\"true\" />\n        </Button>\n      </div>\n    );\n  };\n\n  const renderField = () => {\n    switch (parameter.dataType) {\n      case 'BOOLEAN':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Switch\n                label={parameter.name}\n                description={parameter.description}\n                checked={value === 'true'}\n                disabled={readOnly}\n                onCheckedChange={(checked) => {\n                  onChange(parameter.id, checked ? 'true' : 'false');\n                }}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'LIST':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Select\n                label={parameter.name}\n                options={\n                  (parameter.listOptions ?? [])\n                    .slice()\n                    .sort((a, b) => a.sortOrder - b.sortOrder)\n                    .map((opt) => ({\n                      value: opt.value,\n                      label: opt.label,\n                    }))\n                }\n                value={value}\n                onChange={(val) => onChange(parameter.id, String(val))}\n                disabled={readOnly}\n                error={!!validationError}\n                selectSize=\"sm\"\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'ENTITY': {\n        // If value matches what the user just selected, keep null (uncontrolled)\n        // so LookupField doesn't re-fetch the record it already has.\n        // For pre-existing or externally-set values, pass the ID (controlled)\n        // so LookupField fetches and displays the correct record.\n        const entityValue =\n          value && value === lastEntitySelectionRef.current\n            ? null\n            : value || null;\n\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <LookupField\n                entity={parameter.entityMapping?.targetTableName ?? ''}\n                label={parameter.name}\n                displayFields={[parameter.entityMapping?.descriptionField ?? 'name']}\n                value={entityValue}\n                onChange={(record, previousRecord) => {\n                  const newVal = record ? String(record.Id) : '';\n                  lastEntitySelectionRef.current = newVal;\n                  onChange(parameter.id, newVal);\n                  const descField = parameter.entityMapping?.descriptionField ?? 'name';\n                  if (previousRecord) {\n                    const prevId = String(previousRecord.Id);\n                    const prevLabel = String(previousRecord[descField] ?? '');\n                    onEntityDisplayLabel?.(prevId, prevLabel);\n                  }\n                  if (record) {\n                    onEntityDisplayLabel?.(newVal, String(record[descField] ?? ''));\n                  }\n                }}\n                fetcher={entityFetcher}\n                readOnly={readOnly}\n                error={!!validationError}\n                errorText={validationError}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n      }\n\n      case 'INT':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type=\"number\"\n                step=\"1\"\n                min={min}\n                max={max}\n                value={value}\n                onChange={(e) => onChange(parameter.id, e.target.value)}\n                onBlur={() => handleBlur(value)}\n                disabled={readOnly}\n                error={!!validationError}\n                description={validationError || parameter.description}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'DECIMAL':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type=\"number\"\n                step=\"0.01\"\n                min={min}\n                max={max}\n                value={value}\n                onChange={(e) => onChange(parameter.id, e.target.value)}\n                onBlur={() => handleBlur(value)}\n                disabled={readOnly}\n                error={!!validationError}\n                description={validationError || parameter.description}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'PERCENTAGE':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type=\"number\"\n                step=\"0.01\"\n                min={min ?? 0}\n                max={max ?? 100}\n                value={value}\n                onChange={(e) => onChange(parameter.id, e.target.value)}\n                onBlur={() => handleBlur(value)}\n                disabled={readOnly}\n                error={!!validationError}\n                description={validationError || parameter.description}\n                endIcon={\n                  <span className=\"text-content-secondary dark:text-dark-content-secondary text-sm\">\n                    %\n                  </span>\n                }\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'EMAIL':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type={parameter.isSensitive ? 'password' : 'email'}\n                value={value}\n                onChange={(e) => onChange(parameter.id, e.target.value)}\n                onBlur={() => handleBlur(value)}\n                disabled={readOnly}\n                error={!!validationError}\n                description={validationError || parameter.description}\n                maxLength={maxLength}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'URL':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type={parameter.isSensitive ? 'password' : 'url'}\n                value={value}\n                onChange={(e) => onChange(parameter.id, e.target.value)}\n                onBlur={() => handleBlur(value)}\n                disabled={readOnly}\n                error={!!validationError}\n                description={validationError || parameter.description}\n                maxLength={maxLength}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      case 'STRING':\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type={parameter.isSensitive ? 'password' : 'text'}\n                value={value}\n                onChange={(e) => onChange(parameter.id, e.target.value)}\n                onBlur={() => handleBlur(value)}\n                disabled={readOnly}\n                error={!!validationError}\n                description={validationError || parameter.description}\n                maxLength={maxLength}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n\n      default:\n        return (\n          <div className=\"flex w-full items-start gap-2\">\n            <div className=\"flex-1 min-w-0\">\n              <Input\n                label={parameter.name}\n                type=\"text\"\n                value=\"Tipo no soportado\"\n                disabled\n                description={`Tipo de dato \"${parameter.dataType}\" no es soportado.`}\n              />\n            </div>\n            {renderResetButton()}\n          </div>\n        );\n    }\n  };\n\n  return (\n    <>\n      <div className=\"relative flex flex-col min-w-0\">\n        {isModified && (\n          <div className=\"absolute -top-1 right-0 z-10\">\n            <Badge color=\"blue\" label=\"Modificado\" />\n          </div>\n        )}\n        {renderField()}\n      </div>\n\n      {showResetConfirm && (\n        <div className=\"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50\" onClick={(e) => {\n          if (e.target === e.currentTarget && !isResetting) {\n            setShowResetConfirm(false);\n          }\n        }}>\n          <AlertDialog\n            title=\"¿Restaurar valor predeterminado?\"\n            isProcess={isResetting}\n            onCancel={() => setShowResetConfirm(false)}\n            onConfirm={handleResetToDefault}\n          >\n            <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n              {`El parámetro \"${parameter.name}\" volverá a su valor configurado a nivel global. Cualquier personalización se perderá.`}\n            </p>\n          </AlertDialog>\n        </div>\n      )}\n    </>\n  );\n};\n","import React from 'react';\nimport type { Fetcher } from '../LookupField';\nimport type { ParameterDefinition, ParameterSection } from './ParameterEditor.types';\nimport { ParameterEditorDynamicField } from './ParameterEditorDynamicField';\nimport { getVisibleParameters } from './ParameterEditor.utils';\n\ninterface ParameterEditorFieldListProps {\n  parameters: ParameterDefinition[];\n  sections?: ParameterSection[];\n  editedValues: Map<string, string>;\n  originalValues: Map<string, string>;\n  validationErrors: Map<string, string>;\n  onChange: (parameterId: string, value: string) => void;\n  onValidationError: (parameterId: string, error: string) => void;\n  onEntityDisplayLabel?: (parameterId: string, label: string) => void;\n  fetcher: Fetcher;\n  readOnly?: boolean;\n  onResetToDefault?: (parameterId: string, parameterCode: string) => Promise<void>;\n}\n\nconst ParameterGrid: React.FC<{\n  parameters: ParameterDefinition[];\n  editedValues: Map<string, string>;\n  originalValues: Map<string, string>;\n  validationErrors: Map<string, string>;\n  onChange: (parameterId: string, value: string) => void;\n  onValidationError: (parameterId: string, error: string) => void;\n  onEntityDisplayLabel?: (parameterId: string, label: string) => void;\n  fetcher: Fetcher;\n  readOnly: boolean;\n  onResetToDefault?: (parameterId: string, parameterCode: string) => Promise<void>;\n}> = ({\n  parameters,\n  editedValues,\n  originalValues,\n  validationErrors,\n  onChange,\n  onValidationError,\n  onEntityDisplayLabel,\n  fetcher,\n  readOnly,\n  onResetToDefault,\n}) => {\n  const visibleParams = getVisibleParameters(parameters);\n  if (visibleParams.length === 0) return null;\n\n  return (\n    <div className=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n      {visibleParams.map((param) => {\n        const currentValue = editedValues.has(param.id)\n          ? editedValues.get(param.id)!\n          : originalValues.get(param.id) ?? '';\n        const originalValue = originalValues.get(param.id) ?? '';\n\n        return (\n          <ParameterEditorDynamicField\n            key={param.id}\n            parameter={param}\n            value={currentValue}\n            originalValue={originalValue}\n            onChange={onChange}\n            onValidationError={onValidationError}\n            onEntityDisplayLabel={onEntityDisplayLabel}\n            validationError={validationErrors.get(param.id) || undefined}\n            fetcher={fetcher}\n            readOnly={readOnly}\n            onResetToDefault={onResetToDefault}\n          />\n        );\n      })}\n    </div>\n  );\n};\n\nexport const ParameterEditorFieldList: React.FC<ParameterEditorFieldListProps> = ({\n  parameters,\n  sections,\n  editedValues,\n  originalValues,\n  validationErrors,\n  onChange,\n  onValidationError,\n  onEntityDisplayLabel,\n  fetcher,\n  readOnly = false,\n  onResetToDefault,\n}) => {\n  const visibleDirectParams = getVisibleParameters(parameters);\n  const sortedSections = (sections ?? [])\n    .filter((s) => getVisibleParameters(s.parameters).length > 0)\n    .sort((a, b) => a.sortOrder - b.sortOrder);\n\n  const hasContent = visibleDirectParams.length > 0 || sortedSections.length > 0;\n\n  if (!hasContent) {\n    return (\n      <div className=\"flex items-center justify-center py-12 text-content-secondary dark:text-dark-content-secondary text-sm\">\n        No se encontraron parametros para mostrar.\n      </div>\n    );\n  }\n\n  const gridProps = {\n    editedValues,\n    originalValues,\n    validationErrors,\n    onChange,\n    onValidationError,\n    onEntityDisplayLabel,\n    fetcher,\n    readOnly,\n    onResetToDefault,\n  };\n\n  return (\n    <div className=\"p-4 space-y-6\">\n      {visibleDirectParams.length > 0 && (\n        <ParameterGrid parameters={parameters} {...gridProps} />\n      )}\n\n      {sortedSections.map((section) => (\n        <div key={section.id}>\n          <h3 className=\"text-xs font-semibold text-content-tertiary dark:text-dark-content-tertiary uppercase tracking-wider mb-3 pb-2 border-b border-border-primary dark:border-dark-border-primary\">\n            {section.name}\n          </h3>\n          <ParameterGrid parameters={section.parameters} {...gridProps} />\n        </div>\n      ))}\n    </div>\n  );\n};\n","import React, { useEffect } from 'react';\nimport { Button } from '../Button/Button';\nimport type { ParameterChange } from './ParameterEditor.types';\nimport { getDisplayValue } from './ParameterEditor.utils';\n\ninterface ParameterEditorConfirmPanelProps {\n  changes: ParameterChange[];\n  onConfirm: () => void;\n  onCancel: () => void;\n  onUndoChange: (parameterId: string) => void;\n  saving: boolean;\n  confirmButtonText?: string;\n  cancelButtonText?: string;\n}\n\nconst ChangeRow: React.FC<{\n  change: ParameterChange;\n  onUndoChange: (id: string) => void;\n  XIcon: React.ReactNode;\n}> = ({ change, onUndoChange, XIcon }) => {\n  const oldDisplay = getDisplayValue(\n    change.oldValue,\n    change.dataType,\n    change.isSensitive,\n    change.listOptions,\n    change.oldEntityDisplayLabel\n  );\n  const newDisplay = getDisplayValue(\n    change.newValue,\n    change.dataType,\n    change.isSensitive,\n    change.listOptions,\n    change.newEntityDisplayLabel\n  );\n\n  return (\n    <div className=\"flex items-start justify-between gap-3 p-3 rounded-lg bg-bg-secondary dark:bg-dark-bg-secondary\">\n      <div className=\"flex-1 min-w-0\">\n        <p className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary\">\n          {change.parameterName}\n        </p>\n        <div className=\"flex items-center gap-2 mt-1 text-sm\">\n          <span className=\"text-content-secondary dark:text-dark-content-secondary line-through truncate\">\n            {oldDisplay || '(vacío)'}\n          </span>\n          <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">\n            →\n          </span>\n          <span className=\"text-content-primary dark:text-dark-content-primary font-medium truncate\">\n            {newDisplay || '(vacío)'}\n          </span>\n        </div>\n      </div>\n      <button\n        type=\"button\"\n        onClick={() => onUndoChange(change.parameterId)}\n        aria-label={`Quitar cambio en ${change.parameterName}`}\n        className=\"\n          shrink-0 flex items-center gap-1 px-2 py-1 rounded-md\n          text-xs font-medium\n          text-content-extensions-red dark:text-red-400\n          hover:bg-red-50 dark:hover:bg-red-950/30\n          transition-colors cursor-pointer\n        \"\n      >\n        {XIcon}\n        Quitar\n      </button>\n    </div>\n  );\n};\n\nexport const ParameterEditorConfirmPanel: React.FC<ParameterEditorConfirmPanelProps> = ({\n  changes,\n  onConfirm,\n  onCancel,\n  onUndoChange,\n  saving,\n  confirmButtonText = 'Confirmar',\n  cancelButtonText = 'Cancelar',\n}) => {\n  // Group changes by category, then by section\n  const grouped = changes.reduce<\n    Record<string, { direct: ParameterChange[]; sections: Record<string, ParameterChange[]> }>\n  >((acc, change) => {\n    if (!acc[change.categoryName]) {\n      acc[change.categoryName] = { direct: [], sections: {} };\n    }\n    if (change.sectionName) {\n      if (!acc[change.categoryName].sections[change.sectionName]) {\n        acc[change.categoryName].sections[change.sectionName] = [];\n      }\n      acc[change.categoryName].sections[change.sectionName].push(change);\n    } else {\n      acc[change.categoryName].direct.push(change);\n    }\n    return acc;\n  }, {});\n\n  // Close on Escape key\n  useEffect(() => {\n    const handleKeyDown = (e: KeyboardEvent) => {\n      if (e.key === 'Escape' && !saving) onCancel();\n    };\n    document.addEventListener('keydown', handleKeyDown);\n    return () => document.removeEventListener('keydown', handleKeyDown);\n  }, [onCancel, saving]);\n\n  const XIcon = (\n    <svg\n      xmlns=\"http://www.w3.org/2000/svg\"\n      viewBox=\"0 0 20 20\"\n      fill=\"currentColor\"\n      className=\"w-3.5 h-3.5\"\n    >\n      <path d=\"M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z\" />\n    </svg>\n  );\n\n  return (\n    <div\n      className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50\"\n      onClick={(e) => {\n        if (e.target === e.currentTarget) onCancel();\n      }}\n    >\n      <div className=\"bg-bg-primary dark:bg-dark-bg-primary rounded-2xl shadow-xl max-w-[640px] w-full mx-4 max-h-[80vh] flex flex-col\">\n        {/* Header */}\n        <div className=\"px-6 py-4 border-b border-border-primary dark:border-dark-border-primary\">\n          <h2 className=\"text-lg font-semibold text-content-primary dark:text-dark-content-primary\">\n            Resumen de cambios\n          </h2>\n          <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary mt-1\">\n            {changes.length} {changes.length === 1 ? 'cambio pendiente' : 'cambios pendientes'}\n          </p>\n        </div>\n\n        {/* Body */}\n        <div className=\"flex-1 overflow-y-auto px-6 py-4\">\n          {Object.entries(grouped).map(([categoryName, { direct, sections }]) => (\n            <div key={categoryName} className=\"mb-6 last:mb-0\">\n              <h3 className=\"text-sm font-medium text-content-tertiary dark:text-dark-content-tertiary uppercase tracking-wider mb-3\">\n                {categoryName}\n              </h3>\n\n              {direct.length > 0 && (\n                <div className=\"space-y-3\">\n                  {direct.map((change) => (\n                    <ChangeRow key={change.parameterId} change={change} onUndoChange={onUndoChange} XIcon={XIcon} />\n                  ))}\n                </div>\n              )}\n\n              {Object.entries(sections).map(([sectionName, sectionChanges]) => (\n                <div key={sectionName} className={direct.length > 0 ? 'mt-4' : ''}>\n                  <h4 className=\"text-xs font-medium text-content-tertiary dark:text-dark-content-tertiary tracking-wider mb-2 ml-1\">\n                    {sectionName}\n                  </h4>\n                  <div className=\"space-y-3\">\n                    {sectionChanges.map((change) => (\n                      <ChangeRow key={change.parameterId} change={change} onUndoChange={onUndoChange} XIcon={XIcon} />\n                    ))}\n                  </div>\n                </div>\n              ))}\n            </div>\n          ))}\n        </div>\n\n        {/* Footer */}\n        <div className=\"px-6 py-4 border-t border-border-primary dark:border-dark-border-primary flex items-center justify-end gap-3\">\n          <Button\n            type=\"outline\"\n            onClick={onCancel}\n            disabled={saving}\n          >\n            {cancelButtonText}\n          </Button>\n          <Button\n            onClick={onConfirm}\n            disabled={saving || changes.length === 0}\n          >\n            {saving ? 'Guardando...' : confirmButtonText}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React, { useState, useRef, useMemo, useCallback, useEffect } from 'react';\nimport { Button } from '../Button/Button';\nimport { Badge } from '../Badge/Badge';\nimport type { ParameterEditorProps, ParameterChange } from './ParameterEditor.types';\nimport { ParameterEditorSearchBar } from './ParameterEditorSearchBar';\nimport { ParameterEditorScrollableTabs } from './ParameterEditorScrollableTabs';\nimport { ParameterEditorFieldList } from './ParameterEditorFieldList';\nimport { ParameterEditorConfirmPanel } from './ParameterEditorConfirmPanel';\nimport {\n  buildOriginalValues,\n  filterCategoryBySearch,\n  getCategoryChangeCount,\n  getTotalChangeCount,\n  buildChangeList,\n  buildSavePayload,\n} from './ParameterEditor.utils';\n\nconst SaveIcon = (\n  <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\" className=\"w-4 h-4\">\n    <path d=\"M13.75 2H4.5A1.5 1.5 0 003 3.5v13A1.5 1.5 0 004.5 18h11a1.5 1.5 0 001.5-1.5V5.25L13.75 2zM10 15.5a2 2 0 110-4 2 2 0 010 4zM12.5 7h-6A.5.5 0 016 6.5v-3a.5.5 0 01.5-.5h6a.5.5 0 01.5.5v3a.5.5 0 01-.5.5z\" />\n  </svg>\n);\n\nconst ChevronBackIcon = (\n  <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\" className=\"w-5 h-5\">\n    <path fillRule=\"evenodd\" d=\"M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z\" clipRule=\"evenodd\" />\n  </svg>\n);\n\nexport const ParameterEditor: React.FC<ParameterEditorProps> = ({\n  dataSource,\n  onSave,\n  fetcher,\n  title = 'Centro de configuraciones',\n  onBack,\n  onChange: onChangeExternal,\n  onError,\n  onSaveSuccess,\n  className = '',\n  readOnly = false,\n  saveButtonText = 'Guardar',\n  searchPlaceholder = 'Buscar campo a configurar',\n  confirmButtonText = 'Confirmar',\n  cancelButtonText = 'Cancelar',\n  onResetToDefault,\n}) => {\n  // ===== STATE =====\n  const originalValues = useRef<Map<string, string>>(buildOriginalValues(dataSource));\n  const entityDisplayLabels = useRef<Map<string, string>>(new Map());\n  const [editedValues, setEditedValues] = useState<Map<string, string>>(new Map());\n  const [activeTabId, setActiveTabId] = useState<string>(dataSource[0]?.id ?? '');\n  const [searchTerm, setSearchTerm] = useState('');\n  const [showConfirmPanel, setShowConfirmPanel] = useState(false);\n  const [validationErrors, setValidationErrors] = useState<Map<string, string>>(new Map());\n  const [saving, setSaving] = useState(false);\n\n  // ===== SYNC ORIGINAL VALUES WHEN DATA ACTUALLY CHANGES =====\n  // Only rebuild originalValues when real server data changed (e.g. after refetch),\n  // NOT when the parent merely recreates the dataSource array with the same content.\n  // This prevents pending edits from \"disappearing\" because the parent updates\n  // dataSource in response to the onChange callback.\n  useEffect(() => {\n    const incoming = buildOriginalValues(dataSource);\n    const current = originalValues.current;\n\n    // Check if any value actually changed (different resolvedValue or new/removed params)\n    let hasRealChanges = incoming.size !== current.size;\n    if (!hasRealChanges) {\n      for (const [id, val] of incoming) {\n        if (current.get(id) !== val) {\n          hasRealChanges = true;\n          break;\n        }\n      }\n    }\n\n    if (hasRealChanges) {\n      originalValues.current = incoming;\n    }\n  }, [dataSource]);\n\n  // ===== COMPUTED =====\n\n  // Filter dataSource and parameters by search term\n  const filteredCategories = useMemo(() => {\n    if (!searchTerm.trim()) return dataSource;\n    return dataSource\n      .map((cat) => filterCategoryBySearch(cat, searchTerm))\n      .filter((cat): cat is NonNullable<typeof cat> => cat !== null);\n  }, [dataSource, searchTerm]);\n\n  // Build tab items with change badges\n  const tabItems = useMemo(() => {\n    return filteredCategories.map((cat) => ({\n      id: cat.id,\n      label: cat.name,\n      badge: getCategoryChangeCount(cat, editedValues, originalValues.current) || undefined,\n    }));\n  }, [filteredCategories, editedValues]);\n\n  // Active category parameters\n  const activeCategory = useMemo(() => {\n    return filteredCategories.find((c) => c.id === activeTabId);\n  }, [filteredCategories, activeTabId]);\n\n  const activeDirectParameters = useMemo(() => {\n    if (!activeCategory) return [];\n    return activeCategory.parameters ?? [];\n  }, [activeCategory]);\n\n  const activeSections = useMemo(() => {\n    if (!activeCategory?.sections) return [];\n    return activeCategory.sections;\n  }, [activeCategory]);\n\n  // Total change count\n  const totalChanges = useMemo(\n    () => getTotalChangeCount(editedValues, originalValues.current),\n    [editedValues]\n  );\n\n  // Build change list for confirm panel\n  const changeList = useMemo<ParameterChange[]>(\n    () => buildChangeList(dataSource, editedValues, originalValues.current, entityDisplayLabels.current),\n    [dataSource, editedValues]\n  );\n\n  // ===== HANDLERS =====\n\n  const handleFieldChange = useCallback((parameterId: string, value: string) => {\n    setEditedValues((prev) => {\n      const next = new Map(prev);\n      next.set(parameterId, value);\n      return next;\n    });\n    // Clear validation error on change\n    setValidationErrors((prev) => {\n      if (!prev.has(parameterId)) return prev;\n      const next = new Map(prev);\n      next.delete(parameterId);\n      return next;\n    });\n    onChangeExternal?.(parameterId, value);\n  }, [onChangeExternal]);\n\n  const handleEntityDisplayLabel = useCallback((parameterId: string, label: string) => {\n    entityDisplayLabels.current.set(parameterId, label);\n  }, []);\n\n  const handleValidationError = useCallback((parameterId: string, error: string) => {\n    setValidationErrors((prev) => {\n      const next = new Map(prev);\n      if (error) {\n        next.set(parameterId, error);\n      } else {\n        next.delete(parameterId);\n      }\n      return next;\n    });\n  }, []);\n\n  const handleTabChange = useCallback((id: string) => {\n    setActiveTabId(id);\n  }, []);\n\n  const handleSearchChange = useCallback(\n    (term: string) => {\n      setSearchTerm(term);\n      // If active tab is no longer in filtered results, switch to first available\n      if (term.trim()) {\n        const filtered = dataSource\n          .map((cat) => filterCategoryBySearch(cat, term))\n          .filter((cat): cat is NonNullable<typeof cat> => cat !== null);\n        if (filtered.length > 0 && !filtered.some((c) => c.id === activeTabId)) {\n          setActiveTabId(filtered[0].id);\n        }\n      }\n    },\n    [dataSource, activeTabId]\n  );\n\n  const handleOpenConfirm = useCallback(() => {\n    // Check for validation errors before opening\n    if (validationErrors.size > 0) return;\n    setShowConfirmPanel(true);\n  }, [validationErrors]);\n\n  const handleUndoChange = useCallback((parameterId: string) => {\n    setEditedValues((prev) => {\n      const next = new Map(prev);\n      next.delete(parameterId);\n\n      // Close panel if no real changes remain\n      const hasRealChanges = Array.from(next.entries()).some(\n        ([id, val]) => val !== originalValues.current.get(id)\n      );\n      if (!hasRealChanges) {\n        setShowConfirmPanel(false);\n      }\n\n      return next;\n    });\n  }, []);\n\n  const handleConfirm = useCallback(async () => {\n    if (saving) return;\n    setSaving(true);\n\n    try {\n      const payload = buildSavePayload(changeList);\n      await onSave(payload);\n      // Update original values immediately with saved values\n      // so the UI reflects changes before parent refetches dataSource.\n      // When the parent passes new dataSource (with updated rowVersion),\n      // the useEffect will rebuild originalValues from the fresh data.\n      for (const change of changeList) {\n        originalValues.current.set(change.parameterId, change.newValue);\n      }\n      setEditedValues(new Map());\n      setShowConfirmPanel(false);\n      onSaveSuccess?.();\n    } catch (err) {\n      onError?.(err instanceof Error ? err : new Error('Error al guardar los cambios'));\n    } finally {\n      setSaving(false);\n    }\n  }, [saving, changeList, onSave, onSaveSuccess, onError]);\n\n  // ===== EMPTY STATE =====\n  if (dataSource.length === 0) {\n    return (\n      <div\n        className={`\n          flex items-center justify-center py-16\n          text-content-secondary dark:text-dark-content-secondary text-sm\n          ${className}\n        `.trim().replace(/\\s+/g, ' ')}\n      >\n        No hay categorias de parametros disponibles.\n      </div>\n    );\n  }\n\n  return (\n    <div\n      className={`\n        flex flex-col h-full text-sm\n        bg-background-secondary dark:bg-dark-bg-secondary\n        overflow-hidden rounded-xl\n        ${className}\n      `.trim().replace(/\\s+/g, ' ')}\n    >\n      {/* Header */}\n      <div className=\"shrink-0 flex items-center gap-3 px-4 py-3 border-b border-border-primary dark:border-dark-border-primary\">\n        {/* Left: back + title */}\n        <div className=\"flex items-center gap-1 min-w-0 flex-1\">\n          {onBack && (\n            <button\n              type=\"button\"\n              onClick={onBack}\n              className=\"shrink-0 p-1 -ml-1 rounded-md text-content-primary dark:text-dark-content-primary hover:bg-[rgba(0,0,0,0.03)] dark:hover:bg-white/5 transition-colors cursor-pointer\"\n              aria-label=\"Volver\"\n            >\n              {ChevronBackIcon}\n            </button>\n          )}\n          <div className=\"flex flex-col min-w-0\">\n            <h1 className=\"text-xl font-bold leading-7 tracking-tight text-[#1355b7] dark:text-primary-600 truncate\">\n              {title}\n            </h1>\n            {totalChanges > 0 && (\n              <div className=\"mt-1\">\n                <Badge color=\"blue\" label={`Modificaciones: ${totalChanges}`} />\n              </div>\n            )}\n          </div>\n        </div>\n\n        {/* Right: search + save */}\n        <div className=\"flex items-center gap-3 shrink-0\">\n          <ParameterEditorSearchBar\n            value={searchTerm}\n            onChange={handleSearchChange}\n            placeholder={searchPlaceholder}\n          />\n          {!readOnly && (\n            <Button\n              onClick={handleOpenConfirm}\n              disabled={totalChanges === 0 || validationErrors.size > 0}\n              leftIcon={SaveIcon}\n            >\n              {saveButtonText}\n            </Button>\n          )}\n        </div>\n      </div>\n\n      {/* Scrollable Tabs */}\n      {tabItems.length > 0 && (\n        <div className=\"shrink-0\">\n          <ParameterEditorScrollableTabs\n            tabs={tabItems}\n            activeId={activeTabId}\n            onChange={handleTabChange}\n          />\n        </div>\n      )}\n\n      {/* Field List */}\n      <div className=\"flex-1 overflow-y-auto min-h-0 mx-4 my-3 bg-bg-primary dark:bg-dark-bg-primary rounded-xl\">\n        {filteredCategories.length === 0 ? (\n          <div className=\"flex items-center justify-center py-12 text-content-secondary dark:text-dark-content-secondary text-sm\">\n            No se encontraron parametros que coincidan con la busqueda.\n          </div>\n        ) : (\n          <ParameterEditorFieldList\n            parameters={activeDirectParameters}\n            sections={activeSections}\n            editedValues={editedValues}\n            originalValues={originalValues.current}\n            validationErrors={validationErrors}\n            onChange={handleFieldChange}\n            onValidationError={handleValidationError}\n            onEntityDisplayLabel={handleEntityDisplayLabel}\n            fetcher={fetcher}\n            readOnly={readOnly}\n            onResetToDefault={onResetToDefault}\n          />\n        )}\n      </div>\n\n      {/* Confirm Panel */}\n      {showConfirmPanel && (\n        <ParameterEditorConfirmPanel\n          changes={changeList}\n          onConfirm={handleConfirm}\n          onCancel={() => setShowConfirmPanel(false)}\n          onUndoChange={handleUndoChange}\n          saving={saving}\n          confirmButtonText={confirmButtonText}\n          cancelButtonText={cancelButtonText}\n        />\n      )}\n    </div>\n  );\n};\n","import type { FC } from 'react';\nimport { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nconst cn = (...inputs: ClassValue[]): string => twMerge(clsx(inputs));\n\ninterface TreeCheckboxProps {\n  checked: boolean;\n  indeterminate: boolean;\n  disabled: boolean;\n  readOnly: boolean;\n}\n\n/**\n * TreeCheckbox — Stateless appearance primitive.\n *\n * Renders the checkbox in exactly 3 visual states:\n * - Unchecked: empty bordered box\n * - Checked: filled box with check SVG\n * - Indeterminate: filled box with dash SVG\n *\n * This component is purely presentational:\n * NO state, NO hooks, NO event handlers, NO useTree import.\n */\nexport const TreeCheckbox: FC<TreeCheckboxProps> = ({\n  checked,\n  indeterminate,\n  disabled,\n  readOnly,\n}) => {\n  const isFilled = checked || indeterminate;\n\n  const containerClasses = cn(\n    // Base sizing and shape\n    'w-4 h-4 rounded-[4px] flex items-center justify-center',\n    // Visual state\n    isFilled\n      ? 'bg-primary-600 border-primary-600 shadow-button-inset dark:bg-primary-300'\n      : 'border border-border-primary bg-bg-primary dark:border-dark-border-primary dark:bg-dark-bg-secondary',\n    // Modifiers\n    disabled && 'opacity-50',\n    readOnly && !disabled && 'opacity-70',\n  );\n\n  return (\n    <span data-testid=\"tree-checkbox\" className={containerClasses}>\n      {checked && !indeterminate && <CheckIcon />}\n      {indeterminate && <DashIcon />}\n    </span>\n  );\n};\n\nTreeCheckbox.displayName = 'TreeCheckbox';\n\n/** 12x12 check SVG icon — white stroke on transparent */\nconst CheckIcon: FC = () => (\n  <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\">\n    <path\n      d=\"M2 6L5 9L10 3\"\n      stroke=\"white\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\n/** 12x12 dash SVG icon — white stroke on transparent */\nconst DashIcon: FC = () => (\n  <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\">\n    <path\n      d=\"M2.5 6H9.5\"\n      stroke=\"white\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n    />\n  </svg>\n);\n","import React, { useCallback } from 'react';\nimport { ChevronRight } from 'lucide-react';\nimport { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport { TreeCheckbox } from './TreeCheckbox';\nimport type { NodeState } from '../utils/treeOperations';\n\nconst cn = (...inputs: ClassValue[]): string => twMerge(clsx(inputs));\n\nexport interface TreeNodeProps<T = unknown> {\n  /** Internal NodeState from treeOperations */\n  node: NodeState<T>;\n  /** Indentation level (0 = root) */\n  level: number;\n  /** Whether the node is currently expanded */\n  expanded: boolean;\n  /** Whether the node has children */\n  hasChildren: boolean;\n  /** Read-only mode — suppresses toggle, allows chevron */\n  readOnly: boolean;\n  /** Whether to show child count badge */\n  showBadge: boolean;\n  /** Number of direct children */\n  childCount: number;\n  /** Callback when checkbox is toggled */\n  onToggle: (nodeId: string) => void;\n  /** Callback when expand/collapse chevron is clicked */\n  onExpand: (nodeId: string) => void;\n  /** Tab index for roving tabindex pattern */\n  tabIndex: number;\n  /** Keyboard event handler */\n  onKeyDown: (e: React.KeyboardEvent, nodeId: string) => void;\n}\n\n/**\n * TreeNode — Interaction Mode Layer.\n *\n * Renders a single node row: indent -> chevron -> checkbox -> icon -> label -> badge.\n * Handles click events and applies all ARIA attributes for accessibility.\n *\n * This component MUST NOT import useTree or Tree — it only receives\n * data and callbacks via props (architecture.md Section 2.1).\n */\nfunction TreeNodeInner<T = unknown>(props: TreeNodeProps<T>): React.JSX.Element {\n  const {\n    node,\n    level,\n    expanded,\n    hasChildren,\n    readOnly,\n    showBadge,\n    childCount,\n    onToggle,\n    onExpand,\n    tabIndex,\n    onKeyDown,\n  } = props;\n\n  const isDisabled = node.disabled;\n  const isInteractive = !isDisabled && !readOnly;\n\n  // Indentation: 16 + level * 24 px\n  const paddingLeft = `${16 + level * 24}px`;\n\n  const handleChevronClick = useCallback(\n    (e: React.MouseEvent) => {\n      e.stopPropagation();\n      if (hasChildren) {\n        onExpand(node.id);\n      }\n    },\n    [hasChildren, node.id, onExpand],\n  );\n\n  const handleCheckboxClick = useCallback(\n    (e: React.MouseEvent) => {\n      e.stopPropagation();\n      if (isInteractive) {\n        onToggle(node.id);\n      }\n    },\n    [isInteractive, node.id, onToggle],\n  );\n\n  const handleKeyDown = useCallback(\n    (e: React.KeyboardEvent) => {\n      onKeyDown(e, node.id);\n    },\n    [node.id, onKeyDown],\n  );\n\n  // Row classes\n  const rowClasses = cn(\n    'flex items-center gap-3 py-1 rounded-md outline-none',\n    'transition-colors duration-150',\n    // Hover state — suppressed for disabled and readOnly\n    isInteractive && 'hover:bg-primary-100 dark:hover:bg-[rgba(14,121,253,0.08)]',\n    isInteractive && 'hover:text-primary-600 dark:hover:text-primary-300',\n    // Cursor\n    isDisabled && 'cursor-not-allowed',\n    !isDisabled && readOnly && 'cursor-default',\n  );\n\n  // Chevron SVG rotation — visibility is controlled on the parent button\n  const chevronIconClasses = cn(\n    'w-4 h-4 transition-transform duration-150',\n    expanded && 'rotate-90',\n  );\n\n  return (\n    <div\n      role=\"treeitem\"\n      aria-expanded={hasChildren ? expanded : undefined}\n      aria-checked={\n        node.indeterminate ? 'mixed' : node.checked ? 'true' : 'false'\n      }\n      aria-disabled={isDisabled ? 'true' : undefined}\n      aria-level={level + 1}\n      tabIndex={tabIndex}\n      className={rowClasses}\n      style={{ paddingLeft }}\n      onKeyDown={handleKeyDown}\n    >\n      {/* Chevron — expand/collapse toggle */}\n      <button\n        type=\"button\"\n        data-testid=\"tree-node-chevron\"\n        className={cn(\n          'flex-shrink-0 flex items-center justify-center p-0 border-0 bg-transparent',\n          !hasChildren && 'invisible',\n          isDisabled && 'pointer-events-none',\n        )}\n        onClick={handleChevronClick}\n        tabIndex={-1}\n        aria-hidden=\"true\"\n      >\n        <ChevronRight size={16} className={chevronIconClasses} />\n      </button>\n\n      {/* Checkbox area — clickable region for toggle */}\n      <button\n        type=\"button\"\n        data-testid=\"tree-node-checkbox-area\"\n        className=\"flex-shrink-0 flex items-center justify-center p-0 border-0 bg-transparent\"\n        onClick={handleCheckboxClick}\n        tabIndex={-1}\n        aria-hidden=\"true\"\n      >\n        <TreeCheckbox\n          checked={node.checked}\n          indeterminate={node.indeterminate}\n          disabled={isDisabled}\n          readOnly={readOnly}\n        />\n      </button>\n\n      {/* Optional icon */}\n      {node.icon != null && (\n        <span\n          data-testid=\"tree-node-icon\"\n          className=\"flex-shrink-0 w-4 h-4 flex items-center justify-center text-content-secondary\"\n        >\n          {node.icon}\n        </span>\n      )}\n\n      {/* Label */}\n      <span\n        data-testid=\"tree-node-label\"\n        className={cn(\n          'flex-1 truncate text-sm select-none',\n          'text-content-primary dark:text-dark-content-primary',\n          hasChildren ? 'font-bold' : 'font-normal',\n        )}\n      >\n        {node.label}\n      </span>\n\n      {/* Badge — child count */}\n      {showBadge && hasChildren && (\n        <span\n          data-testid=\"tree-node-badge\"\n          className={cn(\n            'flex-shrink-0 inline-flex items-center justify-center',\n            'min-w-[20px] h-5 px-1.5 rounded-full text-xs font-medium',\n            'bg-bg-secondary text-content-secondary',\n            'dark:bg-dark-bg-secondary dark:text-dark-content-secondary',\n          )}\n        >\n          {childCount}\n        </span>\n      )}\n    </div>\n  );\n}\n\n/**\n * Memoized TreeNode with custom comparator.\n * Only re-renders when state-relevant props change:\n * checked, disabled, indeterminate, expanded, tabIndex.\n */\nexport const TreeNode = React.memo(TreeNodeInner, (prev, next) => {\n  return (\n    prev.node.checked === next.node.checked &&\n    prev.node.disabled === next.node.disabled &&\n    prev.node.indeterminate === next.node.indeterminate &&\n    prev.expanded === next.expanded &&\n    prev.tabIndex === next.tabIndex\n  );\n}) as typeof TreeNodeInner;\n\n(TreeNode as unknown as { displayName: string }).displayName = 'TreeNode';\n","import type { ReactNode } from 'react';\nimport type { TreeNode } from '../Tree.types';\n\n/**\n * Internal node representation with computed fields.\n * NOT exported from index.ts — internal to the tree component.\n */\nexport interface NodeState<T = unknown> {\n  /** Unique identifier */\n  id: string;\n  /** Visible text label */\n  label: string;\n  /** Selection state */\n  checked: boolean;\n  /** Whether the node is interactive */\n  disabled: boolean;\n  /** Computed: true when children have mixed checked states */\n  indeterminate: boolean;\n  /** Parent node ID, null for root nodes */\n  parentId: string | null;\n  /** IDs of direct children */\n  childIds: string[];\n  /** Depth in the tree (0 = root) */\n  depth: number;\n  /** Optional icon */\n  icon?: ReactNode;\n  /** Arbitrary payload */\n  data?: T;\n}\n\n/**\n * Clone a NodeState to avoid mutating the original.\n */\nfunction cloneNode<T>(node: NodeState<T>): NodeState<T> {\n  return { ...node, childIds: [...node.childIds] };\n}\n\n/**\n * Create a shallow clone of the entire Map with cloned NodeState entries.\n */\nfunction cloneMap<T>(nodeMap: Map<string, NodeState<T>>): Map<string, NodeState<T>> {\n  const result = new Map<string, NodeState<T>>();\n  for (const [id, node] of nodeMap) {\n    result.set(id, cloneNode(node));\n  }\n  return result;\n}\n\n/**\n * Build a flat Map from a tree array.\n * Computes parentId, childIds, depth for each node.\n * Performs a DFS traversal to populate all computed fields.\n */\nexport function buildNodeMap<T>(nodes: TreeNode<T>[]): Map<string, NodeState<T>> {\n  const map = new Map<string, NodeState<T>>();\n\n  function walk(treeNodes: TreeNode<T>[], parentId: string | null, depth: number): void {\n    for (const node of treeNodes) {\n      const childIds = (node.children ?? []).map((c) => c.id);\n      const state: NodeState<T> = {\n        id: node.id,\n        label: node.label,\n        checked: node.checked,\n        disabled: node.disabled ?? false,\n        indeterminate: false,\n        parentId,\n        childIds,\n        depth,\n        icon: node.icon,\n        data: node.data,\n      };\n      map.set(node.id, state);\n\n      if (node.children && node.children.length > 0) {\n        walk(node.children, node.id, depth + 1);\n      }\n    }\n  }\n\n  walk(nodes, null, 0);\n  return map;\n}\n\n/**\n * Cascade a checked state change downward to all enabled descendants.\n * Disabled nodes are SKIPPED — they retain their current state.\n * Returns a new Map with updated states.\n */\nexport function cascadeDown<T>(\n  nodeId: string,\n  checked: boolean,\n  nodeMap: Map<string, NodeState<T>>\n): Map<string, NodeState<T>> {\n  const result = cloneMap(nodeMap);\n\n  function dfs(id: string): void {\n    const node = result.get(id);\n    if (!node) return;\n\n    if (!node.disabled) {\n      node.checked = checked;\n    }\n\n    for (const childId of node.childIds) {\n      dfs(childId);\n    }\n  }\n\n  dfs(nodeId);\n  return result;\n}\n\n/**\n * Propagate state change upward through all ancestors.\n * Each ancestor recalculates checked/indeterminate from its children.\n * Returns a new Map with updated ancestor states.\n */\nexport function propagateUp<T>(\n  nodeId: string,\n  nodeMap: Map<string, NodeState<T>>\n): Map<string, NodeState<T>> {\n  const result = cloneMap(nodeMap);\n  const startNode = result.get(nodeId);\n  if (!startNode) return result;\n\n  let currentParentId = startNode.parentId;\n\n  while (currentParentId !== null) {\n    const parent = result.get(currentParentId);\n    if (!parent) break;\n\n    const children = parent.childIds.map((cid) => result.get(cid)!);\n    const allChecked = children.every((c) => c.checked && !c.indeterminate);\n    const noneChecked = children.every((c) => !c.checked && !c.indeterminate);\n\n    if (allChecked) {\n      parent.checked = true;\n      parent.indeterminate = false;\n    } else if (noneChecked) {\n      parent.checked = false;\n      parent.indeterminate = false;\n    } else {\n      parent.checked = false;\n      parent.indeterminate = true;\n    }\n\n    currentParentId = parent.parentId;\n  }\n\n  return result;\n}\n\n/**\n * Flatten the tree into a pre-order depth-first array.\n * Used for keyboard navigation and imperative API.\n */\nexport function flattenTree<T>(\n  nodeMap: Map<string, NodeState<T>>,\n  rootIds: string[]\n): NodeState<T>[] {\n  const result: NodeState<T>[] = [];\n\n  function dfs(id: string): void {\n    const node = nodeMap.get(id);\n    if (!node) return;\n    result.push(node);\n    for (const childId of node.childIds) {\n      dfs(childId);\n    }\n  }\n\n  for (const rootId of rootIds) {\n    dfs(rootId);\n  }\n\n  return result;\n}\n\n/**\n * Get visible nodes considering expand/collapse state.\n * A node is visible if all its ancestors are expanded.\n */\nexport function getVisibleNodes<T>(\n  nodeMap: Map<string, NodeState<T>>,\n  rootIds: string[],\n  expandedIds: Set<string>\n): NodeState<T>[] {\n  const result: NodeState<T>[] = [];\n\n  function dfs(id: string): void {\n    const node = nodeMap.get(id);\n    if (!node) return;\n    result.push(node);\n\n    // Only recurse into children if this node is expanded\n    if (expandedIds.has(id)) {\n      for (const childId of node.childIds) {\n        dfs(childId);\n      }\n    }\n  }\n\n  for (const rootId of rootIds) {\n    dfs(rootId);\n  }\n\n  return result;\n}\n\n/**\n * Diff current checked states against original.\n * Returns nodes whose checked state changed since initialization.\n */\nexport function diffNodes<T>(\n  current: Map<string, NodeState<T>>,\n  original: Map<string, boolean>\n): NodeState<T>[] {\n  const changed: NodeState<T>[] = [];\n\n  for (const [id, node] of current) {\n    const originalChecked = original.get(id);\n    if (originalChecked !== undefined && node.checked !== originalChecked) {\n      changed.push(node);\n    }\n  }\n\n  return changed;\n}\n\n/**\n * Reconstruct TreeNode[] from the flat nodeMap.\n * Used to convert internal state back to public API format.\n */\nexport function toTreeNodes<T>(\n  nodeMap: Map<string, NodeState<T>>,\n  rootIds: string[]\n): TreeNode<T>[] {\n  function buildNode(id: string): TreeNode<T> {\n    const state = nodeMap.get(id)!;\n    const treeNode: TreeNode<T> = {\n      id: state.id,\n      label: state.label,\n      checked: state.checked,\n    };\n\n    if (state.disabled) {\n      treeNode.disabled = state.disabled;\n    }\n\n    if (state.icon !== undefined) {\n      treeNode.icon = state.icon;\n    }\n\n    if (state.data !== undefined) {\n      treeNode.data = state.data;\n    }\n\n    if (state.childIds.length > 0) {\n      treeNode.children = state.childIds.map((childId) => buildNode(childId));\n    }\n\n    return treeNode;\n  }\n\n  return rootIds.map((rootId) => buildNode(rootId));\n}\n","import { useState, useRef, useCallback, useMemo } from 'react';\nimport type { TreeNode, TreeChangeEvent, TreeValidationResult } from '../Tree.types';\nimport {\n  buildNodeMap,\n  cascadeDown,\n  propagateUp,\n  diffNodes,\n  flattenTree,\n  getVisibleNodes,\n  type NodeState,\n} from '../utils/treeOperations';\n\n/**\n * Hook configuration options.\n * Internal to the Tree component — NOT exported from index.ts.\n */\nexport interface TreeOptions<T = unknown> {\n  /** Intercept check/uncheck — return false to cancel */\n  beforeCheck?: (node: TreeNode<T>, nextChecked: boolean) => boolean;\n  /** Callback after every successful state change */\n  onChange?: (event: TreeChangeEvent<T>) => void;\n  /** Default expand state for all branches */\n  defaultExpanded?: boolean;\n  /** Specific node IDs to expand initially */\n  expandedIds?: string[];\n  /** Read-only mode — disables all toggle operations */\n  readOnly?: boolean;\n}\n\n/**\n * Return type of the useTree hook.\n * Internal to the Tree component — NOT exported from index.ts.\n */\nexport interface UseTreeReturn<T = unknown> {\n  /** Visible nodes array for rendering (respects expand/collapse) */\n  nodes: NodeState<T>[];\n  /** Currently expanded branch IDs */\n  expandedIds: Set<string>;\n  /** Toggle a node's checked state with cascade + propagation */\n  toggle: (nodeId: string) => void;\n  /** Expand a branch node */\n  expand: (nodeId: string) => void;\n  /** Collapse a branch node */\n  collapse: (nodeId: string) => void;\n  /** Expand all branch nodes */\n  expandAll: () => void;\n  /** Collapse all branch nodes */\n  collapseAll: () => void;\n  /** All nodes with current state (flat TreeNode[]) */\n  getAll: () => TreeNode<T>[];\n  /** Only checked nodes (flat TreeNode[]) */\n  getChecked: () => TreeNode<T>[];\n  /** Only disabled nodes (flat TreeNode[]) */\n  getDisabled: () => TreeNode<T>[];\n  /** Nodes changed since initial mount (flat TreeNode[]) */\n  getModified: () => TreeNode<T>[];\n  /** Run validation over all nodes */\n  validate: (fn: (node: TreeNode<T>) => boolean) => TreeValidationResult<T>;\n  /** Ordered list of visible nodes as TreeNode[] (memoized) */\n  visibleNodes: TreeNode<T>[];\n  /** Currently focused node ID for keyboard navigation */\n  focusedId: string | null;\n  /** Set the focused node ID */\n  setFocusedId: (id: string) => void;\n}\n\n/**\n * Collect all branch (non-leaf) node IDs from a nodeMap.\n */\nfunction collectBranchIds<T>(nodeMap: Map<string, NodeState<T>>): Set<string> {\n  const branches = new Set<string>();\n  for (const [id, node] of nodeMap) {\n    if (node.childIds.length > 0) {\n      branches.add(id);\n    }\n  }\n  return branches;\n}\n\n/**\n * Initialize the expandedIds set based on options.\n */\nfunction initExpandedIds<T>(\n  nodeMap: Map<string, NodeState<T>>,\n  options?: TreeOptions<T>\n): Set<string> {\n  if (options?.expandedIds) {\n    return new Set(options.expandedIds);\n  }\n  if (options?.defaultExpanded) {\n    return collectBranchIds(nodeMap);\n  }\n  return new Set<string>();\n}\n\n/**\n * Convert a NodeState back to a TreeNode (single node, no children reconstruction).\n */\nfunction nodeStateToTreeNode<T>(state: NodeState<T>): TreeNode<T> {\n  const treeNode: TreeNode<T> = {\n    id: state.id,\n    label: state.label,\n    checked: state.checked,\n  };\n  if (state.disabled) {\n    treeNode.disabled = state.disabled;\n  }\n  if (state.icon !== undefined) {\n    treeNode.icon = state.icon;\n  }\n  if (state.data !== undefined) {\n    treeNode.data = state.data;\n  }\n  return treeNode;\n}\n\n/**\n * Core hook for tree state management.\n *\n * Manages the \"write path\" of the tree: initializing state from nodes,\n * toggling checked states with cascade/propagation, respecting beforeCheck\n * validation, firing onChange, and managing expand/collapse state.\n *\n * All tree algorithms are delegated to `treeOperations.ts` pure functions.\n * This hook MUST NOT implement cascade/propagation logic directly.\n *\n * @param initialNodes - Array of root TreeNode objects\n * @param options - Optional configuration (beforeCheck, onChange, defaultExpanded, expandedIds, readOnly)\n * @returns UseTreeReturn with reactive state and action methods\n */\nexport function useTree<T = unknown>(\n  initialNodes: TreeNode<T>[],\n  options?: TreeOptions<T>\n): UseTreeReturn<T> {\n  // Build the flat nodeMap from the hierarchical tree (runs once on mount)\n  const [nodeMap, setNodeMap] = useState<Map<string, NodeState<T>>>(() =>\n    buildNodeMap(initialNodes)\n  );\n\n  // Keep a mutable ref to the latest nodeMap for synchronous reads in toggle\n  const nodeMapRef = useRef(nodeMap);\n  nodeMapRef.current = nodeMap;\n\n  // Snapshot of original checked states at mount time (for diffNodes)\n  const originalChecked = useRef<Map<string, boolean>>((() => {\n    const snapshot = new Map<string, boolean>();\n    const initialMap = buildNodeMap(initialNodes);\n    for (const [id, node] of initialMap) {\n      snapshot.set(id, node.checked);\n    }\n    return snapshot;\n  })());\n\n  // Root node IDs in order (stable reference)\n  const [rootIds] = useState<string[]>(() => initialNodes.map((n) => n.id));\n\n  // Expand/collapse state\n  const [expandedIds, setExpandedIds] = useState<Set<string>>(() =>\n    initExpandedIds(buildNodeMap(initialNodes), options)\n  );\n\n  // readOnly stored as ref (prop that changes via re-render, not internal state)\n  const readOnlyRef = useRef(options?.readOnly ?? false);\n  readOnlyRef.current = options?.readOnly ?? false;\n\n  // Stable references to callbacks via refs\n  const beforeCheckRef = useRef(options?.beforeCheck);\n  beforeCheckRef.current = options?.beforeCheck;\n\n  const onChangeRef = useRef(options?.onChange);\n  onChangeRef.current = options?.onChange;\n\n  /**\n   * Toggle a node's checked state.\n   * Follows the state flow:\n   *   1. lookup -> 2. guard -> 3. nextChecked -> 4. beforeCheck\n   *   5. cascadeDown -> 6. propagateUp -> 7. diffNodes\n   *   8. setNodeMap (single call) -> 9. onChange\n   */\n  const toggle = useCallback(\n    (nodeId: string) => {\n      const prevMap = nodeMapRef.current;\n\n      // 1. Look up node in nodeMap — O(1)\n      const node = prevMap.get(nodeId);\n      if (!node) return;\n\n      // 2. If node.disabled || readOnly → return (no-op)\n      if (node.disabled || readOnlyRef.current) return;\n\n      // 3. Compute nextChecked\n      const nextChecked = !node.checked;\n\n      // 4. If beforeCheck defined, call it\n      if (beforeCheckRef.current) {\n        const treeNode = nodeStateToTreeNode(node);\n        const allowed = beforeCheckRef.current(treeNode, nextChecked);\n        if (process.env.NODE_ENV !== 'production') {\n          if (typeof allowed !== 'boolean') {\n            console.warn(\n              'Tree: beforeCheck must return a boolean synchronously. ' +\n              'Async functions are not supported and will be ignored.'\n            );\n          }\n        }\n        if (!allowed) return;\n      }\n\n      // 5. cascadeDown\n      const afterCascade = cascadeDown(nodeId, nextChecked, prevMap);\n\n      // 6. propagateUp\n      const afterPropagate = propagateUp(nodeId, afterCascade);\n\n      // 7. Collect affected via diffNodes (comparing new state vs original snapshot)\n      const affectedNodes = diffNodes(afterPropagate, originalChecked.current);\n\n      // 8. setNodeMap — single call (React 19 batching)\n      setNodeMap(afterPropagate);\n\n      // 9. Fire onChange synchronously after state update\n      const sourceNode = afterPropagate.get(nodeId);\n      if (onChangeRef.current && sourceNode) {\n        const event: TreeChangeEvent<T> = {\n          source: nodeStateToTreeNode(sourceNode),\n          affected: affectedNodes.map((n) => nodeStateToTreeNode(n)),\n          checked: nextChecked,\n        };\n        onChangeRef.current(event);\n      }\n    },\n    [] // stable: all external references via refs\n  );\n\n  /**\n   * Expand a single branch node.\n   */\n  const expand = useCallback((nodeId: string) => {\n    setExpandedIds((prev) => {\n      const next = new Set(prev);\n      next.add(nodeId);\n      return next;\n    });\n  }, []);\n\n  /**\n   * Collapse a single branch node.\n   */\n  const collapse = useCallback((nodeId: string) => {\n    setExpandedIds((prev) => {\n      const next = new Set(prev);\n      next.delete(nodeId);\n      return next;\n    });\n  }, []);\n\n  /**\n   * Expand all branch nodes.\n   */\n  const expandAll = useCallback(() => {\n    setExpandedIds(collectBranchIds(nodeMapRef.current));\n  }, []);\n\n  /**\n   * Collapse all branch nodes.\n   */\n  const collapseAll = useCallback(() => {\n    setExpandedIds(new Set<string>());\n  }, []);\n\n  // Compute visible nodes based on current expand/collapse state (NodeState[])\n  const nodes = useMemo(\n    () => getVisibleNodes(nodeMap, rootIds, expandedIds),\n    [nodeMap, rootIds, expandedIds]\n  );\n\n  // ---------------------------------------------------------------------------\n  // Imperative API (S003)\n  // ---------------------------------------------------------------------------\n\n  /** All nodes as flat TreeNode[] */\n  const getAll = useCallback((): TreeNode<T>[] => {\n    return flattenTree(nodeMapRef.current, rootIds).map(nodeStateToTreeNode);\n  }, [rootIds]);\n\n  /** Only checked nodes (flat) */\n  const getChecked = useCallback((): TreeNode<T>[] => {\n    return flattenTree(nodeMapRef.current, rootIds)\n      .filter((n) => n.checked)\n      .map(nodeStateToTreeNode);\n  }, [rootIds]);\n\n  /** Only disabled nodes (flat) */\n  const getDisabled = useCallback((): TreeNode<T>[] => {\n    return flattenTree(nodeMapRef.current, rootIds)\n      .filter((n) => n.disabled)\n      .map(nodeStateToTreeNode);\n  }, [rootIds]);\n\n  /** Nodes changed since mount (flat) */\n  const getModified = useCallback((): TreeNode<T>[] => {\n    return diffNodes(nodeMapRef.current, originalChecked.current)\n      .map(nodeStateToTreeNode);\n  }, []);\n\n  /** Run validation predicate over all nodes */\n  const validate = useCallback(\n    (fn: (node: TreeNode<T>) => boolean): TreeValidationResult<T> => {\n      const allNodes = flattenTree(nodeMapRef.current, rootIds).map(nodeStateToTreeNode);\n      const failures = allNodes.filter((n) => !fn(n));\n      return { valid: failures.length === 0, failures };\n    },\n    [rootIds]\n  );\n\n  // ---------------------------------------------------------------------------\n  // Keyboard navigation state (S003)\n  // ---------------------------------------------------------------------------\n\n  /** Focused node ID — defaults to first root or null */\n  const [focusedId, setFocusedId] = useState<string | null>(\n    rootIds.length > 0 ? rootIds[0] : null\n  );\n\n  /** Visible nodes as public TreeNode[] — memoized */\n  const visibleNodes = useMemo(\n    () => getVisibleNodes(nodeMap, rootIds, expandedIds).map(nodeStateToTreeNode),\n    [nodeMap, rootIds, expandedIds]\n  );\n\n  return {\n    nodes,\n    expandedIds,\n    toggle,\n    expand,\n    collapse,\n    expandAll,\n    collapseAll,\n    getAll,\n    getChecked,\n    getDisabled,\n    getModified,\n    validate,\n    visibleNodes,\n    focusedId,\n    setFocusedId,\n  };\n}\n","import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react';\nimport type { TreeProps, TreeRef } from './Tree.types';\nimport { TreeNode } from './parts/TreeNode';\nimport { useTree } from './hooks/useTree';\nimport type { NodeState } from './utils/treeOperations';\n\n/**\n * Tree — Orchestrator.\n *\n * Wires together useTree (state), TreeNode (rows), and TreeCheckbox (appearance).\n * Manages keyboard navigation with roving tabindex and exposes TreeRef via forwardRef.\n *\n * This component MUST NOT contain business logic — everything is delegated to\n * useTree or pure functions in treeOperations.ts.\n */\nconst TreeInner = <T = unknown>(\n  props: TreeProps<T>,\n  ref: React.ForwardedRef<TreeRef<T>>\n): React.ReactElement => {\n  const {\n    nodes: inputNodes,\n    readOnly = false,\n    onChange,\n    beforeCheck,\n    defaultExpanded = false,\n    expandedIds: expandedIdsProp,\n    showBadge = false,\n    showDividers = false,\n    ariaLabel,\n    className,\n  } = props;\n\n  const tree = useTree(inputNodes, {\n    beforeCheck,\n    onChange,\n    defaultExpanded,\n    expandedIds: expandedIdsProp,\n    readOnly,\n  });\n\n  // Expose imperative API via ref\n  useImperativeHandle(\n    ref,\n    () => ({\n      getAll: tree.getAll,\n      getChecked: tree.getChecked,\n      getDisabled: tree.getDisabled,\n      getModified: tree.getModified,\n      validate: tree.validate,\n    }),\n    [tree.getAll, tree.getChecked, tree.getDisabled, tree.getModified, tree.validate]\n  );\n\n  // DOM refs for roving tabindex focus management\n  const nodeRefs = useRef<Map<string, HTMLElement>>(new Map());\n\n  // Programmatically move DOM focus when focusedId changes\n  useEffect(() => {\n    if (tree.focusedId) {\n      nodeRefs.current.get(tree.focusedId)?.focus();\n    }\n  }, [tree.focusedId]);\n\n  // Visible nodes as NodeState[] for rendering\n  const visibleNodes = tree.nodes;\n\n  /**\n   * Handle expand/collapse toggle.\n   * If already expanded, collapse. Otherwise expand.\n   */\n  const handleExpandToggle = useCallback(\n    (nodeId: string) => {\n      if (tree.expandedIds.has(nodeId)) {\n        tree.collapse(nodeId);\n      } else {\n        tree.expand(nodeId);\n      }\n    },\n    [tree.expandedIds, tree.collapse, tree.expand]\n  );\n\n  /**\n   * Keyboard navigation handler.\n   * Attached to the role=\"tree\" container, dispatched per-node via onKeyDown prop.\n   */\n  const handleKeyDown = useCallback(\n    (e: React.KeyboardEvent, nodeId: string) => {\n      const currentIndex = visibleNodes.findIndex((n) => n.id === nodeId);\n      if (currentIndex === -1) return;\n\n      const currentNode = visibleNodes[currentIndex];\n\n      switch (e.key) {\n        case 'ArrowDown': {\n          e.preventDefault();\n          if (currentIndex < visibleNodes.length - 1) {\n            tree.setFocusedId(visibleNodes[currentIndex + 1].id);\n          }\n          break;\n        }\n\n        case 'ArrowUp': {\n          e.preventDefault();\n          if (currentIndex > 0) {\n            tree.setFocusedId(visibleNodes[currentIndex - 1].id);\n          }\n          break;\n        }\n\n        case 'ArrowRight': {\n          e.preventDefault();\n          const hasChildren = currentNode.childIds.length > 0;\n          if (hasChildren && !tree.expandedIds.has(nodeId)) {\n            // Expand collapsed branch\n            tree.expand(nodeId);\n          } else if (hasChildren && tree.expandedIds.has(nodeId)) {\n            // Move to first child if expanded\n            const firstChildIndex = visibleNodes.findIndex(\n              (n) => n.id === currentNode.childIds[0]\n            );\n            if (firstChildIndex !== -1) {\n              tree.setFocusedId(visibleNodes[firstChildIndex].id);\n            }\n          }\n          break;\n        }\n\n        case 'ArrowLeft': {\n          e.preventDefault();\n          const hasBranchChildren = currentNode.childIds.length > 0;\n          if (hasBranchChildren && tree.expandedIds.has(nodeId)) {\n            // Collapse expanded branch\n            tree.collapse(nodeId);\n          } else if (currentNode.parentId !== null) {\n            // Move to parent\n            tree.setFocusedId(currentNode.parentId);\n          }\n          break;\n        }\n\n        case ' ': {\n          e.preventDefault();\n          if (!currentNode.disabled && !readOnly) {\n            tree.toggle(nodeId);\n          }\n          break;\n        }\n\n        case 'Home': {\n          e.preventDefault();\n          if (visibleNodes.length > 0) {\n            tree.setFocusedId(visibleNodes[0].id);\n          }\n          break;\n        }\n\n        case 'End': {\n          e.preventDefault();\n          if (visibleNodes.length > 0) {\n            tree.setFocusedId(visibleNodes[visibleNodes.length - 1].id);\n          }\n          break;\n        }\n\n        default:\n          break;\n      }\n    },\n    [visibleNodes, tree.expandedIds, tree.expand, tree.collapse, tree.setFocusedId, tree.toggle, readOnly]\n  );\n\n  /**\n   * Ref callback to collect DOM elements for roving tabindex focus.\n   * Stores the role=\"treeitem\" child element, not the wrapper.\n   */\n  const setNodeRef = useCallback((nodeId: string, el: HTMLElement | null) => {\n    if (el) {\n      const treeItem = el.querySelector('[role=\"treeitem\"]') as HTMLElement | null;\n      nodeRefs.current.set(nodeId, treeItem ?? el);\n    } else {\n      nodeRefs.current.delete(nodeId);\n    }\n  }, []);\n\n  /**\n   * Handle focus on a node — update roving tabindex state.\n   * Called when user clicks or tabs into a treeitem.\n   */\n  const handleNodeFocus = useCallback(\n    (nodeId: string) => {\n      tree.setFocusedId(nodeId);\n    },\n    [tree.setFocusedId]\n  );\n\n  // Track which root nodes appear to render dividers between them\n  let rootNodeIndex = 0;\n  const totalRootNodes = visibleNodes.filter((n) => n.parentId === null).length;\n\n  return (\n    <div\n      role=\"tree\"\n      aria-label={ariaLabel}\n      aria-readonly={readOnly || undefined}\n      className={className}\n    >\n      {visibleNodes.map((node) => {\n        const isRoot = node.parentId === null;\n        const showDivider = showDividers && isRoot && rootNodeIndex > 0;\n\n        if (isRoot) {\n          rootNodeIndex++;\n        }\n\n        return (\n          <React.Fragment key={node.id}>\n            {showDivider && (\n              <hr className=\"border-border-primary dark:border-dark-border-primary my-1\" />\n            )}\n            <TreeNodeWithRef\n              node={node}\n              level={node.depth}\n              expanded={tree.expandedIds.has(node.id)}\n              hasChildren={node.childIds.length > 0}\n              readOnly={readOnly}\n              showBadge={showBadge}\n              childCount={node.childIds.length}\n              onToggle={tree.toggle}\n              onExpand={handleExpandToggle}\n              tabIndex={node.id === tree.focusedId ? 0 : -1}\n              onKeyDown={handleKeyDown}\n              setRef={setNodeRef}\n              onNodeFocus={handleNodeFocus}\n            />\n          </React.Fragment>\n        );\n      })}\n    </div>\n  );\n};\n\n/**\n * Wrapper to attach the ref callback to each TreeNode's DOM element.\n * This allows roving tabindex focus management without modifying TreeNode.\n */\ninterface TreeNodeWithRefProps<T = unknown> {\n  node: NodeState<T>;\n  level: number;\n  expanded: boolean;\n  hasChildren: boolean;\n  readOnly: boolean;\n  showBadge: boolean;\n  childCount: number;\n  onToggle: (nodeId: string) => void;\n  onExpand: (nodeId: string) => void;\n  tabIndex: number;\n  onKeyDown: (e: React.KeyboardEvent, nodeId: string) => void;\n  setRef: (nodeId: string, el: HTMLElement | null) => void;\n  onNodeFocus: (nodeId: string) => void;\n}\n\nfunction TreeNodeWithRef<T = unknown>(props: TreeNodeWithRefProps<T>): React.ReactElement {\n  const { setRef, onNodeFocus, node, ...treeNodeProps } = props;\n\n  const refCallback = useCallback(\n    (el: HTMLElement | null) => {\n      setRef(node.id, el);\n    },\n    [setRef, node.id]\n  );\n\n  const handleFocus = useCallback(() => {\n    onNodeFocus(node.id);\n  }, [onNodeFocus, node.id]);\n\n  return (\n    <div ref={refCallback} onFocus={handleFocus}>\n      <TreeNode node={node} {...treeNodeProps} />\n    </div>\n  );\n}\n\nexport const Tree = forwardRef(TreeInner) as <T = unknown>(\n  props: TreeProps<T> & { ref?: React.Ref<TreeRef<T>> }\n) => React.ReactElement;\n\n(Tree as unknown as { displayName: string }).displayName = 'Tree';\n","import React, { useState, useCallback, useMemo } from 'react';\nimport { Navbar } from '../../components/Navbar';\nimport { NavigationRailGroup } from '../../components/NavigationRailGroup';\nimport { useMasterCrudTranslation } from '../../components/MasterCrud/useMasterCrudTranslation';\nimport type { LayoutBaseProps } from './LayoutBase.types';\nimport type { NavigationRailGroupMenuItem } from '../../components/NavigationRailGroup/NavigationRailGroup.types';\n\n// ===== TRADUCCIONES INTERNAS (FALLBACK) =====\nconst internalTranslations: Record<string, any> = {\n  es: {\n    search: 'Buscar módulo',\n    collapse: 'Colapsar',\n    recent: 'Recientes',\n    frequent: 'Opciones frecuentes',\n    logout: 'Cerrar Sesión',\n    account: 'Mi Cuenta',\n    notifications: 'Notificaciones',\n    billing: 'Facturación',\n    darkMode: 'Modo Oscuro',\n  },\n  en: {\n    search: 'Search module',\n    collapse: 'Collapse',\n    recent: 'Recent',\n    frequent: 'Frequent options',\n    logout: 'Sign Out',\n    account: 'My Account',\n    notifications: 'Notifications',\n    billing: 'Billing',\n    darkMode: 'Dark Mode',\n  }\n};\n\n/**\n * LayoutBase - Layout base del sistema Siesa\n *\n * Layout reutilizable que implementa la estructura base con NavigationRail\n * lateral, Navbar superior y área de contenido dinámico. Diseñado para ser\n * usado como wrapper en diferentes vistas de la aplicación.\n *\n * **Composición:**\n * - Navbar: Barra superior con logo Siesa, título del producto y dropdown de usuario\n * - NavigationRailGroup: Rail de navegación lateral con iconos y búsqueda\n * - Área de contenido: Contenido dinámico pasado como children\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Responsive design mobile-first con breakpoints md:, lg:, xl:\n * - Composición con componentes del sistema (NO reimplementación)\n * - Type safety con TypeScript estricto\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see src/components/Navbar - Componente Navbar reutilizado\n * @see src/components/NavigationRailGroup - Componente NavigationRail reutilizado\n *\n * @example\n * ```tsx\n * // Uso básico\n * <LayoutBase\n *   productName=\"Mi Aplicación\"\n *   siesaLogoPath=\"/images/logos/Siesa_Logosimbolo_Blanco.svg\"\n *   siesaLogoWidth=\"100px\"\n *   siesaLogoHeight=\"40px\"\n *   userDropdown={{\n *     avatar: '/avatar.jpg',\n *     name: 'Carlos',\n *     email: 'carlos@siesa.com',\n *   }}\n *   navigationItems={navigationItems}\n * >\n *   <div>Mi contenido personalizado</div>\n * </LayoutBase>\n *\n * // Uso avanzado con props pass-through\n * <LayoutBase\n *   productName=\"Sistema Avanzado\"\n *   navbarProps={{\n *     showNavigationButton: true,\n *     environmentBadge: \"Desarrollo\",\n *     navigationButtonProps: { type: 'outline', size: 'l' },\n *     notifications: { cart: 5, bell: true },\n *     onCartClick: () => openCart(),\n *     onNotificationsClick: () => openNotifications(),\n *   }}\n *   navigationRailProps={{\n *     showSearchButton: true,\n *     labels: { \n *       searchPlaceholder: \"Buscar módulos...\",\n *       collapseButton: \"Minimizar\"\n *     },\n *     onItemClick: (item) => handleNavigation(item),\n *     onItemHover: (item) => showPreview(item),\n *   }}\n * >\n *   <div>Contenido con funcionalidad completa</div>\n * </LayoutBase>\n * ```\n */\nexport const LayoutBase: React.FC<LayoutBaseProps> = ({\n  productName = 'Mi Aplicación',\n  siesaLogoPath,\n  siesaLogoWidth,\n  siesaLogoHeight,\n  userDropdown,\n  navigationItems = [],\n  children,\n  className = '',\n  contentClassName = '',\n  hideSidebar = false,\n  navbarProps = {},\n  navigationRailProps = {},\n  uiPrefix = 'layout',\n  t: tProp,\n  locale = 'es',\n}) => {\n  // ===== MOTOR DE TRADUCCIÓN =====\n  const { t } = useMasterCrudTranslation({\n    locale,\n    uiPrefix,\n    internalTranslations,\n    tProp,\n  });\n\n  // ===== LÓGICA DE TRADUCCIÓN DE MENÚS =====\n  const translateMenuItems = useCallback((items: NavigationRailGroupMenuItem[]): NavigationRailGroupMenuItem[] => {\n    return items.map(item => ({\n      ...item,\n      label: t(`menu.${item.id}`, item.label),\n      children: item.children ? translateMenuItems(item.children) : undefined\n    }));\n  }, [t]);\n\n  const translatedNavigationItems = useMemo(() => \n    translateMenuItems(navigationItems), \n    [navigationItems, translateMenuItems]\n  );\n\n  // Estado local para el NavigationRail\n  const [navState, setNavState] = useState<'collapsed' | 'expanded' | 'hover' | 'searcher'>('collapsed');\n\n  // Handler para cambio de estado del NavigationRail\n  const handleNavStateChange = (state: 'collapsed' | 'expanded' | 'hover' | 'searcher' | undefined) => {\n    if (state) {\n      setNavState(state);\n    }\n  };\n\n  return (\n    <div\n      className={[\n        // ===== BASE CONTAINER =====\n        'h-screen', // Altura fija de pantalla completa\n        'w-full',\n        'bg-white', // Fondo blanco para Navbar y NavigationRail\n        'dark:bg-dark-bg-primary',\n        'flex',\n        'flex-col',\n        'overflow-hidden', // Prevenir scroll en contenedor principal\n        className,\n      ]\n        .join(' ')\n        .replace(/\\s+/g, ' ')\n        .trim()}\n    >\n      {/* ===== NAVBAR ===== */}\n      <Navbar\n        productName={productName}\n        userDropdown={userDropdown}\n        hideActionButtons\n        showSiesaLogoLeading\n        showBusinessLogo={false}\n        siesaLogo={\n          siesaLogoPath ? (\n            <img \n              src={siesaLogoPath} \n              alt=\"Siesa\" \n              className=\"object-contain\"\n              style={{\n                width: siesaLogoWidth || '100%',\n                height: siesaLogoHeight || '100%',\n              }}\n            />\n          ) : undefined\n        }\n        className=\"bg-white dark:bg-dark-bg-primary\"\n        t={t}\n        {...navbarProps}\n      />\n\n      {/* ===== LAYOUT: NAVIGATION RAIL + CONTENT ===== */}\n      <div className=\"flex flex-1 overflow-hidden\">\n        {/* ===== NAVIGATION RAIL ===== */}\n        {!hideSidebar && (\n          <div style={{ position: 'relative', zIndex: 9999 }}>\n          <NavigationRailGroup\n            state={navState}\n            items={translatedNavigationItems}\n            showSearchButton={false}\n            onStateChange={handleNavStateChange}\n            t={t}\n            labels={{\n              searchPlaceholder: t('search', 'Buscar módulo'),\n              collapseButton: t('collapse', 'Colapsar'),\n              recentSection: t('recent', 'Recientes'),\n              frequentSection: t('frequent', 'Opciones frecuentes'),\n            }}\n            {...navigationRailProps}\n          />\n          </div>\n        )}\n\n        {/* ===== CONTENT AREA ===== */}\n        <div\n          className={[\n            'flex-1',\n            'overflow-y-auto',\n            'bg-gray-50',\n            'dark:bg-dark-bg-primary',\n            'p-6',\n            'flex flex-col', // Asegurar que el contenido pueda ser flex y crecer\n            contentClassName,\n          ]\n            .join(' ')\n            .replace(/\\s+/g, ' ')\n            .trim()}\n        >\n          <div className=\"w-full flex-1 flex flex-col\">\n            {children}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Iconos para ListView del sistema de diseño Siesa\n * Basados en Heroicons Micro (16x16)\n */\n\nexport const HomeIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M8.543 2.232a.75.75 0 0 0-1.085 0l-5.25 5.5A.75.75 0 0 0 2.75 9H4v4a1 1 0 0 0 1 1h1.5a.5.5 0 0 0 .5-.5v-2a1 1 0 0 1 1-1h.5a1 1 0 0 1 1 1v2a.5.5 0 0 0 .5.5H12a1 1 0 0 0 1-1V9h1.25a.75.75 0 0 0 .543-1.268l-5.25-5.5Z\" />\n  </svg>\n);\n\nexport const GlobeAltIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0ZM5.37 2.822a6.493 6.493 0 0 0-2.818 3.428h2.103c.088-.907.254-1.778.494-2.595a8.932 8.932 0 0 1 .221-.833ZM1.5 8c0 .522.062 1.03.179 1.516l.135.484h2.49a16.15 16.15 0 0 1 0-4H1.815L1.68 6.484A6.533 6.533 0 0 0 1.5 8Zm.552 2.75A6.493 6.493 0 0 0 5.37 14.18a8.932 8.932 0 0 1-.221-.833 13.2 13.2 0 0 1-.494-2.595H2.552Zm4.058 0c.083.78.23 1.497.429 2.128.197.622.423 1.07.649 1.357.225.286.401.265.312.265.089 0 .265.021.49-.265.226-.287.452-.735.649-1.357.199-.631.346-1.348.429-2.128H6.11Zm4.234 0a13.198 13.198 0 0 1-.494 2.595 8.938 8.938 0 0 1-.22.833 6.493 6.493 0 0 0 2.817-3.428h-2.103Zm2.104-2h-2.48a16.15 16.15 0 0 0 0-4h2.48l.135.484A6.538 6.538 0 0 1 14.5 8a6.538 6.538 0 0 1-.179 1.516l-.135.484h.162Zm-2.818-4.928c.167.251.394.699.221.833.24.817.406 1.688.494 2.595h2.103a6.493 6.493 0 0 0-2.818-3.428ZM9.89 6h-3.78c.083-.78.23-1.497.429-2.128.197-.622.423-1.07.649-1.357.225-.286.401-.265.312-.265.089 0 .265-.021.49.265.226.287.452.735.649 1.357.199.631.346 1.348.429 2.128Zm-4.234 0H3.553a6.493 6.493 0 0 1 2.818-3.428 8.932 8.932 0 0 0-.221.833c-.24.817-.406 1.688-.494 2.595Zm.144 2a14.65 14.65 0 0 0 0 4h4.4a14.65 14.65 0 0 0 0-4H5.8Z\" />\n  </svg>\n);\n\nexport const DocumentTextIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4 2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6.414A2 2 0 0 0 13.414 5L10 1.586A2 2 0 0 0 8.586 1H4Zm1 5a.5.5 0 0 0 0 1h6a.5.5 0 0 0 0-1H5Zm-.5 2.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5Zm.5 1.5a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1H5Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const CloudIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M1 9.5A3.5 3.5 0 0 0 4.5 13H12a3 3 0 0 0 .917-5.857 2.503 2.503 0 0 0-3.198-3.019 3.5 3.5 0 0 0-6.628 2.171A3.5 3.5 0 0 0 1 9.5Z\" />\n  </svg>\n);\n\nexport const SquaresPlusIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M2 4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4ZM10 4a2 2 0 0 1 2-2h.5a.5.5 0 0 1 0 1H12a1 1 0 0 0-1 1v.5a.5.5 0 0 1-1 0V4ZM2 12a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v2ZM10.5 8a.5.5 0 0 0-.5.5V10H8.5a.5.5 0 0 0 0 1H10v1.5a.5.5 0 0 0 1 0V11h1.5a.5.5 0 0 0 0-1H11V8.5a.5.5 0 0 0-.5-.5Z\" />\n  </svg>\n);\n\nexport const MagnifyingGlassIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M9.965 11.026a5 5 0 1 1 1.06-1.06l2.755 2.754a.75.75 0 1 1-1.06 1.06l-2.755-2.754ZM10.5 7a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const PlusIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z\" />\n  </svg>\n);\n\nexport const ListBulletIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M2.5 4a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1ZM4.75 3.25a.75.75 0 0 0 0 1.5h8.5a.75.75 0 0 0 0-1.5h-8.5ZM4 8a.75.75 0 0 1 .75-.75h8.5a.75.75 0 0 1 0 1.5h-8.5A.75.75 0 0 1 4 8Zm.75 3.25a.75.75 0 0 0 0 1.5h8.5a.75.75 0 0 0 0-1.5h-8.5ZM3 8a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0Zm-.5 4.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const FunnelIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M14 2H2c-.55 0-.95.538-.75 1.032l3 7.5c.127.318.44.528.783.528h5.934c.343 0 .656-.21.783-.528l3-7.5C14.95 2.538 14.55 2 14 2Z\" />\n    <path d=\"M6 12.25v1.25a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-1.25H6Z\" />\n  </svg>\n);\n\nexport const DocumentCheckIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4 2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6.414A2 2 0 0 0 13.414 5L10 1.586A2 2 0 0 0 8.586 1H4Zm6.78 5.28a.75.75 0 1 0-1.06-1.06L7 8.94 5.78 7.72a.75.75 0 0 0-1.06 1.06l1.75 1.75a.75.75 0 0 0 1.06 0l3.25-3.25Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const DocumentMinusIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4 2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6.414A2 2 0 0 0 13.414 5L10 1.586A2 2 0 0 0 8.586 1H4Zm1 6.25a.75.75 0 0 0 0 1.5h6a.75.75 0 0 0 0-1.5H5Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const DocumentArrowUpIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4 2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6.414A2 2 0 0 0 13.414 5L10 1.586A2 2 0 0 0 8.586 1H4Zm4.53 4.22a.75.75 0 0 0-1.06 0L5.22 8.47a.75.75 0 1 0 1.06 1.06l.97-.97v2.69a.75.75 0 0 0 1.5 0V8.56l.97.97a.75.75 0 1 0 1.06-1.06L8.53 6.22Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const BellIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M12 5a4 4 0 0 0-8 0v2.379c0 .398-.158.779-.44 1.06L2.294 9.707a1 1 0 0 0 .707 1.707h9.998a1 1 0 0 0 .707-1.707l-1.266-1.268A1.5 1.5 0 0 1 12 7.379V5ZM6.268 13.682a.75.75 0 0 0 1.04.199 1.496 1.496 0 0 0 1.385 0 .75.75 0 1 0-.839-1.244.003.003 0 0 1-.004.003.003.003 0 0 1-.004-.003.75.75 0 0 0-1.244.199.75.75 0 0 0 .666.846Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const ChevronDownIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const ArrowLongLeftIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M14 8a.75.75 0 0 1-.75.75H3.81l2.72 2.72a.75.75 0 1 1-1.06 1.06l-4-4a.75.75 0 0 1 0-1.06l4-4a.75.75 0 0 1 1.06 1.06L3.81 7.25h9.44A.75.75 0 0 1 14 8Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const ArrowLongRightIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M2 8a.75.75 0 0 1 .75-.75h9.44l-2.72-2.72a.75.75 0 0 1 1.06-1.06l4 4a.75.75 0 0 1 0 1.06l-4 4a.75.75 0 1 1-1.06-1.06l2.72-2.72H2.75A.75.75 0 0 1 2 8Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const EllipsisHorizontalIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M2 8a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM6.5 8a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM12.5 6.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3Z\" />\n  </svg>\n);\n\nexport const EnvelopeIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    width=\"16\"\n    height=\"16\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type { ListViewProps } from './ListView.types';\nimport { Badge } from '../../components/Badge/Badge';\nimport { Navbar } from '../../components/Navbar/Navbar';\nimport { NavigationRailGroup } from '../../components/NavigationRailGroup/NavigationRailGroup';\nimport { Button } from '../../components/Button/Button';\nimport { Table } from '../../components/Table/Table';\nimport { Input } from '../../components/Input/Input';\nimport { Select } from '../../components/Select/Select';\nimport type { TableColumn } from '../../components/Table/Table.types';\nimport {\n  HomeIcon,\n  GlobeAltIcon,\n  DocumentTextIcon,\n  CloudIcon,\n  SquaresPlusIcon,\n  MagnifyingGlassIcon,\n  PlusIcon,\n  ListBulletIcon,\n  FunnelIcon,\n  ChevronDownIcon,\n  EnvelopeIcon,\n} from './icons';\n\n/**\n * ListView - Vista de lista completa del sistema de diseño Siesa\n *\n * Vista completa que compone los siguientes componentes del sistema:\n * - NavigationRailGroup: Barra lateral de navegación con panel expandible\n * - Navbar: Barra superior con logo, título, notificaciones y dropdown de usuario\n * - Badge: Filtros rápidos con badges de colores\n * - Table: Tabla de datos con sorting y paginación integrada\n * - Button: Botones de acción (Crear, Auditoría, Filtrar)\n * - Input: Buscador integrado\n * - Select: Dropdown de opciones de vista\n *\n * Mejores prácticas implementadas:\n * - REUSO DE COMPONENTES: Usa componentes del sistema, NUNCA reimplementa\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n * - Responsive design (mobile-first)\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see src/components/NavigationRailGroup - Componente de navegación lateral\n * @see src/components/Navbar - Componente de barra superior\n * @see src/components/Table - Componente de tabla con paginación\n * @see src/components/Button - Componente de botón\n * @see src/components/Badge - Componente de badge\n *\n * @example\n * ```tsx\n * <ListView\n *   title=\"List View\"\n *   tableTitle=\"Usuarios\"\n *   columns={columns}\n *   data={users}\n *   userDropdown={{\n *     avatar: '/avatar.jpg',\n *     name: 'John Doe',\n *     role: 'Administrador',\n *   }}\n *   pagination={{\n *     currentPage: 1,\n *     totalPages: 10,\n *     onPageChange: (page) => console.log(page),\n *   }}\n * />\n * ```\n */\nexport const ListView = <T extends Record<string, any>>({\n  title = 'List View',\n  navbarProductName = 'SB Commercial',\n  tableTitle = 'Usuarios',\n  columns,\n  data,\n  navigationItems,\n  quickFilters,\n  actionButtons,\n  userDropdown,\n  notifications,\n  environmentBadge,\n  showNavigationRail = true,\n  navigationRailState = 'collapsed',\n  onNavigationRailStateChange,\n  onNavItemClick,\n  onSearch,\n  searchPlaceholder = 'Buscar',\n  onSort,\n  sortColumn: externalSortColumn,\n  sortDirection: externalSortDirection,\n  pagination,\n  loading = false,\n  loadingRows = 5,\n  emptyMessage = 'No hay datos disponibles',\n  className = '',\n  onNotificationsClick,\n  viewOptions,\n  selectedViewOption,\n  onViewOptionChange,\n}: ListViewProps<T>) => {\n  // ===== ESTADO INTERNO =====\n  const [searchValue, setSearchValue] = useState('');\n  const [showViewDropdown, setShowViewDropdown] = useState(false);\n\n  // ===== NAVIGATION ITEMS DEFAULT =====\n  const defaultNavigationItems = navigationItems || [\n    {\n      id: 'home',\n      icon: <HomeIcon className=\"w-4 h-4\" />,\n      label: 'Inicio',\n      active: true,\n    },\n    {\n      id: 'option1',\n      icon: <GlobeAltIcon className=\"w-4 h-4\" />,\n      label: 'Opción 1',\n    },\n    {\n      id: 'option2',\n      icon: <DocumentTextIcon className=\"w-4 h-4\" />,\n      label: 'Opción 2',\n    },\n    {\n      id: 'option3',\n      icon: <CloudIcon className=\"w-4 h-4\" />,\n      label: 'Opción 3',\n    },\n    {\n      id: 'more',\n      icon: <SquaresPlusIcon className=\"w-4 h-4\" />,\n      label: 'Ver más...',\n    },\n  ];\n\n  // ===== QUICK FILTERS DEFAULT =====\n  const defaultQuickFilters = quickFilters || [\n    {\n      id: 'paid',\n      label: 'Facturas Pagadas',\n      color: 'lime' as const,\n    },\n    {\n      id: 'pending',\n      label: 'Facturas Pendientes por Pago',\n      color: 'rose' as const,\n    },\n    {\n      id: 'orders',\n      label: 'Órdenes de Compra',\n      color: 'sky' as const,\n    },\n  ];\n\n  // ===== ACTION BUTTONS DEFAULT =====\n  const defaultActionButtons = actionButtons || [\n    {\n      id: 'audit',\n      label: 'Auditoría',\n      leftIcon: <ListBulletIcon className=\"w-4 h-4\" />,\n      type: 'default' as const,\n      onClick: () => {},\n    },\n    {\n      id: 'filter',\n      label: 'Filtrar',\n      leftIcon: <FunnelIcon className=\"w-4 h-4\" />,\n      type: 'default' as const,\n      onClick: () => {},\n    },\n    {\n      id: 'create',\n      label: 'Crear',\n      leftIcon: <PlusIcon className=\"w-4 h-4\" />,\n      type: 'default' as const,\n      onClick: () => {},\n    },\n  ];\n\n  // ===== HANDLERS =====\n  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setSearchValue(e.target.value);\n    onSearch?.(e.target.value);\n  };\n\n  // ===== CONVERTIR COLUMNAS AL FORMATO DE TABLE =====\n  const tableColumns: TableColumn<T>[] = columns.map((col) => ({\n    header: col.header,\n    accessor: col.accessor,\n    sortable: col.sortable,\n    render: col.render,\n    align: col.align,\n    width: col.width,\n  }));\n\n  return (\n    <div\n      className={[\n        'bg-background-secondary',\n        'dark:bg-dark-bg-primary',\n        'flex',\n        'w-full',\n        'h-full',\n        'min-h-screen',\n        className,\n      ].join(' ')}\n    >\n      {/* ===== NAVIGATION RAIL GROUP ===== */}\n      {showNavigationRail && (\n        <NavigationRailGroup\n          state={navigationRailState}\n          items={defaultNavigationItems}\n          onStateChange={onNavigationRailStateChange}\n          onItemClick={onNavItemClick}\n          showSearchButton={true}\n        />\n      )}\n\n      {/* ===== CONTENEDOR PRINCIPAL ===== */}\n      <div className=\"flex flex-col flex-1 overflow-hidden\">\n        {/* ===== NAVBAR ===== */}\n        <Navbar\n          productName={navbarProductName}\n          environmentBadge={environmentBadge}\n          userDropdown={userDropdown}\n          notifications={notifications}\n          hideActionButtons={false}\n          onNotificationsClick={onNotificationsClick}\n          className=\"bg-background-secondary dark:bg-dark-bg-primary\"\n        />\n\n        {/* ===== QUICK FILTERS BAR ===== */}\n        <div className=\"flex items-center gap-2 px-4 py-2 w-full bg-background-secondary dark:bg-dark-bg-primary\">\n          {defaultQuickFilters.map((filter) => (\n            <Badge\n              key={filter.id}\n              color={filter.color}\n              label={filter.label}\n              leftIcon={filter.icon}\n            />\n          ))}\n        </div>\n\n        {/* ===== BODY ===== */}\n        <div className=\"flex flex-1 overflow-hidden bg-background-secondary dark:bg-dark-bg-primary\">\n          <div className=\"flex flex-col gap-4 flex-1 bg-white dark:bg-dark-bg-primary p-4 rounded-tl-3xl overflow-hidden\">\n            {/* Header Row */}\n            <div className=\"flex items-center justify-between w-full\">\n              <h2 className=\"font-bold text-xl leading-7 tracking-[-0.5px] text-content-primary dark:text-dark-content-primary\">\n                {title}\n              </h2>\n\n              {/* Action Buttons */}\n              <div className=\"flex items-center gap-2\">\n                {defaultActionButtons.map((btn) => (\n                  <Button\n                    key={btn.id}\n                    type={btn.type}\n                    size=\"sm\"\n                    leftIcon={btn.leftIcon}\n                    onClick={btn.onClick}\n                  >\n                    {btn.label}\n                  </Button>\n                ))}\n              </div>\n            </div>\n\n            {/* ===== TABLE CONTAINER ===== */}\n            <div className=\"flex flex-col gap-4 flex-1 bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-xl p-8 overflow-hidden\">\n              {/* Table Header */}\n              <div className=\"flex items-center gap-4 w-full\">\n                <h3 className=\"flex-1 font-bold text-base leading-6 text-content-primary dark:text-dark-content-primary overflow-hidden text-ellipsis whitespace-nowrap\">\n                  {tableTitle}\n                </h3>\n                <Input\n                  placeholder={searchPlaceholder}\n                  startIcon={<EnvelopeIcon className=\"w-4 h-4\" />}\n                  value={searchValue}\n                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {\n                    handleSearch(e);\n                  }}\n                  className=\"w-[200px]\"\n                />\n                {/* View Dropdown */}\n                {viewOptions && (\n                  <div className=\"relative\">\n                    <button\n                      onClick={() => setShowViewDropdown(!showViewDropdown)}\n                      className=\"flex items-center gap-3 px-3 py-2 bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-lg shadow-xs hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors\"\n                    >\n                      <span className=\"font-bold text-sm text-content-secondary dark:text-content-secondary\">\n                        Ver\n                      </span>\n                      <ChevronDownIcon className=\"w-5 h-5 text-content-secondary dark:text-content-secondary\" />\n                    </button>\n                    {showViewDropdown && (\n                      <div className=\"absolute top-full right-0 mt-1 bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-lg shadow-lg z-10 min-w-[150px]\">\n                        {viewOptions.map((option) => (\n                          <button\n                            key={option.id}\n                            onClick={() => {\n                              onViewOptionChange?.(option.id);\n                              setShowViewDropdown(false);\n                            }}\n                            className={[\n                              'block',\n                              'w-full',\n                              'px-4',\n                              'py-2',\n                              'text-left',\n                              'text-sm',\n                              'hover:bg-background-secondary',\n                              'dark:hover:bg-dark-bg-secondary',\n                              selectedViewOption === option.id\n                                ? 'bg-primary-100 dark:bg-primary-600/20'\n                                : '',\n                            ].join(' ')}\n                          >\n                            {option.label}\n                          </button>\n                        ))}\n                      </div>\n                    )}\n                  </div>\n                )}\n              </div>\n\n              {/* ===== TABLE ===== */}\n              <Table\n                columns={tableColumns}\n                data={data}\n                variant=\"grid\"\n                showBorder={false}\n                showShadow={false}\n                loading={loading}\n                loadingRows={loadingRows}\n                emptyMessage={emptyMessage}\n                onSort={onSort}\n                sortColumn={externalSortColumn}\n                sortDirection={externalSortDirection}\n                pagination={pagination}\n                className=\"flex-1\"\n              />\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono de sobre (envelope) para el input de email\n */\nexport const EnvelopeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n\n/**\n * Icono de candado cerrado (lock) para el input de contraseña\n */\nexport const LockClosedIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V7A1.5 1.5 0 0 0 3 8.5v5A1.5 1.5 0 0 0 4.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 11.5 7V4.5A3.5 3.5 0 0 0 8 1Zm2 6V4.5a2 2 0 1 0-4 0V7h4Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono de ojo (eye) para mostrar/ocultar contraseña\n */\nexport const EyeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z\" />\n    <path\n      fillRule=\"evenodd\"\n      d=\"M1.38 8.28a.87.87 0 0 1 0-.566 7.003 7.003 0 0 1 13.238.006.87.87 0 0 1 0 .56A7.003 7.003 0 0 1 1.379 8.28ZM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Logo de Siesa\n */\nexport const SiesaLogo: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    width=\"200\"\n    height=\"50\"\n    viewBox=\"0 0 200 50\"\n    fill=\"none\"\n    xmlns=\"http://www.w3.org/2000/svg\"\n    {...props}\n  >\n    {/* Símbolo de Siesa (cuadrados azules) */}\n    <rect x=\"0\" y=\"0\" width=\"15\" height=\"20\" fill=\"#0e79fd\" />\n    <rect x=\"0\" y=\"30\" width=\"10\" height=\"20\" fill=\"#0e79fd\" />\n    <rect x=\"20\" y=\"0\" width=\"15\" height=\"20\" fill=\"#0e79fd\" />\n    <rect x=\"30\" y=\"30\" width=\"10\" height=\"20\" fill=\"#0e79fd\" />\n\n    {/* Texto \"Siesa\" */}\n    <text\n      x=\"68\"\n      y=\"35\"\n      fontFamily=\"Inter, sans-serif\"\n      fontSize=\"32\"\n      fontWeight=\"400\"\n      fill=\"#0e79fd\"\n    >\n      Siesa\n    </text>\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type { FormEvent } from 'react';\nimport type { LoginViewProps } from './LoginView.types';\nimport { EnvelopeIcon, LockClosedIcon, EyeIcon } from './icons';\n\n/**\n * LoginView - Vista de inicio de sesión del sistema Siesa\n *\n * Vista completa de login con formulario de autenticación que incluye:\n * - Logo de Siesa\n * - Campos de email y contraseña\n * - Opción de \"olvidé mi contraseña\"\n * - Link para crear cuenta nueva\n * - Fondo decorativo opcional\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels y manejo de formulario semántico\n * - Validación de email básica\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * <LoginView\n *   onSubmit={(email, password) => console.log('Login', email, password)}\n *   onForgotPassword={() => console.log('Forgot password')}\n *   onSignUp={() => console.log('Sign up')}\n * />\n * ```\n */\nexport const LoginView: React.FC<LoginViewProps> = ({\n  onSubmit,\n  onForgotPassword,\n  onSignUp,\n  isLoading = false,\n  errorMessage,\n  className = '',\n  showBackground = true,\n  variant = 'responsive',\n}) => {\n  // ===== ESTADO LOCAL =====\n  const [email, setEmail] = useState('');\n  const [password, setPassword] = useState('');\n  const [showPassword, setShowPassword] = useState(false);\n  const [emailError, setEmailError] = useState('');\n\n  // ===== HANDLERS =====\n  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n\n    // Validación básica de email\n    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n    if (!emailRegex.test(email)) {\n      setEmailError('Por favor ingresa un email válido');\n      return;\n    }\n\n    setEmailError('');\n    onSubmit?.(email, password);\n  };\n\n  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n    if (emailError) setEmailError('');\n  };\n\n  const togglePasswordVisibility = () => {\n    setShowPassword(!showPassword);\n  };\n\n  return (\n    <div\n      className={[\n        'relative',\n        'min-h-screen',\n        'w-full',\n        'flex',\n        'flex-col',\n        'items-center',\n        'justify-center',\n        'box-border',\n        // Mobile: sin padding en el wrapper (el padding está en el contenedor)\n        'p-0',\n        // Desktop: padding para centrar el card\n        'md:p-4',\n        className,\n      ].join(' ')}\n    >\n      {/* ===== FONDO DECORATIVO ===== */}\n      {showBackground && (\n        <div className=\"absolute inset-0 pointer-events-none\" aria-hidden=\"true\">\n          <div className=\"absolute inset-0 bg-primary-100 dark:bg-dark-bg-custom\" />\n          <img\n            src=\"/bg_siesa.png\"\n            alt=\"\"\n            className=\"absolute inset-0 w-full h-full object-cover opacity-10\"\n          />\n        </div>\n      )}\n\n      {/* ===== CONTENEDOR PRINCIPAL ===== */}\n      <div\n        className={[\n          // Clases base comunes\n          'relative',\n          'box-border',\n          'flex',\n          'flex-col',\n          'items-center',\n          'justify-center',\n          'gap-4',\n          'p-16',\n          'shrink-0',\n          'bg-bg-primary',\n          'dark:bg-dark-bg-primary',\n\n          // Clases específicas según variant\n          ...(variant === 'mobile' ? [\n            // Forzar mobile: sin efectos de card\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n          ] : variant === 'desktop' ? [\n            // Forzar desktop: con efectos de card\n            'w-[400px]',\n            'h-auto',\n            'rounded-2xl',\n            'shadow-lg',\n            'dark:shadow-2xl',\n            'overflow-clip',\n            'border',\n            'border-transparent',\n            'dark:border-dark-border-primary',\n          ] : [\n            // Responsive: cambia según viewport\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n            'md:w-[400px]',\n            'md:h-auto',\n            'md:rounded-2xl',\n            'md:shadow-lg',\n            'md:dark:shadow-2xl',\n            'md:overflow-clip',\n            'md:border',\n            'md:border-transparent',\n            'md:dark:border-dark-border-primary',\n          ]),\n        ].join(' ')}\n      >\n        {/* ===== LOGO ===== */}\n        <div className=\"w-full flex flex-col items-center pb-4\">\n          <img\n            src=\"/.Siesa Logo.png\"\n            alt=\"Siesa\"\n            className=\"w-[200px] h-[50px] object-contain\"\n          />\n        </div>\n\n        {/* ===== HEADING ===== */}\n        <div className=\"w-full text-center\">\n          <h1\n            className={[\n              'text-[20px]',\n              'leading-[28px]',\n              'font-bold',\n              'tracking-[-0.5px]',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Iniciar Sesión\n          </h1>\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Inicia sesión ingresando con tu correo electrónico y contraseña.\n          </p>\n        </div>\n\n        {/* ===== MENSAJE DE ERROR GENERAL ===== */}\n        {errorMessage && (\n          <div\n            className={[\n              'w-full',\n              'p-3',\n              'bg-error-bg',\n              'dark:bg-error-bg',\n              'border',\n              'border-error-border',\n              'dark:border-error-border',\n              'rounded-md',\n              'text-error-content',\n              'dark:text-error-content',\n              'text-sm',\n            ].join(' ')}\n            role=\"alert\"\n          >\n            {errorMessage}\n          </div>\n        )}\n\n        {/* ===== FORMULARIO ===== */}\n        <form onSubmit={handleSubmit} className=\"w-full flex flex-col gap-2\">\n          {/* Email Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"email-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Correo Electrónico <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <EnvelopeIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"email-input\"\n                type=\"email\"\n                placeholder=\"ejemplo@miempresa.com\"\n                value={email}\n                onChange={handleEmailChange}\n                disabled={isLoading}\n                required\n                autoComplete=\"email\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                  emailError ? 'border-error-border!' : '',\n                ].filter(Boolean).join(' ')}\n              />\n            </div>\n            {emailError && (\n              <p className=\"text-xs text-error-content dark:text-error-content\">\n                {emailError}\n              </p>\n            )}\n          </div>\n\n          {/* Password Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <div className=\"flex items-center justify-between\">\n              <label\n                htmlFor=\"password-input\"\n                className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n              >\n                Contraseña <span className=\"text-red-600\">*</span>\n              </label>\n              <button\n                type=\"button\"\n                onClick={onForgotPassword}\n                className=\"text-[12px] leading-4 font-bold text-primary-600 dark:text-[#93d1fd] hover:underline transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-[#93d1fd] rounded-sm px-1\"\n              >\n                Olvidé mi Contraseña\n              </button>\n            </div>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <LockClosedIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"password-input\"\n                type={showPassword ? 'text' : 'password'}\n                placeholder=\"••••••••\"\n                value={password}\n                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}\n                disabled={isLoading}\n                required\n                autoComplete=\"current-password\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-10',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                ].join(' ')}\n              />\n              <button\n                type=\"button\"\n                onClick={togglePasswordVisibility}\n                className=\"absolute right-3 top-1/2 -translate-y-1/2 opacity-50 hover:opacity-100 text-content-tertiary dark:text-dark-content-tertiary transition-opacity duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-dark-border-custom rounded-sm p-1\"\n                aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}\n              >\n                <EyeIcon className=\"w-4 h-4\" />\n              </button>\n            </div>\n          </div>\n\n          {/* Submit Button */}\n          <button\n            type=\"submit\"\n            disabled={isLoading || !email || !password}\n            className={[\n              'relative',\n              'w-full',\n              'px-2.5',\n              'py-1.5',\n              'flex',\n              'items-center',\n              'justify-center',\n              'gap-2',\n              'font-bold',\n              'text-sm',\n              'leading-5',\n              'text-primary-inverse-content',\n              'dark:text-[#0e79fd]',\n              'bg-[#0e79fd]',\n              'dark:bg-dark-bg-inverse',\n              'border',\n              'border-[#3c9bf6]',\n              'dark:border-[#93d1fd]',\n              'rounded-md',\n              'shadow-button-inset',\n              'hover:bg-primary-500',\n              'dark:hover:bg-[#93d1fd]',\n              'active:scale-95',\n              'transition-all',\n              'duration-150',\n              'focus:outline-hidden',\n              'focus:ring-2',\n              'focus:ring-primary-400',\n              'dark:focus:ring-[#93d1fd]',\n              'focus:ring-offset-2',\n              'dark:focus:ring-offset-[#3f3f46]',\n              'disabled:opacity-50',\n              'disabled:cursor-not-allowed',\n            ].join(' ')}\n          >\n            {isLoading ? 'Iniciando sesión...' : 'Iniciar Sesión'}\n          </button>\n        </form>\n\n        {/* ===== SIGN UP LINK ===== */}\n        <button\n          type=\"button\"\n          onClick={onSignUp}\n          className={[\n            'w-full',\n            'px-2.5',\n            'py-1.5',\n            'flex',\n            'items-center',\n            'justify-center',\n            'gap-2',\n            'font-bold',\n            'text-sm',\n            'leading-5',\n            'text-[#0e79fd]',\n            'dark:text-[#93d1fd]',\n            'hover:bg-primary-100',\n            'dark:hover:bg-[#93d1fd]/10',\n            'rounded-md',\n            'transition-all',\n            'duration-150',\n            'focus:outline-hidden',\n            'focus:ring-2',\n            'focus:ring-primary-400',\n            'dark:focus:ring-[#93d1fd]',\n            'focus:ring-offset-2',\n            'dark:focus:ring-offset-[#3f3f46]',\n          ].join(' ')}\n        >\n          ¿No tienes una cuenta?\n        </button>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Iconos para ProductsView\n * Basados en Heroicons Micro (16x16px)\n */\n\nexport const ArrowLeftIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M14 8a.75.75 0 0 1-.75.75H4.56l3.22 3.22a.75.75 0 1 1-1.06 1.06l-4.5-4.5a.75.75 0 0 1 0-1.06l4.5-4.5a.75.75 0 0 1 1.06 1.06L4.56 7.25h8.69A.75.75 0 0 1 14 8Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\nexport const CheckIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M12.416 3.376a.75.75 0 0 1 .208 1.04l-5 7.5a.75.75 0 0 1-1.154.114l-3-3a.75.75 0 0 1 1.06-1.06l2.353 2.353 4.493-6.74a.75.75 0 0 1 1.04-.207Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n","import React from 'react';\nimport type { ProductsViewProps } from './ProductsView.types';\nimport { Button } from '../../components/Button';\nimport { POSProductButton } from '../../components/POSProductButton';\nimport { POSProductCard } from '../../components/POSProductCard';\nimport { POSProductSidebarItems } from '../../components/POSProductSidebarItems';\nimport { Divider } from '../../components/Divider/Divider';\nimport { Navbar } from '../../components/Navbar';\nimport {\n  ArrowLeftIcon,\n  CheckIcon,\n} from './icons';\n\n/**\n * ProductsView - Vista de selección de productos para sistema POS\n *\n * Vista completa para sistemas POS que permite:\n * - Seleccionar categorías de productos\n * - Ver y agregar productos al pedido\n * - Gestionar items del pedido (cantidad, eliminar)\n * - Ver resumen con subtotal, impuestos y total\n * - Confirmar pedido\n *\n * **Composición:**\n * - Navbar superior con navegación y usuario\n * - Área de contenido con 3 columnas:\n *   - Columna 1: Sidebar de categorías (POSProductButton)\n *   - Columna 2: Grid de productos (POSProductCard)\n *   - Columna 3: Sidebar de pedido (POSProductSidebarItems)\n *\n * **Responsive:**\n * - Mobile (< 768px): Layout vertical adaptativo\n * - Desktop (≥ 768px): Layout de 3 columnas según Figma\n *\n * **Dark Mode:**\n * - Soporte completo con tokens del sistema\n * - Fondos, textos y bordes adaptativos\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Responsive design con breakpoints\n * - Composición con componentes del sistema\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see src/components/POSProductButton - Botón de categoría\n * @see src/components/POSProductCard - Card de producto\n * @see src/components/POSProductSidebarItems - Item de pedido\n *\n * @example\n * ```tsx\n * <ProductsView\n *   tableTitle=\"Mesa 1\"\n *   categories={categories}\n *   products={products}\n *   orderItems={orderItems}\n *   onAddProduct={(id) => console.log('Agregar', id)}\n *   onConfirmOrder={() => console.log('Confirmar')}\n * />\n * ```\n */\nexport const ProductsView: React.FC<ProductsViewProps> = ({\n  tableTitle = 'Mesa 1',\n  changeTableLabel = 'Cambiar Mesa',\n  menusTitle = 'Menús',\n  menus = [\n    { id: '1', label: 'Corral' },\n    { id: '2', label: 'Burguer One' },\n    { id: '3', label: 'Andrés Carne de Res' },\n    { id: '4', label: 'Aceites' },\n    { id: '5', label: 'Kiosco Mac' },\n    { id: '6', label: 'Kiosco Qbano' },\n    { id: '7', label: 'Premier Dinning' },\n  ],\n  selectedMenuId = '1',\n  onMenuSelect,\n  onChangeTable,\n  categoryTitle = 'Categoría',\n  categories = [],\n  selectedCategoryId,\n  onCategorySelect,\n  productsTitle = 'Productos',\n  products = [],\n  onAddProduct,\n  activeTab = 'products',\n  onTabChange,\n  orderItems = [],\n  onOrderItemQuantityChange,\n  onOrderItemDelete,\n  subtotal = '40,000.00',\n  taxes = '40,000.00',\n  total = '40,000.00',\n  confirmLabel = 'Confirmar Pedido',\n  onConfirmOrder,\n  isLoading = false,\n  errorMessage,\n  userAvatar,\n  userName = 'Jhonnatan Diaz',\n  userRole = 'Administrador',\n  businessLogo,\n  siesaLogo,\n  className = '',\n}) => {\n  return (\n    <div\n      className={`\n        min-h-screen\n        w-full\n        bg-background-secondary\n        dark:bg-dark-bg-primary\n        flex\n        flex-col\n        ${className}\n      `.trim().replace(/\\s+/g, ' ')}\n    >\n      {/* ===== NAVBAR ===== */}\n      <Navbar\n        logo={\n          businessLogo && (\n            <div className=\"h-[30px] w-[168px] overflow-hidden\">\n              {typeof businessLogo === 'string' ? (\n                <img src={businessLogo} alt=\"Business Logo\" className=\"h-full w-full object-contain\" />\n              ) : (\n                businessLogo\n              )}\n            </div>\n          )\n        }\n        productName=\"\"\n        userDropdown={\n          userAvatar\n            ? {\n              avatar: userAvatar,\n              name: userName,\n              role: userRole,\n            }\n            : undefined\n        }\n        hideActionButtons\n        siesaLogo={\n          siesaLogo && (\n            <div className=\"h-[30px] w-[120px] overflow-hidden\">\n              {typeof siesaLogo === 'string' ? (\n                <img src={siesaLogo} alt=\"Siesa Logo\" className=\"h-full w-full object-contain\" />\n              ) : (\n                siesaLogo\n              )}\n            </div>\n          )\n        }\n        variant=\"desktop\"\n        className=\"bg-background-secondary dark:bg-dark-bg-primary\"\n      />\n\n      {/* ===== CONTAINER ===== */}\n      <div className=\"flex flex-1 w-full overflow-hidden\">\n        {/* ===== ROW PRINCIPAL ===== */}\n        <div className=\"flex flex-1 w-full overflow-hidden\">\n          {/* ===== COLUMNA 1: ÁREA DE CONTENIDO (Menu + Body) ===== */}\n          <div\n            className=\"\n              flex-1\n              flex\n              flex-col\n              gap-4\n              p-4\n              bg-white\n              dark:bg-dark-bg-primary\n              rounded-tl-3xl\n              rounded-tr-3xl\n              overflow-hidden\n            \"\n          >\n            {/* Menu de navegación */}\n            <div className=\"flex items-center gap-4 w-full\">\n              {/* Cambiar Mesa Button */}\n              <div className=\"shrink-0\">\n                <Button\n                  type=\"default\"\n                  leftIcon={<ArrowLeftIcon className=\"w-4 h-4\" />}\n                  onClick={onChangeTable}\n                  ariaLabel={changeTableLabel}\n                >\n                  {changeTableLabel}\n                </Button>\n              </div>\n\n              {/* Divider */}\n              <div className=\"h-8 w-px bg-border-primary dark:bg-dark-border-primary shrink-0\" />\n\n              {/* Título Menús */}\n              <div className=\"shrink-0\">\n                <h2 className=\"text-xl font-bold leading-7 tracking-tight text-content-primary dark:text-dark-content-primary\">\n                  {menusTitle}\n                </h2>\n              </div>\n\n              {/* Botones de menús con scroll horizontal */}\n              <div className=\"flex-1 flex gap-2 overflow-x-auto overflow-y-hidden\">\n                {menus.map((menu) => (\n                  <Button\n                    key={menu.id}\n                    type={selectedMenuId === menu.id ? 'default' : 'outline'}\n                    onClick={() => onMenuSelect?.(menu.id)}\n                  >\n                    {menu.label}\n                  </Button>\n                ))}\n              </div>\n            </div>\n\n            {/* Body: Categorías + Productos */}\n            <div\n              className=\"\n                flex-1\n                flex\n                gap-0\n                bg-background-secondary\n                dark:bg-dark-bg-primary/50\n                rounded-xl\n                overflow-hidden\n              \"\n            >\n              {/* ===== SIDEBAR IZQUIERDO: CATEGORÍAS ===== */}\n              <div className=\"w-[213px] p-4 border-b border-border-primary dark:border-dark-border-primary\">\n                <div className=\"flex flex-col gap-4 h-full\">\n                  {/* Título */}\n                  <div className=\"flex items-center justify-center w-full\">\n                    <h3 className=\"text-xl font-bold leading-6 text-content-primary dark:text-dark-content-primary\">\n                      {categoryTitle}\n                    </h3>\n                  </div>\n\n                  {/* Lista de categorías con scroll */}\n                  <div className=\"flex-1 flex flex-col gap-2 overflow-x-hidden overflow-y-auto\">\n                    {categories.map((category) => (\n                      <POSProductButton\n                        key={category.id}\n                        image={category.image}\n                        label={category.label}\n                        active={selectedCategoryId === category.id}\n                        onClick={() => onCategorySelect?.(category.id)}\n                      />\n                    ))}\n                  </div>\n                </div>\n              </div>\n\n              {/* ===== CONTENIDO PRINCIPAL: PRODUCTOS ===== */}\n              <div className=\"flex-1 p-4 border-l border-b border-border-primary dark:border-dark-border-primary\">\n                <div className=\"flex flex-col gap-4 h-full\">\n                  {/* Título */}\n                  <div className=\"flex items-center justify-center w-full\">\n                    <h3 className=\"text-xl font-bold leading-6 text-content-primary dark:text-dark-content-primary\">\n                      {productsTitle}\n                    </h3>\n                  </div>\n\n                  {/* Grid de productos con scroll - Flexbox centrado con max-width para 4 columnas (170px * 4 + 8px * 3 = 704px) */}\n                  <div className=\"flex-1 overflow-x-hidden overflow-y-auto\">\n                    <div className=\"flex flex-col items-center justify-start min-h-full w-full\">\n                      <div className=\"flex flex-wrap gap-2 justify-center max-w-[704px]\">\n                        {products.map((product) => (\n                          <POSProductCard\n                            key={product.id}\n                            image={product.image}\n                            productName={product.name}\n                            price={product.price}\n                            onAddClick={() => onAddProduct?.(product.id)}\n                          />\n                        ))}\n                      </div>\n                    </div>\n\n                    {/* Estado vacío */}\n                    {products.length === 0 && (\n                      <div className=\"flex items-center justify-center h-full\">\n                        <p className=\"text-content-secondary dark:text-content-secondary\">\n                          No hay productos disponibles\n                        </p>\n                      </div>\n                    )}\n\n                    {/* Estado de carga */}\n                    {isLoading && (\n                      <div className=\"flex items-center justify-center h-full\">\n                        <p className=\"text-content-secondary dark:text-content-secondary\">\n                          Cargando productos...\n                        </p>\n                      </div>\n                    )}\n\n                    {/* Estado de error */}\n                    {errorMessage && (\n                      <div className=\"flex items-center justify-center h-full\">\n                        <p className=\"text-red-600 dark:text-red-400\">\n                          {errorMessage}\n                        </p>\n                      </div>\n                    )}\n                  </div>\n                </div>\n              </div>\n            </div>\n          </div>\n\n          {/* ===== COLUMNA 2: SIDEBAR DERECHO (Pedido) ===== */}\n          <div className=\"w-[304px] p-4 flex flex-col gap-0 h-full overflow-hidden\">\n            <div className=\"flex flex-col h-full relative\">\n              {/* Heading */}\n              <div className=\"border-b border-border-primary dark:border-dark-border-primary pb-4 z-10\">\n                <h2 className=\"text-xl font-bold leading-7 tracking-tight text-content-primary dark:text-dark-content-primary\">\n                  {tableTitle}\n                </h2>\n              </div>\n\n              {/* Tabs */}\n              <div className=\"flex items-start py-2.5 z-10\">\n                <button\n                  className={`\n                    flex-1\n                    flex\n                    flex-col\n                    items-center\n                    p-2\n                    rounded-lg\n                    transition-colors\n                    duration-150\n                    ${activeTab === 'products' ? 'relative' : ''}\n                  `}\n                  onClick={() => onTabChange?.('products')}\n                >\n                  <span\n                    className={`\n                      text-sm\n                      font-bold\n                      leading-5\n                      ${activeTab === 'products'\n                        ? 'text-primary-600 dark:text-primary-600'\n                        : 'text-content-primary dark:text-dark-content-primary'\n                      }\n                    `}\n                  >\n                    Productos\n                  </span>\n                  {activeTab === 'products' && (\n                    <div className=\"absolute -bottom-2.5 left-0 right-0 h-0.5 bg-primary-600 dark:bg-primary-600 rounded-full\" />\n                  )}\n                </button>\n\n                <button\n                  className={`\n                    flex-1\n                    flex\n                    flex-col\n                    items-center\n                    p-2\n                    rounded-lg\n                    transition-colors\n                    duration-150\n                    ${activeTab === 'client' ? 'relative' : ''}\n                  `}\n                  onClick={() => onTabChange?.('client')}\n                >\n                  <span\n                    className={`\n                      text-sm\n                      font-bold\n                      leading-5\n                      ${activeTab === 'client'\n                        ? 'text-primary-600 dark:text-primary-600'\n                        : 'text-content-primary dark:text-dark-content-primary'\n                      }\n                    `}\n                  >\n                    Cliente\n                  </span>\n                  {activeTab === 'client' && (\n                    <div className=\"absolute -bottom-2.5 left-0 right-0 h-0.5 bg-primary-600 dark:bg-primary-600 rounded-full\" />\n                  )}\n                </button>\n              </div>\n\n              {/* Body: Lista de items del pedido */}\n              <div\n                className=\"\n                  flex-1\n                  flex\n                  flex-col\n                  gap-2\n                  p-4\n                  bg-white\n                  dark:bg-dark-bg-primary\n                  rounded-bl-lg\n                  rounded-br-lg\n                  overflow-x-hidden\n                  overflow-y-auto\n                  z-10\n                \"\n              >\n                {orderItems.map((item, index) => (\n                  <React.Fragment key={item.productId}>\n                    <POSProductSidebarItems\n                      categoryLabel={item.categoryLabel}\n                      categoryColor={item.categoryColor}\n                      productRef={item.productRef}\n                      price={item.price}\n                      productName={item.productName}\n                      descriptionItems={item.descriptionItems}\n                      showDescription={!!item.descriptionItems && item.descriptionItems.length > 0}\n                      quantity={item.quantity}\n                      onQuantityChange={(qty) => onOrderItemQuantityChange?.(item.productId, qty)}\n                      onDelete={() => onOrderItemDelete?.(item.productId)}\n                    />\n                    {index < orderItems.length - 1 && <Divider />}\n                  </React.Fragment>\n                ))}\n\n                {/* Estado vacío */}\n                {orderItems.length === 0 && (\n                  <div className=\"flex items-center justify-center h-full\">\n                    <p className=\"text-content-secondary dark:text-content-secondary text-center\">\n                      No hay productos en el pedido\n                    </p>\n                  </div>\n                )}\n              </div>\n\n              {/* Footer: Resumen y botón confirmar */}\n              <div className=\"flex flex-col gap-4 pt-4 z-10\">\n                {/* Resumen de precios */}\n                <div className=\"flex flex-col gap-2\">\n                  {/* Subtotal */}\n                  <div className=\"flex items-start text-base font-bold leading-6 text-content-primary dark:text-dark-content-primary\">\n                    <div className=\"flex-1\">Subtotal</div>\n                    <div className=\"flex-1 text-right\">{subtotal}</div>\n                  </div>\n\n                  {/* Impuestos */}\n                  <div className=\"flex items-start text-base font-bold leading-6 text-content-primary dark:text-dark-content-primary\">\n                    <div className=\"flex-1\">Impuestos</div>\n                    <div className=\"flex-1 text-right\">{taxes}</div>\n                  </div>\n\n                  {/* Divider */}\n                  <Divider />\n\n                  {/* Total */}\n                  <div className=\"flex items-start text-lg font-bold leading-7 text-content-primary dark:text-dark-content-primary\">\n                    <div className=\"flex-1\">Total</div>\n                    <div className=\"flex-1 text-right\">{total}</div>\n                  </div>\n                </div>\n\n                {/* Botón confirmar */}\n                <div className=\"flex gap-2 w-full\">\n                  <Button\n                    type=\"default\"\n                    leftIcon={<CheckIcon className=\"w-4 h-4\" />}\n                    onClick={onConfirmOrder}\n                    fullWidth\n                    disabled={orderItems.length === 0 || isLoading}\n                  >\n                    {confirmLabel}\n                  </Button>\n                </div>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n};\n\nProductsView.displayName = 'ProductsView';\n","import React from 'react';\n\n/**\n * Icono de sobre (envelope) para el campo de email\n * @see https://heroicons.com/\n */\nexport const EnvelopeIcon: React.FC<{ className?: string }> = ({ className = 'w-4 h-4' }) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    className={className}\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type { FormEvent } from 'react';\nimport type { RecoverPasswordViewProps } from './RecoverPasswordView.types';\nimport { EnvelopeIcon } from './icons';\n\n/**\n * RecoverPasswordView - Vista de recuperación de contraseña del sistema Siesa\n *\n * Vista completa para restablecer contraseña que incluye:\n * - Logo de Siesa\n * - Campo de email para enviar instrucciones\n * - Botón para regresar al login\n * - Fondo decorativo opcional\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels y manejo de formulario semántico\n * - Validación de email básica\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * <RecoverPasswordView\n *   onSubmit={(email) => console.log('Recover password for', email)}\n *   onBackToLogin={() => console.log('Back to login')}\n * />\n * ```\n */\nexport const RecoverPasswordView: React.FC<RecoverPasswordViewProps> = ({\n  onSubmit,\n  onBackToLogin,\n  isLoading = false,\n  errorMessage,\n  successMessage,\n  className = '',\n  showBackground = true,\n  variant = 'responsive',\n}) => {\n  // ===== ESTADO LOCAL =====\n  const [email, setEmail] = useState('');\n  const [emailError, setEmailError] = useState('');\n\n  // ===== HANDLERS =====\n  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n\n    // Validación básica de email\n    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n    if (!emailRegex.test(email)) {\n      setEmailError('Por favor ingresa un email válido');\n      return;\n    }\n\n    setEmailError('');\n    onSubmit?.(email);\n  };\n\n  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n    if (emailError) setEmailError('');\n  };\n\n  return (\n    <div\n      className={[\n        'relative',\n        'min-h-screen',\n        'w-full',\n        'flex',\n        'flex-col',\n        'items-center',\n        'justify-center',\n        'box-border',\n        // Mobile: sin padding en el wrapper (el padding está en el contenedor)\n        'p-0',\n        // Desktop: padding para centrar el card\n        'md:p-4',\n        className,\n      ].join(' ')}\n    >\n      {/* ===== FONDO DECORATIVO (solo desktop) ===== */}\n      {showBackground && (\n        <div className=\"hidden md:block absolute inset-0 pointer-events-none\" aria-hidden=\"true\">\n          <div className=\"absolute inset-0 bg-primary-100 dark:bg-dark-bg-custom\" />\n          <img\n            src=\"/bg_siesa.jpg\"\n            alt=\"\"\n            className=\"absolute inset-0 w-full h-full object-cover opacity-10\"\n          />\n        </div>\n      )}\n\n      {/* ===== CONTENEDOR PRINCIPAL ===== */}\n      <div\n        className={[\n          // Clases base comunes\n          'relative',\n          'box-border',\n          'flex',\n          'flex-col',\n          'items-center',\n          'justify-center',\n          'gap-4',\n          'p-16',\n          'shrink-0',\n          'bg-bg-primary',\n          'dark:bg-zinc-700',\n\n          // Clases específicas según variant\n          ...(variant === 'mobile' ? [\n            // Forzar mobile: sin efectos de card\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n          ] : variant === 'desktop' ? [\n            // Forzar desktop: con efectos de card\n            'w-[400px]',\n            'h-auto',\n            'rounded-2xl',\n            'shadow-lg',\n            'dark:shadow-2xl',\n            'overflow-clip',\n            'border',\n            'border-transparent',\n            'dark:border-dark-border-primary',\n          ] : [\n            // Responsive: cambia según viewport\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n            'md:w-[400px]',\n            'md:h-auto',\n            'md:rounded-2xl',\n            'md:shadow-lg',\n            'md:dark:shadow-2xl',\n            'md:overflow-clip',\n            'md:border',\n            'md:border-transparent',\n            'md:dark:border-dark-border-primary',\n          ]),\n        ].join(' ')}\n      >\n        {/* ===== LOGO ===== */}\n        <div className=\"w-full flex flex-col items-center pb-4\">\n          <img\n            src=\"/.Siesa Logo.png\"\n            alt=\"Siesa\"\n            className=\"w-[200px] h-[50px] object-contain\"\n          />\n        </div>\n\n        {/* ===== HEADING ===== */}\n        <div className=\"w-full text-center\">\n          <h1\n            className={[\n              'text-[20px]',\n              'leading-[28px]',\n              'font-bold',\n              'tracking-[-0.5px]',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Restablecer Contraseña\n          </h1>\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Reestablece tu contraseña ingresando con tu correo electrónico.\n          </p>\n        </div>\n\n        {/* ===== MENSAJE DE ERROR GENERAL ===== */}\n        {errorMessage && (\n          <div\n            className={[\n              'w-full',\n              'p-3',\n              'bg-error-bg',\n              'dark:bg-error-bg',\n              'border',\n              'border-error-border',\n              'dark:border-error-border',\n              'rounded-md',\n              'text-error-content',\n              'dark:text-error-content',\n              'text-sm',\n            ].join(' ')}\n            role=\"alert\"\n          >\n            {errorMessage}\n          </div>\n        )}\n\n        {/* ===== MENSAJE DE ÉXITO ===== */}\n        {successMessage && (\n          <div\n            className={[\n              'w-full',\n              'p-3',\n              'bg-[#d1fae5]',\n              'dark:bg-[#064e3b]',\n              'border',\n              'border-[#a7f3d0]',\n              'dark:border-[#065f46]',\n              'rounded-md',\n              'text-[#065f46]',\n              'dark:text-[#a7f3d0]',\n              'text-sm',\n            ].join(' ')}\n            role=\"status\"\n          >\n            {successMessage}\n          </div>\n        )}\n\n        {/* ===== FORMULARIO ===== */}\n        <form onSubmit={handleSubmit} className=\"w-full flex flex-col gap-2\">\n          {/* Email Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"email-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Correo Electrónico <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <EnvelopeIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"email-input\"\n                type=\"email\"\n                placeholder=\"ejemplo@miempresa.com\"\n                value={email}\n                onChange={handleEmailChange}\n                disabled={isLoading}\n                required\n                autoComplete=\"email\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-zinc-700',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                  emailError ? 'border-error-border!' : '',\n                ].filter(Boolean).join(' ')}\n              />\n            </div>\n            {emailError && (\n              <p className=\"text-xs text-error-content dark:text-error-content\">\n                {emailError}\n              </p>\n            )}\n          </div>\n\n          {/* Submit Button */}\n          <button\n            type=\"submit\"\n            disabled={isLoading || !email}\n            className={[\n              'relative',\n              'w-full',\n              'px-2.5',\n              'py-1.5',\n              'flex',\n              'items-center',\n              'justify-center',\n              'gap-2',\n              'font-bold',\n              'text-sm',\n              'leading-5',\n              'text-primary-inverse-content',\n              'dark:text-[#0e79fd]',\n              'bg-[#0e79fd]',\n              'dark:bg-dark-bg-inverse',\n              'border',\n              'border-[#3c9bf6]',\n              'dark:border-[#93d1fd]',\n              'rounded-md',\n              'shadow-button-inset',\n              'hover:bg-primary-500',\n              'dark:hover:bg-[#93d1fd]',\n              'active:scale-95',\n              'transition-all',\n              'duration-150',\n              'focus:outline-hidden',\n              'focus:ring-2',\n              'focus:ring-primary-400',\n              'dark:focus:ring-[#93d1fd]',\n              'focus:ring-offset-2',\n              'dark:focus:ring-offset-[#3f3f46]',\n              'disabled:opacity-50',\n              'disabled:cursor-not-allowed',\n            ].join(' ')}\n          >\n            {isLoading ? 'Enviando...' : 'Reestablecer Contraseña'}\n          </button>\n        </form>\n\n        {/* ===== BACK TO LOGIN BUTTON ===== */}\n        <button\n          type=\"button\"\n          onClick={onBackToLogin}\n          className={[\n            'w-full',\n            'px-2.5',\n            'py-1.5',\n            'flex',\n            'items-center',\n            'justify-center',\n            'gap-2',\n            'font-bold',\n            'text-sm',\n            'leading-5',\n            'text-[#0e79fd]',\n            'dark:text-[#93d1fd]',\n            'bg-transparent',\n            'border',\n            'border-[#93d1fd]',\n            'dark:border-[#93d1fd]',\n            'rounded-md',\n            'hover:bg-primary-100',\n            'dark:hover:bg-[#93d1fd]/10',\n            'transition-all',\n            'duration-150',\n            'focus:outline-hidden',\n            'focus:ring-2',\n            'focus:ring-primary-400',\n            'dark:focus:ring-[#93d1fd]',\n            'focus:ring-offset-2',\n            'dark:focus:ring-offset-[#3f3f46]',\n          ].join(' ')}\n        >\n          Iniciar Sesión\n        </button>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Icono de círculo de usuario para el input de nombre\n */\nexport const UserCircleIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M15 8A7 7 0 1 1 1 8a7 7 0 0 1 14 0Zm-5-2a2 2 0 1 1-4 0 2 2 0 0 1 4 0ZM8 9c-1.825 0-3.422.977-4.295 2.437A5.49 5.49 0 0 0 8 13.5a5.49 5.49 0 0 0 4.294-2.063A4.997 4.997 0 0 0 8 9Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono de sobre (envelope) para el input de email\n */\nexport const EnvelopeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z\" />\n    <path d=\"M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z\" />\n  </svg>\n);\n\n/**\n * Icono de candado cerrado (lock) para el input de contraseña\n */\nexport const LockClosedIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V7A1.5 1.5 0 0 0 3 8.5v5A1.5 1.5 0 0 0 4.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 11.5 7V4.5A3.5 3.5 0 0 0 8 1Zm2 6V4.5a2 2 0 1 0-4 0V7h4Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n/**\n * Icono de ojo (eye) para mostrar/ocultar contraseña\n */\nexport const EyeIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <svg\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    {...props}\n  >\n    <path d=\"M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z\" />\n    <path\n      fillRule=\"evenodd\"\n      d=\"M1.38 8.28a.87.87 0 0 1 0-.566 7.003 7.003 0 0 1 13.238.006.87.87 0 0 1 0 .56A7.003 7.003 0 0 1 1.379 8.28ZM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n","import React, { useState } from 'react';\nimport type { FormEvent } from 'react';\nimport type { SignUpViewProps } from './SignUpView.types';\nimport { UserCircleIcon, EnvelopeIcon, LockClosedIcon, EyeIcon } from './icons';\n\n/**\n * SignUpView - Vista de registro del sistema Siesa\n *\n * Vista completa de registro con formulario que incluye:\n * - Logo de Siesa\n * - Campos de nombre, email y contraseña\n * - Botón de registro\n * - Link para iniciar sesión\n * - Texto de términos y condiciones\n * - Fondo decorativo opcional\n *\n * Mejores prácticas implementadas:\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels y manejo de formulario semántico\n * - Validación de email básica\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * <SignUpView\n *   onSubmit={(name, email, password) => console.log('Sign up', name, email, password)}\n *   onSignIn={() => console.log('Go to sign in')}\n *   onTermsClick={() => console.log('View terms')}\n *   onPrivacyClick={() => console.log('View privacy')}\n * />\n * ```\n */\nexport const SignUpView: React.FC<SignUpViewProps> = ({\n  onSubmit,\n  onSignIn,\n  onTermsClick,\n  onPrivacyClick,\n  isLoading = false,\n  errorMessage,\n  className = '',\n  showBackground = true,\n  variant = 'responsive',\n}) => {\n  // ===== ESTADO LOCAL =====\n  const [name, setName] = useState('');\n  const [email, setEmail] = useState('');\n  const [password, setPassword] = useState('');\n  const [showPassword, setShowPassword] = useState(false);\n  const [emailError, setEmailError] = useState('');\n\n  // ===== HANDLERS =====\n  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n\n    // Validación básica de email\n    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n    if (!emailRegex.test(email)) {\n      setEmailError('Por favor ingresa un email válido');\n      return;\n    }\n\n    setEmailError('');\n    onSubmit?.(name, email, password);\n  };\n\n  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n    if (emailError) setEmailError('');\n  };\n\n  const togglePasswordVisibility = () => {\n    setShowPassword(!showPassword);\n  };\n\n  return (\n    <div\n      className={[\n        'relative',\n        'min-h-screen',\n        'w-full',\n        'flex',\n        'flex-col',\n        'items-center',\n        'justify-center',\n        'box-border',\n        // Mobile: sin padding en el wrapper\n        'p-0',\n        // Desktop: padding para centrar el card\n        'md:p-4',\n        className,\n      ].join(' ')}\n    >\n      {/* ===== FONDO DECORATIVO ===== */}\n      {showBackground && (\n        <div className=\"absolute inset-0 pointer-events-none\" aria-hidden=\"true\">\n          <div className=\"absolute inset-0 bg-primary-100 dark:bg-dark-bg-custom\" />\n          <img\n            src=\"/bg_siesa.png\"\n            alt=\"\"\n            className=\"absolute inset-0 w-full h-full object-cover opacity-10\"\n          />\n        </div>\n      )}\n\n      {/* ===== CONTENEDOR PRINCIPAL ===== */}\n      <div\n        className={[\n          // Clases base comunes\n          'relative',\n          'box-border',\n          'flex',\n          'flex-col',\n          'items-center',\n          'justify-center',\n          'gap-4',\n          'p-16',\n          'shrink-0',\n          'bg-bg-primary',\n          'dark:bg-dark-bg-primary',\n\n          // Clases específicas según variant\n          ...(variant === 'mobile' ? [\n            // Forzar mobile: sin efectos de card\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n          ] : variant === 'desktop' ? [\n            // Forzar desktop: con efectos de card\n            'w-[400px]',\n            'h-auto',\n            'rounded-2xl',\n            'shadow-lg',\n            'dark:shadow-2xl',\n            'overflow-clip',\n            'border',\n            'border-transparent',\n            'dark:border-dark-border-primary',\n          ] : [\n            // Responsive: cambia según viewport\n            'w-full',\n            'h-full',\n            'shadow-none',\n            'rounded-none',\n            'border-0',\n            'md:w-[400px]',\n            'md:h-auto',\n            'md:rounded-2xl',\n            'md:shadow-lg',\n            'md:dark:shadow-2xl',\n            'md:overflow-clip',\n            'md:border',\n            'md:border-transparent',\n            'md:dark:border-dark-border-primary',\n          ]),\n        ].join(' ')}\n      >\n        {/* ===== LOGO ===== */}\n        <div className=\"w-full flex flex-col items-center pb-4\">\n          <img\n            src=\"/.Siesa Logo.png\"\n            alt=\"Siesa\"\n            className=\"w-[200px] h-[50px] object-contain\"\n          />\n        </div>\n\n        {/* ===== HEADING ===== */}\n        <div className=\"w-full text-center\">\n          <h1\n            className={[\n              'text-[20px]',\n              'leading-[28px]',\n              'font-bold',\n              'tracking-[-0.5px]',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Crear Cuenta\n          </h1>\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Ingresa todos los datos para crear tu cuenta.\n          </p>\n        </div>\n\n        {/* ===== MENSAJE DE ERROR GENERAL ===== */}\n        {errorMessage && (\n          <div\n            className={[\n              'w-full',\n              'p-3',\n              'bg-error-bg',\n              'dark:bg-error-bg',\n              'border',\n              'border-error-border',\n              'dark:border-error-border',\n              'rounded-md',\n              'text-error-content',\n              'dark:text-error-content',\n              'text-sm',\n            ].join(' ')}\n            role=\"alert\"\n          >\n            {errorMessage}\n          </div>\n        )}\n\n        {/* ===== FORMULARIO ===== */}\n        <form onSubmit={handleSubmit} className=\"w-full flex flex-col gap-2\">\n          {/* Name Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"name-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Nombre <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <UserCircleIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"name-input\"\n                type=\"text\"\n                placeholder=\"Juan Pérez\"\n                value={name}\n                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}\n                disabled={isLoading}\n                required\n                autoComplete=\"name\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                ].join(' ')}\n              />\n            </div>\n          </div>\n\n          {/* Email Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"email-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Correo Electrónico <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <EnvelopeIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"email-input\"\n                type=\"email\"\n                placeholder=\"ejemplo@miempresa.com\"\n                value={email}\n                onChange={handleEmailChange}\n                disabled={isLoading}\n                required\n                autoComplete=\"email\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-3',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                  emailError ? 'border-error-border!' : '',\n                ].filter(Boolean).join(' ')}\n              />\n            </div>\n            {emailError && (\n              <p className=\"text-xs text-error-content dark:text-error-content\">\n                {emailError}\n              </p>\n            )}\n          </div>\n\n          {/* Password Input */}\n          <div className=\"flex flex-col gap-2 w-full\">\n            <label\n              htmlFor=\"password-input\"\n              className=\"font-bold text-sm leading-5 text-content-primary dark:text-dark-content-primary\"\n            >\n              Contraseña <span className=\"text-red-600\">*</span>\n            </label>\n            <div className=\"relative\">\n              <div className=\"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none opacity-50\">\n                <LockClosedIcon className=\"w-4 h-4 text-content-tertiary dark:text-dark-content-tertiary\" />\n              </div>\n              <input\n                id=\"password-input\"\n                type={showPassword ? 'text' : 'password'}\n                placeholder=\"••••••••\"\n                value={password}\n                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}\n                disabled={isLoading}\n                required\n                autoComplete=\"new-password\"\n                className={[\n                  'w-full',\n                  'pl-9',\n                  'pr-10',\n                  'py-1.5',\n                  'text-base',\n                  'leading-6',\n                  'bg-bg-primary',\n                  'dark:bg-dark-bg-primary',\n                  'border',\n                  'border-border-primary',\n                  'dark:border-dark-border-primary',\n                  'rounded-lg',\n                  'placeholder:text-content-tertiary',\n                  'dark:placeholder:text-dark-content-tertiary',\n                  'text-content-primary',\n                  'dark:text-dark-content-primary',\n                  'focus:outline-hidden',\n                  'focus:border-primary-600',\n                  'dark:focus:border-dark-border-custom',\n                  'focus:ring-2',\n                  'focus:ring-primary-400',\n                  'dark:focus:ring-dark-border-custom',\n                  'transition-all',\n                  'duration-150',\n                ].join(' ')}\n              />\n              <button\n                type=\"button\"\n                onClick={togglePasswordVisibility}\n                className=\"absolute right-3 top-1/2 -translate-y-1/2 opacity-50 hover:opacity-100 text-content-tertiary dark:text-dark-content-tertiary transition-opacity duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-dark-border-custom rounded-sm p-1\"\n                aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}\n              >\n                <EyeIcon className=\"w-4 h-4\" />\n              </button>\n            </div>\n          </div>\n\n          {/* Submit Button */}\n          <button\n            type=\"submit\"\n            disabled={isLoading || !name || !email || !password}\n            className={[\n              'relative',\n              'w-full',\n              'px-2.5',\n              'py-1.5',\n              'flex',\n              'items-center',\n              'justify-center',\n              'gap-2',\n              'font-bold',\n              'text-sm',\n              'leading-5',\n              'text-primary-inverse-content',\n              'dark:text-[#0e79fd]',\n              'bg-[#0e79fd]',\n              'dark:bg-dark-bg-inverse',\n              'border',\n              'border-[#3c9bf6]',\n              'dark:border-[#93d1fd]',\n              'rounded-md',\n              'shadow-button-inset',\n              'hover:bg-primary-500',\n              'dark:hover:bg-[#93d1fd]',\n              'active:scale-95',\n              'transition-all',\n              'duration-150',\n              'focus:outline-hidden',\n              'focus:ring-2',\n              'focus:ring-primary-400',\n              'dark:focus:ring-[#93d1fd]',\n              'focus:ring-offset-2',\n              'dark:focus:ring-offset-[#3f3f46]',\n              'disabled:opacity-50',\n              'disabled:cursor-not-allowed',\n            ].join(' ')}\n          >\n            {isLoading ? 'Registrando...' : 'Registrarse'}\n          </button>\n        </form>\n\n        {/* ===== SIGN IN LINK ===== */}\n        <button\n          type=\"button\"\n          onClick={onSignIn}\n          className={[\n            'w-full',\n            'px-2.5',\n            'py-1.5',\n            'flex',\n            'items-center',\n            'justify-center',\n            'gap-2',\n            'font-bold',\n            'text-sm',\n            'leading-5',\n            'text-[#0e79fd]',\n            'dark:text-[#93d1fd]',\n            'hover:bg-primary-100',\n            'dark:hover:bg-[#93d1fd]/10',\n            'rounded-md',\n            'transition-all',\n            'duration-150',\n            'focus:outline-hidden',\n            'focus:ring-2',\n            'focus:ring-primary-400',\n            'dark:focus:ring-[#93d1fd]',\n            'focus:ring-offset-2',\n            'dark:focus:ring-offset-[#3f3f46]',\n          ].join(' ')}\n        >\n          Ya tengo una cuenta\n        </button>\n\n        {/* ===== TÉRMINOS Y CONDICIONES ===== */}\n        <div className=\"w-full text-center\">\n          <p\n            className={[\n              'text-[12px]',\n              'leading-[16px]',\n              'font-normal',\n              'text-content-primary',\n              'dark:text-dark-content-primary',\n            ].join(' ')}\n          >\n            Al registrarse, estás aceptando nuestras{' '}\n            <button\n              type=\"button\"\n              onClick={onTermsClick}\n              className=\"text-[#0e79fd] dark:text-[#93d1fd] underline hover:no-underline focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-[#93d1fd] rounded-sm\"\n            >\n              Condiciones de Uso\n            </button>\n            {' '}y nuestras{' '}\n            <button\n              type=\"button\"\n              onClick={onPrivacyClick}\n              className=\"text-[#0e79fd] dark:text-[#93d1fd] underline hover:no-underline focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-[#93d1fd] rounded-sm\"\n            >\n              Políticas de Privacidad\n            </button>\n            .\n          </p>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React from 'react';\n\n/**\n * Iconos para TableLayoutView\n * Basados en Heroicons Micro (16x16px)\n */\n\n// Icono Plus (heroicons-micro/plus)\nexport const PlusIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path d=\"M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z\" />\n  </svg>\n);\n\n// Icono Arrows Pointing In (heroicons-micro/arrows-pointing-in)\nexport const ArrowsPointingInIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M2.22 2.22a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06l-.72-.72v2.69a.75.75 0 0 1-1.5 0V2.5c0-.69.56-1.25 1.25-1.25h4.75a.75.75 0 0 1 0 1.5H4.81l.72.72a.75.75 0 0 1-1.06 1.06l-2-2a.75.75 0 0 1 0-1.06ZM9 2.75a.75.75 0 0 1 .75-.75h4.75C15.19 2 15.75 2.56 15.75 3.25v4.75a.75.75 0 0 1-1.5 0V5.31l-.72.72a.75.75 0 1 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06l-.72-.72V8a.75.75 0 0 1-1.5 0V3.5H9.75A.75.75 0 0 1 9 2.75ZM2.75 9a.75.75 0 0 1 .75.75v2.69l.72-.72a.75.75 0 1 1 1.06 1.06l-2 2a.75.75 0 0 1-1.06 0l-2-2a.75.75 0 1 1 1.06-1.06l.72.72V9.75c0-.41.34-.75.75-.75Zm10.5 0a.75.75 0 0 1 .75.75v3.5h3.5a.75.75 0 0 1 0 1.5h-4.75c-.69 0-1.25-.56-1.25-1.25V9.75a.75.75 0 0 1 .75-.75Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n// Icono Arrows Pointing Out (heroicons-micro/arrows-pointing-out)\nexport const ArrowsPointingOutIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M2.75 2a.75.75 0 0 0-.75.75v3.5a.75.75 0 0 0 1.5 0V3.81l2.47 2.47a.75.75 0 1 0 1.06-1.06L4.56 2.75h2.69a.75.75 0 0 0 0-1.5h-4.5ZM9 2.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 0 1.5h-2.69l2.47 2.47a.75.75 0 1 1-1.06 1.06L10.5 4.56v2.69a.75.75 0 0 1-1.5 0v-4.5ZM2.75 9a.75.75 0 0 1 .75.75v2.69l2.47-2.47a.75.75 0 1 1 1.06 1.06L4.56 13.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 1 .75-.75Zm10.5 0a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-.75.75h-4.5a.75.75 0 0 1 0-1.5h2.69l-2.47-2.47a.75.75 0 1 1 1.06-1.06l2.47 2.47V9.75a.75.75 0 0 1 .75-.75Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n// Icono Arrow Right End On Rectangle (heroicons-micro/arrow-right-end-on-rectangle)\nexport const ArrowRightEndOnRectangleIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M2 4.75A2.75 2.75 0 0 1 4.75 2h3a2.75 2.75 0 0 1 2.75 2.75v.5a.75.75 0 0 1-1.5 0v-.5c0-.69-.56-1.25-1.25-1.25h-3c-.69 0-1.25.56-1.25 1.25v6.5c0 .69.56 1.25 1.25 1.25h3c.69 0 1.25-.56 1.25-1.25v-.5a.75.75 0 0 1 1.5 0v.5A2.75 2.75 0 0 1 7.75 14h-3A2.75 2.75 0 0 1 2 11.25v-6.5Zm10.58 2.96-1.72-1.72a.75.75 0 1 1 1.06-1.06l2.78 2.78c.3.29.3.76 0 1.06l-2.78 2.78a.75.75 0 1 1-1.06-1.06l1.72-1.72H7.25a.75.75 0 0 1 0-1.5h5.33Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n// Icono Arrows Right Left (heroicons-micro/arrows-right-left)\nexport const ArrowsRightLeftIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path\n      fillRule=\"evenodd\"\n      d=\"M13.78 10.47a.75.75 0 0 1 0 1.06l-2.25 2.25a.75.75 0 1 1-1.06-1.06l.97-.97H5.75a.75.75 0 0 1 0-1.5h5.69l-.97-.97a.75.75 0 0 1 1.06-1.06l2.25 2.25ZM2.22 5.53a.75.75 0 0 1 0-1.06l2.25-2.25a.75.75 0 0 1 1.06 1.06l-.97.97h5.69a.75.75 0 0 1 0 1.5H4.56l.97.97a.75.75 0 1 1-1.06 1.06L2.22 5.53Z\"\n      clipRule=\"evenodd\"\n    />\n  </svg>\n);\n\n// Icono Rectangle Group (heroicons-micro/rectangle-group)\nexport const RectangleGroupIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path d=\"M2.5 3.5h3v3h-3v-3ZM6.5 2a.5.5 0 0 0-.5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5h-4ZM2.5 10.5h3v3h-3v-3ZM6.5 9a.5.5 0 0 0-.5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5h-4ZM10.5 3.5h3v3h-3v-3ZM13.5 2h-3a.5.5 0 0 0-.5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5h-.5ZM10.5 10.5h3v3h-3v-3Z\" />\n  </svg>\n);\n\n// Icono X Mark (heroicons-micro/x-mark)\nexport const XMarkIcon: React.FC<{ className?: string }> = ({ className = '' }) => (\n  <svg\n    className={className}\n    xmlns=\"http://www.w3.org/2000/svg\"\n    viewBox=\"0 0 16 16\"\n    fill=\"currentColor\"\n    aria-hidden=\"true\"\n  >\n    <path d=\"M5.28 4.22a.75.75 0 0 0-1.06 1.06L6.94 8l-2.72 2.72a.75.75 0 1 0 1.06 1.06L8 9.06l2.72 2.72a.75.75 0 1 0 1.06-1.06L9.06 8l2.72-2.72a.75.75 0 0 0-1.06-1.06L8 6.94 5.28 4.22Z\" />\n  </svg>\n);\n","import React from 'react';\nimport type { TableLayoutViewProps } from './TableLayoutView.types';\nimport { Navbar } from '../../components/Navbar/Navbar';\nimport { POSLocationButton } from '../../components/POSLocationButton/POSLocationButton';\nimport { POSTable } from '../../components/POSTable/POSTable';\nimport { POSConvention } from '../../components/POSConvention/POSConvention';\nimport { POSNumberButton } from '../../components/POSNumberButton/POSNumberButton';\nimport { Switch } from '../../components/Switch/Switch';\nimport { Button } from '../../components/Button/Button';\nimport {\n  PlusIcon,\n  ArrowsPointingInIcon,\n  ArrowsPointingOutIcon,\n  ArrowRightEndOnRectangleIcon,\n  ArrowsRightLeftIcon,\n  RectangleGroupIcon,\n  XMarkIcon,\n} from './icons';\n\n/**\n * TableLayoutView - Vista de layout de mesas para restaurante (POS)\n *\n * Vista completa pixel-perfect según especificaciones de Figma que incluye:\n * - Navbar superior con usuario y acciones\n * - Sidebar izquierdo con lista de salones/ubicaciones\n * - Área central con grid de mesas y controles\n * - Sidebar derecho con selector de cantidad de personas\n * - Leyenda de convenciones al pie del área central\n *\n * **Layout responsive:**\n * - Mobile: Columnas apiladas verticalmente\n * - Desktop: 3 columnas (sidebar izq 245px + centro flex + sidebar der 304px)\n *\n * **Mejores prácticas implementadas:**\n * - Orden de modificadores: {responsive}:{dark}:{state}:{utility}\n * - Dark mode con estrategia 'class' (darkMode: 'class')\n * - Tokens de color consistentes con la documentación\n * - Type safety con TypeScript estricto\n * - Accesibilidad con ARIA labels\n * - Mobile-first responsive design\n *\n * @see docs/colors.md - Sistema de colores\n * @see docs/typography.md - Sistema tipográfico\n * @see docs/spacing.md - Sistema de espaciado\n * @see docs/shadows.md - Sistema de sombras\n *\n * @example\n * ```tsx\n * <TableLayoutView\n *   locations={[\n *     { id: '1', name: 'Antejardín', status: 'available', capacity: { current: 1, total: 8 } },\n *     { id: '2', name: 'Terraza', status: 'occupied', capacity: { current: 8, total: 8 } },\n *   ]}\n *   tables={[\n *     { tableNumber: '01', status: 'available', shape: 'square', chairs: 8, isActive: true },\n *     { tableNumber: '02', status: 'available', shape: 'circle', chairs: 2 },\n *   ]}\n *   onTableSelect={(tableNum) => console.log('Mesa seleccionada:', tableNum)}\n * />\n * ```\n */\nexport const TableLayoutView: React.FC<TableLayoutViewProps> = ({\n  locations = [],\n  activeLocationId,\n  tables = [],\n  tablesTitle = 'Mesas de Antejardín',\n  showPeopleCountPanel = false,\n  selectedTable,\n  onLocationSelect,\n  onTableSelect,\n  onCreateTables,\n  onMergeTables,\n  onSplitTables,\n  onPeopleCountSelect,\n  onAssignTable,\n  onTransferTable,\n  onSetCutlery,\n  onClosePeoplePanel,\n  onTableSwitchChange,\n  isLoading = false,\n  errorMessage,\n  tableLayout = 'grid',\n  className = '',\n  userInfo,\n}) => {\n  // ===== RENDER NAVBAR =====\n  const renderNavbar = () => (\n    <div className=\"w-full shrink-0\">\n      <Navbar\n        variant=\"desktop\"\n        productName=\"\"\n        userDropdown={\n          userInfo\n            ? {\n              avatar: userInfo.avatar,\n              name: userInfo.name,\n              email: userInfo.role,\n              onMenuClick: () => { },\n            }\n            : undefined\n        }\n      />\n    </div>\n  );\n\n  // ===== RENDER SIDEBAR IZQUIERDO (SALONES) =====\n  const renderLocationsSidebar = () => (\n    <div\n      className={[\n        'w-full',\n        'md:w-[245px]',\n        'h-auto',\n        'md:h-full',\n        'shrink-0',\n        'flex',\n        'flex-col',\n        'gap-2.5',\n        'p-4',\n        'overflow-auto',\n      ].join(' ')}\n    >\n      {/* Título */}\n      <div className=\"w-full\">\n        <h2\n          className={[\n            'text-xl',\n            'leading-7',\n            'font-bold',\n            'tracking-[-0.5px]',\n            'text-content-primary',\n            'dark:text-dark-content-primary',\n          ].join(' ')}\n        >\n          Salones\n        </h2>\n      </div>\n\n      {/* Lista de ubicaciones */}\n      <div className=\"flex flex-col gap-2 w-full\">\n        {isLoading ? (\n          <div className=\"text-content-secondary dark:text-content-secondary text-sm\">\n            Cargando salones...\n          </div>\n        ) : locations.length === 0 ? (\n          <div className=\"text-content-secondary dark:text-content-secondary text-sm\">\n            No hay salones disponibles\n          </div>\n        ) : (\n          locations.map((location) => (\n            <POSLocationButton\n              key={location.id}\n              locationName={location.name}\n              status={location.status}\n              state={location.id === activeLocationId ? 'actived' : 'enabled'}\n              capacity={location.capacity}\n              onClick={() => onLocationSelect?.(location.id)}\n            />\n          ))\n        )}\n      </div>\n    </div>\n  );\n\n  // ===== RENDER ÁREA CENTRAL (MESAS) =====\n  const renderTablesArea = () => (\n    <div\n      className={[\n        'flex-1',\n        'min-w-0',\n        'flex',\n        'flex-col',\n        'gap-4',\n        'p-4',\n        'bg-white',\n        'dark:bg-dark-bg-primary',\n        'rounded-tl-3xl',\n        'rounded-tr-3xl',\n        'overflow-auto',\n      ].join(' ')}\n    >\n      {/* Header con título y botones */}\n      <div className=\"flex flex-col md:flex-row gap-4 items-start md:items-center justify-between w-full\">\n        {/* Título */}\n        <h2\n          className={[\n            'text-xl',\n            'leading-7',\n            'font-bold',\n            'tracking-[-0.5px]',\n            'text-content-primary',\n            'dark:text-dark-content-primary',\n            'flex-1',\n          ].join(' ')}\n        >\n          {tablesTitle}\n        </h2>\n\n        {/* Botones de acción */}\n        <div className=\"flex gap-2 flex-wrap\">\n          <Button\n            type=\"default\"\n            size=\"sm\"\n            leftIcon={<PlusIcon />}\n            onClick={onCreateTables}\n          >\n            Crear Mesas\n          </Button>\n          <Button\n            type=\"default\"\n            size=\"sm\"\n            leftIcon={<ArrowsPointingInIcon />}\n            onClick={onMergeTables}\n          >\n            Unir Mesas\n          </Button>\n          <Button\n            type=\"default\"\n            size=\"sm\"\n            leftIcon={<ArrowsPointingOutIcon />}\n            onClick={onSplitTables}\n          >\n            Separar Mesas\n          </Button>\n        </div>\n      </div>\n\n      {/* Área de mesas */}\n      <div\n        className={[\n          'flex-1',\n          'bg-background-secondary',\n          'dark:bg-dark-bg-secondary',\n          'rounded-xl',\n          'p-4',\n          'overflow-auto',\n          'min-h-[400px]',\n        ].join(' ')}\n      >\n        {isLoading ? (\n          <div className=\"flex items-center justify-center h-full text-content-secondary dark:text-content-secondary\">\n            Cargando mesas...\n          </div>\n        ) : errorMessage ? (\n          <div className=\"flex items-center justify-center h-full text-error-content dark:text-error-content\">\n            {errorMessage}\n          </div>\n        ) : tables.length === 0 ? (\n          <div className=\"flex items-center justify-center h-full text-content-secondary dark:text-content-secondary\">\n            No hay mesas en esta ubicación\n          </div>\n        ) : tableLayout === 'grid' ? (\n          /* Layout Flexbox centrado con ancho máximo restringido para 4 columnas (160px * 4 + 8px * 3 = 664px) */\n          <div className=\"flex flex-col items-center justify-center min-h-full w-full p-4\">\n            <div className=\"flex flex-wrap gap-2 justify-center max-w-[664px]\">\n              {tables.map((table) => (\n                <POSTable\n                  key={table.tableNumber}\n                  tableNumber={table.tableNumber}\n                  status={table.status}\n                  shape={table.shape}\n                  chairs={table.chairs}\n                  isActive={table.isActive}\n                  onClick={() => onTableSelect?.(table.tableNumber)}\n                />\n              ))}\n            </div>\n          </div>\n        ) : (\n          /* Layout libre con posicionamiento absoluto */\n          <div className=\"relative w-full h-full min-h-[400px]\">\n            {tables.map((table) => (\n              <div\n                key={table.tableNumber}\n                className=\"absolute\"\n                style={\n                  table.position\n                    ? {\n                      left: `${table.position.x}%`,\n                      top: `${table.position.y}%`,\n                      transform: 'translate(-50%, -50%)',\n                    }\n                    : undefined\n                }\n              >\n                <POSTable\n                  tableNumber={table.tableNumber}\n                  status={table.status}\n                  shape={table.shape}\n                  chairs={table.chairs}\n                  isActive={table.isActive}\n                  onClick={() => onTableSelect?.(table.tableNumber)}\n                />\n              </div>\n            ))}\n          </div>\n        )}\n      </div>\n\n      {/* Leyenda de convenciones */}\n      <div className=\"flex flex-wrap gap-4 items-center w-full\">\n        <POSConvention status=\"available\" />\n        <POSConvention status=\"occupied\" />\n        <POSConvention status=\"reserved\" />\n        <POSConvention status=\"outOfService\" />\n      </div>\n    </div>\n  );\n\n  // ===== RENDER SIDEBAR DERECHO (SELECTOR DE PERSONAS) =====\n  const renderPeopleCountSidebar = () => {\n    if (!showPeopleCountPanel) return null;\n\n    return (\n      <div\n        className={[\n          'w-full',\n          'md:w-[304px]',\n          'shrink-0',\n          'flex',\n          'flex-col',\n          'p-4',\n          'overflow-hidden',\n        ].join(' ')}\n      >\n        {/* Header con switch y botón cerrar */}\n        <div className=\"flex items-center justify-between w-full pb-4 border-b border-border-primary dark:border-dark-border-primary shrink-0\">\n          <Switch\n            label={selectedTable?.locationName || 'Ubicación'}\n            description={selectedTable?.tableName || 'Mesa'}\n            labelPosition=\"end\"\n            checked={false}\n            onCheckedChange={(checked) => onTableSwitchChange?.(checked)}\n          />\n          <button\n            className={[\n              'p-2',\n              'rounded-md',\n              'border',\n              'border-primary-300',\n              'text-primary-600',\n              'hover:bg-background-secondary',\n              'dark:border-dark-border-custom',\n              'dark:hover:bg-dark-bg-primary',\n              'transition-colors',\n            ].join(' ')}\n            onClick={onClosePeoplePanel}\n            aria-label=\"Cerrar panel\"\n          >\n            <XMarkIcon className=\"w-4 h-4\" />\n          </button>\n        </div>\n\n        {/* Body - Título, descripción y teclado numérico */}\n        <div className=\"flex flex-col gap-2 w-full flex-1 overflow-auto pt-4\">\n          {/* Título y descripción */}\n          <div className=\"flex flex-col gap-1 w-full\">\n            <h3\n              className={[\n                'text-xl',\n                'leading-7',\n                'font-bold',\n                'tracking-[-0.5px]',\n                'text-content-primary',\n                'dark:text-dark-content-primary',\n              ].join(' ')}\n            >\n              Tomar pedido\n            </h3>\n            <p\n              className={[\n                'text-sm',\n                'leading-5',\n                'text-content-primary',\n                'dark:text-dark-content-primary',\n              ].join(' ')}\n            >\n              Selecciona la cantidad de personas\n            </p>\n          </div>\n\n          {/* Teclado numérico 3x3 */}\n          <div className=\"grid grid-cols-3 gap-2 w-full mt-2\">\n            {[1, 2, 3, 4, 5, 6, 7, 8].map((num) => (\n              <POSNumberButton\n                key={num}\n                size=\"l\"\n                border\n                onClick={() => onPeopleCountSelect?.(num)}\n              >\n                {num}\n              </POSNumberButton>\n            ))}\n          </div>\n        </div>\n\n        {/* Footer - Botones de acción FIJADOS AL BOTTOM con border-top */}\n        <div className=\"flex flex-col gap-4 w-full pt-4 mt-auto shrink-0 grow-0 basis-auto border-t border-border-primary dark:border-dark-border-primary\">\n          <Button\n            type=\"default\"\n            size=\"sm\"\n            fullWidth\n            leftIcon={<ArrowRightEndOnRectangleIcon />}\n            onClick={onAssignTable}\n          >\n            Asignar\n          </Button>\n          <div className=\"flex gap-2 w-full\">\n            <Button\n              type=\"outline\"\n              size=\"sm\"\n              fullWidth\n              leftIcon={<ArrowsRightLeftIcon />}\n              onClick={onTransferTable}\n            >\n              Transferir\n            </Button>\n            <Button\n              type=\"outline\"\n              size=\"sm\"\n              fullWidth\n              leftIcon={<RectangleGroupIcon />}\n              onClick={onSetCutlery}\n            >\n              Cubiertos\n            </Button>\n          </div>\n        </div>\n      </div>\n    );\n  };\n\n  // ===== RENDER PRINCIPAL =====\n  return (\n    <div\n      className={[\n        'flex',\n        'flex-col',\n        'w-full',\n        'min-h-screen',\n        'bg-background-secondary',\n        'dark:bg-dark-bg-primary',\n        className,\n      ].join(' ')}\n    >\n      {/* Navbar */}\n      {renderNavbar()}\n\n      {/* Contenedor principal con sidebars y área central */}\n      <div className=\"flex flex-1 w-full overflow-hidden\">\n        {/* Sidebar izquierdo - Salones */}\n        {renderLocationsSidebar()}\n\n        {/* Área central - Mesas */}\n        {renderTablesArea()}\n\n        {/* Sidebar derecho - Selector de personas (condicional) */}\n        {renderPeopleCountSidebar()}\n      </div>\n    </div>\n  );\n};\n","import React, { createContext, useContext, useEffect, useState } from 'react';\n\nexport type Theme = 'light' | 'dark';\n\ninterface ThemeContextType {\n  theme: Theme;\n  toggleTheme: () => void;\n  setTheme: (theme: Theme) => void;\n}\n\nconst ThemeContext = createContext<ThemeContextType | undefined>(undefined);\n\ninterface ThemeProviderProps {\n  children: React.ReactNode;\n  defaultTheme?: Theme;\n}\n\n/**\n * ThemeProvider - Proveedor de contexto para el tema de la aplicación\n *\n * Maneja el estado del tema (light/dark) y lo persiste en localStorage.\n * Aplica la clase 'dark' al elemento HTML root cuando el tema es dark.\n *\n * @example\n * ```tsx\n * <ThemeProvider defaultTheme=\"light\">\n *   <App />\n * </ThemeProvider>\n * ```\n */\nexport const ThemeProvider: React.FC<ThemeProviderProps> = ({\n  children,\n  defaultTheme = 'light'\n}) => {\n  const [theme, setThemeState] = useState<Theme>(() => {\n    // Intenta obtener el tema del localStorage\n    if (typeof window !== 'undefined') {\n      const savedTheme = localStorage.getItem('siesa-ui-theme') as Theme;\n      return savedTheme || defaultTheme;\n    }\n    return defaultTheme;\n  });\n\n  useEffect(() => {\n    // Aplica o remueve la clase 'dark' del elemento root\n    const root = window.document.documentElement;\n\n    if (theme === 'dark') {\n      root.classList.add('dark');\n    } else {\n      root.classList.remove('dark');\n    }\n\n    // Guarda el tema en localStorage\n    localStorage.setItem('siesa-ui-theme', theme);\n  }, [theme]);\n\n  const toggleTheme = () => {\n    setThemeState((prev) => (prev === 'light' ? 'dark' : 'light'));\n  };\n\n  const setTheme = (newTheme: Theme) => {\n    setThemeState(newTheme);\n  };\n\n  return (\n    <ThemeContext.Provider value={{ theme, toggleTheme, setTheme }}>\n      {children}\n    </ThemeContext.Provider>\n  );\n};\n\n/**\n * useTheme - Hook para acceder al contexto del tema\n *\n * @returns {ThemeContextType} Objeto con el tema actual y funciones para modificarlo\n *\n * @example\n * ```tsx\n * function MyComponent() {\n *   const { theme, toggleTheme } = useTheme();\n *\n *   return (\n *     <button onClick={toggleTheme}>\n *       Tema actual: {theme}\n *     </button>\n *   );\n * }\n * ```\n */\nexport const useTheme = (): ThemeContextType => {\n  const context = useContext(ThemeContext);\n\n  if (context === undefined) {\n    throw new Error('useTheme debe ser usado dentro de un ThemeProvider');\n  }\n\n  return context;\n};\n","import { create } from 'zustand';\nimport type { FileUploaderGalleryProps } from './FileUploaderGallery.types';\n\ninterface FileUploaderGalleryStore {\n  /** Indicates if the gallery is currently open */\n  isOpen: boolean;\n  /** Current props of the open gallery instance */\n  galleryProps: FileUploaderGalleryProps | null;\n  /** \n   * Opens the gallery from anywhere in the system \n   * @param props Gallery configuration properties\n   */\n  openGallery: (props: FileUploaderGalleryProps) => void;\n  /** Closes the active gallery instance */\n  closeGallery: () => void;\n  /** Updates the current props of the open gallery instance */\n  updateGalleryProps: (props: Partial<FileUploaderGalleryProps>) => void;\n  /** Specialized update for the resources list */\n  updateResources: (uuid: string, checked: boolean) => void;\n  /** Specialized update for error messages */\n  setError: (error: { title: string; message: string } | null) => void;\n}\n\n/**\n * Zustand hook to manage the file gallery globally.\n * \n * Este store proporciona el método solicitado para abrir la galería\n * (en modo modal o página) desde cualquier parte del frontend.\n */\nexport const useFileUploaderGallery = create<FileUploaderGalleryStore>((set, get) => ({\n  isOpen: false,\n  galleryProps: null,\n  openGallery: (props) => set({ \n    isOpen: true, \n    galleryProps: {\n      ...props,\n      // Ensure that the onClose from store triggers the internal closeGallery\n      onClose: () => {\n        props.onClose?.();\n        set({ isOpen: false, galleryProps: null });\n      }\n    } \n  }),\n  closeGallery: () => set({ isOpen: false, galleryProps: null }),\n  updateGalleryProps: (props) => set((state) => ({\n    galleryProps: state.galleryProps ? { ...state.galleryProps, ...props } : null\n  })),\n  setError: (error) => set((state) => ({\n    galleryProps: state.galleryProps ? { ...state.galleryProps, error } : null\n  })),\n  updateResources: (uuid, checked) => {\n    const { galleryProps } = get();\n    if (!galleryProps) return;\n\n    const updatedResources = galleryProps.resources.map(r => \n      r.uuid === uuid ? { ...r, checked } : r\n    );\n\n    set({\n      galleryProps: {\n        ...galleryProps,\n        resources: updatedResources\n      }\n    });\n  }\n}));\n","import React from 'react';\nimport { useFileUploaderGallery } from './useFileUploaderGallery';\nimport { FileUploaderGallery } from './FileUploaderGallery';\n\n/**\n * Componente que debe renderizarse una sola vez en la raíz de la aplicación\n * (App.tsx o similar) para permitir el uso del método global openGallery().\n */\nexport const FileUploaderGalleryGlobal: React.FC = () => {\n  const { isOpen, galleryProps, closeGallery, updateResources } = useFileUploaderGallery();\n\n  if (!isOpen || !galleryProps) return null;\n\n  return (\n    <FileUploaderGallery \n      {...galleryProps} \n      onResourceCheck={(uuid, checked, selected) => {\n        // First update internal state of store\n        updateResources(uuid, checked);\n        // Then call the original callback from props if it exists with the selected items\n        galleryProps.onResourceCheck?.(uuid, checked, selected);\n      }}\n      onUpload={async (file) => {\n        if (galleryProps.onUpload) {\n          await galleryProps.onUpload(file);\n        }\n      }}\n      onDelete={async (uuid) => {\n        if (galleryProps.onDelete) {\n          await galleryProps.onDelete(uuid);\n        }\n      }}\n      onClose={() => {\n        galleryProps.onClose?.();\n        closeGallery();\n      }}\n      // Intercept local clear to clear global store too\n      error={galleryProps.error}\n    />\n  );\n};\n","import React, { useEffect, useState } from 'react';\nimport { useDynamicEntitiesContext, useDynamicEntitiesPermissions } from '../core/DynamicEntitiesProvider';\nimport { PencilSquareIcon, DocumentTextIcon, ExclamationTriangleIcon } from '@heroicons/react/24/outline';\nimport { useFeatureService } from './services/useFeatureService';\nimport type { Feature } from './services/FeatureService';\nimport { Button } from '../../Button/Button';\nimport { Switch } from '../../Switch/Switch';\n\nexport interface FeatureListProps {\n    onSelectFeature?: (id: string) => void;\n    onCreatePlansAndCriteria?: (feature: Feature) => void;\n    searchTerm?: string;\n}\n\nexport const FeatureList: React.FC<FeatureListProps> = ({ onSelectFeature, onCreatePlansAndCriteria, searchTerm = '' }) => {\n    const { onError } = useDynamicEntitiesContext();\n    const { canUpdate } = useDynamicEntitiesPermissions();\n    const service = useFeatureService();\n\n    const [features, setFeatures] = useState<Feature[]>([]);\n    const [loading, setLoading] = useState(true);\n    const [loadError, setLoadError] = useState<Error | null>(null);\n    const [debouncedSearch, setDebouncedSearch] = useState('');\n    const [togglingId, setTogglingId] = useState<string | null>(null);\n\n    useEffect(() => {\n        const handler = setTimeout(() => {\n            setDebouncedSearch(searchTerm);\n        }, 300);\n        return () => clearTimeout(handler);\n    }, [searchTerm]);\n\n    const loadFeatures = async () => {\n        setLoading(true);\n        setLoadError(null);\n        try {\n            const data = await service.getAll({ page: 1, limit: 100, search: debouncedSearch });\n            setFeatures(data.data);\n        } catch (error) {\n            // Un fallo de lectura tiene que verse: antes un 401 pintaba el mismo\n            // vacío que \"no hay maestros creados\".\n            console.error('Error loading features:', error);\n            setFeatures([]);\n            setLoadError(error as Error);\n            onError?.(error as Error);\n        } finally {\n            setLoading(false);\n        }\n    };\n\n    useEffect(() => {\n        loadFeatures();\n    }, [service, debouncedSearch]);\n\n    const handleToggleFileManagement = async (feature: Feature) => {\n        if (togglingId === feature.id) return;\n        setTogglingId(feature.id);\n        try {\n            await service.setFileManagement(feature.id, !feature.hasFileManagement);\n            setFeatures(prev =>\n                prev.map(f => f.id === feature.id ? { ...f, hasFileManagement: !f.hasFileManagement } : f)\n            );\n        } catch (error) {\n            console.error('Error actualizando gestión de archivos:', error);\n            onError?.(error as Error);\n            alert('Error al actualizar la gestión de archivos. Revisa la consola.');\n        } finally {\n            setTogglingId(null);\n        }\n    };\n\n    return (\n        <div className=\"bg-white rounded-2xl w-full p-5\">\n            {loading ? (\n                <div className=\"p-6 text-gray-500\">Cargando...</div>\n            ) : loadError ? (\n                <div\n                    role=\"alert\"\n                    className=\"flex items-start gap-3 rounded-lg border border-red-200 bg-red-50 px-4 py-3\"\n                >\n                    <ExclamationTriangleIcon className=\"w-5 h-5 text-red-600 shrink-0 mt-0.5\" />\n                    <div className=\"flex flex-col gap-1\">\n                        <p className=\"text-sm font-medium text-red-700\">\n                            No se pudieron cargar los maestros.\n                        </p>\n                        <p className=\"text-sm text-red-600\">{loadError.message}</p>\n                    </div>\n                </div>\n            ) : (\n                <div className=\"w-full overflow-x-auto\">\n                    <table className=\"w-full text-left border-collapse\">\n                        <thead>\n                            <tr>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200\">Código</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200\">Nombre</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200\">Tipo</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200 text-center\">Gestión de Archivos</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200 text-center w-[100px]\">Acciones</th>\n                            </tr>\n                        </thead>\n                        <tbody>\n                            {features.length === 0 && (\n                                <tr>\n                                    <td colSpan={5} className=\"px-5 py-6 text-center text-gray-500\">\n                                        No hay maestros creados.\n                                    </td>\n                                </tr>\n                            )}\n                            {features.map((feature) => (\n                                <tr key={feature.id} className=\"group\">\n                                    <td className=\"px-5 py-4 text-sm text-gray-900 border-b border-gray-200\">\n                                        {feature.code}\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm text-gray-900 border-b border-gray-200\">\n                                        {feature.description || feature.name}\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm border-b border-gray-200\">\n                                        <span className=\"inline-flex items-center px-2 py-0.5 rounded-md text-xs font-normal bg-[#dbeefe] text-[#0e79fd]\">\n                                            {feature.type === 'Transaction' ? 'Transacción' :\n                                                feature.type === 'Document' ? 'Documento' :\n                                                    'Maestro'}\n                                        </span>\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm border-b border-gray-200\">\n                                        <div className=\"flex items-center justify-center w-full\">\n                                            <Switch\n                                                checked={!!feature.hasFileManagement}\n                                                onCheckedChange={() => handleToggleFileManagement(feature)}\n                                                disabled={!canUpdate || togglingId === feature.id}\n                                            />\n                                        </div>\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm border-b border-gray-200 text-center\">\n                                        <div className=\"flex items-center justify-center gap-2\">\n                                            <Button\n                                                type=\"outline\"\n                                                size=\"xs\"\n                                                onClick={() => onSelectFeature && onSelectFeature(feature.id)}\n                                                leftIcon={<PencilSquareIcon className=\"h-3 w-3\" />}\n                                                ariaLabel=\"Editar\"\n                                                title=\"Entidad Dinámica\"\n                                            >\n                                                ED\n                                            </Button>\n                                            {feature.allowsPlansAndCriteria && onCreatePlansAndCriteria && (\n                                                <Button\n                                                    type=\"outline\"\n                                                    size=\"xs\"\n                                                    onClick={() => onCreatePlansAndCriteria(feature)}\n                                                    leftIcon={<DocumentTextIcon className=\"h-3 w-3\" />}\n                                                    ariaLabel=\"Planes y Criterios\"\n                                                    title=\"Planes y Criterios\"\n                                                >\n                                                    PC\n                                                </Button>\n                                            )}\n                                        </div>\n                                    </td>\n                                </tr>\n                            ))}\n                        </tbody>\n                    </table>\n                </div>\n            )}\n        </div>\n    );\n};\n","import { useMemo, useLayoutEffect, useEffect, useRef, useCallback } from 'react';\n\nfunction useCombinedRefs() {\n  for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {\n    refs[_key] = arguments[_key];\n  }\n\n  return useMemo(() => node => {\n    refs.forEach(ref => ref(node));\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  refs);\n}\n\n// https://github.com/facebook/react/blob/master/packages/shared/ExecutionEnvironment.js\nconst canUseDOM = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined';\n\nfunction isWindow(element) {\n  const elementString = Object.prototype.toString.call(element);\n  return elementString === '[object Window]' || // In Electron context the Window object serializes to [object global]\n  elementString === '[object global]';\n}\n\nfunction isNode(node) {\n  return 'nodeType' in node;\n}\n\nfunction getWindow(target) {\n  var _target$ownerDocument, _target$ownerDocument2;\n\n  if (!target) {\n    return window;\n  }\n\n  if (isWindow(target)) {\n    return target;\n  }\n\n  if (!isNode(target)) {\n    return window;\n  }\n\n  return (_target$ownerDocument = (_target$ownerDocument2 = target.ownerDocument) == null ? void 0 : _target$ownerDocument2.defaultView) != null ? _target$ownerDocument : window;\n}\n\nfunction isDocument(node) {\n  const {\n    Document\n  } = getWindow(node);\n  return node instanceof Document;\n}\n\nfunction isHTMLElement(node) {\n  if (isWindow(node)) {\n    return false;\n  }\n\n  return node instanceof getWindow(node).HTMLElement;\n}\n\nfunction isSVGElement(node) {\n  return node instanceof getWindow(node).SVGElement;\n}\n\nfunction getOwnerDocument(target) {\n  if (!target) {\n    return document;\n  }\n\n  if (isWindow(target)) {\n    return target.document;\n  }\n\n  if (!isNode(target)) {\n    return document;\n  }\n\n  if (isDocument(target)) {\n    return target;\n  }\n\n  if (isHTMLElement(target) || isSVGElement(target)) {\n    return target.ownerDocument;\n  }\n\n  return document;\n}\n\n/**\r\n * A hook that resolves to useEffect on the server and useLayoutEffect on the client\r\n * @param callback {function} Callback function that is invoked when the dependencies of the hook change\r\n */\n\nconst useIsomorphicLayoutEffect = canUseDOM ? useLayoutEffect : useEffect;\n\nfunction useEvent(handler) {\n  const handlerRef = useRef(handler);\n  useIsomorphicLayoutEffect(() => {\n    handlerRef.current = handler;\n  });\n  return useCallback(function () {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n\n    return handlerRef.current == null ? void 0 : handlerRef.current(...args);\n  }, []);\n}\n\nfunction useInterval() {\n  const intervalRef = useRef(null);\n  const set = useCallback((listener, duration) => {\n    intervalRef.current = setInterval(listener, duration);\n  }, []);\n  const clear = useCallback(() => {\n    if (intervalRef.current !== null) {\n      clearInterval(intervalRef.current);\n      intervalRef.current = null;\n    }\n  }, []);\n  return [set, clear];\n}\n\nfunction useLatestValue(value, dependencies) {\n  if (dependencies === void 0) {\n    dependencies = [value];\n  }\n\n  const valueRef = useRef(value);\n  useIsomorphicLayoutEffect(() => {\n    if (valueRef.current !== value) {\n      valueRef.current = value;\n    }\n  }, dependencies);\n  return valueRef;\n}\n\nfunction useLazyMemo(callback, dependencies) {\n  const valueRef = useRef();\n  return useMemo(() => {\n    const newValue = callback(valueRef.current);\n    valueRef.current = newValue;\n    return newValue;\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [...dependencies]);\n}\n\nfunction useNodeRef(onChange) {\n  const onChangeHandler = useEvent(onChange);\n  const node = useRef(null);\n  const setNodeRef = useCallback(element => {\n    if (element !== node.current) {\n      onChangeHandler == null ? void 0 : onChangeHandler(element, node.current);\n    }\n\n    node.current = element;\n  }, //eslint-disable-next-line\n  []);\n  return [node, setNodeRef];\n}\n\nfunction usePrevious(value) {\n  const ref = useRef();\n  useEffect(() => {\n    ref.current = value;\n  }, [value]);\n  return ref.current;\n}\n\nlet ids = {};\nfunction useUniqueId(prefix, value) {\n  return useMemo(() => {\n    if (value) {\n      return value;\n    }\n\n    const id = ids[prefix] == null ? 0 : ids[prefix] + 1;\n    ids[prefix] = id;\n    return prefix + \"-\" + id;\n  }, [prefix, value]);\n}\n\nfunction createAdjustmentFn(modifier) {\n  return function (object) {\n    for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      adjustments[_key - 1] = arguments[_key];\n    }\n\n    return adjustments.reduce((accumulator, adjustment) => {\n      const entries = Object.entries(adjustment);\n\n      for (const [key, valueAdjustment] of entries) {\n        const value = accumulator[key];\n\n        if (value != null) {\n          accumulator[key] = value + modifier * valueAdjustment;\n        }\n      }\n\n      return accumulator;\n    }, { ...object\n    });\n  };\n}\n\nconst add = /*#__PURE__*/createAdjustmentFn(1);\nconst subtract = /*#__PURE__*/createAdjustmentFn(-1);\n\nfunction hasViewportRelativeCoordinates(event) {\n  return 'clientX' in event && 'clientY' in event;\n}\n\nfunction isKeyboardEvent(event) {\n  if (!event) {\n    return false;\n  }\n\n  const {\n    KeyboardEvent\n  } = getWindow(event.target);\n  return KeyboardEvent && event instanceof KeyboardEvent;\n}\n\nfunction isTouchEvent(event) {\n  if (!event) {\n    return false;\n  }\n\n  const {\n    TouchEvent\n  } = getWindow(event.target);\n  return TouchEvent && event instanceof TouchEvent;\n}\n\n/**\r\n * Returns the normalized x and y coordinates for mouse and touch events.\r\n */\n\nfunction getEventCoordinates(event) {\n  if (isTouchEvent(event)) {\n    if (event.touches && event.touches.length) {\n      const {\n        clientX: x,\n        clientY: y\n      } = event.touches[0];\n      return {\n        x,\n        y\n      };\n    } else if (event.changedTouches && event.changedTouches.length) {\n      const {\n        clientX: x,\n        clientY: y\n      } = event.changedTouches[0];\n      return {\n        x,\n        y\n      };\n    }\n  }\n\n  if (hasViewportRelativeCoordinates(event)) {\n    return {\n      x: event.clientX,\n      y: event.clientY\n    };\n  }\n\n  return null;\n}\n\nconst CSS = /*#__PURE__*/Object.freeze({\n  Translate: {\n    toString(transform) {\n      if (!transform) {\n        return;\n      }\n\n      const {\n        x,\n        y\n      } = transform;\n      return \"translate3d(\" + (x ? Math.round(x) : 0) + \"px, \" + (y ? Math.round(y) : 0) + \"px, 0)\";\n    }\n\n  },\n  Scale: {\n    toString(transform) {\n      if (!transform) {\n        return;\n      }\n\n      const {\n        scaleX,\n        scaleY\n      } = transform;\n      return \"scaleX(\" + scaleX + \") scaleY(\" + scaleY + \")\";\n    }\n\n  },\n  Transform: {\n    toString(transform) {\n      if (!transform) {\n        return;\n      }\n\n      return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(' ');\n    }\n\n  },\n  Transition: {\n    toString(_ref) {\n      let {\n        property,\n        duration,\n        easing\n      } = _ref;\n      return property + \" \" + duration + \"ms \" + easing;\n    }\n\n  }\n});\n\nconst SELECTOR = 'a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]';\nfunction findFirstFocusableNode(element) {\n  if (element.matches(SELECTOR)) {\n    return element;\n  }\n\n  return element.querySelector(SELECTOR);\n}\n\nexport { CSS, add, canUseDOM, findFirstFocusableNode, getEventCoordinates, getOwnerDocument, getWindow, hasViewportRelativeCoordinates, isDocument, isHTMLElement, isKeyboardEvent, isNode, isSVGElement, isTouchEvent, isWindow, subtract, useCombinedRefs, useEvent, useInterval, useIsomorphicLayoutEffect, useLatestValue, useLazyMemo, useNodeRef, usePrevious, useUniqueId };\n//# sourceMappingURL=utilities.esm.js.map\n","import React, { useState, useCallback } from 'react';\n\nconst hiddenStyles = {\n  display: 'none'\n};\nfunction HiddenText(_ref) {\n  let {\n    id,\n    value\n  } = _ref;\n  return React.createElement(\"div\", {\n    id: id,\n    style: hiddenStyles\n  }, value);\n}\n\nfunction LiveRegion(_ref) {\n  let {\n    id,\n    announcement,\n    ariaLiveType = \"assertive\"\n  } = _ref;\n  // Hide element visually but keep it readable by screen readers\n  const visuallyHidden = {\n    position: 'fixed',\n    top: 0,\n    left: 0,\n    width: 1,\n    height: 1,\n    margin: -1,\n    border: 0,\n    padding: 0,\n    overflow: 'hidden',\n    clip: 'rect(0 0 0 0)',\n    clipPath: 'inset(100%)',\n    whiteSpace: 'nowrap'\n  };\n  return React.createElement(\"div\", {\n    id: id,\n    style: visuallyHidden,\n    role: \"status\",\n    \"aria-live\": ariaLiveType,\n    \"aria-atomic\": true\n  }, announcement);\n}\n\nfunction useAnnouncement() {\n  const [announcement, setAnnouncement] = useState('');\n  const announce = useCallback(value => {\n    if (value != null) {\n      setAnnouncement(value);\n    }\n  }, []);\n  return {\n    announce,\n    announcement\n  };\n}\n\nexport { HiddenText, LiveRegion, useAnnouncement };\n//# sourceMappingURL=accessibility.esm.js.map\n","import React, { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef, memo, useReducer, cloneElement, forwardRef } from 'react';\nimport { createPortal, unstable_batchedUpdates } from 'react-dom';\nimport { useUniqueId, getEventCoordinates, getWindow, isDocument, isHTMLElement, isSVGElement, canUseDOM, isWindow, isNode, getOwnerDocument, add, isKeyboardEvent, subtract, useLazyMemo, useInterval, usePrevious, useLatestValue, useEvent, useIsomorphicLayoutEffect, useNodeRef, findFirstFocusableNode, CSS } from '@dnd-kit/utilities';\nimport { useAnnouncement, HiddenText, LiveRegion } from '@dnd-kit/accessibility';\n\nconst DndMonitorContext = /*#__PURE__*/createContext(null);\n\nfunction useDndMonitor(listener) {\n  const registerListener = useContext(DndMonitorContext);\n  useEffect(() => {\n    if (!registerListener) {\n      throw new Error('useDndMonitor must be used within a children of <DndContext>');\n    }\n\n    const unsubscribe = registerListener(listener);\n    return unsubscribe;\n  }, [listener, registerListener]);\n}\n\nfunction useDndMonitorProvider() {\n  const [listeners] = useState(() => new Set());\n  const registerListener = useCallback(listener => {\n    listeners.add(listener);\n    return () => listeners.delete(listener);\n  }, [listeners]);\n  const dispatch = useCallback(_ref => {\n    let {\n      type,\n      event\n    } = _ref;\n    listeners.forEach(listener => {\n      var _listener$type;\n\n      return (_listener$type = listener[type]) == null ? void 0 : _listener$type.call(listener, event);\n    });\n  }, [listeners]);\n  return [dispatch, registerListener];\n}\n\nconst defaultScreenReaderInstructions = {\n  draggable: \"\\n    To pick up a draggable item, press the space bar.\\n    While dragging, use the arrow keys to move the item.\\n    Press space again to drop the item in its new position, or press escape to cancel.\\n  \"\n};\nconst defaultAnnouncements = {\n  onDragStart(_ref) {\n    let {\n      active\n    } = _ref;\n    return \"Picked up draggable item \" + active.id + \".\";\n  },\n\n  onDragOver(_ref2) {\n    let {\n      active,\n      over\n    } = _ref2;\n\n    if (over) {\n      return \"Draggable item \" + active.id + \" was moved over droppable area \" + over.id + \".\";\n    }\n\n    return \"Draggable item \" + active.id + \" is no longer over a droppable area.\";\n  },\n\n  onDragEnd(_ref3) {\n    let {\n      active,\n      over\n    } = _ref3;\n\n    if (over) {\n      return \"Draggable item \" + active.id + \" was dropped over droppable area \" + over.id;\n    }\n\n    return \"Draggable item \" + active.id + \" was dropped.\";\n  },\n\n  onDragCancel(_ref4) {\n    let {\n      active\n    } = _ref4;\n    return \"Dragging was cancelled. Draggable item \" + active.id + \" was dropped.\";\n  }\n\n};\n\nfunction Accessibility(_ref) {\n  let {\n    announcements = defaultAnnouncements,\n    container,\n    hiddenTextDescribedById,\n    screenReaderInstructions = defaultScreenReaderInstructions\n  } = _ref;\n  const {\n    announce,\n    announcement\n  } = useAnnouncement();\n  const liveRegionId = useUniqueId(\"DndLiveRegion\");\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => {\n    setMounted(true);\n  }, []);\n  useDndMonitor(useMemo(() => ({\n    onDragStart(_ref2) {\n      let {\n        active\n      } = _ref2;\n      announce(announcements.onDragStart({\n        active\n      }));\n    },\n\n    onDragMove(_ref3) {\n      let {\n        active,\n        over\n      } = _ref3;\n\n      if (announcements.onDragMove) {\n        announce(announcements.onDragMove({\n          active,\n          over\n        }));\n      }\n    },\n\n    onDragOver(_ref4) {\n      let {\n        active,\n        over\n      } = _ref4;\n      announce(announcements.onDragOver({\n        active,\n        over\n      }));\n    },\n\n    onDragEnd(_ref5) {\n      let {\n        active,\n        over\n      } = _ref5;\n      announce(announcements.onDragEnd({\n        active,\n        over\n      }));\n    },\n\n    onDragCancel(_ref6) {\n      let {\n        active,\n        over\n      } = _ref6;\n      announce(announcements.onDragCancel({\n        active,\n        over\n      }));\n    }\n\n  }), [announce, announcements]));\n\n  if (!mounted) {\n    return null;\n  }\n\n  const markup = React.createElement(React.Fragment, null, React.createElement(HiddenText, {\n    id: hiddenTextDescribedById,\n    value: screenReaderInstructions.draggable\n  }), React.createElement(LiveRegion, {\n    id: liveRegionId,\n    announcement: announcement\n  }));\n  return container ? createPortal(markup, container) : markup;\n}\n\nvar Action;\n\n(function (Action) {\n  Action[\"DragStart\"] = \"dragStart\";\n  Action[\"DragMove\"] = \"dragMove\";\n  Action[\"DragEnd\"] = \"dragEnd\";\n  Action[\"DragCancel\"] = \"dragCancel\";\n  Action[\"DragOver\"] = \"dragOver\";\n  Action[\"RegisterDroppable\"] = \"registerDroppable\";\n  Action[\"SetDroppableDisabled\"] = \"setDroppableDisabled\";\n  Action[\"UnregisterDroppable\"] = \"unregisterDroppable\";\n})(Action || (Action = {}));\n\nfunction noop() {}\n\nfunction useSensor(sensor, options) {\n  return useMemo(() => ({\n    sensor,\n    options: options != null ? options : {}\n  }), // eslint-disable-next-line react-hooks/exhaustive-deps\n  [sensor, options]);\n}\n\nfunction useSensors() {\n  for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) {\n    sensors[_key] = arguments[_key];\n  }\n\n  return useMemo(() => [...sensors].filter(sensor => sensor != null), // eslint-disable-next-line react-hooks/exhaustive-deps\n  [...sensors]);\n}\n\nconst defaultCoordinates = /*#__PURE__*/Object.freeze({\n  x: 0,\n  y: 0\n});\n\n/**\r\n * Returns the distance between two points\r\n */\nfunction distanceBetween(p1, p2) {\n  return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));\n}\n\nfunction getRelativeTransformOrigin(event, rect) {\n  const eventCoordinates = getEventCoordinates(event);\n\n  if (!eventCoordinates) {\n    return '0 0';\n  }\n\n  const transformOrigin = {\n    x: (eventCoordinates.x - rect.left) / rect.width * 100,\n    y: (eventCoordinates.y - rect.top) / rect.height * 100\n  };\n  return transformOrigin.x + \"% \" + transformOrigin.y + \"%\";\n}\n\n/**\r\n * Sort collisions from smallest to greatest value\r\n */\nfunction sortCollisionsAsc(_ref, _ref2) {\n  let {\n    data: {\n      value: a\n    }\n  } = _ref;\n  let {\n    data: {\n      value: b\n    }\n  } = _ref2;\n  return a - b;\n}\n/**\r\n * Sort collisions from greatest to smallest value\r\n */\n\nfunction sortCollisionsDesc(_ref3, _ref4) {\n  let {\n    data: {\n      value: a\n    }\n  } = _ref3;\n  let {\n    data: {\n      value: b\n    }\n  } = _ref4;\n  return b - a;\n}\n/**\r\n * Returns the coordinates of the corners of a given rectangle:\r\n * [TopLeft {x, y}, TopRight {x, y}, BottomLeft {x, y}, BottomRight {x, y}]\r\n */\n\nfunction cornersOfRectangle(_ref5) {\n  let {\n    left,\n    top,\n    height,\n    width\n  } = _ref5;\n  return [{\n    x: left,\n    y: top\n  }, {\n    x: left + width,\n    y: top\n  }, {\n    x: left,\n    y: top + height\n  }, {\n    x: left + width,\n    y: top + height\n  }];\n}\nfunction getFirstCollision(collisions, property) {\n  if (!collisions || collisions.length === 0) {\n    return null;\n  }\n\n  const [firstCollision] = collisions;\n  return property ? firstCollision[property] : firstCollision;\n}\n\n/**\r\n * Returns the coordinates of the center of a given ClientRect\r\n */\n\nfunction centerOfRectangle(rect, left, top) {\n  if (left === void 0) {\n    left = rect.left;\n  }\n\n  if (top === void 0) {\n    top = rect.top;\n  }\n\n  return {\n    x: left + rect.width * 0.5,\n    y: top + rect.height * 0.5\n  };\n}\n/**\r\n * Returns the closest rectangles from an array of rectangles to the center of a given\r\n * rectangle.\r\n */\n\n\nconst closestCenter = _ref => {\n  let {\n    collisionRect,\n    droppableRects,\n    droppableContainers\n  } = _ref;\n  const centerRect = centerOfRectangle(collisionRect, collisionRect.left, collisionRect.top);\n  const collisions = [];\n\n  for (const droppableContainer of droppableContainers) {\n    const {\n      id\n    } = droppableContainer;\n    const rect = droppableRects.get(id);\n\n    if (rect) {\n      const distBetween = distanceBetween(centerOfRectangle(rect), centerRect);\n      collisions.push({\n        id,\n        data: {\n          droppableContainer,\n          value: distBetween\n        }\n      });\n    }\n  }\n\n  return collisions.sort(sortCollisionsAsc);\n};\n\n/**\r\n * Returns the closest rectangles from an array of rectangles to the corners of\r\n * another rectangle.\r\n */\n\nconst closestCorners = _ref => {\n  let {\n    collisionRect,\n    droppableRects,\n    droppableContainers\n  } = _ref;\n  const corners = cornersOfRectangle(collisionRect);\n  const collisions = [];\n\n  for (const droppableContainer of droppableContainers) {\n    const {\n      id\n    } = droppableContainer;\n    const rect = droppableRects.get(id);\n\n    if (rect) {\n      const rectCorners = cornersOfRectangle(rect);\n      const distances = corners.reduce((accumulator, corner, index) => {\n        return accumulator + distanceBetween(rectCorners[index], corner);\n      }, 0);\n      const effectiveDistance = Number((distances / 4).toFixed(4));\n      collisions.push({\n        id,\n        data: {\n          droppableContainer,\n          value: effectiveDistance\n        }\n      });\n    }\n  }\n\n  return collisions.sort(sortCollisionsAsc);\n};\n\n/**\r\n * Returns the intersecting rectangle area between two rectangles\r\n */\n\nfunction getIntersectionRatio(entry, target) {\n  const top = Math.max(target.top, entry.top);\n  const left = Math.max(target.left, entry.left);\n  const right = Math.min(target.left + target.width, entry.left + entry.width);\n  const bottom = Math.min(target.top + target.height, entry.top + entry.height);\n  const width = right - left;\n  const height = bottom - top;\n\n  if (left < right && top < bottom) {\n    const targetArea = target.width * target.height;\n    const entryArea = entry.width * entry.height;\n    const intersectionArea = width * height;\n    const intersectionRatio = intersectionArea / (targetArea + entryArea - intersectionArea);\n    return Number(intersectionRatio.toFixed(4));\n  } // Rectangles do not overlap, or overlap has an area of zero (edge/corner overlap)\n\n\n  return 0;\n}\n/**\r\n * Returns the rectangles that has the greatest intersection area with a given\r\n * rectangle in an array of rectangles.\r\n */\n\nconst rectIntersection = _ref => {\n  let {\n    collisionRect,\n    droppableRects,\n    droppableContainers\n  } = _ref;\n  const collisions = [];\n\n  for (const droppableContainer of droppableContainers) {\n    const {\n      id\n    } = droppableContainer;\n    const rect = droppableRects.get(id);\n\n    if (rect) {\n      const intersectionRatio = getIntersectionRatio(rect, collisionRect);\n\n      if (intersectionRatio > 0) {\n        collisions.push({\n          id,\n          data: {\n            droppableContainer,\n            value: intersectionRatio\n          }\n        });\n      }\n    }\n  }\n\n  return collisions.sort(sortCollisionsDesc);\n};\n\n/**\r\n * Check if a given point is contained within a bounding rectangle\r\n */\n\nfunction isPointWithinRect(point, rect) {\n  const {\n    top,\n    left,\n    bottom,\n    right\n  } = rect;\n  return top <= point.y && point.y <= bottom && left <= point.x && point.x <= right;\n}\n/**\r\n * Returns the rectangles that the pointer is hovering over\r\n */\n\n\nconst pointerWithin = _ref => {\n  let {\n    droppableContainers,\n    droppableRects,\n    pointerCoordinates\n  } = _ref;\n\n  if (!pointerCoordinates) {\n    return [];\n  }\n\n  const collisions = [];\n\n  for (const droppableContainer of droppableContainers) {\n    const {\n      id\n    } = droppableContainer;\n    const rect = droppableRects.get(id);\n\n    if (rect && isPointWithinRect(pointerCoordinates, rect)) {\n      /* There may be more than a single rectangle intersecting\r\n       * with the pointer coordinates. In order to sort the\r\n       * colliding rectangles, we measure the distance between\r\n       * the pointer and the corners of the intersecting rectangle\r\n       */\n      const corners = cornersOfRectangle(rect);\n      const distances = corners.reduce((accumulator, corner) => {\n        return accumulator + distanceBetween(pointerCoordinates, corner);\n      }, 0);\n      const effectiveDistance = Number((distances / 4).toFixed(4));\n      collisions.push({\n        id,\n        data: {\n          droppableContainer,\n          value: effectiveDistance\n        }\n      });\n    }\n  }\n\n  return collisions.sort(sortCollisionsAsc);\n};\n\nfunction adjustScale(transform, rect1, rect2) {\n  return { ...transform,\n    scaleX: rect1 && rect2 ? rect1.width / rect2.width : 1,\n    scaleY: rect1 && rect2 ? rect1.height / rect2.height : 1\n  };\n}\n\nfunction getRectDelta(rect1, rect2) {\n  return rect1 && rect2 ? {\n    x: rect1.left - rect2.left,\n    y: rect1.top - rect2.top\n  } : defaultCoordinates;\n}\n\nfunction createRectAdjustmentFn(modifier) {\n  return function adjustClientRect(rect) {\n    for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      adjustments[_key - 1] = arguments[_key];\n    }\n\n    return adjustments.reduce((acc, adjustment) => ({ ...acc,\n      top: acc.top + modifier * adjustment.y,\n      bottom: acc.bottom + modifier * adjustment.y,\n      left: acc.left + modifier * adjustment.x,\n      right: acc.right + modifier * adjustment.x\n    }), { ...rect\n    });\n  };\n}\nconst getAdjustedRect = /*#__PURE__*/createRectAdjustmentFn(1);\n\nfunction parseTransform(transform) {\n  if (transform.startsWith('matrix3d(')) {\n    const transformArray = transform.slice(9, -1).split(/, /);\n    return {\n      x: +transformArray[12],\n      y: +transformArray[13],\n      scaleX: +transformArray[0],\n      scaleY: +transformArray[5]\n    };\n  } else if (transform.startsWith('matrix(')) {\n    const transformArray = transform.slice(7, -1).split(/, /);\n    return {\n      x: +transformArray[4],\n      y: +transformArray[5],\n      scaleX: +transformArray[0],\n      scaleY: +transformArray[3]\n    };\n  }\n\n  return null;\n}\n\nfunction inverseTransform(rect, transform, transformOrigin) {\n  const parsedTransform = parseTransform(transform);\n\n  if (!parsedTransform) {\n    return rect;\n  }\n\n  const {\n    scaleX,\n    scaleY,\n    x: translateX,\n    y: translateY\n  } = parsedTransform;\n  const x = rect.left - translateX - (1 - scaleX) * parseFloat(transformOrigin);\n  const y = rect.top - translateY - (1 - scaleY) * parseFloat(transformOrigin.slice(transformOrigin.indexOf(' ') + 1));\n  const w = scaleX ? rect.width / scaleX : rect.width;\n  const h = scaleY ? rect.height / scaleY : rect.height;\n  return {\n    width: w,\n    height: h,\n    top: y,\n    right: x + w,\n    bottom: y + h,\n    left: x\n  };\n}\n\nconst defaultOptions = {\n  ignoreTransform: false\n};\n/**\r\n * Returns the bounding client rect of an element relative to the viewport.\r\n */\n\nfunction getClientRect(element, options) {\n  if (options === void 0) {\n    options = defaultOptions;\n  }\n\n  let rect = element.getBoundingClientRect();\n\n  if (options.ignoreTransform) {\n    const {\n      transform,\n      transformOrigin\n    } = getWindow(element).getComputedStyle(element);\n\n    if (transform) {\n      rect = inverseTransform(rect, transform, transformOrigin);\n    }\n  }\n\n  const {\n    top,\n    left,\n    width,\n    height,\n    bottom,\n    right\n  } = rect;\n  return {\n    top,\n    left,\n    width,\n    height,\n    bottom,\n    right\n  };\n}\n/**\r\n * Returns the bounding client rect of an element relative to the viewport.\r\n *\r\n * @remarks\r\n * The ClientRect returned by this method does not take into account transforms\r\n * applied to the element it measures.\r\n *\r\n */\n\nfunction getTransformAgnosticClientRect(element) {\n  return getClientRect(element, {\n    ignoreTransform: true\n  });\n}\n\nfunction getWindowClientRect(element) {\n  const width = element.innerWidth;\n  const height = element.innerHeight;\n  return {\n    top: 0,\n    left: 0,\n    right: width,\n    bottom: height,\n    width,\n    height\n  };\n}\n\nfunction isFixed(node, computedStyle) {\n  if (computedStyle === void 0) {\n    computedStyle = getWindow(node).getComputedStyle(node);\n  }\n\n  return computedStyle.position === 'fixed';\n}\n\nfunction isScrollable(element, computedStyle) {\n  if (computedStyle === void 0) {\n    computedStyle = getWindow(element).getComputedStyle(element);\n  }\n\n  const overflowRegex = /(auto|scroll|overlay)/;\n  const properties = ['overflow', 'overflowX', 'overflowY'];\n  return properties.some(property => {\n    const value = computedStyle[property];\n    return typeof value === 'string' ? overflowRegex.test(value) : false;\n  });\n}\n\nfunction getScrollableAncestors(element, limit) {\n  const scrollParents = [];\n\n  function findScrollableAncestors(node) {\n    if (limit != null && scrollParents.length >= limit) {\n      return scrollParents;\n    }\n\n    if (!node) {\n      return scrollParents;\n    }\n\n    if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) {\n      scrollParents.push(node.scrollingElement);\n      return scrollParents;\n    }\n\n    if (!isHTMLElement(node) || isSVGElement(node)) {\n      return scrollParents;\n    }\n\n    if (scrollParents.includes(node)) {\n      return scrollParents;\n    }\n\n    const computedStyle = getWindow(element).getComputedStyle(node);\n\n    if (node !== element) {\n      if (isScrollable(node, computedStyle)) {\n        scrollParents.push(node);\n      }\n    }\n\n    if (isFixed(node, computedStyle)) {\n      return scrollParents;\n    }\n\n    return findScrollableAncestors(node.parentNode);\n  }\n\n  if (!element) {\n    return scrollParents;\n  }\n\n  return findScrollableAncestors(element);\n}\nfunction getFirstScrollableAncestor(node) {\n  const [firstScrollableAncestor] = getScrollableAncestors(node, 1);\n  return firstScrollableAncestor != null ? firstScrollableAncestor : null;\n}\n\nfunction getScrollableElement(element) {\n  if (!canUseDOM || !element) {\n    return null;\n  }\n\n  if (isWindow(element)) {\n    return element;\n  }\n\n  if (!isNode(element)) {\n    return null;\n  }\n\n  if (isDocument(element) || element === getOwnerDocument(element).scrollingElement) {\n    return window;\n  }\n\n  if (isHTMLElement(element)) {\n    return element;\n  }\n\n  return null;\n}\n\nfunction getScrollXCoordinate(element) {\n  if (isWindow(element)) {\n    return element.scrollX;\n  }\n\n  return element.scrollLeft;\n}\nfunction getScrollYCoordinate(element) {\n  if (isWindow(element)) {\n    return element.scrollY;\n  }\n\n  return element.scrollTop;\n}\nfunction getScrollCoordinates(element) {\n  return {\n    x: getScrollXCoordinate(element),\n    y: getScrollYCoordinate(element)\n  };\n}\n\nvar Direction;\n\n(function (Direction) {\n  Direction[Direction[\"Forward\"] = 1] = \"Forward\";\n  Direction[Direction[\"Backward\"] = -1] = \"Backward\";\n})(Direction || (Direction = {}));\n\nfunction isDocumentScrollingElement(element) {\n  if (!canUseDOM || !element) {\n    return false;\n  }\n\n  return element === document.scrollingElement;\n}\n\nfunction getScrollPosition(scrollingContainer) {\n  const minScroll = {\n    x: 0,\n    y: 0\n  };\n  const dimensions = isDocumentScrollingElement(scrollingContainer) ? {\n    height: window.innerHeight,\n    width: window.innerWidth\n  } : {\n    height: scrollingContainer.clientHeight,\n    width: scrollingContainer.clientWidth\n  };\n  const maxScroll = {\n    x: scrollingContainer.scrollWidth - dimensions.width,\n    y: scrollingContainer.scrollHeight - dimensions.height\n  };\n  const isTop = scrollingContainer.scrollTop <= minScroll.y;\n  const isLeft = scrollingContainer.scrollLeft <= minScroll.x;\n  const isBottom = scrollingContainer.scrollTop >= maxScroll.y;\n  const isRight = scrollingContainer.scrollLeft >= maxScroll.x;\n  return {\n    isTop,\n    isLeft,\n    isBottom,\n    isRight,\n    maxScroll,\n    minScroll\n  };\n}\n\nconst defaultThreshold = {\n  x: 0.2,\n  y: 0.2\n};\nfunction getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) {\n  let {\n    top,\n    left,\n    right,\n    bottom\n  } = _ref;\n\n  if (acceleration === void 0) {\n    acceleration = 10;\n  }\n\n  if (thresholdPercentage === void 0) {\n    thresholdPercentage = defaultThreshold;\n  }\n\n  const {\n    isTop,\n    isBottom,\n    isLeft,\n    isRight\n  } = getScrollPosition(scrollContainer);\n  const direction = {\n    x: 0,\n    y: 0\n  };\n  const speed = {\n    x: 0,\n    y: 0\n  };\n  const threshold = {\n    height: scrollContainerRect.height * thresholdPercentage.y,\n    width: scrollContainerRect.width * thresholdPercentage.x\n  };\n\n  if (!isTop && top <= scrollContainerRect.top + threshold.height) {\n    // Scroll Up\n    direction.y = Direction.Backward;\n    speed.y = acceleration * Math.abs((scrollContainerRect.top + threshold.height - top) / threshold.height);\n  } else if (!isBottom && bottom >= scrollContainerRect.bottom - threshold.height) {\n    // Scroll Down\n    direction.y = Direction.Forward;\n    speed.y = acceleration * Math.abs((scrollContainerRect.bottom - threshold.height - bottom) / threshold.height);\n  }\n\n  if (!isRight && right >= scrollContainerRect.right - threshold.width) {\n    // Scroll Right\n    direction.x = Direction.Forward;\n    speed.x = acceleration * Math.abs((scrollContainerRect.right - threshold.width - right) / threshold.width);\n  } else if (!isLeft && left <= scrollContainerRect.left + threshold.width) {\n    // Scroll Left\n    direction.x = Direction.Backward;\n    speed.x = acceleration * Math.abs((scrollContainerRect.left + threshold.width - left) / threshold.width);\n  }\n\n  return {\n    direction,\n    speed\n  };\n}\n\nfunction getScrollElementRect(element) {\n  if (element === document.scrollingElement) {\n    const {\n      innerWidth,\n      innerHeight\n    } = window;\n    return {\n      top: 0,\n      left: 0,\n      right: innerWidth,\n      bottom: innerHeight,\n      width: innerWidth,\n      height: innerHeight\n    };\n  }\n\n  const {\n    top,\n    left,\n    right,\n    bottom\n  } = element.getBoundingClientRect();\n  return {\n    top,\n    left,\n    right,\n    bottom,\n    width: element.clientWidth,\n    height: element.clientHeight\n  };\n}\n\nfunction getScrollOffsets(scrollableAncestors) {\n  return scrollableAncestors.reduce((acc, node) => {\n    return add(acc, getScrollCoordinates(node));\n  }, defaultCoordinates);\n}\nfunction getScrollXOffset(scrollableAncestors) {\n  return scrollableAncestors.reduce((acc, node) => {\n    return acc + getScrollXCoordinate(node);\n  }, 0);\n}\nfunction getScrollYOffset(scrollableAncestors) {\n  return scrollableAncestors.reduce((acc, node) => {\n    return acc + getScrollYCoordinate(node);\n  }, 0);\n}\n\nfunction scrollIntoViewIfNeeded(element, measure) {\n  if (measure === void 0) {\n    measure = getClientRect;\n  }\n\n  if (!element) {\n    return;\n  }\n\n  const {\n    top,\n    left,\n    bottom,\n    right\n  } = measure(element);\n  const firstScrollableAncestor = getFirstScrollableAncestor(element);\n\n  if (!firstScrollableAncestor) {\n    return;\n  }\n\n  if (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) {\n    element.scrollIntoView({\n      block: 'center',\n      inline: 'center'\n    });\n  }\n}\n\nconst properties = [['x', ['left', 'right'], getScrollXOffset], ['y', ['top', 'bottom'], getScrollYOffset]];\nclass Rect {\n  constructor(rect, element) {\n    this.rect = void 0;\n    this.width = void 0;\n    this.height = void 0;\n    this.top = void 0;\n    this.bottom = void 0;\n    this.right = void 0;\n    this.left = void 0;\n    const scrollableAncestors = getScrollableAncestors(element);\n    const scrollOffsets = getScrollOffsets(scrollableAncestors);\n    this.rect = { ...rect\n    };\n    this.width = rect.width;\n    this.height = rect.height;\n\n    for (const [axis, keys, getScrollOffset] of properties) {\n      for (const key of keys) {\n        Object.defineProperty(this, key, {\n          get: () => {\n            const currentOffsets = getScrollOffset(scrollableAncestors);\n            const scrollOffsetsDeltla = scrollOffsets[axis] - currentOffsets;\n            return this.rect[key] + scrollOffsetsDeltla;\n          },\n          enumerable: true\n        });\n      }\n    }\n\n    Object.defineProperty(this, 'rect', {\n      enumerable: false\n    });\n  }\n\n}\n\nclass Listeners {\n  constructor(target) {\n    this.target = void 0;\n    this.listeners = [];\n\n    this.removeAll = () => {\n      this.listeners.forEach(listener => {\n        var _this$target;\n\n        return (_this$target = this.target) == null ? void 0 : _this$target.removeEventListener(...listener);\n      });\n    };\n\n    this.target = target;\n  }\n\n  add(eventName, handler, options) {\n    var _this$target2;\n\n    (_this$target2 = this.target) == null ? void 0 : _this$target2.addEventListener(eventName, handler, options);\n    this.listeners.push([eventName, handler, options]);\n  }\n\n}\n\nfunction getEventListenerTarget(target) {\n  // If the `event.target` element is removed from the document events will still be targeted\n  // at it, and hence won't always bubble up to the window or document anymore.\n  // If there is any risk of an element being removed while it is being dragged,\n  // the best practice is to attach the event listeners directly to the target.\n  // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget\n  const {\n    EventTarget\n  } = getWindow(target);\n  return target instanceof EventTarget ? target : getOwnerDocument(target);\n}\n\nfunction hasExceededDistance(delta, measurement) {\n  const dx = Math.abs(delta.x);\n  const dy = Math.abs(delta.y);\n\n  if (typeof measurement === 'number') {\n    return Math.sqrt(dx ** 2 + dy ** 2) > measurement;\n  }\n\n  if ('x' in measurement && 'y' in measurement) {\n    return dx > measurement.x && dy > measurement.y;\n  }\n\n  if ('x' in measurement) {\n    return dx > measurement.x;\n  }\n\n  if ('y' in measurement) {\n    return dy > measurement.y;\n  }\n\n  return false;\n}\n\nvar EventName;\n\n(function (EventName) {\n  EventName[\"Click\"] = \"click\";\n  EventName[\"DragStart\"] = \"dragstart\";\n  EventName[\"Keydown\"] = \"keydown\";\n  EventName[\"ContextMenu\"] = \"contextmenu\";\n  EventName[\"Resize\"] = \"resize\";\n  EventName[\"SelectionChange\"] = \"selectionchange\";\n  EventName[\"VisibilityChange\"] = \"visibilitychange\";\n})(EventName || (EventName = {}));\n\nfunction preventDefault(event) {\n  event.preventDefault();\n}\nfunction stopPropagation(event) {\n  event.stopPropagation();\n}\n\nvar KeyboardCode;\n\n(function (KeyboardCode) {\n  KeyboardCode[\"Space\"] = \"Space\";\n  KeyboardCode[\"Down\"] = \"ArrowDown\";\n  KeyboardCode[\"Right\"] = \"ArrowRight\";\n  KeyboardCode[\"Left\"] = \"ArrowLeft\";\n  KeyboardCode[\"Up\"] = \"ArrowUp\";\n  KeyboardCode[\"Esc\"] = \"Escape\";\n  KeyboardCode[\"Enter\"] = \"Enter\";\n  KeyboardCode[\"Tab\"] = \"Tab\";\n})(KeyboardCode || (KeyboardCode = {}));\n\nconst defaultKeyboardCodes = {\n  start: [KeyboardCode.Space, KeyboardCode.Enter],\n  cancel: [KeyboardCode.Esc],\n  end: [KeyboardCode.Space, KeyboardCode.Enter, KeyboardCode.Tab]\n};\nconst defaultKeyboardCoordinateGetter = (event, _ref) => {\n  let {\n    currentCoordinates\n  } = _ref;\n\n  switch (event.code) {\n    case KeyboardCode.Right:\n      return { ...currentCoordinates,\n        x: currentCoordinates.x + 25\n      };\n\n    case KeyboardCode.Left:\n      return { ...currentCoordinates,\n        x: currentCoordinates.x - 25\n      };\n\n    case KeyboardCode.Down:\n      return { ...currentCoordinates,\n        y: currentCoordinates.y + 25\n      };\n\n    case KeyboardCode.Up:\n      return { ...currentCoordinates,\n        y: currentCoordinates.y - 25\n      };\n  }\n\n  return undefined;\n};\n\nclass KeyboardSensor {\n  constructor(props) {\n    this.props = void 0;\n    this.autoScrollEnabled = false;\n    this.referenceCoordinates = void 0;\n    this.listeners = void 0;\n    this.windowListeners = void 0;\n    this.props = props;\n    const {\n      event: {\n        target\n      }\n    } = props;\n    this.props = props;\n    this.listeners = new Listeners(getOwnerDocument(target));\n    this.windowListeners = new Listeners(getWindow(target));\n    this.handleKeyDown = this.handleKeyDown.bind(this);\n    this.handleCancel = this.handleCancel.bind(this);\n    this.attach();\n  }\n\n  attach() {\n    this.handleStart();\n    this.windowListeners.add(EventName.Resize, this.handleCancel);\n    this.windowListeners.add(EventName.VisibilityChange, this.handleCancel);\n    setTimeout(() => this.listeners.add(EventName.Keydown, this.handleKeyDown));\n  }\n\n  handleStart() {\n    const {\n      activeNode,\n      onStart\n    } = this.props;\n    const node = activeNode.node.current;\n\n    if (node) {\n      scrollIntoViewIfNeeded(node);\n    }\n\n    onStart(defaultCoordinates);\n  }\n\n  handleKeyDown(event) {\n    if (isKeyboardEvent(event)) {\n      const {\n        active,\n        context,\n        options\n      } = this.props;\n      const {\n        keyboardCodes = defaultKeyboardCodes,\n        coordinateGetter = defaultKeyboardCoordinateGetter,\n        scrollBehavior = 'smooth'\n      } = options;\n      const {\n        code\n      } = event;\n\n      if (keyboardCodes.end.includes(code)) {\n        this.handleEnd(event);\n        return;\n      }\n\n      if (keyboardCodes.cancel.includes(code)) {\n        this.handleCancel(event);\n        return;\n      }\n\n      const {\n        collisionRect\n      } = context.current;\n      const currentCoordinates = collisionRect ? {\n        x: collisionRect.left,\n        y: collisionRect.top\n      } : defaultCoordinates;\n\n      if (!this.referenceCoordinates) {\n        this.referenceCoordinates = currentCoordinates;\n      }\n\n      const newCoordinates = coordinateGetter(event, {\n        active,\n        context: context.current,\n        currentCoordinates\n      });\n\n      if (newCoordinates) {\n        const coordinatesDelta = subtract(newCoordinates, currentCoordinates);\n        const scrollDelta = {\n          x: 0,\n          y: 0\n        };\n        const {\n          scrollableAncestors\n        } = context.current;\n\n        for (const scrollContainer of scrollableAncestors) {\n          const direction = event.code;\n          const {\n            isTop,\n            isRight,\n            isLeft,\n            isBottom,\n            maxScroll,\n            minScroll\n          } = getScrollPosition(scrollContainer);\n          const scrollElementRect = getScrollElementRect(scrollContainer);\n          const clampedCoordinates = {\n            x: Math.min(direction === KeyboardCode.Right ? scrollElementRect.right - scrollElementRect.width / 2 : scrollElementRect.right, Math.max(direction === KeyboardCode.Right ? scrollElementRect.left : scrollElementRect.left + scrollElementRect.width / 2, newCoordinates.x)),\n            y: Math.min(direction === KeyboardCode.Down ? scrollElementRect.bottom - scrollElementRect.height / 2 : scrollElementRect.bottom, Math.max(direction === KeyboardCode.Down ? scrollElementRect.top : scrollElementRect.top + scrollElementRect.height / 2, newCoordinates.y))\n          };\n          const canScrollX = direction === KeyboardCode.Right && !isRight || direction === KeyboardCode.Left && !isLeft;\n          const canScrollY = direction === KeyboardCode.Down && !isBottom || direction === KeyboardCode.Up && !isTop;\n\n          if (canScrollX && clampedCoordinates.x !== newCoordinates.x) {\n            const newScrollCoordinates = scrollContainer.scrollLeft + coordinatesDelta.x;\n            const canScrollToNewCoordinates = direction === KeyboardCode.Right && newScrollCoordinates <= maxScroll.x || direction === KeyboardCode.Left && newScrollCoordinates >= minScroll.x;\n\n            if (canScrollToNewCoordinates && !coordinatesDelta.y) {\n              // We don't need to update coordinates, the scroll adjustment alone will trigger\n              // logic to auto-detect the new container we are over\n              scrollContainer.scrollTo({\n                left: newScrollCoordinates,\n                behavior: scrollBehavior\n              });\n              return;\n            }\n\n            if (canScrollToNewCoordinates) {\n              scrollDelta.x = scrollContainer.scrollLeft - newScrollCoordinates;\n            } else {\n              scrollDelta.x = direction === KeyboardCode.Right ? scrollContainer.scrollLeft - maxScroll.x : scrollContainer.scrollLeft - minScroll.x;\n            }\n\n            if (scrollDelta.x) {\n              scrollContainer.scrollBy({\n                left: -scrollDelta.x,\n                behavior: scrollBehavior\n              });\n            }\n\n            break;\n          } else if (canScrollY && clampedCoordinates.y !== newCoordinates.y) {\n            const newScrollCoordinates = scrollContainer.scrollTop + coordinatesDelta.y;\n            const canScrollToNewCoordinates = direction === KeyboardCode.Down && newScrollCoordinates <= maxScroll.y || direction === KeyboardCode.Up && newScrollCoordinates >= minScroll.y;\n\n            if (canScrollToNewCoordinates && !coordinatesDelta.x) {\n              // We don't need to update coordinates, the scroll adjustment alone will trigger\n              // logic to auto-detect the new container we are over\n              scrollContainer.scrollTo({\n                top: newScrollCoordinates,\n                behavior: scrollBehavior\n              });\n              return;\n            }\n\n            if (canScrollToNewCoordinates) {\n              scrollDelta.y = scrollContainer.scrollTop - newScrollCoordinates;\n            } else {\n              scrollDelta.y = direction === KeyboardCode.Down ? scrollContainer.scrollTop - maxScroll.y : scrollContainer.scrollTop - minScroll.y;\n            }\n\n            if (scrollDelta.y) {\n              scrollContainer.scrollBy({\n                top: -scrollDelta.y,\n                behavior: scrollBehavior\n              });\n            }\n\n            break;\n          }\n        }\n\n        this.handleMove(event, add(subtract(newCoordinates, this.referenceCoordinates), scrollDelta));\n      }\n    }\n  }\n\n  handleMove(event, coordinates) {\n    const {\n      onMove\n    } = this.props;\n    event.preventDefault();\n    onMove(coordinates);\n  }\n\n  handleEnd(event) {\n    const {\n      onEnd\n    } = this.props;\n    event.preventDefault();\n    this.detach();\n    onEnd();\n  }\n\n  handleCancel(event) {\n    const {\n      onCancel\n    } = this.props;\n    event.preventDefault();\n    this.detach();\n    onCancel();\n  }\n\n  detach() {\n    this.listeners.removeAll();\n    this.windowListeners.removeAll();\n  }\n\n}\nKeyboardSensor.activators = [{\n  eventName: 'onKeyDown',\n  handler: (event, _ref, _ref2) => {\n    let {\n      keyboardCodes = defaultKeyboardCodes,\n      onActivation\n    } = _ref;\n    let {\n      active\n    } = _ref2;\n    const {\n      code\n    } = event.nativeEvent;\n\n    if (keyboardCodes.start.includes(code)) {\n      const activator = active.activatorNode.current;\n\n      if (activator && event.target !== activator) {\n        return false;\n      }\n\n      event.preventDefault();\n      onActivation == null ? void 0 : onActivation({\n        event: event.nativeEvent\n      });\n      return true;\n    }\n\n    return false;\n  }\n}];\n\nfunction isDistanceConstraint(constraint) {\n  return Boolean(constraint && 'distance' in constraint);\n}\n\nfunction isDelayConstraint(constraint) {\n  return Boolean(constraint && 'delay' in constraint);\n}\n\nclass AbstractPointerSensor {\n  constructor(props, events, listenerTarget) {\n    var _getEventCoordinates;\n\n    if (listenerTarget === void 0) {\n      listenerTarget = getEventListenerTarget(props.event.target);\n    }\n\n    this.props = void 0;\n    this.events = void 0;\n    this.autoScrollEnabled = true;\n    this.document = void 0;\n    this.activated = false;\n    this.initialCoordinates = void 0;\n    this.timeoutId = null;\n    this.listeners = void 0;\n    this.documentListeners = void 0;\n    this.windowListeners = void 0;\n    this.props = props;\n    this.events = events;\n    const {\n      event\n    } = props;\n    const {\n      target\n    } = event;\n    this.props = props;\n    this.events = events;\n    this.document = getOwnerDocument(target);\n    this.documentListeners = new Listeners(this.document);\n    this.listeners = new Listeners(listenerTarget);\n    this.windowListeners = new Listeners(getWindow(target));\n    this.initialCoordinates = (_getEventCoordinates = getEventCoordinates(event)) != null ? _getEventCoordinates : defaultCoordinates;\n    this.handleStart = this.handleStart.bind(this);\n    this.handleMove = this.handleMove.bind(this);\n    this.handleEnd = this.handleEnd.bind(this);\n    this.handleCancel = this.handleCancel.bind(this);\n    this.handleKeydown = this.handleKeydown.bind(this);\n    this.removeTextSelection = this.removeTextSelection.bind(this);\n    this.attach();\n  }\n\n  attach() {\n    const {\n      events,\n      props: {\n        options: {\n          activationConstraint,\n          bypassActivationConstraint\n        }\n      }\n    } = this;\n    this.listeners.add(events.move.name, this.handleMove, {\n      passive: false\n    });\n    this.listeners.add(events.end.name, this.handleEnd);\n\n    if (events.cancel) {\n      this.listeners.add(events.cancel.name, this.handleCancel);\n    }\n\n    this.windowListeners.add(EventName.Resize, this.handleCancel);\n    this.windowListeners.add(EventName.DragStart, preventDefault);\n    this.windowListeners.add(EventName.VisibilityChange, this.handleCancel);\n    this.windowListeners.add(EventName.ContextMenu, preventDefault);\n    this.documentListeners.add(EventName.Keydown, this.handleKeydown);\n\n    if (activationConstraint) {\n      if (bypassActivationConstraint != null && bypassActivationConstraint({\n        event: this.props.event,\n        activeNode: this.props.activeNode,\n        options: this.props.options\n      })) {\n        return this.handleStart();\n      }\n\n      if (isDelayConstraint(activationConstraint)) {\n        this.timeoutId = setTimeout(this.handleStart, activationConstraint.delay);\n        this.handlePending(activationConstraint);\n        return;\n      }\n\n      if (isDistanceConstraint(activationConstraint)) {\n        this.handlePending(activationConstraint);\n        return;\n      }\n    }\n\n    this.handleStart();\n  }\n\n  detach() {\n    this.listeners.removeAll();\n    this.windowListeners.removeAll(); // Wait until the next event loop before removing document listeners\n    // This is necessary because we listen for `click` and `selection` events on the document\n\n    setTimeout(this.documentListeners.removeAll, 50);\n\n    if (this.timeoutId !== null) {\n      clearTimeout(this.timeoutId);\n      this.timeoutId = null;\n    }\n  }\n\n  handlePending(constraint, offset) {\n    const {\n      active,\n      onPending\n    } = this.props;\n    onPending(active, constraint, this.initialCoordinates, offset);\n  }\n\n  handleStart() {\n    const {\n      initialCoordinates\n    } = this;\n    const {\n      onStart\n    } = this.props;\n\n    if (initialCoordinates) {\n      this.activated = true; // Stop propagation of click events once activation constraints are met\n\n      this.documentListeners.add(EventName.Click, stopPropagation, {\n        capture: true\n      }); // Remove any text selection from the document\n\n      this.removeTextSelection(); // Prevent further text selection while dragging\n\n      this.documentListeners.add(EventName.SelectionChange, this.removeTextSelection);\n      onStart(initialCoordinates);\n    }\n  }\n\n  handleMove(event) {\n    var _getEventCoordinates2;\n\n    const {\n      activated,\n      initialCoordinates,\n      props\n    } = this;\n    const {\n      onMove,\n      options: {\n        activationConstraint\n      }\n    } = props;\n\n    if (!initialCoordinates) {\n      return;\n    }\n\n    const coordinates = (_getEventCoordinates2 = getEventCoordinates(event)) != null ? _getEventCoordinates2 : defaultCoordinates;\n    const delta = subtract(initialCoordinates, coordinates); // Constraint validation\n\n    if (!activated && activationConstraint) {\n      if (isDistanceConstraint(activationConstraint)) {\n        if (activationConstraint.tolerance != null && hasExceededDistance(delta, activationConstraint.tolerance)) {\n          return this.handleCancel();\n        }\n\n        if (hasExceededDistance(delta, activationConstraint.distance)) {\n          return this.handleStart();\n        }\n      }\n\n      if (isDelayConstraint(activationConstraint)) {\n        if (hasExceededDistance(delta, activationConstraint.tolerance)) {\n          return this.handleCancel();\n        }\n      }\n\n      this.handlePending(activationConstraint, delta);\n      return;\n    }\n\n    if (event.cancelable) {\n      event.preventDefault();\n    }\n\n    onMove(coordinates);\n  }\n\n  handleEnd() {\n    const {\n      onAbort,\n      onEnd\n    } = this.props;\n    this.detach();\n\n    if (!this.activated) {\n      onAbort(this.props.active);\n    }\n\n    onEnd();\n  }\n\n  handleCancel() {\n    const {\n      onAbort,\n      onCancel\n    } = this.props;\n    this.detach();\n\n    if (!this.activated) {\n      onAbort(this.props.active);\n    }\n\n    onCancel();\n  }\n\n  handleKeydown(event) {\n    if (event.code === KeyboardCode.Esc) {\n      this.handleCancel();\n    }\n  }\n\n  removeTextSelection() {\n    var _this$document$getSel;\n\n    (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges();\n  }\n\n}\n\nconst events = {\n  cancel: {\n    name: 'pointercancel'\n  },\n  move: {\n    name: 'pointermove'\n  },\n  end: {\n    name: 'pointerup'\n  }\n};\nclass PointerSensor extends AbstractPointerSensor {\n  constructor(props) {\n    const {\n      event\n    } = props; // Pointer events stop firing if the target is unmounted while dragging\n    // Therefore we attach listeners to the owner document instead\n\n    const listenerTarget = getOwnerDocument(event.target);\n    super(props, events, listenerTarget);\n  }\n\n}\nPointerSensor.activators = [{\n  eventName: 'onPointerDown',\n  handler: (_ref, _ref2) => {\n    let {\n      nativeEvent: event\n    } = _ref;\n    let {\n      onActivation\n    } = _ref2;\n\n    if (!event.isPrimary || event.button !== 0) {\n      return false;\n    }\n\n    onActivation == null ? void 0 : onActivation({\n      event\n    });\n    return true;\n  }\n}];\n\nconst events$1 = {\n  move: {\n    name: 'mousemove'\n  },\n  end: {\n    name: 'mouseup'\n  }\n};\nvar MouseButton;\n\n(function (MouseButton) {\n  MouseButton[MouseButton[\"RightClick\"] = 2] = \"RightClick\";\n})(MouseButton || (MouseButton = {}));\n\nclass MouseSensor extends AbstractPointerSensor {\n  constructor(props) {\n    super(props, events$1, getOwnerDocument(props.event.target));\n  }\n\n}\nMouseSensor.activators = [{\n  eventName: 'onMouseDown',\n  handler: (_ref, _ref2) => {\n    let {\n      nativeEvent: event\n    } = _ref;\n    let {\n      onActivation\n    } = _ref2;\n\n    if (event.button === MouseButton.RightClick) {\n      return false;\n    }\n\n    onActivation == null ? void 0 : onActivation({\n      event\n    });\n    return true;\n  }\n}];\n\nconst events$2 = {\n  cancel: {\n    name: 'touchcancel'\n  },\n  move: {\n    name: 'touchmove'\n  },\n  end: {\n    name: 'touchend'\n  }\n};\nclass TouchSensor extends AbstractPointerSensor {\n  constructor(props) {\n    super(props, events$2);\n  }\n\n  static setup() {\n    // Adding a non-capture and non-passive `touchmove` listener in order\n    // to force `event.preventDefault()` calls to work in dynamically added\n    // touchmove event handlers. This is required for iOS Safari.\n    window.addEventListener(events$2.move.name, noop, {\n      capture: false,\n      passive: false\n    });\n    return function teardown() {\n      window.removeEventListener(events$2.move.name, noop);\n    }; // We create a new handler because the teardown function of another sensor\n    // could remove our event listener if we use a referentially equal listener.\n\n    function noop() {}\n  }\n\n}\nTouchSensor.activators = [{\n  eventName: 'onTouchStart',\n  handler: (_ref, _ref2) => {\n    let {\n      nativeEvent: event\n    } = _ref;\n    let {\n      onActivation\n    } = _ref2;\n    const {\n      touches\n    } = event;\n\n    if (touches.length > 1) {\n      return false;\n    }\n\n    onActivation == null ? void 0 : onActivation({\n      event\n    });\n    return true;\n  }\n}];\n\nvar AutoScrollActivator;\n\n(function (AutoScrollActivator) {\n  AutoScrollActivator[AutoScrollActivator[\"Pointer\"] = 0] = \"Pointer\";\n  AutoScrollActivator[AutoScrollActivator[\"DraggableRect\"] = 1] = \"DraggableRect\";\n})(AutoScrollActivator || (AutoScrollActivator = {}));\n\nvar TraversalOrder;\n\n(function (TraversalOrder) {\n  TraversalOrder[TraversalOrder[\"TreeOrder\"] = 0] = \"TreeOrder\";\n  TraversalOrder[TraversalOrder[\"ReversedTreeOrder\"] = 1] = \"ReversedTreeOrder\";\n})(TraversalOrder || (TraversalOrder = {}));\n\nfunction useAutoScroller(_ref) {\n  let {\n    acceleration,\n    activator = AutoScrollActivator.Pointer,\n    canScroll,\n    draggingRect,\n    enabled,\n    interval = 5,\n    order = TraversalOrder.TreeOrder,\n    pointerCoordinates,\n    scrollableAncestors,\n    scrollableAncestorRects,\n    delta,\n    threshold\n  } = _ref;\n  const scrollIntent = useScrollIntent({\n    delta,\n    disabled: !enabled\n  });\n  const [setAutoScrollInterval, clearAutoScrollInterval] = useInterval();\n  const scrollSpeed = useRef({\n    x: 0,\n    y: 0\n  });\n  const scrollDirection = useRef({\n    x: 0,\n    y: 0\n  });\n  const rect = useMemo(() => {\n    switch (activator) {\n      case AutoScrollActivator.Pointer:\n        return pointerCoordinates ? {\n          top: pointerCoordinates.y,\n          bottom: pointerCoordinates.y,\n          left: pointerCoordinates.x,\n          right: pointerCoordinates.x\n        } : null;\n\n      case AutoScrollActivator.DraggableRect:\n        return draggingRect;\n    }\n  }, [activator, draggingRect, pointerCoordinates]);\n  const scrollContainerRef = useRef(null);\n  const autoScroll = useCallback(() => {\n    const scrollContainer = scrollContainerRef.current;\n\n    if (!scrollContainer) {\n      return;\n    }\n\n    const scrollLeft = scrollSpeed.current.x * scrollDirection.current.x;\n    const scrollTop = scrollSpeed.current.y * scrollDirection.current.y;\n    scrollContainer.scrollBy(scrollLeft, scrollTop);\n  }, []);\n  const sortedScrollableAncestors = useMemo(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]);\n  useEffect(() => {\n    if (!enabled || !scrollableAncestors.length || !rect) {\n      clearAutoScrollInterval();\n      return;\n    }\n\n    for (const scrollContainer of sortedScrollableAncestors) {\n      if ((canScroll == null ? void 0 : canScroll(scrollContainer)) === false) {\n        continue;\n      }\n\n      const index = scrollableAncestors.indexOf(scrollContainer);\n      const scrollContainerRect = scrollableAncestorRects[index];\n\n      if (!scrollContainerRect) {\n        continue;\n      }\n\n      const {\n        direction,\n        speed\n      } = getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, rect, acceleration, threshold);\n\n      for (const axis of ['x', 'y']) {\n        if (!scrollIntent[axis][direction[axis]]) {\n          speed[axis] = 0;\n          direction[axis] = 0;\n        }\n      }\n\n      if (speed.x > 0 || speed.y > 0) {\n        clearAutoScrollInterval();\n        scrollContainerRef.current = scrollContainer;\n        setAutoScrollInterval(autoScroll, interval);\n        scrollSpeed.current = speed;\n        scrollDirection.current = direction;\n        return;\n      }\n    }\n\n    scrollSpeed.current = {\n      x: 0,\n      y: 0\n    };\n    scrollDirection.current = {\n      x: 0,\n      y: 0\n    };\n    clearAutoScrollInterval();\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [acceleration, autoScroll, canScroll, clearAutoScrollInterval, enabled, interval, // eslint-disable-next-line react-hooks/exhaustive-deps\n  JSON.stringify(rect), // eslint-disable-next-line react-hooks/exhaustive-deps\n  JSON.stringify(scrollIntent), setAutoScrollInterval, scrollableAncestors, sortedScrollableAncestors, scrollableAncestorRects, // eslint-disable-next-line react-hooks/exhaustive-deps\n  JSON.stringify(threshold)]);\n}\nconst defaultScrollIntent = {\n  x: {\n    [Direction.Backward]: false,\n    [Direction.Forward]: false\n  },\n  y: {\n    [Direction.Backward]: false,\n    [Direction.Forward]: false\n  }\n};\n\nfunction useScrollIntent(_ref2) {\n  let {\n    delta,\n    disabled\n  } = _ref2;\n  const previousDelta = usePrevious(delta);\n  return useLazyMemo(previousIntent => {\n    if (disabled || !previousDelta || !previousIntent) {\n      // Reset scroll intent tracking when auto-scrolling is disabled\n      return defaultScrollIntent;\n    }\n\n    const direction = {\n      x: Math.sign(delta.x - previousDelta.x),\n      y: Math.sign(delta.y - previousDelta.y)\n    }; // Keep track of the user intent to scroll in each direction for both axis\n\n    return {\n      x: {\n        [Direction.Backward]: previousIntent.x[Direction.Backward] || direction.x === -1,\n        [Direction.Forward]: previousIntent.x[Direction.Forward] || direction.x === 1\n      },\n      y: {\n        [Direction.Backward]: previousIntent.y[Direction.Backward] || direction.y === -1,\n        [Direction.Forward]: previousIntent.y[Direction.Forward] || direction.y === 1\n      }\n    };\n  }, [disabled, delta, previousDelta]);\n}\n\nfunction useCachedNode(draggableNodes, id) {\n  const draggableNode = id != null ? draggableNodes.get(id) : undefined;\n  const node = draggableNode ? draggableNode.node.current : null;\n  return useLazyMemo(cachedNode => {\n    var _ref;\n\n    if (id == null) {\n      return null;\n    } // In some cases, the draggable node can unmount while dragging\n    // This is the case for virtualized lists. In those situations,\n    // we fall back to the last known value for that node.\n\n\n    return (_ref = node != null ? node : cachedNode) != null ? _ref : null;\n  }, [node, id]);\n}\n\nfunction useCombineActivators(sensors, getSyntheticHandler) {\n  return useMemo(() => sensors.reduce((accumulator, sensor) => {\n    const {\n      sensor: Sensor\n    } = sensor;\n    const sensorActivators = Sensor.activators.map(activator => ({\n      eventName: activator.eventName,\n      handler: getSyntheticHandler(activator.handler, sensor)\n    }));\n    return [...accumulator, ...sensorActivators];\n  }, []), [sensors, getSyntheticHandler]);\n}\n\nvar MeasuringStrategy;\n\n(function (MeasuringStrategy) {\n  MeasuringStrategy[MeasuringStrategy[\"Always\"] = 0] = \"Always\";\n  MeasuringStrategy[MeasuringStrategy[\"BeforeDragging\"] = 1] = \"BeforeDragging\";\n  MeasuringStrategy[MeasuringStrategy[\"WhileDragging\"] = 2] = \"WhileDragging\";\n})(MeasuringStrategy || (MeasuringStrategy = {}));\n\nvar MeasuringFrequency;\n\n(function (MeasuringFrequency) {\n  MeasuringFrequency[\"Optimized\"] = \"optimized\";\n})(MeasuringFrequency || (MeasuringFrequency = {}));\n\nconst defaultValue = /*#__PURE__*/new Map();\nfunction useDroppableMeasuring(containers, _ref) {\n  let {\n    dragging,\n    dependencies,\n    config\n  } = _ref;\n  const [queue, setQueue] = useState(null);\n  const {\n    frequency,\n    measure,\n    strategy\n  } = config;\n  const containersRef = useRef(containers);\n  const disabled = isDisabled();\n  const disabledRef = useLatestValue(disabled);\n  const measureDroppableContainers = useCallback(function (ids) {\n    if (ids === void 0) {\n      ids = [];\n    }\n\n    if (disabledRef.current) {\n      return;\n    }\n\n    setQueue(value => {\n      if (value === null) {\n        return ids;\n      }\n\n      return value.concat(ids.filter(id => !value.includes(id)));\n    });\n  }, [disabledRef]);\n  const timeoutId = useRef(null);\n  const droppableRects = useLazyMemo(previousValue => {\n    if (disabled && !dragging) {\n      return defaultValue;\n    }\n\n    if (!previousValue || previousValue === defaultValue || containersRef.current !== containers || queue != null) {\n      const map = new Map();\n\n      for (let container of containers) {\n        if (!container) {\n          continue;\n        }\n\n        if (queue && queue.length > 0 && !queue.includes(container.id) && container.rect.current) {\n          // This container does not need to be re-measured\n          map.set(container.id, container.rect.current);\n          continue;\n        }\n\n        const node = container.node.current;\n        const rect = node ? new Rect(measure(node), node) : null;\n        container.rect.current = rect;\n\n        if (rect) {\n          map.set(container.id, rect);\n        }\n      }\n\n      return map;\n    }\n\n    return previousValue;\n  }, [containers, queue, dragging, disabled, measure]);\n  useEffect(() => {\n    containersRef.current = containers;\n  }, [containers]);\n  useEffect(() => {\n    if (disabled) {\n      return;\n    }\n\n    measureDroppableContainers();\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [dragging, disabled]);\n  useEffect(() => {\n    if (queue && queue.length > 0) {\n      setQueue(null);\n    }\n  }, //eslint-disable-next-line react-hooks/exhaustive-deps\n  [JSON.stringify(queue)]);\n  useEffect(() => {\n    if (disabled || typeof frequency !== 'number' || timeoutId.current !== null) {\n      return;\n    }\n\n    timeoutId.current = setTimeout(() => {\n      measureDroppableContainers();\n      timeoutId.current = null;\n    }, frequency);\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [frequency, disabled, measureDroppableContainers, ...dependencies]);\n  return {\n    droppableRects,\n    measureDroppableContainers,\n    measuringScheduled: queue != null\n  };\n\n  function isDisabled() {\n    switch (strategy) {\n      case MeasuringStrategy.Always:\n        return false;\n\n      case MeasuringStrategy.BeforeDragging:\n        return dragging;\n\n      default:\n        return !dragging;\n    }\n  }\n}\n\nfunction useInitialValue(value, computeFn) {\n  return useLazyMemo(previousValue => {\n    if (!value) {\n      return null;\n    }\n\n    if (previousValue) {\n      return previousValue;\n    }\n\n    return typeof computeFn === 'function' ? computeFn(value) : value;\n  }, [computeFn, value]);\n}\n\nfunction useInitialRect(node, measure) {\n  return useInitialValue(node, measure);\n}\n\n/**\r\n * Returns a new MutationObserver instance.\r\n * If `MutationObserver` is undefined in the execution environment, returns `undefined`.\r\n */\n\nfunction useMutationObserver(_ref) {\n  let {\n    callback,\n    disabled\n  } = _ref;\n  const handleMutations = useEvent(callback);\n  const mutationObserver = useMemo(() => {\n    if (disabled || typeof window === 'undefined' || typeof window.MutationObserver === 'undefined') {\n      return undefined;\n    }\n\n    const {\n      MutationObserver\n    } = window;\n    return new MutationObserver(handleMutations);\n  }, [handleMutations, disabled]);\n  useEffect(() => {\n    return () => mutationObserver == null ? void 0 : mutationObserver.disconnect();\n  }, [mutationObserver]);\n  return mutationObserver;\n}\n\n/**\r\n * Returns a new ResizeObserver instance bound to the `onResize` callback.\r\n * If `ResizeObserver` is undefined in the execution environment, returns `undefined`.\r\n */\n\nfunction useResizeObserver(_ref) {\n  let {\n    callback,\n    disabled\n  } = _ref;\n  const handleResize = useEvent(callback);\n  const resizeObserver = useMemo(() => {\n    if (disabled || typeof window === 'undefined' || typeof window.ResizeObserver === 'undefined') {\n      return undefined;\n    }\n\n    const {\n      ResizeObserver\n    } = window;\n    return new ResizeObserver(handleResize);\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [disabled]);\n  useEffect(() => {\n    return () => resizeObserver == null ? void 0 : resizeObserver.disconnect();\n  }, [resizeObserver]);\n  return resizeObserver;\n}\n\nfunction defaultMeasure(element) {\n  return new Rect(getClientRect(element), element);\n}\n\nfunction useRect(element, measure, fallbackRect) {\n  if (measure === void 0) {\n    measure = defaultMeasure;\n  }\n\n  const [rect, setRect] = useState(null);\n\n  function measureRect() {\n    setRect(currentRect => {\n      if (!element) {\n        return null;\n      }\n\n      if (element.isConnected === false) {\n        var _ref;\n\n        // Fall back to last rect we measured if the element is\n        // no longer connected to the DOM.\n        return (_ref = currentRect != null ? currentRect : fallbackRect) != null ? _ref : null;\n      }\n\n      const newRect = measure(element);\n\n      if (JSON.stringify(currentRect) === JSON.stringify(newRect)) {\n        return currentRect;\n      }\n\n      return newRect;\n    });\n  }\n\n  const mutationObserver = useMutationObserver({\n    callback(records) {\n      if (!element) {\n        return;\n      }\n\n      for (const record of records) {\n        const {\n          type,\n          target\n        } = record;\n\n        if (type === 'childList' && target instanceof HTMLElement && target.contains(element)) {\n          measureRect();\n          break;\n        }\n      }\n    }\n\n  });\n  const resizeObserver = useResizeObserver({\n    callback: measureRect\n  });\n  useIsomorphicLayoutEffect(() => {\n    measureRect();\n\n    if (element) {\n      resizeObserver == null ? void 0 : resizeObserver.observe(element);\n      mutationObserver == null ? void 0 : mutationObserver.observe(document.body, {\n        childList: true,\n        subtree: true\n      });\n    } else {\n      resizeObserver == null ? void 0 : resizeObserver.disconnect();\n      mutationObserver == null ? void 0 : mutationObserver.disconnect();\n    }\n  }, [element]);\n  return rect;\n}\n\nfunction useRectDelta(rect) {\n  const initialRect = useInitialValue(rect);\n  return getRectDelta(rect, initialRect);\n}\n\nconst defaultValue$1 = [];\nfunction useScrollableAncestors(node) {\n  const previousNode = useRef(node);\n  const ancestors = useLazyMemo(previousValue => {\n    if (!node) {\n      return defaultValue$1;\n    }\n\n    if (previousValue && previousValue !== defaultValue$1 && node && previousNode.current && node.parentNode === previousNode.current.parentNode) {\n      return previousValue;\n    }\n\n    return getScrollableAncestors(node);\n  }, [node]);\n  useEffect(() => {\n    previousNode.current = node;\n  }, [node]);\n  return ancestors;\n}\n\nfunction useScrollOffsets(elements) {\n  const [scrollCoordinates, setScrollCoordinates] = useState(null);\n  const prevElements = useRef(elements); // To-do: Throttle the handleScroll callback\n\n  const handleScroll = useCallback(event => {\n    const scrollingElement = getScrollableElement(event.target);\n\n    if (!scrollingElement) {\n      return;\n    }\n\n    setScrollCoordinates(scrollCoordinates => {\n      if (!scrollCoordinates) {\n        return null;\n      }\n\n      scrollCoordinates.set(scrollingElement, getScrollCoordinates(scrollingElement));\n      return new Map(scrollCoordinates);\n    });\n  }, []);\n  useEffect(() => {\n    const previousElements = prevElements.current;\n\n    if (elements !== previousElements) {\n      cleanup(previousElements);\n      const entries = elements.map(element => {\n        const scrollableElement = getScrollableElement(element);\n\n        if (scrollableElement) {\n          scrollableElement.addEventListener('scroll', handleScroll, {\n            passive: true\n          });\n          return [scrollableElement, getScrollCoordinates(scrollableElement)];\n        }\n\n        return null;\n      }).filter(entry => entry != null);\n      setScrollCoordinates(entries.length ? new Map(entries) : null);\n      prevElements.current = elements;\n    }\n\n    return () => {\n      cleanup(elements);\n      cleanup(previousElements);\n    };\n\n    function cleanup(elements) {\n      elements.forEach(element => {\n        const scrollableElement = getScrollableElement(element);\n        scrollableElement == null ? void 0 : scrollableElement.removeEventListener('scroll', handleScroll);\n      });\n    }\n  }, [handleScroll, elements]);\n  return useMemo(() => {\n    if (elements.length) {\n      return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements);\n    }\n\n    return defaultCoordinates;\n  }, [elements, scrollCoordinates]);\n}\n\nfunction useScrollOffsetsDelta(scrollOffsets, dependencies) {\n  if (dependencies === void 0) {\n    dependencies = [];\n  }\n\n  const initialScrollOffsets = useRef(null);\n  useEffect(() => {\n    initialScrollOffsets.current = null;\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  dependencies);\n  useEffect(() => {\n    const hasScrollOffsets = scrollOffsets !== defaultCoordinates;\n\n    if (hasScrollOffsets && !initialScrollOffsets.current) {\n      initialScrollOffsets.current = scrollOffsets;\n    }\n\n    if (!hasScrollOffsets && initialScrollOffsets.current) {\n      initialScrollOffsets.current = null;\n    }\n  }, [scrollOffsets]);\n  return initialScrollOffsets.current ? subtract(scrollOffsets, initialScrollOffsets.current) : defaultCoordinates;\n}\n\nfunction useSensorSetup(sensors) {\n  useEffect(() => {\n    if (!canUseDOM) {\n      return;\n    }\n\n    const teardownFns = sensors.map(_ref => {\n      let {\n        sensor\n      } = _ref;\n      return sensor.setup == null ? void 0 : sensor.setup();\n    });\n    return () => {\n      for (const teardown of teardownFns) {\n        teardown == null ? void 0 : teardown();\n      }\n    };\n  }, // TO-DO: Sensors length could theoretically change which would not be a valid dependency\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  sensors.map(_ref2 => {\n    let {\n      sensor\n    } = _ref2;\n    return sensor;\n  }));\n}\n\nfunction useSyntheticListeners(listeners, id) {\n  return useMemo(() => {\n    return listeners.reduce((acc, _ref) => {\n      let {\n        eventName,\n        handler\n      } = _ref;\n\n      acc[eventName] = event => {\n        handler(event, id);\n      };\n\n      return acc;\n    }, {});\n  }, [listeners, id]);\n}\n\nfunction useWindowRect(element) {\n  return useMemo(() => element ? getWindowClientRect(element) : null, [element]);\n}\n\nconst defaultValue$2 = [];\nfunction useRects(elements, measure) {\n  if (measure === void 0) {\n    measure = getClientRect;\n  }\n\n  const [firstElement] = elements;\n  const windowRect = useWindowRect(firstElement ? getWindow(firstElement) : null);\n  const [rects, setRects] = useState(defaultValue$2);\n\n  function measureRects() {\n    setRects(() => {\n      if (!elements.length) {\n        return defaultValue$2;\n      }\n\n      return elements.map(element => isDocumentScrollingElement(element) ? windowRect : new Rect(measure(element), element));\n    });\n  }\n\n  const resizeObserver = useResizeObserver({\n    callback: measureRects\n  });\n  useIsomorphicLayoutEffect(() => {\n    resizeObserver == null ? void 0 : resizeObserver.disconnect();\n    measureRects();\n    elements.forEach(element => resizeObserver == null ? void 0 : resizeObserver.observe(element));\n  }, [elements]);\n  return rects;\n}\n\nfunction getMeasurableNode(node) {\n  if (!node) {\n    return null;\n  }\n\n  if (node.children.length > 1) {\n    return node;\n  }\n\n  const firstChild = node.children[0];\n  return isHTMLElement(firstChild) ? firstChild : node;\n}\n\nfunction useDragOverlayMeasuring(_ref) {\n  let {\n    measure\n  } = _ref;\n  const [rect, setRect] = useState(null);\n  const handleResize = useCallback(entries => {\n    for (const {\n      target\n    } of entries) {\n      if (isHTMLElement(target)) {\n        setRect(rect => {\n          const newRect = measure(target);\n          return rect ? { ...rect,\n            width: newRect.width,\n            height: newRect.height\n          } : newRect;\n        });\n        break;\n      }\n    }\n  }, [measure]);\n  const resizeObserver = useResizeObserver({\n    callback: handleResize\n  });\n  const handleNodeChange = useCallback(element => {\n    const node = getMeasurableNode(element);\n    resizeObserver == null ? void 0 : resizeObserver.disconnect();\n\n    if (node) {\n      resizeObserver == null ? void 0 : resizeObserver.observe(node);\n    }\n\n    setRect(node ? measure(node) : null);\n  }, [measure, resizeObserver]);\n  const [nodeRef, setRef] = useNodeRef(handleNodeChange);\n  return useMemo(() => ({\n    nodeRef,\n    rect,\n    setRef\n  }), [rect, nodeRef, setRef]);\n}\n\nconst defaultSensors = [{\n  sensor: PointerSensor,\n  options: {}\n}, {\n  sensor: KeyboardSensor,\n  options: {}\n}];\nconst defaultData = {\n  current: {}\n};\nconst defaultMeasuringConfiguration = {\n  draggable: {\n    measure: getTransformAgnosticClientRect\n  },\n  droppable: {\n    measure: getTransformAgnosticClientRect,\n    strategy: MeasuringStrategy.WhileDragging,\n    frequency: MeasuringFrequency.Optimized\n  },\n  dragOverlay: {\n    measure: getClientRect\n  }\n};\n\nclass DroppableContainersMap extends Map {\n  get(id) {\n    var _super$get;\n\n    return id != null ? (_super$get = super.get(id)) != null ? _super$get : undefined : undefined;\n  }\n\n  toArray() {\n    return Array.from(this.values());\n  }\n\n  getEnabled() {\n    return this.toArray().filter(_ref => {\n      let {\n        disabled\n      } = _ref;\n      return !disabled;\n    });\n  }\n\n  getNodeFor(id) {\n    var _this$get$node$curren, _this$get;\n\n    return (_this$get$node$curren = (_this$get = this.get(id)) == null ? void 0 : _this$get.node.current) != null ? _this$get$node$curren : undefined;\n  }\n\n}\n\nconst defaultPublicContext = {\n  activatorEvent: null,\n  active: null,\n  activeNode: null,\n  activeNodeRect: null,\n  collisions: null,\n  containerNodeRect: null,\n  draggableNodes: /*#__PURE__*/new Map(),\n  droppableRects: /*#__PURE__*/new Map(),\n  droppableContainers: /*#__PURE__*/new DroppableContainersMap(),\n  over: null,\n  dragOverlay: {\n    nodeRef: {\n      current: null\n    },\n    rect: null,\n    setRef: noop\n  },\n  scrollableAncestors: [],\n  scrollableAncestorRects: [],\n  measuringConfiguration: defaultMeasuringConfiguration,\n  measureDroppableContainers: noop,\n  windowRect: null,\n  measuringScheduled: false\n};\nconst defaultInternalContext = {\n  activatorEvent: null,\n  activators: [],\n  active: null,\n  activeNodeRect: null,\n  ariaDescribedById: {\n    draggable: ''\n  },\n  dispatch: noop,\n  draggableNodes: /*#__PURE__*/new Map(),\n  over: null,\n  measureDroppableContainers: noop\n};\nconst InternalContext = /*#__PURE__*/createContext(defaultInternalContext);\nconst PublicContext = /*#__PURE__*/createContext(defaultPublicContext);\n\nfunction getInitialState() {\n  return {\n    draggable: {\n      active: null,\n      initialCoordinates: {\n        x: 0,\n        y: 0\n      },\n      nodes: new Map(),\n      translate: {\n        x: 0,\n        y: 0\n      }\n    },\n    droppable: {\n      containers: new DroppableContainersMap()\n    }\n  };\n}\nfunction reducer(state, action) {\n  switch (action.type) {\n    case Action.DragStart:\n      return { ...state,\n        draggable: { ...state.draggable,\n          initialCoordinates: action.initialCoordinates,\n          active: action.active\n        }\n      };\n\n    case Action.DragMove:\n      if (state.draggable.active == null) {\n        return state;\n      }\n\n      return { ...state,\n        draggable: { ...state.draggable,\n          translate: {\n            x: action.coordinates.x - state.draggable.initialCoordinates.x,\n            y: action.coordinates.y - state.draggable.initialCoordinates.y\n          }\n        }\n      };\n\n    case Action.DragEnd:\n    case Action.DragCancel:\n      return { ...state,\n        draggable: { ...state.draggable,\n          active: null,\n          initialCoordinates: {\n            x: 0,\n            y: 0\n          },\n          translate: {\n            x: 0,\n            y: 0\n          }\n        }\n      };\n\n    case Action.RegisterDroppable:\n      {\n        const {\n          element\n        } = action;\n        const {\n          id\n        } = element;\n        const containers = new DroppableContainersMap(state.droppable.containers);\n        containers.set(id, element);\n        return { ...state,\n          droppable: { ...state.droppable,\n            containers\n          }\n        };\n      }\n\n    case Action.SetDroppableDisabled:\n      {\n        const {\n          id,\n          key,\n          disabled\n        } = action;\n        const element = state.droppable.containers.get(id);\n\n        if (!element || key !== element.key) {\n          return state;\n        }\n\n        const containers = new DroppableContainersMap(state.droppable.containers);\n        containers.set(id, { ...element,\n          disabled\n        });\n        return { ...state,\n          droppable: { ...state.droppable,\n            containers\n          }\n        };\n      }\n\n    case Action.UnregisterDroppable:\n      {\n        const {\n          id,\n          key\n        } = action;\n        const element = state.droppable.containers.get(id);\n\n        if (!element || key !== element.key) {\n          return state;\n        }\n\n        const containers = new DroppableContainersMap(state.droppable.containers);\n        containers.delete(id);\n        return { ...state,\n          droppable: { ...state.droppable,\n            containers\n          }\n        };\n      }\n\n    default:\n      {\n        return state;\n      }\n  }\n}\n\nfunction RestoreFocus(_ref) {\n  let {\n    disabled\n  } = _ref;\n  const {\n    active,\n    activatorEvent,\n    draggableNodes\n  } = useContext(InternalContext);\n  const previousActivatorEvent = usePrevious(activatorEvent);\n  const previousActiveId = usePrevious(active == null ? void 0 : active.id); // Restore keyboard focus on the activator node\n\n  useEffect(() => {\n    if (disabled) {\n      return;\n    }\n\n    if (!activatorEvent && previousActivatorEvent && previousActiveId != null) {\n      if (!isKeyboardEvent(previousActivatorEvent)) {\n        return;\n      }\n\n      if (document.activeElement === previousActivatorEvent.target) {\n        // No need to restore focus\n        return;\n      }\n\n      const draggableNode = draggableNodes.get(previousActiveId);\n\n      if (!draggableNode) {\n        return;\n      }\n\n      const {\n        activatorNode,\n        node\n      } = draggableNode;\n\n      if (!activatorNode.current && !node.current) {\n        return;\n      }\n\n      requestAnimationFrame(() => {\n        for (const element of [activatorNode.current, node.current]) {\n          if (!element) {\n            continue;\n          }\n\n          const focusableNode = findFirstFocusableNode(element);\n\n          if (focusableNode) {\n            focusableNode.focus();\n            break;\n          }\n        }\n      });\n    }\n  }, [activatorEvent, disabled, draggableNodes, previousActiveId, previousActivatorEvent]);\n  return null;\n}\n\nfunction applyModifiers(modifiers, _ref) {\n  let {\n    transform,\n    ...args\n  } = _ref;\n  return modifiers != null && modifiers.length ? modifiers.reduce((accumulator, modifier) => {\n    return modifier({\n      transform: accumulator,\n      ...args\n    });\n  }, transform) : transform;\n}\n\nfunction useMeasuringConfiguration(config) {\n  return useMemo(() => ({\n    draggable: { ...defaultMeasuringConfiguration.draggable,\n      ...(config == null ? void 0 : config.draggable)\n    },\n    droppable: { ...defaultMeasuringConfiguration.droppable,\n      ...(config == null ? void 0 : config.droppable)\n    },\n    dragOverlay: { ...defaultMeasuringConfiguration.dragOverlay,\n      ...(config == null ? void 0 : config.dragOverlay)\n    }\n  }), // eslint-disable-next-line react-hooks/exhaustive-deps\n  [config == null ? void 0 : config.draggable, config == null ? void 0 : config.droppable, config == null ? void 0 : config.dragOverlay]);\n}\n\nfunction useLayoutShiftScrollCompensation(_ref) {\n  let {\n    activeNode,\n    measure,\n    initialRect,\n    config = true\n  } = _ref;\n  const initialized = useRef(false);\n  const {\n    x,\n    y\n  } = typeof config === 'boolean' ? {\n    x: config,\n    y: config\n  } : config;\n  useIsomorphicLayoutEffect(() => {\n    const disabled = !x && !y;\n\n    if (disabled || !activeNode) {\n      initialized.current = false;\n      return;\n    }\n\n    if (initialized.current || !initialRect) {\n      // Return early if layout shift scroll compensation was already attempted\n      // or if there is no initialRect to compare to.\n      return;\n    } // Get the most up to date node ref for the active draggable\n\n\n    const node = activeNode == null ? void 0 : activeNode.node.current;\n\n    if (!node || node.isConnected === false) {\n      // Return early if there is no attached node ref or if the node is\n      // disconnected from the document.\n      return;\n    }\n\n    const rect = measure(node);\n    const rectDelta = getRectDelta(rect, initialRect);\n\n    if (!x) {\n      rectDelta.x = 0;\n    }\n\n    if (!y) {\n      rectDelta.y = 0;\n    } // Only perform layout shift scroll compensation once\n\n\n    initialized.current = true;\n\n    if (Math.abs(rectDelta.x) > 0 || Math.abs(rectDelta.y) > 0) {\n      const firstScrollableAncestor = getFirstScrollableAncestor(node);\n\n      if (firstScrollableAncestor) {\n        firstScrollableAncestor.scrollBy({\n          top: rectDelta.y,\n          left: rectDelta.x\n        });\n      }\n    }\n  }, [activeNode, x, y, initialRect, measure]);\n}\n\nconst ActiveDraggableContext = /*#__PURE__*/createContext({ ...defaultCoordinates,\n  scaleX: 1,\n  scaleY: 1\n});\nvar Status;\n\n(function (Status) {\n  Status[Status[\"Uninitialized\"] = 0] = \"Uninitialized\";\n  Status[Status[\"Initializing\"] = 1] = \"Initializing\";\n  Status[Status[\"Initialized\"] = 2] = \"Initialized\";\n})(Status || (Status = {}));\n\nconst DndContext = /*#__PURE__*/memo(function DndContext(_ref) {\n  var _sensorContext$curren, _dragOverlay$nodeRef$, _dragOverlay$rect, _over$rect;\n\n  let {\n    id,\n    accessibility,\n    autoScroll = true,\n    children,\n    sensors = defaultSensors,\n    collisionDetection = rectIntersection,\n    measuring,\n    modifiers,\n    ...props\n  } = _ref;\n  const store = useReducer(reducer, undefined, getInitialState);\n  const [state, dispatch] = store;\n  const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider();\n  const [status, setStatus] = useState(Status.Uninitialized);\n  const isInitialized = status === Status.Initialized;\n  const {\n    draggable: {\n      active: activeId,\n      nodes: draggableNodes,\n      translate\n    },\n    droppable: {\n      containers: droppableContainers\n    }\n  } = state;\n  const node = activeId != null ? draggableNodes.get(activeId) : null;\n  const activeRects = useRef({\n    initial: null,\n    translated: null\n  });\n  const active = useMemo(() => {\n    var _node$data;\n\n    return activeId != null ? {\n      id: activeId,\n      // It's possible for the active node to unmount while dragging\n      data: (_node$data = node == null ? void 0 : node.data) != null ? _node$data : defaultData,\n      rect: activeRects\n    } : null;\n  }, [activeId, node]);\n  const activeRef = useRef(null);\n  const [activeSensor, setActiveSensor] = useState(null);\n  const [activatorEvent, setActivatorEvent] = useState(null);\n  const latestProps = useLatestValue(props, Object.values(props));\n  const draggableDescribedById = useUniqueId(\"DndDescribedBy\", id);\n  const enabledDroppableContainers = useMemo(() => droppableContainers.getEnabled(), [droppableContainers]);\n  const measuringConfiguration = useMeasuringConfiguration(measuring);\n  const {\n    droppableRects,\n    measureDroppableContainers,\n    measuringScheduled\n  } = useDroppableMeasuring(enabledDroppableContainers, {\n    dragging: isInitialized,\n    dependencies: [translate.x, translate.y],\n    config: measuringConfiguration.droppable\n  });\n  const activeNode = useCachedNode(draggableNodes, activeId);\n  const activationCoordinates = useMemo(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]);\n  const autoScrollOptions = getAutoScrollerOptions();\n  const initialActiveNodeRect = useInitialRect(activeNode, measuringConfiguration.draggable.measure);\n  useLayoutShiftScrollCompensation({\n    activeNode: activeId != null ? draggableNodes.get(activeId) : null,\n    config: autoScrollOptions.layoutShiftCompensation,\n    initialRect: initialActiveNodeRect,\n    measure: measuringConfiguration.draggable.measure\n  });\n  const activeNodeRect = useRect(activeNode, measuringConfiguration.draggable.measure, initialActiveNodeRect);\n  const containerNodeRect = useRect(activeNode ? activeNode.parentElement : null);\n  const sensorContext = useRef({\n    activatorEvent: null,\n    active: null,\n    activeNode,\n    collisionRect: null,\n    collisions: null,\n    droppableRects,\n    draggableNodes,\n    draggingNode: null,\n    draggingNodeRect: null,\n    droppableContainers,\n    over: null,\n    scrollableAncestors: [],\n    scrollAdjustedTranslate: null\n  });\n  const overNode = droppableContainers.getNodeFor((_sensorContext$curren = sensorContext.current.over) == null ? void 0 : _sensorContext$curren.id);\n  const dragOverlay = useDragOverlayMeasuring({\n    measure: measuringConfiguration.dragOverlay.measure\n  }); // Use the rect of the drag overlay if it is mounted\n\n  const draggingNode = (_dragOverlay$nodeRef$ = dragOverlay.nodeRef.current) != null ? _dragOverlay$nodeRef$ : activeNode;\n  const draggingNodeRect = isInitialized ? (_dragOverlay$rect = dragOverlay.rect) != null ? _dragOverlay$rect : activeNodeRect : null;\n  const usesDragOverlay = Boolean(dragOverlay.nodeRef.current && dragOverlay.rect); // The delta between the previous and new position of the draggable node\n  // is only relevant when there is no drag overlay\n\n  const nodeRectDelta = useRectDelta(usesDragOverlay ? null : activeNodeRect); // Get the window rect of the dragging node\n\n  const windowRect = useWindowRect(draggingNode ? getWindow(draggingNode) : null); // Get scrollable ancestors of the dragging node\n\n  const scrollableAncestors = useScrollableAncestors(isInitialized ? overNode != null ? overNode : activeNode : null);\n  const scrollableAncestorRects = useRects(scrollableAncestors); // Apply modifiers\n\n  const modifiedTranslate = applyModifiers(modifiers, {\n    transform: {\n      x: translate.x - nodeRectDelta.x,\n      y: translate.y - nodeRectDelta.y,\n      scaleX: 1,\n      scaleY: 1\n    },\n    activatorEvent,\n    active,\n    activeNodeRect,\n    containerNodeRect,\n    draggingNodeRect,\n    over: sensorContext.current.over,\n    overlayNodeRect: dragOverlay.rect,\n    scrollableAncestors,\n    scrollableAncestorRects,\n    windowRect\n  });\n  const pointerCoordinates = activationCoordinates ? add(activationCoordinates, translate) : null;\n  const scrollOffsets = useScrollOffsets(scrollableAncestors); // Represents the scroll delta since dragging was initiated\n\n  const scrollAdjustment = useScrollOffsetsDelta(scrollOffsets); // Represents the scroll delta since the last time the active node rect was measured\n\n  const activeNodeScrollDelta = useScrollOffsetsDelta(scrollOffsets, [activeNodeRect]);\n  const scrollAdjustedTranslate = add(modifiedTranslate, scrollAdjustment);\n  const collisionRect = draggingNodeRect ? getAdjustedRect(draggingNodeRect, modifiedTranslate) : null;\n  const collisions = active && collisionRect ? collisionDetection({\n    active,\n    collisionRect,\n    droppableRects,\n    droppableContainers: enabledDroppableContainers,\n    pointerCoordinates\n  }) : null;\n  const overId = getFirstCollision(collisions, 'id');\n  const [over, setOver] = useState(null); // When there is no drag overlay used, we need to account for the\n  // window scroll delta\n\n  const appliedTranslate = usesDragOverlay ? modifiedTranslate : add(modifiedTranslate, activeNodeScrollDelta);\n  const transform = adjustScale(appliedTranslate, (_over$rect = over == null ? void 0 : over.rect) != null ? _over$rect : null, activeNodeRect);\n  const activeSensorRef = useRef(null);\n  const instantiateSensor = useCallback((event, _ref2) => {\n    let {\n      sensor: Sensor,\n      options\n    } = _ref2;\n\n    if (activeRef.current == null) {\n      return;\n    }\n\n    const activeNode = draggableNodes.get(activeRef.current);\n\n    if (!activeNode) {\n      return;\n    }\n\n    const activatorEvent = event.nativeEvent;\n    const sensorInstance = new Sensor({\n      active: activeRef.current,\n      activeNode,\n      event: activatorEvent,\n      options,\n      // Sensors need to be instantiated with refs for arguments that change over time\n      // otherwise they are frozen in time with the stale arguments\n      context: sensorContext,\n\n      onAbort(id) {\n        const draggableNode = draggableNodes.get(id);\n\n        if (!draggableNode) {\n          return;\n        }\n\n        const {\n          onDragAbort\n        } = latestProps.current;\n        const event = {\n          id\n        };\n        onDragAbort == null ? void 0 : onDragAbort(event);\n        dispatchMonitorEvent({\n          type: 'onDragAbort',\n          event\n        });\n      },\n\n      onPending(id, constraint, initialCoordinates, offset) {\n        const draggableNode = draggableNodes.get(id);\n\n        if (!draggableNode) {\n          return;\n        }\n\n        const {\n          onDragPending\n        } = latestProps.current;\n        const event = {\n          id,\n          constraint,\n          initialCoordinates,\n          offset\n        };\n        onDragPending == null ? void 0 : onDragPending(event);\n        dispatchMonitorEvent({\n          type: 'onDragPending',\n          event\n        });\n      },\n\n      onStart(initialCoordinates) {\n        const id = activeRef.current;\n\n        if (id == null) {\n          return;\n        }\n\n        const draggableNode = draggableNodes.get(id);\n\n        if (!draggableNode) {\n          return;\n        }\n\n        const {\n          onDragStart\n        } = latestProps.current;\n        const event = {\n          activatorEvent,\n          active: {\n            id,\n            data: draggableNode.data,\n            rect: activeRects\n          }\n        };\n        unstable_batchedUpdates(() => {\n          onDragStart == null ? void 0 : onDragStart(event);\n          setStatus(Status.Initializing);\n          dispatch({\n            type: Action.DragStart,\n            initialCoordinates,\n            active: id\n          });\n          dispatchMonitorEvent({\n            type: 'onDragStart',\n            event\n          });\n          setActiveSensor(activeSensorRef.current);\n          setActivatorEvent(activatorEvent);\n        });\n      },\n\n      onMove(coordinates) {\n        dispatch({\n          type: Action.DragMove,\n          coordinates\n        });\n      },\n\n      onEnd: createHandler(Action.DragEnd),\n      onCancel: createHandler(Action.DragCancel)\n    });\n    activeSensorRef.current = sensorInstance;\n\n    function createHandler(type) {\n      return async function handler() {\n        const {\n          active,\n          collisions,\n          over,\n          scrollAdjustedTranslate\n        } = sensorContext.current;\n        let event = null;\n\n        if (active && scrollAdjustedTranslate) {\n          const {\n            cancelDrop\n          } = latestProps.current;\n          event = {\n            activatorEvent,\n            active: active,\n            collisions,\n            delta: scrollAdjustedTranslate,\n            over\n          };\n\n          if (type === Action.DragEnd && typeof cancelDrop === 'function') {\n            const shouldCancel = await Promise.resolve(cancelDrop(event));\n\n            if (shouldCancel) {\n              type = Action.DragCancel;\n            }\n          }\n        }\n\n        activeRef.current = null;\n        unstable_batchedUpdates(() => {\n          dispatch({\n            type\n          });\n          setStatus(Status.Uninitialized);\n          setOver(null);\n          setActiveSensor(null);\n          setActivatorEvent(null);\n          activeSensorRef.current = null;\n          const eventName = type === Action.DragEnd ? 'onDragEnd' : 'onDragCancel';\n\n          if (event) {\n            const handler = latestProps.current[eventName];\n            handler == null ? void 0 : handler(event);\n            dispatchMonitorEvent({\n              type: eventName,\n              event\n            });\n          }\n        });\n      };\n    }\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [draggableNodes]);\n  const bindActivatorToSensorInstantiator = useCallback((handler, sensor) => {\n    return (event, active) => {\n      const nativeEvent = event.nativeEvent;\n      const activeDraggableNode = draggableNodes.get(active);\n\n      if ( // Another sensor is already instantiating\n      activeRef.current !== null || // No active draggable\n      !activeDraggableNode || // Event has already been captured\n      nativeEvent.dndKit || nativeEvent.defaultPrevented) {\n        return;\n      }\n\n      const activationContext = {\n        active: activeDraggableNode\n      };\n      const shouldActivate = handler(event, sensor.options, activationContext);\n\n      if (shouldActivate === true) {\n        nativeEvent.dndKit = {\n          capturedBy: sensor.sensor\n        };\n        activeRef.current = active;\n        instantiateSensor(event, sensor);\n      }\n    };\n  }, [draggableNodes, instantiateSensor]);\n  const activators = useCombineActivators(sensors, bindActivatorToSensorInstantiator);\n  useSensorSetup(sensors);\n  useIsomorphicLayoutEffect(() => {\n    if (activeNodeRect && status === Status.Initializing) {\n      setStatus(Status.Initialized);\n    }\n  }, [activeNodeRect, status]);\n  useEffect(() => {\n    const {\n      onDragMove\n    } = latestProps.current;\n    const {\n      active,\n      activatorEvent,\n      collisions,\n      over\n    } = sensorContext.current;\n\n    if (!active || !activatorEvent) {\n      return;\n    }\n\n    const event = {\n      active,\n      activatorEvent,\n      collisions,\n      delta: {\n        x: scrollAdjustedTranslate.x,\n        y: scrollAdjustedTranslate.y\n      },\n      over\n    };\n    unstable_batchedUpdates(() => {\n      onDragMove == null ? void 0 : onDragMove(event);\n      dispatchMonitorEvent({\n        type: 'onDragMove',\n        event\n      });\n    });\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y]);\n  useEffect(() => {\n    const {\n      active,\n      activatorEvent,\n      collisions,\n      droppableContainers,\n      scrollAdjustedTranslate\n    } = sensorContext.current;\n\n    if (!active || activeRef.current == null || !activatorEvent || !scrollAdjustedTranslate) {\n      return;\n    }\n\n    const {\n      onDragOver\n    } = latestProps.current;\n    const overContainer = droppableContainers.get(overId);\n    const over = overContainer && overContainer.rect.current ? {\n      id: overContainer.id,\n      rect: overContainer.rect.current,\n      data: overContainer.data,\n      disabled: overContainer.disabled\n    } : null;\n    const event = {\n      active,\n      activatorEvent,\n      collisions,\n      delta: {\n        x: scrollAdjustedTranslate.x,\n        y: scrollAdjustedTranslate.y\n      },\n      over\n    };\n    unstable_batchedUpdates(() => {\n      setOver(over);\n      onDragOver == null ? void 0 : onDragOver(event);\n      dispatchMonitorEvent({\n        type: 'onDragOver',\n        event\n      });\n    });\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [overId]);\n  useIsomorphicLayoutEffect(() => {\n    sensorContext.current = {\n      activatorEvent,\n      active,\n      activeNode,\n      collisionRect,\n      collisions,\n      droppableRects,\n      draggableNodes,\n      draggingNode,\n      draggingNodeRect,\n      droppableContainers,\n      over,\n      scrollableAncestors,\n      scrollAdjustedTranslate\n    };\n    activeRects.current = {\n      initial: draggingNodeRect,\n      translated: collisionRect\n    };\n  }, [active, activeNode, collisions, collisionRect, draggableNodes, draggingNode, draggingNodeRect, droppableRects, droppableContainers, over, scrollableAncestors, scrollAdjustedTranslate]);\n  useAutoScroller({ ...autoScrollOptions,\n    delta: translate,\n    draggingRect: collisionRect,\n    pointerCoordinates,\n    scrollableAncestors,\n    scrollableAncestorRects\n  });\n  const publicContext = useMemo(() => {\n    const context = {\n      active,\n      activeNode,\n      activeNodeRect,\n      activatorEvent,\n      collisions,\n      containerNodeRect,\n      dragOverlay,\n      draggableNodes,\n      droppableContainers,\n      droppableRects,\n      over,\n      measureDroppableContainers,\n      scrollableAncestors,\n      scrollableAncestorRects,\n      measuringConfiguration,\n      measuringScheduled,\n      windowRect\n    };\n    return context;\n  }, [active, activeNode, activeNodeRect, activatorEvent, collisions, containerNodeRect, dragOverlay, draggableNodes, droppableContainers, droppableRects, over, measureDroppableContainers, scrollableAncestors, scrollableAncestorRects, measuringConfiguration, measuringScheduled, windowRect]);\n  const internalContext = useMemo(() => {\n    const context = {\n      activatorEvent,\n      activators,\n      active,\n      activeNodeRect,\n      ariaDescribedById: {\n        draggable: draggableDescribedById\n      },\n      dispatch,\n      draggableNodes,\n      over,\n      measureDroppableContainers\n    };\n    return context;\n  }, [activatorEvent, activators, active, activeNodeRect, dispatch, draggableDescribedById, draggableNodes, over, measureDroppableContainers]);\n  return React.createElement(DndMonitorContext.Provider, {\n    value: registerMonitorListener\n  }, React.createElement(InternalContext.Provider, {\n    value: internalContext\n  }, React.createElement(PublicContext.Provider, {\n    value: publicContext\n  }, React.createElement(ActiveDraggableContext.Provider, {\n    value: transform\n  }, children)), React.createElement(RestoreFocus, {\n    disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false\n  })), React.createElement(Accessibility, { ...accessibility,\n    hiddenTextDescribedById: draggableDescribedById\n  }));\n\n  function getAutoScrollerOptions() {\n    const activeSensorDisablesAutoscroll = (activeSensor == null ? void 0 : activeSensor.autoScrollEnabled) === false;\n    const autoScrollGloballyDisabled = typeof autoScroll === 'object' ? autoScroll.enabled === false : autoScroll === false;\n    const enabled = isInitialized && !activeSensorDisablesAutoscroll && !autoScrollGloballyDisabled;\n\n    if (typeof autoScroll === 'object') {\n      return { ...autoScroll,\n        enabled\n      };\n    }\n\n    return {\n      enabled\n    };\n  }\n});\n\nconst NullContext = /*#__PURE__*/createContext(null);\nconst defaultRole = 'button';\nconst ID_PREFIX = 'Draggable';\nfunction useDraggable(_ref) {\n  let {\n    id,\n    data,\n    disabled = false,\n    attributes\n  } = _ref;\n  const key = useUniqueId(ID_PREFIX);\n  const {\n    activators,\n    activatorEvent,\n    active,\n    activeNodeRect,\n    ariaDescribedById,\n    draggableNodes,\n    over\n  } = useContext(InternalContext);\n  const {\n    role = defaultRole,\n    roleDescription = 'draggable',\n    tabIndex = 0\n  } = attributes != null ? attributes : {};\n  const isDragging = (active == null ? void 0 : active.id) === id;\n  const transform = useContext(isDragging ? ActiveDraggableContext : NullContext);\n  const [node, setNodeRef] = useNodeRef();\n  const [activatorNode, setActivatorNodeRef] = useNodeRef();\n  const listeners = useSyntheticListeners(activators, id);\n  const dataRef = useLatestValue(data);\n  useIsomorphicLayoutEffect(() => {\n    draggableNodes.set(id, {\n      id,\n      key,\n      node,\n      activatorNode,\n      data: dataRef\n    });\n    return () => {\n      const node = draggableNodes.get(id);\n\n      if (node && node.key === key) {\n        draggableNodes.delete(id);\n      }\n    };\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [draggableNodes, id]);\n  const memoizedAttributes = useMemo(() => ({\n    role,\n    tabIndex,\n    'aria-disabled': disabled,\n    'aria-pressed': isDragging && role === defaultRole ? true : undefined,\n    'aria-roledescription': roleDescription,\n    'aria-describedby': ariaDescribedById.draggable\n  }), [disabled, role, tabIndex, isDragging, roleDescription, ariaDescribedById.draggable]);\n  return {\n    active,\n    activatorEvent,\n    activeNodeRect,\n    attributes: memoizedAttributes,\n    isDragging,\n    listeners: disabled ? undefined : listeners,\n    node,\n    over,\n    setNodeRef,\n    setActivatorNodeRef,\n    transform\n  };\n}\n\nfunction useDndContext() {\n  return useContext(PublicContext);\n}\n\nconst ID_PREFIX$1 = 'Droppable';\nconst defaultResizeObserverConfig = {\n  timeout: 25\n};\nfunction useDroppable(_ref) {\n  let {\n    data,\n    disabled = false,\n    id,\n    resizeObserverConfig\n  } = _ref;\n  const key = useUniqueId(ID_PREFIX$1);\n  const {\n    active,\n    dispatch,\n    over,\n    measureDroppableContainers\n  } = useContext(InternalContext);\n  const previous = useRef({\n    disabled\n  });\n  const resizeObserverConnected = useRef(false);\n  const rect = useRef(null);\n  const callbackId = useRef(null);\n  const {\n    disabled: resizeObserverDisabled,\n    updateMeasurementsFor,\n    timeout: resizeObserverTimeout\n  } = { ...defaultResizeObserverConfig,\n    ...resizeObserverConfig\n  };\n  const ids = useLatestValue(updateMeasurementsFor != null ? updateMeasurementsFor : id);\n  const handleResize = useCallback(() => {\n    if (!resizeObserverConnected.current) {\n      // ResizeObserver invokes the `handleResize` callback as soon as `observe` is called,\n      // assuming the element is rendered and displayed.\n      resizeObserverConnected.current = true;\n      return;\n    }\n\n    if (callbackId.current != null) {\n      clearTimeout(callbackId.current);\n    }\n\n    callbackId.current = setTimeout(() => {\n      measureDroppableContainers(Array.isArray(ids.current) ? ids.current : [ids.current]);\n      callbackId.current = null;\n    }, resizeObserverTimeout);\n  }, //eslint-disable-next-line react-hooks/exhaustive-deps\n  [resizeObserverTimeout]);\n  const resizeObserver = useResizeObserver({\n    callback: handleResize,\n    disabled: resizeObserverDisabled || !active\n  });\n  const handleNodeChange = useCallback((newElement, previousElement) => {\n    if (!resizeObserver) {\n      return;\n    }\n\n    if (previousElement) {\n      resizeObserver.unobserve(previousElement);\n      resizeObserverConnected.current = false;\n    }\n\n    if (newElement) {\n      resizeObserver.observe(newElement);\n    }\n  }, [resizeObserver]);\n  const [nodeRef, setNodeRef] = useNodeRef(handleNodeChange);\n  const dataRef = useLatestValue(data);\n  useEffect(() => {\n    if (!resizeObserver || !nodeRef.current) {\n      return;\n    }\n\n    resizeObserver.disconnect();\n    resizeObserverConnected.current = false;\n    resizeObserver.observe(nodeRef.current);\n  }, [nodeRef, resizeObserver]);\n  useEffect(() => {\n    dispatch({\n      type: Action.RegisterDroppable,\n      element: {\n        id,\n        key,\n        disabled,\n        node: nodeRef,\n        rect,\n        data: dataRef\n      }\n    });\n    return () => dispatch({\n      type: Action.UnregisterDroppable,\n      key,\n      id\n    });\n  }, // eslint-disable-next-line react-hooks/exhaustive-deps\n  [id]);\n  useEffect(() => {\n    if (disabled !== previous.current.disabled) {\n      dispatch({\n        type: Action.SetDroppableDisabled,\n        id,\n        key,\n        disabled\n      });\n      previous.current.disabled = disabled;\n    }\n  }, [id, key, disabled, dispatch]);\n  return {\n    active,\n    rect,\n    isOver: (over == null ? void 0 : over.id) === id,\n    node: nodeRef,\n    over,\n    setNodeRef\n  };\n}\n\nfunction AnimationManager(_ref) {\n  let {\n    animation,\n    children\n  } = _ref;\n  const [clonedChildren, setClonedChildren] = useState(null);\n  const [element, setElement] = useState(null);\n  const previousChildren = usePrevious(children);\n\n  if (!children && !clonedChildren && previousChildren) {\n    setClonedChildren(previousChildren);\n  }\n\n  useIsomorphicLayoutEffect(() => {\n    if (!element) {\n      return;\n    }\n\n    const key = clonedChildren == null ? void 0 : clonedChildren.key;\n    const id = clonedChildren == null ? void 0 : clonedChildren.props.id;\n\n    if (key == null || id == null) {\n      setClonedChildren(null);\n      return;\n    }\n\n    Promise.resolve(animation(id, element)).then(() => {\n      setClonedChildren(null);\n    });\n  }, [animation, clonedChildren, element]);\n  return React.createElement(React.Fragment, null, children, clonedChildren ? cloneElement(clonedChildren, {\n    ref: setElement\n  }) : null);\n}\n\nconst defaultTransform = {\n  x: 0,\n  y: 0,\n  scaleX: 1,\n  scaleY: 1\n};\nfunction NullifiedContextProvider(_ref) {\n  let {\n    children\n  } = _ref;\n  return React.createElement(InternalContext.Provider, {\n    value: defaultInternalContext\n  }, React.createElement(ActiveDraggableContext.Provider, {\n    value: defaultTransform\n  }, children));\n}\n\nconst baseStyles = {\n  position: 'fixed',\n  touchAction: 'none'\n};\n\nconst defaultTransition = activatorEvent => {\n  const isKeyboardActivator = isKeyboardEvent(activatorEvent);\n  return isKeyboardActivator ? 'transform 250ms ease' : undefined;\n};\n\nconst PositionedOverlay = /*#__PURE__*/forwardRef((_ref, ref) => {\n  let {\n    as,\n    activatorEvent,\n    adjustScale,\n    children,\n    className,\n    rect,\n    style,\n    transform,\n    transition = defaultTransition\n  } = _ref;\n\n  if (!rect) {\n    return null;\n  }\n\n  const scaleAdjustedTransform = adjustScale ? transform : { ...transform,\n    scaleX: 1,\n    scaleY: 1\n  };\n  const styles = { ...baseStyles,\n    width: rect.width,\n    height: rect.height,\n    top: rect.top,\n    left: rect.left,\n    transform: CSS.Transform.toString(scaleAdjustedTransform),\n    transformOrigin: adjustScale && activatorEvent ? getRelativeTransformOrigin(activatorEvent, rect) : undefined,\n    transition: typeof transition === 'function' ? transition(activatorEvent) : transition,\n    ...style\n  };\n  return React.createElement(as, {\n    className,\n    style: styles,\n    ref\n  }, children);\n});\n\nconst defaultDropAnimationSideEffects = options => _ref => {\n  let {\n    active,\n    dragOverlay\n  } = _ref;\n  const originalStyles = {};\n  const {\n    styles,\n    className\n  } = options;\n\n  if (styles != null && styles.active) {\n    for (const [key, value] of Object.entries(styles.active)) {\n      if (value === undefined) {\n        continue;\n      }\n\n      originalStyles[key] = active.node.style.getPropertyValue(key);\n      active.node.style.setProperty(key, value);\n    }\n  }\n\n  if (styles != null && styles.dragOverlay) {\n    for (const [key, value] of Object.entries(styles.dragOverlay)) {\n      if (value === undefined) {\n        continue;\n      }\n\n      dragOverlay.node.style.setProperty(key, value);\n    }\n  }\n\n  if (className != null && className.active) {\n    active.node.classList.add(className.active);\n  }\n\n  if (className != null && className.dragOverlay) {\n    dragOverlay.node.classList.add(className.dragOverlay);\n  }\n\n  return function cleanup() {\n    for (const [key, value] of Object.entries(originalStyles)) {\n      active.node.style.setProperty(key, value);\n    }\n\n    if (className != null && className.active) {\n      active.node.classList.remove(className.active);\n    }\n  };\n};\n\nconst defaultKeyframeResolver = _ref2 => {\n  let {\n    transform: {\n      initial,\n      final\n    }\n  } = _ref2;\n  return [{\n    transform: CSS.Transform.toString(initial)\n  }, {\n    transform: CSS.Transform.toString(final)\n  }];\n};\n\nconst defaultDropAnimationConfiguration = {\n  duration: 250,\n  easing: 'ease',\n  keyframes: defaultKeyframeResolver,\n  sideEffects: /*#__PURE__*/defaultDropAnimationSideEffects({\n    styles: {\n      active: {\n        opacity: '0'\n      }\n    }\n  })\n};\nfunction useDropAnimation(_ref3) {\n  let {\n    config,\n    draggableNodes,\n    droppableContainers,\n    measuringConfiguration\n  } = _ref3;\n  return useEvent((id, node) => {\n    if (config === null) {\n      return;\n    }\n\n    const activeDraggable = draggableNodes.get(id);\n\n    if (!activeDraggable) {\n      return;\n    }\n\n    const activeNode = activeDraggable.node.current;\n\n    if (!activeNode) {\n      return;\n    }\n\n    const measurableNode = getMeasurableNode(node);\n\n    if (!measurableNode) {\n      return;\n    }\n\n    const {\n      transform\n    } = getWindow(node).getComputedStyle(node);\n    const parsedTransform = parseTransform(transform);\n\n    if (!parsedTransform) {\n      return;\n    }\n\n    const animation = typeof config === 'function' ? config : createDefaultDropAnimation(config);\n    scrollIntoViewIfNeeded(activeNode, measuringConfiguration.draggable.measure);\n    return animation({\n      active: {\n        id,\n        data: activeDraggable.data,\n        node: activeNode,\n        rect: measuringConfiguration.draggable.measure(activeNode)\n      },\n      draggableNodes,\n      dragOverlay: {\n        node,\n        rect: measuringConfiguration.dragOverlay.measure(measurableNode)\n      },\n      droppableContainers,\n      measuringConfiguration,\n      transform: parsedTransform\n    });\n  });\n}\n\nfunction createDefaultDropAnimation(options) {\n  const {\n    duration,\n    easing,\n    sideEffects,\n    keyframes\n  } = { ...defaultDropAnimationConfiguration,\n    ...options\n  };\n  return _ref4 => {\n    let {\n      active,\n      dragOverlay,\n      transform,\n      ...rest\n    } = _ref4;\n\n    if (!duration) {\n      // Do not animate if animation duration is zero.\n      return;\n    }\n\n    const delta = {\n      x: dragOverlay.rect.left - active.rect.left,\n      y: dragOverlay.rect.top - active.rect.top\n    };\n    const scale = {\n      scaleX: transform.scaleX !== 1 ? active.rect.width * transform.scaleX / dragOverlay.rect.width : 1,\n      scaleY: transform.scaleY !== 1 ? active.rect.height * transform.scaleY / dragOverlay.rect.height : 1\n    };\n    const finalTransform = {\n      x: transform.x - delta.x,\n      y: transform.y - delta.y,\n      ...scale\n    };\n    const animationKeyframes = keyframes({ ...rest,\n      active,\n      dragOverlay,\n      transform: {\n        initial: transform,\n        final: finalTransform\n      }\n    });\n    const [firstKeyframe] = animationKeyframes;\n    const lastKeyframe = animationKeyframes[animationKeyframes.length - 1];\n\n    if (JSON.stringify(firstKeyframe) === JSON.stringify(lastKeyframe)) {\n      // The start and end keyframes are the same, infer that there is no animation needed.\n      return;\n    }\n\n    const cleanup = sideEffects == null ? void 0 : sideEffects({\n      active,\n      dragOverlay,\n      ...rest\n    });\n    const animation = dragOverlay.node.animate(animationKeyframes, {\n      duration,\n      easing,\n      fill: 'forwards'\n    });\n    return new Promise(resolve => {\n      animation.onfinish = () => {\n        cleanup == null ? void 0 : cleanup();\n        resolve();\n      };\n    });\n  };\n}\n\nlet key = 0;\nfunction useKey(id) {\n  return useMemo(() => {\n    if (id == null) {\n      return;\n    }\n\n    key++;\n    return key;\n  }, [id]);\n}\n\nconst DragOverlay = /*#__PURE__*/React.memo(_ref => {\n  let {\n    adjustScale = false,\n    children,\n    dropAnimation: dropAnimationConfig,\n    style,\n    transition,\n    modifiers,\n    wrapperElement = 'div',\n    className,\n    zIndex = 999\n  } = _ref;\n  const {\n    activatorEvent,\n    active,\n    activeNodeRect,\n    containerNodeRect,\n    draggableNodes,\n    droppableContainers,\n    dragOverlay,\n    over,\n    measuringConfiguration,\n    scrollableAncestors,\n    scrollableAncestorRects,\n    windowRect\n  } = useDndContext();\n  const transform = useContext(ActiveDraggableContext);\n  const key = useKey(active == null ? void 0 : active.id);\n  const modifiedTransform = applyModifiers(modifiers, {\n    activatorEvent,\n    active,\n    activeNodeRect,\n    containerNodeRect,\n    draggingNodeRect: dragOverlay.rect,\n    over,\n    overlayNodeRect: dragOverlay.rect,\n    scrollableAncestors,\n    scrollableAncestorRects,\n    transform,\n    windowRect\n  });\n  const initialRect = useInitialValue(activeNodeRect);\n  const dropAnimation = useDropAnimation({\n    config: dropAnimationConfig,\n    draggableNodes,\n    droppableContainers,\n    measuringConfiguration\n  }); // We need to wait for the active node to be measured before connecting the drag overlay ref\n  // otherwise collisions can be computed against a mispositioned drag overlay\n\n  const ref = initialRect ? dragOverlay.setRef : undefined;\n  return React.createElement(NullifiedContextProvider, null, React.createElement(AnimationManager, {\n    animation: dropAnimation\n  }, active && key ? React.createElement(PositionedOverlay, {\n    key: key,\n    id: active.id,\n    ref: ref,\n    as: wrapperElement,\n    activatorEvent: activatorEvent,\n    adjustScale: adjustScale,\n    className: className,\n    transition: transition,\n    rect: initialRect,\n    style: {\n      zIndex,\n      ...style\n    },\n    transform: modifiedTransform\n  }, children) : null));\n});\n\nexport { AutoScrollActivator, DndContext, DragOverlay, KeyboardCode, KeyboardSensor, MeasuringFrequency, MeasuringStrategy, MouseSensor, PointerSensor, TouchSensor, TraversalOrder, applyModifiers, closestCenter, closestCorners, defaultAnnouncements, defaultCoordinates, defaultDropAnimationConfiguration as defaultDropAnimation, defaultDropAnimationSideEffects, defaultKeyboardCoordinateGetter, defaultScreenReaderInstructions, getClientRect, getFirstCollision, getScrollableAncestors, pointerWithin, rectIntersection, useDndContext, useDndMonitor, useDraggable, useDroppable, useSensor, useSensors };\n//# sourceMappingURL=core.esm.js.map\n","import React, { useMemo, useRef, useEffect, useState, useContext } from 'react';\nimport { useDndContext, getClientRect, useDroppable, useDraggable, closestCorners, getFirstCollision, getScrollableAncestors, KeyboardCode } from '@dnd-kit/core';\nimport { useUniqueId, useIsomorphicLayoutEffect, CSS, useCombinedRefs, isKeyboardEvent, subtract } from '@dnd-kit/utilities';\n\n/**\r\n * Move an array item to a different position. Returns a new array with the item moved to the new position.\r\n */\nfunction arrayMove(array, from, to) {\n  const newArray = array.slice();\n  newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0]);\n  return newArray;\n}\n\n/**\r\n * Swap an array item to a different position. Returns a new array with the item swapped to the new position.\r\n */\nfunction arraySwap(array, from, to) {\n  const newArray = array.slice();\n  newArray[from] = array[to];\n  newArray[to] = array[from];\n  return newArray;\n}\n\nfunction getSortedRects(items, rects) {\n  return items.reduce((accumulator, id, index) => {\n    const rect = rects.get(id);\n\n    if (rect) {\n      accumulator[index] = rect;\n    }\n\n    return accumulator;\n  }, Array(items.length));\n}\n\nfunction isValidIndex(index) {\n  return index !== null && index >= 0;\n}\n\nfunction itemsEqual(a, b) {\n  if (a === b) {\n    return true;\n  }\n\n  if (a.length !== b.length) {\n    return false;\n  }\n\n  for (let i = 0; i < a.length; i++) {\n    if (a[i] !== b[i]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction normalizeDisabled(disabled) {\n  if (typeof disabled === 'boolean') {\n    return {\n      draggable: disabled,\n      droppable: disabled\n    };\n  }\n\n  return disabled;\n}\n\n// To-do: We should be calculating scale transformation\nconst defaultScale = {\n  scaleX: 1,\n  scaleY: 1\n};\nconst horizontalListSortingStrategy = _ref => {\n  var _rects$activeIndex;\n\n  let {\n    rects,\n    activeNodeRect: fallbackActiveRect,\n    activeIndex,\n    overIndex,\n    index\n  } = _ref;\n  const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect;\n\n  if (!activeNodeRect) {\n    return null;\n  }\n\n  const itemGap = getItemGap(rects, index, activeIndex);\n\n  if (index === activeIndex) {\n    const newIndexRect = rects[overIndex];\n\n    if (!newIndexRect) {\n      return null;\n    }\n\n    return {\n      x: activeIndex < overIndex ? newIndexRect.left + newIndexRect.width - (activeNodeRect.left + activeNodeRect.width) : newIndexRect.left - activeNodeRect.left,\n      y: 0,\n      ...defaultScale\n    };\n  }\n\n  if (index > activeIndex && index <= overIndex) {\n    return {\n      x: -activeNodeRect.width - itemGap,\n      y: 0,\n      ...defaultScale\n    };\n  }\n\n  if (index < activeIndex && index >= overIndex) {\n    return {\n      x: activeNodeRect.width + itemGap,\n      y: 0,\n      ...defaultScale\n    };\n  }\n\n  return {\n    x: 0,\n    y: 0,\n    ...defaultScale\n  };\n};\n\nfunction getItemGap(rects, index, activeIndex) {\n  const currentRect = rects[index];\n  const previousRect = rects[index - 1];\n  const nextRect = rects[index + 1];\n\n  if (!currentRect || !previousRect && !nextRect) {\n    return 0;\n  }\n\n  if (activeIndex < index) {\n    return previousRect ? currentRect.left - (previousRect.left + previousRect.width) : nextRect.left - (currentRect.left + currentRect.width);\n  }\n\n  return nextRect ? nextRect.left - (currentRect.left + currentRect.width) : currentRect.left - (previousRect.left + previousRect.width);\n}\n\nconst rectSortingStrategy = _ref => {\n  let {\n    rects,\n    activeIndex,\n    overIndex,\n    index\n  } = _ref;\n  const newRects = arrayMove(rects, overIndex, activeIndex);\n  const oldRect = rects[index];\n  const newRect = newRects[index];\n\n  if (!newRect || !oldRect) {\n    return null;\n  }\n\n  return {\n    x: newRect.left - oldRect.left,\n    y: newRect.top - oldRect.top,\n    scaleX: newRect.width / oldRect.width,\n    scaleY: newRect.height / oldRect.height\n  };\n};\n\nconst rectSwappingStrategy = _ref => {\n  let {\n    activeIndex,\n    index,\n    rects,\n    overIndex\n  } = _ref;\n  let oldRect;\n  let newRect;\n\n  if (index === activeIndex) {\n    oldRect = rects[index];\n    newRect = rects[overIndex];\n  }\n\n  if (index === overIndex) {\n    oldRect = rects[index];\n    newRect = rects[activeIndex];\n  }\n\n  if (!newRect || !oldRect) {\n    return null;\n  }\n\n  return {\n    x: newRect.left - oldRect.left,\n    y: newRect.top - oldRect.top,\n    scaleX: newRect.width / oldRect.width,\n    scaleY: newRect.height / oldRect.height\n  };\n};\n\n// To-do: We should be calculating scale transformation\nconst defaultScale$1 = {\n  scaleX: 1,\n  scaleY: 1\n};\nconst verticalListSortingStrategy = _ref => {\n  var _rects$activeIndex;\n\n  let {\n    activeIndex,\n    activeNodeRect: fallbackActiveRect,\n    index,\n    rects,\n    overIndex\n  } = _ref;\n  const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect;\n\n  if (!activeNodeRect) {\n    return null;\n  }\n\n  if (index === activeIndex) {\n    const overIndexRect = rects[overIndex];\n\n    if (!overIndexRect) {\n      return null;\n    }\n\n    return {\n      x: 0,\n      y: activeIndex < overIndex ? overIndexRect.top + overIndexRect.height - (activeNodeRect.top + activeNodeRect.height) : overIndexRect.top - activeNodeRect.top,\n      ...defaultScale$1\n    };\n  }\n\n  const itemGap = getItemGap$1(rects, index, activeIndex);\n\n  if (index > activeIndex && index <= overIndex) {\n    return {\n      x: 0,\n      y: -activeNodeRect.height - itemGap,\n      ...defaultScale$1\n    };\n  }\n\n  if (index < activeIndex && index >= overIndex) {\n    return {\n      x: 0,\n      y: activeNodeRect.height + itemGap,\n      ...defaultScale$1\n    };\n  }\n\n  return {\n    x: 0,\n    y: 0,\n    ...defaultScale$1\n  };\n};\n\nfunction getItemGap$1(clientRects, index, activeIndex) {\n  const currentRect = clientRects[index];\n  const previousRect = clientRects[index - 1];\n  const nextRect = clientRects[index + 1];\n\n  if (!currentRect) {\n    return 0;\n  }\n\n  if (activeIndex < index) {\n    return previousRect ? currentRect.top - (previousRect.top + previousRect.height) : nextRect ? nextRect.top - (currentRect.top + currentRect.height) : 0;\n  }\n\n  return nextRect ? nextRect.top - (currentRect.top + currentRect.height) : previousRect ? currentRect.top - (previousRect.top + previousRect.height) : 0;\n}\n\nconst ID_PREFIX = 'Sortable';\nconst Context = /*#__PURE__*/React.createContext({\n  activeIndex: -1,\n  containerId: ID_PREFIX,\n  disableTransforms: false,\n  items: [],\n  overIndex: -1,\n  useDragOverlay: false,\n  sortedRects: [],\n  strategy: rectSortingStrategy,\n  disabled: {\n    draggable: false,\n    droppable: false\n  }\n});\nfunction SortableContext(_ref) {\n  let {\n    children,\n    id,\n    items: userDefinedItems,\n    strategy = rectSortingStrategy,\n    disabled: disabledProp = false\n  } = _ref;\n  const {\n    active,\n    dragOverlay,\n    droppableRects,\n    over,\n    measureDroppableContainers\n  } = useDndContext();\n  const containerId = useUniqueId(ID_PREFIX, id);\n  const useDragOverlay = Boolean(dragOverlay.rect !== null);\n  const items = useMemo(() => userDefinedItems.map(item => typeof item === 'object' && 'id' in item ? item.id : item), [userDefinedItems]);\n  const isDragging = active != null;\n  const activeIndex = active ? items.indexOf(active.id) : -1;\n  const overIndex = over ? items.indexOf(over.id) : -1;\n  const previousItemsRef = useRef(items);\n  const itemsHaveChanged = !itemsEqual(items, previousItemsRef.current);\n  const disableTransforms = overIndex !== -1 && activeIndex === -1 || itemsHaveChanged;\n  const disabled = normalizeDisabled(disabledProp);\n  useIsomorphicLayoutEffect(() => {\n    if (itemsHaveChanged && isDragging) {\n      measureDroppableContainers(items);\n    }\n  }, [itemsHaveChanged, items, isDragging, measureDroppableContainers]);\n  useEffect(() => {\n    previousItemsRef.current = items;\n  }, [items]);\n  const contextValue = useMemo(() => ({\n    activeIndex,\n    containerId,\n    disabled,\n    disableTransforms,\n    items,\n    overIndex,\n    useDragOverlay,\n    sortedRects: getSortedRects(items, droppableRects),\n    strategy\n  }), // eslint-disable-next-line react-hooks/exhaustive-deps\n  [activeIndex, containerId, disabled.draggable, disabled.droppable, disableTransforms, items, overIndex, droppableRects, useDragOverlay, strategy]);\n  return React.createElement(Context.Provider, {\n    value: contextValue\n  }, children);\n}\n\nconst defaultNewIndexGetter = _ref => {\n  let {\n    id,\n    items,\n    activeIndex,\n    overIndex\n  } = _ref;\n  return arrayMove(items, activeIndex, overIndex).indexOf(id);\n};\nconst defaultAnimateLayoutChanges = _ref2 => {\n  let {\n    containerId,\n    isSorting,\n    wasDragging,\n    index,\n    items,\n    newIndex,\n    previousItems,\n    previousContainerId,\n    transition\n  } = _ref2;\n\n  if (!transition || !wasDragging) {\n    return false;\n  }\n\n  if (previousItems !== items && index === newIndex) {\n    return false;\n  }\n\n  if (isSorting) {\n    return true;\n  }\n\n  return newIndex !== index && containerId === previousContainerId;\n};\nconst defaultTransition = {\n  duration: 200,\n  easing: 'ease'\n};\nconst transitionProperty = 'transform';\nconst disabledTransition = /*#__PURE__*/CSS.Transition.toString({\n  property: transitionProperty,\n  duration: 0,\n  easing: 'linear'\n});\nconst defaultAttributes = {\n  roleDescription: 'sortable'\n};\n\n/*\r\n * When the index of an item changes while sorting,\r\n * we need to temporarily disable the transforms\r\n */\n\nfunction useDerivedTransform(_ref) {\n  let {\n    disabled,\n    index,\n    node,\n    rect\n  } = _ref;\n  const [derivedTransform, setDerivedtransform] = useState(null);\n  const previousIndex = useRef(index);\n  useIsomorphicLayoutEffect(() => {\n    if (!disabled && index !== previousIndex.current && node.current) {\n      const initial = rect.current;\n\n      if (initial) {\n        const current = getClientRect(node.current, {\n          ignoreTransform: true\n        });\n        const delta = {\n          x: initial.left - current.left,\n          y: initial.top - current.top,\n          scaleX: initial.width / current.width,\n          scaleY: initial.height / current.height\n        };\n\n        if (delta.x || delta.y) {\n          setDerivedtransform(delta);\n        }\n      }\n    }\n\n    if (index !== previousIndex.current) {\n      previousIndex.current = index;\n    }\n  }, [disabled, index, node, rect]);\n  useEffect(() => {\n    if (derivedTransform) {\n      setDerivedtransform(null);\n    }\n  }, [derivedTransform]);\n  return derivedTransform;\n}\n\nfunction useSortable(_ref) {\n  let {\n    animateLayoutChanges = defaultAnimateLayoutChanges,\n    attributes: userDefinedAttributes,\n    disabled: localDisabled,\n    data: customData,\n    getNewIndex = defaultNewIndexGetter,\n    id,\n    strategy: localStrategy,\n    resizeObserverConfig,\n    transition = defaultTransition\n  } = _ref;\n  const {\n    items,\n    containerId,\n    activeIndex,\n    disabled: globalDisabled,\n    disableTransforms,\n    sortedRects,\n    overIndex,\n    useDragOverlay,\n    strategy: globalStrategy\n  } = useContext(Context);\n  const disabled = normalizeLocalDisabled(localDisabled, globalDisabled);\n  const index = items.indexOf(id);\n  const data = useMemo(() => ({\n    sortable: {\n      containerId,\n      index,\n      items\n    },\n    ...customData\n  }), [containerId, customData, index, items]);\n  const itemsAfterCurrentSortable = useMemo(() => items.slice(items.indexOf(id)), [items, id]);\n  const {\n    rect,\n    node,\n    isOver,\n    setNodeRef: setDroppableNodeRef\n  } = useDroppable({\n    id,\n    data,\n    disabled: disabled.droppable,\n    resizeObserverConfig: {\n      updateMeasurementsFor: itemsAfterCurrentSortable,\n      ...resizeObserverConfig\n    }\n  });\n  const {\n    active,\n    activatorEvent,\n    activeNodeRect,\n    attributes,\n    setNodeRef: setDraggableNodeRef,\n    listeners,\n    isDragging,\n    over,\n    setActivatorNodeRef,\n    transform\n  } = useDraggable({\n    id,\n    data,\n    attributes: { ...defaultAttributes,\n      ...userDefinedAttributes\n    },\n    disabled: disabled.draggable\n  });\n  const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);\n  const isSorting = Boolean(active);\n  const displaceItem = isSorting && !disableTransforms && isValidIndex(activeIndex) && isValidIndex(overIndex);\n  const shouldDisplaceDragSource = !useDragOverlay && isDragging;\n  const dragSourceDisplacement = shouldDisplaceDragSource && displaceItem ? transform : null;\n  const strategy = localStrategy != null ? localStrategy : globalStrategy;\n  const finalTransform = displaceItem ? dragSourceDisplacement != null ? dragSourceDisplacement : strategy({\n    rects: sortedRects,\n    activeNodeRect,\n    activeIndex,\n    overIndex,\n    index\n  }) : null;\n  const newIndex = isValidIndex(activeIndex) && isValidIndex(overIndex) ? getNewIndex({\n    id,\n    items,\n    activeIndex,\n    overIndex\n  }) : index;\n  const activeId = active == null ? void 0 : active.id;\n  const previous = useRef({\n    activeId,\n    items,\n    newIndex,\n    containerId\n  });\n  const itemsHaveChanged = items !== previous.current.items;\n  const shouldAnimateLayoutChanges = animateLayoutChanges({\n    active,\n    containerId,\n    isDragging,\n    isSorting,\n    id,\n    index,\n    items,\n    newIndex: previous.current.newIndex,\n    previousItems: previous.current.items,\n    previousContainerId: previous.current.containerId,\n    transition,\n    wasDragging: previous.current.activeId != null\n  });\n  const derivedTransform = useDerivedTransform({\n    disabled: !shouldAnimateLayoutChanges,\n    index,\n    node,\n    rect\n  });\n  useEffect(() => {\n    if (isSorting && previous.current.newIndex !== newIndex) {\n      previous.current.newIndex = newIndex;\n    }\n\n    if (containerId !== previous.current.containerId) {\n      previous.current.containerId = containerId;\n    }\n\n    if (items !== previous.current.items) {\n      previous.current.items = items;\n    }\n  }, [isSorting, newIndex, containerId, items]);\n  useEffect(() => {\n    if (activeId === previous.current.activeId) {\n      return;\n    }\n\n    if (activeId != null && previous.current.activeId == null) {\n      previous.current.activeId = activeId;\n      return;\n    }\n\n    const timeoutId = setTimeout(() => {\n      previous.current.activeId = activeId;\n    }, 50);\n    return () => clearTimeout(timeoutId);\n  }, [activeId]);\n  return {\n    active,\n    activeIndex,\n    attributes,\n    data,\n    rect,\n    index,\n    newIndex,\n    items,\n    isOver,\n    isSorting,\n    isDragging,\n    listeners,\n    node,\n    overIndex,\n    over,\n    setNodeRef,\n    setActivatorNodeRef,\n    setDroppableNodeRef,\n    setDraggableNodeRef,\n    transform: derivedTransform != null ? derivedTransform : finalTransform,\n    transition: getTransition()\n  };\n\n  function getTransition() {\n    if ( // Temporarily disable transitions for a single frame to set up derived transforms\n    derivedTransform || // Or to prevent items jumping to back to their \"new\" position when items change\n    itemsHaveChanged && previous.current.newIndex === index) {\n      return disabledTransition;\n    }\n\n    if (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent) || !transition) {\n      return undefined;\n    }\n\n    if (isSorting || shouldAnimateLayoutChanges) {\n      return CSS.Transition.toString({ ...transition,\n        property: transitionProperty\n      });\n    }\n\n    return undefined;\n  }\n}\n\nfunction normalizeLocalDisabled(localDisabled, globalDisabled) {\n  var _localDisabled$dragga, _localDisabled$droppa;\n\n  if (typeof localDisabled === 'boolean') {\n    return {\n      draggable: localDisabled,\n      // Backwards compatibility\n      droppable: false\n    };\n  }\n\n  return {\n    draggable: (_localDisabled$dragga = localDisabled == null ? void 0 : localDisabled.draggable) != null ? _localDisabled$dragga : globalDisabled.draggable,\n    droppable: (_localDisabled$droppa = localDisabled == null ? void 0 : localDisabled.droppable) != null ? _localDisabled$droppa : globalDisabled.droppable\n  };\n}\n\nfunction hasSortableData(entry) {\n  if (!entry) {\n    return false;\n  }\n\n  const data = entry.data.current;\n\n  if (data && 'sortable' in data && typeof data.sortable === 'object' && 'containerId' in data.sortable && 'items' in data.sortable && 'index' in data.sortable) {\n    return true;\n  }\n\n  return false;\n}\n\nconst directions = [KeyboardCode.Down, KeyboardCode.Right, KeyboardCode.Up, KeyboardCode.Left];\nconst sortableKeyboardCoordinates = (event, _ref) => {\n  let {\n    context: {\n      active,\n      collisionRect,\n      droppableRects,\n      droppableContainers,\n      over,\n      scrollableAncestors\n    }\n  } = _ref;\n\n  if (directions.includes(event.code)) {\n    event.preventDefault();\n\n    if (!active || !collisionRect) {\n      return;\n    }\n\n    const filteredContainers = [];\n    droppableContainers.getEnabled().forEach(entry => {\n      if (!entry || entry != null && entry.disabled) {\n        return;\n      }\n\n      const rect = droppableRects.get(entry.id);\n\n      if (!rect) {\n        return;\n      }\n\n      switch (event.code) {\n        case KeyboardCode.Down:\n          if (collisionRect.top < rect.top) {\n            filteredContainers.push(entry);\n          }\n\n          break;\n\n        case KeyboardCode.Up:\n          if (collisionRect.top > rect.top) {\n            filteredContainers.push(entry);\n          }\n\n          break;\n\n        case KeyboardCode.Left:\n          if (collisionRect.left > rect.left) {\n            filteredContainers.push(entry);\n          }\n\n          break;\n\n        case KeyboardCode.Right:\n          if (collisionRect.left < rect.left) {\n            filteredContainers.push(entry);\n          }\n\n          break;\n      }\n    });\n    const collisions = closestCorners({\n      active,\n      collisionRect: collisionRect,\n      droppableRects,\n      droppableContainers: filteredContainers,\n      pointerCoordinates: null\n    });\n    let closestId = getFirstCollision(collisions, 'id');\n\n    if (closestId === (over == null ? void 0 : over.id) && collisions.length > 1) {\n      closestId = collisions[1].id;\n    }\n\n    if (closestId != null) {\n      const activeDroppable = droppableContainers.get(active.id);\n      const newDroppable = droppableContainers.get(closestId);\n      const newRect = newDroppable ? droppableRects.get(newDroppable.id) : null;\n      const newNode = newDroppable == null ? void 0 : newDroppable.node.current;\n\n      if (newNode && newRect && activeDroppable && newDroppable) {\n        const newScrollAncestors = getScrollableAncestors(newNode);\n        const hasDifferentScrollAncestors = newScrollAncestors.some((element, index) => scrollableAncestors[index] !== element);\n        const hasSameContainer = isSameContainer(activeDroppable, newDroppable);\n        const isAfterActive = isAfter(activeDroppable, newDroppable);\n        const offset = hasDifferentScrollAncestors || !hasSameContainer ? {\n          x: 0,\n          y: 0\n        } : {\n          x: isAfterActive ? collisionRect.width - newRect.width : 0,\n          y: isAfterActive ? collisionRect.height - newRect.height : 0\n        };\n        const rectCoordinates = {\n          x: newRect.left,\n          y: newRect.top\n        };\n        const newCoordinates = offset.x && offset.y ? rectCoordinates : subtract(rectCoordinates, offset);\n        return newCoordinates;\n      }\n    }\n  }\n\n  return undefined;\n};\n\nfunction isSameContainer(a, b) {\n  if (!hasSortableData(a) || !hasSortableData(b)) {\n    return false;\n  }\n\n  return a.data.current.sortable.containerId === b.data.current.sortable.containerId;\n}\n\nfunction isAfter(a, b) {\n  if (!hasSortableData(a) || !hasSortableData(b)) {\n    return false;\n  }\n\n  if (!isSameContainer(a, b)) {\n    return false;\n  }\n\n  return a.data.current.sortable.index < b.data.current.sortable.index;\n}\n\nexport { SortableContext, arrayMove, arraySwap, defaultAnimateLayoutChanges, defaultNewIndexGetter, hasSortableData, horizontalListSortingStrategy, rectSortingStrategy, rectSwappingStrategy, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy };\n//# sourceMappingURL=sortable.esm.js.map\n","import React from 'react';\nimport {\n    DndContext,\n    closestCenter,\n    KeyboardSensor,\n    PointerSensor,\n    useSensor,\n    useSensors\n} from '@dnd-kit/core';\nimport type { DragEndEvent } from '@dnd-kit/core';\nimport {\n    arrayMove,\n    SortableContext,\n    sortableKeyboardCoordinates,\n    verticalListSortingStrategy,\n    useSortable\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport type { DynamicField } from '../core/types/DynamicField.types';\nimport { Button } from '../../Button/Button';\nimport { PencilSquareIcon, TrashIcon, Bars3Icon, InformationCircleIcon, EyeIcon } from '@heroicons/react/24/outline';\n\nconst GripIcon = () => (\n    <div className=\"text-gray-400 cursor-grab active:cursor-grabbing hover:text-gray-600 transition-colors p-1\">\n        <Bars3Icon className=\"w-5 h-5\" />\n    </div>\n);\n\ninterface SortableItemProps {\n    id: string;\n    field: DynamicField;\n    onEdit: (field: DynamicField) => void;\n    onDelete: (id: string) => void;\n    isReadonly?: boolean;\n}\n\nconst SortableItem: React.FC<SortableItemProps> = ({ id, field, onEdit, onDelete, isReadonly }) => {\n    const {\n        attributes,\n        listeners,\n        setNodeRef,\n        transform,\n        transition,\n    } = useSortable({ id, disabled: isReadonly });\n\n    const style = {\n        transform: CSS.Transform.toString(transform),\n        transition,\n    };\n\n    return (\n        <div ref={setNodeRef} style={style} className=\"flex items-center border-b border-gray-200 py-2 group hover:bg-gray-50/50 transition-colors bg-white\">\n            <div className=\"flex flex-col items-center justify-center min-h-[56px] px-4 py-2 shrink-0\">\n                {!isReadonly && (\n                    <div {...attributes} {...listeners} className=\"outline-none\">\n                        <GripIcon />\n                    </div>\n                )}\n                {isReadonly && <div className=\"w-7\" />}\n            </div>\n            <div className=\"flex flex-1 flex-col items-start justify-center min-h-[56px] px-4 py-2\">\n                <p className=\"leading-[20px] text-sm text-gray-900 font-medium\">\n                    {field.labels['es'] || field.code}\n                </p>\n            </div>\n            <div className=\"flex items-center gap-2 min-h-[56px] px-4 py-2 shrink-0 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity\">\n                {isReadonly ? (\n                    <Button\n                        type=\"plain\"\n                        iconOnly\n                        leftIcon={<EyeIcon className=\"w-5 h-5 text-gray-400 hover:text-gray-600\" />}\n                        ariaLabel=\"Ver campo\"\n                        onClick={() => onEdit(field)}\n                    />\n                ) : (\n                    <>\n                        <Button\n                            type=\"plain\"\n                            iconOnly\n                            leftIcon={<PencilSquareIcon className=\"w-5 h-5 text-[#0e79fd] hover:text-blue-700\" />}\n                            ariaLabel=\"Editar campo\"\n                            onClick={() => onEdit(field)}\n                        />\n                        <Button\n                            type=\"plain\"\n                            iconOnly\n                            leftIcon={<TrashIcon className=\"w-5 h-5 text-red-500 hover:text-red-700\" />}\n                            ariaLabel=\"Eliminar campo\"\n                            onClick={() => onDelete(field.id)}\n                        />\n                    </>\n                )}\n            </div>\n        </div>\n    );\n};\n\nexport interface FieldDesignerProps {\n    fields: DynamicField[];\n    onChange: (fields: DynamicField[]) => void;\n    onEdit: (field: DynamicField) => void;\n    onAdd: () => void;\n    isPlansAndCriteria?: boolean;\n    isReadonly?: boolean;\n}\n\nexport const FieldDesigner: React.FC<FieldDesignerProps> = ({ fields, onChange, onEdit, onAdd, isPlansAndCriteria, isReadonly }) => {\n    const sensors = useSensors(\n        useSensor(PointerSensor),\n        useSensor(KeyboardSensor, {\n            coordinateGetter: sortableKeyboardCoordinates,\n        })\n    );\n\n    const handleDragEnd = (event: DragEndEvent) => {\n        if (isReadonly) return;\n        const { active, over } = event;\n\n        if (over && active.id !== over.id) {\n            const oldIndex = fields.findIndex((f) => f.id === active.id);\n            const newIndex = fields.findIndex((f) => f.id === over.id);\n\n            const newFields = arrayMove(fields, oldIndex, newIndex);\n\n            // Update Order property\n            const reorderedFields = newFields.map((f, index) => ({ ...f, order: index }));\n            onChange(reorderedFields);\n        }\n    };\n\n    const handleDelete = (id: string) => {\n        if (!confirm('¿Seguro que deseas eliminar este campo?')) return;\n        onChange(fields.filter(f => f.id !== id));\n    };\n\n    const handleEdit = (field: DynamicField) => {\n        onEdit(field);\n    };\n\n    // Sort fields by order before rendering\n    const sortedFields = [...fields].sort((a, b) => a.order - b.order);\n\n    return (\n        <DndContext\n            sensors={sensors}\n            collisionDetection={closestCenter}\n            onDragEnd={handleDragEnd}\n        >\n            <div className=\"flex flex-col w-full h-full space-y-5\">\n                <div className=\"flex items-center justify-between w-full\">\n                    {isReadonly ? (\n                        <div className=\"bg-amber-50 border border-amber-200 flex gap-2 items-center px-4 py-2 rounded-lg\">\n                            <InformationCircleIcon className=\"w-6 h-6 text-amber-600 shrink-0\" />\n                            <p className=\"font-normal text-sm text-amber-700\">\n                                Los campos de las entidades de sistema son de solo lectura y no pueden modificarse.\n                            </p>\n                        </div>\n                    ) : (\n                        <>\n                            <div className=\"bg-[#cffafe] border border-[#67e8f9] flex gap-2 items-center px-4 py-2 rounded-lg\">\n                                <InformationCircleIcon className=\"w-6 h-6 text-[#0e7490]\" />\n                                <p className=\"font-normal text-sm text-[#0e7490]\">\n                                    Arrastra las opciones para definir el orden en el formulario\n                                </p>\n                            </div>\n                                <Button type=\"outline\" size=\"sm\" onClick={onAdd}>\n                                {isPlansAndCriteria ? 'Nuevo Plan' : 'Nuevo Campo'}\n                            </Button>\n                        </>\n                    )}\n                </div>\n\n                <div className=\"flex flex-col w-full border-t border-gray-200\">\n                    <SortableContext\n                        items={sortedFields.map(f => f.id)}\n                        strategy={verticalListSortingStrategy}\n                    >\n                        {sortedFields.map((field) => (\n                            <SortableItem\n                                key={field.id}\n                                id={field.id}\n                                field={field}\n                                onEdit={handleEdit}\n                                onDelete={handleDelete}\n                                isReadonly={isReadonly}\n                            />\n                        ))}\n                    </SortableContext>\n\n                    {fields.length === 0 && (\n                        <div className=\"text-center text-gray-400 py-12 border-b border-gray-200 bg-gray-50/30\">\n                            No hay campos definidos. Haz clic en \"Nuevo\" para comenzar.\n                        </div>\n                    )}\n                </div>\n            </div>\n        </DndContext>\n    );\n};\n","import React from 'react';\nimport type { DynamicField } from '../core/types/DynamicField.types';\nimport { DynamicFieldType } from '../core/types/DynamicField.types';\nimport { Input } from '../../Input/Input';\nimport { Select } from '../../Select/Select';\nimport { Switch } from '../../Switch/Switch';\nimport { Button } from '../../Button/Button';\nimport { LookupField } from '../../LookupField';\nimport { useOptionalDynamicEntitiesContext, useDynamicEntitiesFetcher } from '../core/DynamicEntitiesProvider';\nimport { XMarkIcon } from '@heroicons/react/24/outline';\n\n// Custom for now as it's specific metadata.\n\ninterface FieldEditorProps {\n    field: DynamicField;\n    genericLists?: any[];\n    onSave: (field: DynamicField) => void;\n    isPlansAndCriteria?: boolean;\n    isNew?: boolean;\n    isReadonly?: boolean;\n    onCancel: () => void;\n}\n\nconst FIELD_TYPE_LABELS: Record<string, string> = {\n    [DynamicFieldType.Text]: 'Texto Corto',\n    [DynamicFieldType.TextArea]: 'Texto Largo (Área)',\n    [DynamicFieldType.NumberInteger]: 'Número Entero',\n    [DynamicFieldType.NumberDecimal]: 'Número Decimal',\n    [DynamicFieldType.Currency]: 'Moneda',\n    [DynamicFieldType.Date]: 'Fecha',\n    [DynamicFieldType.Time]: 'Hora',\n    [DynamicFieldType.DateTime]: 'Fecha y Hora',\n    [DynamicFieldType.Checkbox]: 'Casilla de Verificación',\n    [DynamicFieldType.Select]: 'Selección Simple',\n    [DynamicFieldType.Radio]: 'Botones de Opción (Radio)',\n    [DynamicFieldType.Multiselect]: 'Selección Múltiple',\n    [DynamicFieldType.Lookup]: 'Búsqueda (Lookup)',\n    [DynamicFieldType.Switch]: 'Interruptor (Switch)',\n    [DynamicFieldType.GenericEntity]: 'Entidad Genérica'\n};\n\nexport const FieldEditor: React.FC<FieldEditorProps> = ({ field, genericLists = [], onSave, onCancel, isPlansAndCriteria, isNew, isReadonly }) => {\n    const ctx = useOptionalDynamicEntitiesContext();\n    // baseUrl ya termina en /api; la API v1 cuelga del mismo prefijo (${baseUrl}/v1/...).\n    // No extraemos el origin para soportar baseUrl relativo (modo MFE detrás del shell).\n    const baseUrl = ctx?.baseUrl ?? '';\n    const http = useDynamicEntitiesFetcher();\n\n    const [data, setData] = React.useState<DynamicField>({ ...field });\n\n    const handleChange = (key: keyof DynamicField, value: any) => {\n        setData(prev => ({ ...prev, [key]: value }));\n    };\n\n    const handleLabelChange = (lang: string, value: string) => {\n        setData(prev => ({\n            ...prev,\n            labels: { ...prev.labels, [lang]: value }\n        }));\n    };\n\n    return (\n        <div className=\"flex flex-col w-full h-full relative overflow-hidden\">\n            {/* Header */}\n            <div className=\"flex justify-between items-center mb-6 shrink-0 border-b border-gray-100 pb-4\">\n                <p className=\"font-medium text-base leading-6 text-primary-custom-600 dark:text-primary-custom-500 m-0\">\n                    {isReadonly\n                        ? 'Ver campo'\n                        : isPlansAndCriteria\n                            ? (isNew ? 'Crear Plan' : 'Editar Plan')\n                            : (isNew ? 'Nuevo Campo' : 'Editar campo')\n                    }\n                </p>\n                <Button\n                    type=\"outline\"\n                    iconOnly\n                    size=\"sm\"\n                    onClick={onCancel}\n                    leftIcon={<XMarkIcon className=\"w-5 h-5\" />}\n                    ariaLabel=\"Cerrar\"\n                />\n            </div>\n\n            {/* Scrollable Content */}\n            <div className=\"flex flex-col gap-5 overflow-y-auto flex-1 pr-2 pb-2\">\n                {isPlansAndCriteria && (\n                    <Input\n                        label=\"Código\"\n                        value={data.code}\n                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleChange('code', e.target.value)}\n                        disabled={isReadonly || (!isNew && !isPlansAndCriteria)}\n                        required\n                        inputSize=\"sm\"\n                        {...({ fullWidth: true } as any)}\n                    />\n                )}\n\n                <div className=\"flex flex-col gap-5 w-full\">\n                    <Input\n                        label=\"Etiqueta (ES)\"\n                        value={data.labels['es'] || ''}\n                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleLabelChange('es', e.target.value)}\n                        disabled={isReadonly}\n                        required\n                        inputSize=\"sm\"\n                    />\n                    <Input\n                        label=\"Etiqueta (EN)\"\n                        value={data.labels['en'] || ''}\n                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleLabelChange('en', e.target.value)}\n                        disabled={isReadonly}\n                        inputSize=\"sm\"\n                    />\n                </div>\n\n                {!isPlansAndCriteria && (\n                    <Select\n                        label=\"Tipo\"\n                        options={Object.values(DynamicFieldType)\n                            .filter(t => ![DynamicFieldType.Select, DynamicFieldType.Multiselect, DynamicFieldType.Lookup].includes(t as any))\n                            .map(t => ({ label: FIELD_TYPE_LABELS[t as string] || t, value: t as string }))}\n                        value={data.type as string}\n                        onChange={val => handleChange('type', val as DynamicFieldType)}\n                        disabled={isReadonly}\n                        required\n                        selectSize=\"sm\"\n                    />\n                )}\n\n                {!isPlansAndCriteria && (\n                    <Select\n                        label=\"Espacio horizontal\"\n                        options={[\n                            { label: '50%', value: '1' },\n                            { label: '100%', value: '2' }\n                        ]}\n                        value={String(data.layouts?.[0]?.colSpan || 1)}\n                        onChange={val => {\n                            const parsedVal = typeof val === \"string\" ? parseInt(val) : (val as number) || 1;\n                            setData(prev => ({\n                                ...prev,\n                                layouts: [{\n                                    ...(prev.layouts?.[0] || { breakpoint: 'md', rowSpan: 1, colStart: 0, rowStart: 0 }),\n                                    colSpan: parsedVal\n                                }]\n                            }));\n                        }}\n                        disabled={isReadonly}\n                        required\n                        selectSize=\"sm\"\n                    />\n                )}\n\n                <div className=\"flex flex-col gap-3 w-full mt-2\">\n                    <Switch\n                        label=\"Requerido\"\n                        labelPosition=\"end\"\n                        checked={data.required}\n                        onCheckedChange={(checked: boolean) => handleChange('required', checked)}\n                        disabled={isReadonly}\n                        size=\"sm\"\n                    />\n                    {!isPlansAndCriteria && (\n                        <>\n                            <Switch\n                                label=\"Solo lectura\"\n                                labelPosition=\"end\"\n                                checked={data.readonly}\n                                onCheckedChange={(checked: boolean) => handleChange('readonly', checked)}\n                                disabled={isReadonly}\n                                size=\"sm\"\n                            />\n                            <Switch\n                                label=\"Visible\"\n                                labelPosition=\"end\"\n                                checked={data.visible}\n                                onCheckedChange={(checked: boolean) => handleChange('visible', checked)}\n                                disabled={isReadonly}\n                                size=\"sm\"\n                            />\n                            <Switch\n                                label=\"Único\"\n                                labelPosition=\"end\"\n                                checked={data.isUnique || false}\n                                onCheckedChange={(checked: boolean) => handleChange('isUnique', checked)}\n                                disabled={isReadonly}\n                                size=\"sm\"\n                            />\n                        </>\n                    )}\n                </div>\n\n                {/* Type specific settings */}\n                {(data.type === DynamicFieldType.NumberInteger ||\n                    data.type === DynamicFieldType.NumberDecimal ||\n                    data.type === DynamicFieldType.Currency) && (\n                        <div className=\"flex flex-col gap-5\">\n                            <Input type=\"number\" inputSize=\"sm\" label=\"Mínimo\" value={data.minValue === undefined || data.minValue === null ? '' : String(data.minValue)} onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleChange('minValue', parseFloat(e.target.value))} disabled={isReadonly} />\n                            <Input type=\"number\" inputSize=\"sm\" label=\"Máximo\" value={data.maxValue === undefined || data.maxValue === null ? '' : String(data.maxValue)} onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleChange('maxValue', parseFloat(e.target.value))} disabled={isReadonly} />\n                        </div>\n                    )}\n\n                {(data.type === DynamicFieldType.Select ||\n                    data.type === DynamicFieldType.Radio ||\n                    data.type === DynamicFieldType.Multiselect) && (\n                        <div className=\"flex flex-col gap-2\">\n                            <Select\n                                label=\"Catálogo de Opciones\"\n                                options={genericLists.map((l: any) => ({ label: l.description || l.code, value: l.id }))}\n                                value={data.genericListId}\n                                onChange={val => handleChange('genericListId', val)}\n                                placeholder={genericLists.length === 0 ? \"No hay catálogos creados\" : \"Seleccionar catálogo...\"}\n                                disabled={isReadonly || genericLists.length === 0}\n                                selectSize=\"sm\"\n                            />\n                            {!isReadonly && genericLists.length === 0 && (\n                                <p className=\"text-xs text-orange-600 bg-orange-50 p-2 rounded border border-orange-200 m-0\">\n                                    ⚠️ Debes crear un catálogo en \"Configuración &gt; Listas Generales\" antes de usar este tipo de campo.\n                                </p>\n                            )}\n                        </div>\n                    )}\n\n                {data.type === DynamicFieldType.GenericEntity && (\n                    <div className=\"flex flex-col gap-2\">\n                        <LookupField\n                            label=\"Entidad Genérica\"\n                            entity=\"generic-entities\"\n                            displayFields={['Code', 'Description']}\n                            value={data.genericEntityId || null}\n                            onChange={(record) => handleChange('genericEntityId', record?.Id || null)}\n                            fetcher={async (entity, request) => {\n                                // 1. Map `Id` to `ID` in request to satisfy backend validation\n                                const mappedRequest = {\n                                    ...request,\n                                    fields: request.fields.filter(f => f !== 'Id').concat('ID'),\n                                    searchFields: request.searchFields?.map(f => f === 'Id' ? 'ID' : f),\n                                    filters: request.filters?.map(group => group.map(cond => {\n                                        const mappedCond: any = {};\n                                        for (const key in cond) {\n                                            mappedCond[key === 'Id' ? 'ID' : key] = cond[key as keyof typeof cond];\n                                        }\n                                        return mappedCond;\n                                    }))\n                                };\n\n                                const res = await http(`${baseUrl}/v1/${entity}/search`, {\n                                    method: 'POST',\n                                    headers: { 'Content-Type': 'application/json' },\n                                    body: JSON.stringify(mappedRequest)\n                                });\n\n                                if (!res.ok) throw new Error('Error fetching generic entities');\n                                const responseData = await res.json();\n\n                                // 2. Map `ID` back to `Id` for LookupField compatibility\n                                return {\n                                    ...responseData,\n                                    data: responseData.data.map((item: any) => ({\n                                        ...item,\n                                        Id: item.ID\n                                    }))\n                                };\n                            }}\n                        />\n                        {!data.genericEntityId && (\n                            <p className=\"text-xs text-orange-600 bg-orange-50 p-2 rounded border border-orange-200 m-0\">\n                                ⚠️ Debes elegir la entidad genérica relacionada a este campo.\n                            </p>\n                        )}\n                    </div>\n                )}\n            </div>\n\n            {/* Footer */}\n            {!isReadonly && (\n                <div className=\"mt-5 shrink-0 w-full pt-1\">\n                    <Button\n                        type=\"outline\"\n                        size=\"sm\"\n                        onClick={() => onSave(data)}\n                        className=\"w-full flex justify-center\"\n                    >\n                        Guardar\n                    </Button>\n                </div>\n            )}\n        </div>\n    );\n};\n","import React, { useState, useEffect } from 'react';\nimport { useFeatureService } from './services/useFeatureService';\nimport type { DynamicFieldRule } from '../core/types/DynamicEntity.types';\nimport { FieldDesigner } from './FieldDesigner';\nimport { FieldEditor } from './FieldEditor';\nimport { RuleEditor } from './RuleEditor';\nimport { LayoutContent } from '../../LayoutContent';\nimport {\n    useDynamicEntitiesContext,\n    useDynamicEntitiesFetcher,\n    useDynamicEntitiesPermissions\n} from '../core/DynamicEntitiesProvider';\nimport { CheckIcon, LockClosedIcon } from '@heroicons/react/24/outline';\nimport { AlertDialog } from '../../AlertDialog/AlertDialog';\n\ninterface EntityEditorProps {\n    entityId: string;\n    featureId?: string;\n    featureEntityId?: string;\n    initialRenderMode?: 'tab' | 'inline' | 'modal';\n    onBack: () => void;\n}\n\nexport const EntityEditor: React.FC<EntityEditorProps> = ({\n    entityId,\n    featureId,\n    featureEntityId,\n    initialRenderMode,\n    onBack\n}) => {\n    const { baseUrl, onError } = useDynamicEntitiesContext();\n    const http = useDynamicEntitiesFetcher();\n    const { canUpdate } = useDynamicEntitiesPermissions();\n    const service = useFeatureService();\n    const [entity, setEntity] = useState<any | null>(null);\n    const [fields, setFields] = useState<any[]>([]);\n    const [rules, setRules] = useState<DynamicFieldRule[]>([]);\n    const [loading, setLoading] = useState(true);\n    const [editingField, setEditingField] = useState<any | null>(null);\n    const [activeTab, setActiveTab] = useState<'fields' | 'rules'>('fields');\n    const [renderMode, setRenderMode] = useState<'tab' | 'inline' | 'modal'>(initialRenderMode || 'tab');\n    const [alertConfig, setAlertConfig] = useState<{ isOpen: boolean, config: Partial<React.ComponentProps<typeof AlertDialog>> & { title?: string } }>({ isOpen: false, config: {} });\n\n    const loadEntity = () => {\n        http(`${baseUrl}/dynamic-entities/${entityId}`)\n            .then(res => {\n                if (!res.ok) throw new Error(`Failed to fetch entity: ${res.status} ${res.statusText}`);\n                return res.json();\n            })\n            .then(data => {\n                setEntity(data);\n                setFields(data.fields || []);\n                setRules(data.rules || []);\n                setLoading(false);\n            })\n            .catch(err => {\n                console.error(err);\n                onError?.(err as Error);\n                setLoading(false);\n            });\n    };\n\n    useEffect(() => {\n        loadEntity();\n    }, [entityId, baseUrl, http]);\n\n    const handleSaveEntity = async () => {\n        if (!entity) return;\n        setLoading(true);\n        try {\n            // 1. Update entity properties\n            await service.updateEntity(entityId, {\n                id: entityId,\n                code: entity.entityCode, // The DTO uses entityCode, not code\n                multiRecord: entity.isPlansAndCriteria ? false : entity.multiRecord,\n                description: entity.description,\n                isReadonly: entity.isReadonly,\n                isDisabled: entity.isDisabled,\n                isPlansAndCriteria: entity.isPlansAndCriteria\n            });\n\n            // 2. Update fields\n            await service.saveFields(entityId, fields);\n\n            // 3. Update rules\n            await service.saveRules(entityId, rules);\n\n            // 4. Update FeatureEntity link (RenderMode) if applicable\n            if (featureId && featureEntityId) {\n                await service.updateFeatureEntity(featureId, entityId, {\n                    id: featureEntityId,\n                    featureId: featureId,\n                    dynamicEntityId: entityId,\n                    renderMode: renderMode,\n                    order: 0, // We don't change order here, backend should ignore or keep it\n                });\n            }\n\n            setAlertConfig({\n                isOpen: true,\n                config: {\n                    title: '¡Éxito!',\n                    cancelText: 'Cerrar',\n                    onCancel: () => setAlertConfig({ isOpen: false, config: {} }),\n                    onConfirm: undefined, // No primary button needed\n                }\n            });\n            loadEntity();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            setAlertConfig({\n                isOpen: true,\n                config: {\n                    title: 'Error',\n                    description: 'Hubo un error al guardar.',\n                    cancelText: 'Cerrar',\n                    onCancel: () => setAlertConfig({ isOpen: false, config: {} }),\n                    onConfirm: undefined,\n                }\n            });\n        } finally {\n            setLoading(false);\n        }\n    };\n\n    if (loading) return <div className=\"p-6 text-gray-500\">Cargando...</div>;\n    if (!entity) return <div className=\"p-6 text-red-500\">Entidad no encontrada</div>;\n\n    const isSystem = entity.isSystem === true;\n    // Sin permiso de escritura la pantalla se comporta como una entidad de\n    // sistema: se puede consultar, no modificar.\n    const isReadonly = isSystem || !canUpdate;\n\n    const saveAction = !isReadonly ? {\n        label: \"Guardar Cambios\",\n        onClick: handleSaveEntity,\n        icon: <CheckIcon className=\"w-4 h-4\" />,\n        size: \"sm\" as const\n    } : undefined;\n\n    return (\n        <LayoutContent\n            title={entity.description || entity.entityCode}\n            onBack={onBack}\n            primaryAction={saveAction}\n        >\n            <div className=\"flex flex-col gap-6 w-full\">\n\n                {/* Banner entidad de sistema */}\n                {isSystem && (\n                    <div className=\"bg-amber-50 border border-amber-200 rounded-xl px-5 py-3 flex items-center gap-3\">\n                        <LockClosedIcon className=\"w-5 h-5 text-amber-600 shrink-0\" />\n                        <p className=\"text-sm text-amber-700\">\n                            Esta es una entidad de sistema. Su configuración es de solo lectura y no puede modificarse.\n                        </p>\n                    </div>\n                )}\n\n                {/* Banner sin permiso de escritura */}\n                {!isSystem && !canUpdate && (\n                    <div className=\"bg-amber-50 border border-amber-200 rounded-xl px-5 py-3 flex items-center gap-3\">\n                        <LockClosedIcon className=\"w-5 h-5 text-amber-600 shrink-0\" />\n                        <p className=\"text-sm text-amber-700\">\n                            No tienes permiso para modificar esta entidad. Puedes consultarla en modo lectura.\n                        </p>\n                    </div>\n                )}\n\n                {/* Configuration Options Panel */}\n                <div className=\"bg-white rounded-2xl p-5 flex items-start w-full\">\n                    <div className=\"grid grid-cols-1 md:grid-cols-3 gap-5 w-full items-end\">\n\n                        {entity.isPlansAndCriteria && (\n                            <div className=\"flex flex-col gap-1\">\n                                <label className=\"text-sm font-medium text-gray-900\">Código</label>\n                                <input\n                                    type=\"text\"\n                                    value={entity.entityCode || ''}\n                                    onChange={(e) => setEntity({ ...entity, entityCode: e.target.value })}\n                                    disabled={isReadonly}\n                                    className=\"px-2 h-8 border border-gray-300 rounded-lg text-sm outline-none focus:ring-2 focus:ring-[#0e79fd] focus:border-transparent transition-all disabled:bg-gray-50 disabled:text-gray-400 disabled:cursor-not-allowed\"\n                                />\n                            </div>\n                        )}\n                        <div className=\"flex flex-col gap-1\">\n                            <label className=\"text-sm font-medium text-gray-900\">Nombre</label>\n                            <input\n                                type=\"text\"\n                                value={entity.description || ''}\n                                onChange={(e) => setEntity({ ...entity, description: e.target.value })}\n                                disabled={isReadonly}\n                                className=\"px-2 h-8 border border-gray-300 rounded-lg text-sm outline-none focus:ring-2 focus:ring-[#0e79fd] focus:border-transparent transition-all disabled:bg-gray-50 disabled:text-gray-400 disabled:cursor-not-allowed\"\n                            />\n                        </div>\n\n                        {/* Multi registro — oculto temporalmente\n                        <div className={`flex gap-3 items-start ${(entity.isPlansAndCriteria || isSystem) ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer group'}`}\n                            onClick={() => !entity.isPlansAndCriteria && !isSystem && setEntity({ ...entity, multiRecord: !entity.multiRecord })}>\n                            <div className=\"mt-0.5\">\n                                <div className={`w-8 h-5 rounded-full relative transition-colors duration-200 ease-in-out ${(entity.isPlansAndCriteria ? false : entity.multiRecord) ? 'bg-[#0e79fd]' : 'bg-gray-200'}`}>\n                                    <div className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform duration-200 ease-in-out shadow-sm ${(entity.isPlansAndCriteria ? false : entity.multiRecord) ? 'transform translate-x-3' : ''}`} />\n                                </div>\n                            </div>\n                            <div className=\"flex flex-col\">\n                                <span className={`text-sm font-medium ${(entity.isPlansAndCriteria || isSystem) ? 'text-gray-500' : 'text-gray-900 group-hover:text-blue-600'} transition-colors`}>Multi registro</span>\n                                <span className=\"text-sm text-gray-400\">Se agregan múltiples filas por cada definición</span>\n                            </div>\n                        </div>\n                        */}\n\n                        {/* Render Mode Options (only if feature context exists) */}\n                        {featureId && (\n                            <>\n                                <div\n                                    className={`flex gap-3 items-start ${isReadonly ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer group'}`}\n                                    onClick={() => !isReadonly && setRenderMode('tab')}\n                                >\n                                    <div className=\"mt-0.5\">\n                                        <div className={`w-8 h-5 rounded-full relative transition-colors duration-200 ease-in-out ${renderMode === 'tab' ? 'bg-[#0e79fd]' : 'bg-gray-200'}`}>\n                                            <div className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform duration-200 ease-in-out shadow-sm ${renderMode === 'tab' ? 'transform translate-x-3' : ''}`} />\n                                        </div>\n                                    </div>\n                                    <div className=\"flex flex-col\">\n                                        <span className={`text-sm font-medium ${isReadonly ? 'text-gray-500' : 'text-gray-900 group-hover:text-blue-600'} transition-colors`}>Mostrar en pestaña</span>\n                                        <span className=\"text-sm text-gray-400\">Se creará una pestaña para los campos</span>\n                                    </div>\n                                </div>\n\n                                <div\n                                    className={`flex gap-3 items-start ${isReadonly ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer group'}`}\n                                    onClick={() => !isReadonly && setRenderMode('inline')}\n                                >\n                                    <div className=\"mt-0.5\">\n                                        <div className={`w-8 h-5 rounded-full relative transition-colors duration-200 ease-in-out ${renderMode === 'inline' ? 'bg-[#0e79fd]' : 'bg-gray-200'}`}>\n                                            <div className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform duration-200 ease-in-out shadow-sm ${renderMode === 'inline' ? 'transform translate-x-3' : ''}`} />\n                                        </div>\n                                    </div>\n                                    <div className=\"flex flex-col\">\n                                        <span className={`text-sm font-medium ${isReadonly ? 'text-gray-500' : 'text-gray-900 group-hover:text-blue-600'} transition-colors`}>Mostrar en línea</span>\n                                        <span className=\"text-sm text-gray-400\">Se agregarán los campos en el flujo</span>\n                                    </div>\n                                </div>\n                            </>\n                        )}\n                    </div>\n                </div>\n\n                {/* Main Tabs Navigation */}\n                <div className=\"flex gap-2 border-b border-gray-200 pb-1\">\n                    <button\n                        className={`relative py-2 px-2 text-sm font-medium transition-colors ${activeTab === 'fields' ? 'text-[#0e79fd]' : 'text-gray-900 hover:text-gray-600'}`}\n                        onClick={() => setActiveTab('fields')}\n                    >\n                        Campos\n                        {activeTab === 'fields' && (\n                            <div className=\"absolute bottom-[-5px] left-0 right-0 h-[2px] bg-[#0e79fd] rounded-full\" />\n                        )}\n                    </button>\n                    {/* Oculto por ahora:\n                    {!entity.isPlansAndCriteria && (<button\n                        className={`relative py-2 px-2 text-sm font-medium transition-colors ${activeTab === 'rules' ? 'text-[#0e79fd]' : 'text-gray-900 hover:text-gray-600'}`}\n                        onClick={() => setActiveTab('rules')}\n                    >\n                        Reglas\n                        {activeTab === 'rules' && (\n                            <div className=\"absolute bottom-[-5px] left-0 right-0 h-[2px] bg-[#0e79fd] rounded-full\" />\n                        )}\n                    </button>)}\n                    */}\n                </div>\n\n                {/* Tab Content */}\n                <div className=\"w-full min-h-[400px]\">\n                    {activeTab === 'fields' && (\n                        <div className=\"flex w-full items-start gap-6\">\n                            {/* Tarjeta de la Lista (Izquierda) */}\n                            <div\n                                className={`bg-white rounded-2xl p-6 h-fit border border-transparent transition-all duration-300 ease-in-out origin-left ${editingField ? 'lg:w-[calc(65%-24px)]' : 'w-full'} shrink-0`}\n                            >\n                                <FieldDesigner\n                                    fields={fields}\n                                    isPlansAndCriteria={entity.isPlansAndCriteria}\n                                    isReadonly={isReadonly}\n                                    onChange={setFields}\n                                    onEdit={setEditingField}\n                                    onAdd={() => {\n                                        if (isReadonly) return;\n                                        const newField: any = {\n                                            id: crypto.randomUUID(),\n                                            code: `FIELD_${fields.length + 1}`,\n                                            type: entity.isPlansAndCriteria ? 'GenericEntity' : 'Text',\n                                            labels: { es: 'Nuevo Campo', en: 'New Field' },\n                                            order: fields.length,\n                                            layouts: entity.isPlansAndCriteria ? [{ breakpoint: 'md', colSpan: 2, rowSpan: 1, colStart: 0, rowStart: 0 }] : undefined,\n                                            required: false,\n                                            visible: true,\n                                            readonly: false,\n                                            isUnique: false\n                                        };\n                                        setEditingField(newField);\n                                    }}\n                                />\n                            </div>\n\n                            {/* Tarjeta del Editor (Derecha - Panel Deslizante) */}\n                            {editingField && (\n                                <div className=\"bg-white rounded-2xl p-6 h-fit border border-transparent w-full lg:w-[35%] shrink-0 animate-in slide-in-from-right-8 fade-in duration-300\">\n                                    <FieldEditor\n                                        field={editingField}\n                                        genericLists={entity.lists || []}\n                                        isPlansAndCriteria={entity.isPlansAndCriteria}\n                                        isReadonly={isReadonly}\n                                        isNew={!fields.some(f => f.id === editingField.id)}\n                                        onSave={(updated) => {\n                                            setFields(prev => {\n                                                const exists = prev.find(f => f.id === updated.id);\n                                                if (exists) return prev.map(f => f.id === updated.id ? updated : f);\n                                                return [...prev, updated];\n                                            });\n                                            setEditingField(null);\n                                        }}\n                                        onCancel={() => setEditingField(null)}\n                                    />\n                                </div>\n                            )}\n                        </div>\n                    )}\n                    {/* Oculto por ahora:\n                    {activeTab === 'rules' && (\n                        <RuleEditor\n                            fields={fields}\n                            rules={rules}\n                            onSave={(updatedRules) => {\n                                setRules(updatedRules);\n                                setAlertConfig({\n                                    isOpen: true,\n                                    config: {\n                                        title: 'Reglas actualizadas',\n                                        description: 'Reglas actualizadas en memoria. Presiona \"Guardar Cambios\" para aplicarlas de forma permanente.',\n                                        cancelText: 'Cerrar',\n                                        onCancel: () => setAlertConfig({ isOpen: false, config: {} }),\n                                        onConfirm: undefined,\n                                    }\n                                });\n                            }}\n                        />\n                    )}\n                    */}\n\n                </div>\n            </div>\n\n            {alertConfig.isOpen && alertConfig.config.title && (\n                <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50\">\n                    <AlertDialog title={alertConfig.config.title} {...alertConfig.config} />\n                </div>\n            )}\n        </LayoutContent>\n    );\n};\n","import React, { useState, useEffect } from 'react';\nimport {\n    DndContext,\n    closestCenter,\n    KeyboardSensor,\n    PointerSensor,\n    useSensor,\n    useSensors\n} from '@dnd-kit/core';\nimport type { DragEndEvent } from '@dnd-kit/core';\nimport {\n    arrayMove,\n    SortableContext,\n    sortableKeyboardCoordinates,\n    verticalListSortingStrategy,\n    useSortable\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport { useFeatureService } from './services/useFeatureService';\nimport type { Feature, SystemEntityStatus } from './services/FeatureService';\nimport { EntityEditor } from './EntityEditor';\nimport { Button } from '../../Button/Button';\nimport { Input } from '../../Input/Input';\nimport { AlertDialog } from '../../AlertDialog/AlertDialog';\nimport { LayoutContent } from '../../LayoutContent';\nimport { useDynamicEntitiesContext, useDynamicEntitiesPermissions } from '../core/DynamicEntitiesProvider';\nimport {\n    PencilSquareIcon,\n    TrashIcon,\n    Bars3Icon,\n    PlusIcon,\n    CheckIcon,\n    LockClosedIcon,\n    ChevronDownIcon,\n    EyeIcon,\n} from '@heroicons/react/24/outline';\n\ninterface FeatureEditorProps {\n    featureId: string;\n    onBack: () => void;\n}\n\nconst GripIcon = () => (\n    <div className=\"text-gray-400 cursor-grab active:cursor-grabbing hover:text-gray-600 transition-colors p-1\">\n        <Bars3Icon className=\"w-5 h-5\" />\n    </div>\n);\n\nconst SortableFeatureEntity = ({ fe, onEdit, onDelete, canDelete = true }: any) => {\n    const {\n        attributes,\n        listeners,\n        setNodeRef,\n        transform,\n        transition,\n    } = useSortable({ id: fe.id });\n\n    const style = {\n        transform: CSS.Transform.toString(transform),\n        transition,\n    };\n\n    const isSystem = fe.dynamicEntity?.isSystem === true;\n\n    return (\n        <div ref={setNodeRef} style={style} className=\"flex items-center justify-between py-4 border-b border-gray-100 group bg-white hover:bg-gray-50/50 transition-colors px-2\">\n            <div className=\"flex items-center gap-4 flex-1\">\n                <div {...attributes} {...listeners} className=\"outline-none\">\n                    <GripIcon />\n                </div>\n                <div className=\"flex-1 grid grid-cols-12 gap-4 items-center\">\n                    <div className=\"col-span-4 font-medium text-sm text-gray-900 flex items-center gap-1.5\">\n                        {isSystem && (\n                            <LockClosedIcon className=\"w-3.5 h-3.5 text-gray-400 shrink-0\" />\n                        )}\n                        {fe.dynamicEntity?.code}\n                    </div>\n                    <div className=\"col-span-5 text-sm text-gray-500\">\n                        {fe.dynamicEntity?.description || fe.dynamicEntity?.code}\n                    </div>\n                    <div className=\"col-span-3\">\n                        <span className=\"inline-flex items-center px-2 py-0.5 rounded-md text-xs font-normal bg-[#dbeefe] text-[#0e79fd]\">\n                            {fe.renderMode === 'tab' ? 'Pestaña' : 'En Línea'}\n                        </span>\n                    </div>\n                </div>\n            </div>\n            <div className=\"flex items-center gap-2 w-[100px] justify-center\">\n                {isSystem ? (\n                    <Button\n                        type=\"plain\"\n                        iconOnly\n                        leftIcon={<EyeIcon className=\"w-5 h-5 text-gray-400 hover:text-gray-600\" />}\n                        ariaLabel=\"Ver campos\"\n                        onClick={() => onEdit(fe)}\n                    />\n                ) : (\n                    <>\n                        <Button\n                            type=\"plain\"\n                            iconOnly\n                            leftIcon={<PencilSquareIcon className=\"w-5 h-5 text-blue-500 hover:text-blue-700\" />}\n                            ariaLabel=\"Editar feature\"\n                            onClick={() => onEdit(fe)}\n                        />\n                        {canDelete && (\n                            <Button\n                                type=\"plain\"\n                                iconOnly\n                                leftIcon={<TrashIcon className=\"w-5 h-5 text-red-500 hover:text-red-700\" />}\n                                ariaLabel=\"Eliminar feature\"\n                                onClick={() => onDelete(fe)}\n                            />\n                        )}\n                    </>\n                )}\n            </div>\n        </div>\n    );\n};\n\nexport const FeatureEditor: React.FC<FeatureEditorProps> = ({ featureId, onBack }) => {\n    const { onError } = useDynamicEntitiesContext();\n    const { canCreate, canUpdate, canDelete } = useDynamicEntitiesPermissions();\n    const service = useFeatureService();\n    const [feature, setFeature] = useState<Feature | null>(null);\n    const [loading, setLoading] = useState(true);\n    const [view, setView] = useState<'feature' | 'entity'>('feature');\n    const [selectedFeatureEntity, setSelectedFeatureEntity] = useState<any | null>(null);\n\n    // Modal State — add regular entity\n    const [isAddModalOpen, setIsAddModalOpen] = useState(false);\n    const [newEntityCode, setNewEntityCode] = useState('');\n    const [newEntityDesc, setNewEntityDesc] = useState('');\n    const [newEntityRenderMode, setNewEntityRenderMode] = useState<'tab' | 'inline'>('tab');\n\n    // Order State\n    const [isOrderDirty, setIsOrderDirty] = useState(false);\n\n    // System entities state\n    const [systemEntities, setSystemEntities] = useState<SystemEntityStatus[]>([]);\n    const [systemEntitiesLoading, setSystemEntitiesLoading] = useState(false);\n    const [isSystemPanelOpen, setIsSystemPanelOpen] = useState(false);\n\n    // Enable modal state\n    const [enableModalEntity, setEnableModalEntity] = useState<SystemEntityStatus | null>(null);\n    const [enableRenderMode, setEnableRenderMode] = useState<'tab' | 'inline'>('tab');\n    const [isEnabling, setIsEnabling] = useState(false);\n\n    // Disable confirmation modal state\n    const [disableModalEntity, setDisableModalEntity] = useState<SystemEntityStatus | null>(null);\n    const [isDisabling, setIsDisabling] = useState(false);\n\n    const loadFeature = () => {\n\n        service.getById(featureId).then(f => {\n            setFeature({\n                ...f,\n                featureEntities: f.featureEntities ? f.featureEntities.filter((fe: any) => !fe.dynamicEntity?.isPlansAndCriteria) : []\n            });\n            setLoading(false);\n        }).catch(err => {\n            console.error(err);\n            onError?.(err as Error);\n            setLoading(false);\n        });\n    };\n\n    const loadSystemEntities = () => {\n        setSystemEntitiesLoading(true);\n        service.getSystemEntities(featureId).then(data => {\n            setSystemEntities(data);\n        }).catch(err => {\n            console.error(err);\n            onError?.(err as Error);\n        }).finally(() => {\n            setSystemEntitiesLoading(false);\n        });\n    };\n\n    useEffect(() => {\n        loadFeature();\n        loadSystemEntities();\n    }, [featureId, service]);\n\n    // Handlers — regular entities\n    const handleConfirmAddEntity = async () => {\n        if (!newEntityCode.trim()) {\n            alert('El código de la entidad es requerido');\n            return;\n        }\n\n        try {\n            setLoading(true);\n\n\n            const entity = await service.createEntity({\n                code: newEntityCode.trim(),\n                description: newEntityDesc.trim() || newEntityCode.trim(),\n                id: crypto.randomUUID(),\n                multiRecord: false\n            });\n\n            await service.addFeatureEntity(featureId, {\n                id: crypto.randomUUID(),\n                featureId: featureId,\n                dynamicEntityId: entity.id,\n                renderMode: newEntityRenderMode,\n                order: (feature?.featureEntities?.length || 0) + 1,\n                properties: {}\n            });\n\n            setIsAddModalOpen(false);\n            setNewEntityCode('');\n            setNewEntityDesc('');\n            setNewEntityRenderMode('tab');\n            loadFeature();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            alert('Error al crear la entidad');\n            setLoading(false);\n        }\n    };\n\n    const handleSaveOrder = async () => {\n        if (!feature || !feature.featureEntities) return;\n\n        setLoading(true);\n        try {\n\n            await Promise.all(feature.featureEntities.map((e: any) =>\n                service.updateFeatureEntity(featureId, e.dynamicEntityId, e)\n            ));\n            setIsOrderDirty(false);\n            loadFeature();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            alert('Error al guardar el nuevo orden');\n        } finally {\n            setLoading(false);\n        }\n    };\n\n    const sensors = useSensors(\n        useSensor(PointerSensor),\n        useSensor(KeyboardSensor, {\n            coordinateGetter: sortableKeyboardCoordinates,\n        })\n    );\n\n    const handleDragEnd = async (event: DragEndEvent) => {\n        const { active, over } = event;\n        if (!feature || !feature.featureEntities || !over) return;\n\n        if (active.id !== over.id) {\n            const entities = [...feature.featureEntities].sort((a, b) => (a.order || 0) - (b.order || 0));\n            const oldIndex = entities.findIndex((e) => e.id === active.id);\n            const newIndex = entities.findIndex((e) => e.id === over.id);\n\n            const newEntities = arrayMove(entities, oldIndex, newIndex);\n            const updatedEntities = newEntities.map((e, idx) => ({ ...e, order: idx }));\n\n            setFeature({ ...feature, featureEntities: updatedEntities });\n            setIsOrderDirty(true);\n        }\n    };\n\n    const handleDeleteEntity = async (fe: any) => {\n        if (!confirm('¿Está seguro? Esto elimina el vínculo, pero conserva la definición de la entidad.')) return;\n        try {\n            setLoading(true);\n\n            await service.removeFeatureEntity(featureId, fe.dynamicEntityId);\n            loadFeature();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            setLoading(false);\n        }\n    };\n\n    // Handlers — system entities\n    const handleOpenEnableModal = (entity: SystemEntityStatus) => {\n        setEnableRenderMode('tab');\n        setEnableModalEntity(entity);\n    };\n\n    const handleConfirmEnable = async () => {\n        if (!enableModalEntity) return;\n        setIsEnabling(true);\n        try {\n\n            await service.enableSystemEntity(featureId, enableModalEntity.id, enableRenderMode);\n            setEnableModalEntity(null);\n            loadFeature();\n            loadSystemEntities();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            alert('Error al habilitar la entidad de sistema');\n        } finally {\n            setIsEnabling(false);\n        }\n    };\n\n    const handleConfirmDisable = async () => {\n        if (!disableModalEntity?.enabledSystemEntityId) return;\n        setIsDisabling(true);\n        try {\n\n            await service.disableSystemEntity(featureId, disableModalEntity.enabledSystemEntityId);\n            setDisableModalEntity(null);\n            loadFeature();\n            loadSystemEntities();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            alert('Error al deshabilitar la entidad de sistema');\n        } finally {\n            setIsDisabling(false);\n        }\n    };\n\n    if (loading && !feature) return <div className=\"p-6 text-gray-500\">Cargando maestro...</div>;\n    if (!feature) return <div className=\"p-6 text-red-500\">Maestro no encontrado</div>;\n\n    if (view === 'entity' && selectedFeatureEntity) {\n        return (\n            <div className=\"w-full h-full\">\n                <EntityEditor\n                    entityId={selectedFeatureEntity.dynamicEntityId}\n                    featureId={featureId}\n                    featureEntityId={selectedFeatureEntity.id}\n                    initialRenderMode={selectedFeatureEntity.renderMode || 'tab'}\n                    onBack={() => {\n                        setView('feature');\n                        setSelectedFeatureEntity(null);\n                        loadFeature();\n                    }}\n                />\n            </div>\n        );\n    }\n\n    const sortedEntities = feature.featureEntities\n        ? [...feature.featureEntities].sort((a, b) => (a.order || 0) - (b.order || 0))\n        : [];\n\n    const enabledSystemCount = systemEntities.filter(e => e.isEnabled).length;\n\n    const customToolbarActions = (\n        <div className=\"flex gap-3\">\n            {isOrderDirty && canUpdate && (\n                <Button\n                    type=\"outline\"\n                    size=\"sm\"\n                    onClick={handleSaveOrder}\n                    disabled={loading}\n                    leftIcon={<CheckIcon className=\"w-4 h-4\" />}\n                >\n                    Guardar Orden\n                </Button>\n            )}\n            {canCreate && (\n                <Button\n                    type=\"default\"\n                    size=\"sm\"\n                    onClick={() => setIsAddModalOpen(true)}\n                    leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n                >\n                    Nueva Entidad\n                </Button>\n            )}\n        </div>\n    );\n\n    return (\n        <LayoutContent\n            title={`Opción - ${feature.name || feature.description || feature.code}`}\n            onBack={onBack}\n            toolbarEndContent={customToolbarActions}\n        >\n            <div className=\"flex flex-col w-full relative space-y-6\">\n\n                {/* Zona B — Lista principal de entidades */}\n                <div className=\"bg-white rounded-2xl w-full p-6\">\n                    <div className=\"w-full\">\n                        <div className=\"flex w-full border-b border-gray-200 pb-3 mb-2 px-2\">\n                            <div className=\"w-9\"></div>\n                            <div className=\"flex-1 grid grid-cols-12 gap-4\">\n                                <div className=\"col-span-4 text-sm font-medium text-gray-400\">Código</div>\n                                <div className=\"col-span-5 text-sm font-medium text-gray-400\">Nombre</div>\n                                <div className=\"col-span-3 text-sm font-medium text-gray-400\">Visualización</div>\n                            </div>\n                            <div className=\"w-[100px] text-center text-sm font-medium text-gray-400\">Acciones</div>\n                        </div>\n\n                        {sortedEntities.length === 0 && (\n                            <div className=\"text-center py-12 text-sm text-gray-400 border-b border-gray-100\">\n                                No hay entidades vinculadas. Haz clic en \"Nueva Entidad\" para empezar.\n                            </div>\n                        )}\n\n                        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>\n                            <SortableContext items={sortedEntities.map(e => e.id)} strategy={verticalListSortingStrategy}>\n                                {sortedEntities.map((fe: any) => (\n                                    <SortableFeatureEntity\n                                        key={fe.id}\n                                        fe={fe}\n                                        onEdit={(feToEdit: any) => { setSelectedFeatureEntity(feToEdit); setView('entity'); }}\n                                        onDelete={handleDeleteEntity}\n                                        canDelete={canDelete}\n                                    />\n                                ))}\n                            </SortableContext>\n                        </DndContext>\n                    </div>\n                </div>\n\n                {/* Zona A — Entidades de Sistema (acordeón) */}\n                <div className=\"bg-white rounded-2xl w-full overflow-hidden\">\n                    <button\n                        className=\"w-full flex items-center justify-between px-6 py-4 hover:bg-gray-50 transition-colors text-left\"\n                        onClick={() => setIsSystemPanelOpen(!isSystemPanelOpen)}\n                    >\n                        <div className=\"flex items-center gap-2\">\n                            <LockClosedIcon className=\"w-4 h-4 text-gray-400\" />\n                            <span className=\"text-sm font-semibold text-gray-700\">Entidades de Sistema</span>\n                            {enabledSystemCount > 0 && (\n                                <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700\">\n                                    {enabledSystemCount} habilitada{enabledSystemCount !== 1 ? 's' : ''}\n                                </span>\n                            )}\n                        </div>\n                        <ChevronDownIcon\n                            className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${isSystemPanelOpen ? 'rotate-180' : ''}`}\n                        />\n                    </button>\n\n                    {isSystemPanelOpen && (\n                        <div className=\"border-t border-gray-100\">\n                            {systemEntitiesLoading ? (\n                                <div className=\"px-6 py-8 text-center text-sm text-gray-400\">\n                                    Cargando entidades de sistema...\n                                </div>\n                            ) : systemEntities.length === 0 ? (\n                                <div className=\"px-6 py-8 text-center text-sm text-gray-400\">\n                                    No hay entidades de sistema disponibles.\n                                </div>\n                            ) : (\n                                <>\n                                    {/* Header */}\n                                    <div className=\"flex w-full border-b border-gray-100 px-6 py-2\">\n                                        <div className=\"flex-1 grid grid-cols-12 gap-4\">\n                                            <div className=\"col-span-3 text-xs font-medium text-gray-400\">Código</div>\n                                            <div className=\"col-span-3 text-xs font-medium text-gray-400\">Nombre</div>\n                                            <div className=\"col-span-3 text-xs font-medium text-gray-400\">Estado</div>\n                                            <div className=\"col-span-3 text-xs font-medium text-gray-400\">Visualización</div>\n                                        </div>\n                                        <div className=\"w-[110px] text-center text-xs font-medium text-gray-400\">Acción</div>\n                                    </div>\n\n                                    {/* Rows */}\n                                    {systemEntities.map(entity => {\n                                        const enabledAtFormatted = entity.enabledAt\n                                            ? new Date(entity.enabledAt).toLocaleString('es-CO', {\n                                                day: '2-digit', month: 'short', year: 'numeric',\n                                                hour: '2-digit', minute: '2-digit'\n                                            })\n                                            : null;\n                                        const enabledByShort = entity.enabledBy\n                                            ? entity.enabledBy.slice(0, 8) + '…'\n                                            : null;\n\n                                        return (\n                                            <div\n                                                key={entity.id}\n                                                className=\"flex items-center justify-between py-4 border-b border-gray-50 px-6 hover:bg-gray-50/40 transition-colors\"\n                                            >\n                                                <div className=\"flex-1 grid grid-cols-12 gap-4 items-start\">\n                                                    <div className=\"col-span-3 text-sm font-medium text-gray-900 pt-0.5\">\n                                                        {entity.code}\n                                                    </div>\n                                                    <div className=\"col-span-3 text-sm text-gray-500 pt-0.5\">\n                                                        {entity.description || entity.code}\n                                                    </div>\n                                                    <div className=\"col-span-3 flex flex-col gap-1\">\n                                                        {entity.isEnabled ? (\n                                                            <>\n                                                                <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700 w-fit\">\n                                                                    Habilitada\n                                                                </span>\n                                                                {enabledAtFormatted && (\n                                                                    <span className=\"text-xs text-gray-400\" title={entity.enabledAt}>\n                                                                        {enabledAtFormatted}\n                                                                    </span>\n                                                                )}\n                                                                {enabledByShort && (\n                                                                    <span className=\"text-xs text-gray-400\" title={entity.enabledBy}>\n                                                                        Por: {enabledByShort}\n                                                                    </span>\n                                                                )}\n                                                            </>\n                                                        ) : (\n                                                            <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500 w-fit\">\n                                                                No habilitada\n                                                            </span>\n                                                        )}\n                                                    </div>\n                                                    <div className=\"col-span-3 text-sm text-gray-400 pt-0.5\">\n                                                        {entity.isEnabled && entity.renderMode\n                                                            ? (entity.renderMode === 'tab' ? 'Pestaña' : 'En Línea')\n                                                            : '—'\n                                                        }\n                                                    </div>\n                                                </div>\n                                                <div className=\"w-[110px] flex justify-center shrink-0\">\n                                                    {entity.isEnabled ? (\n                                                        canDelete && (\n                                                            <Button\n                                                                type=\"plain\"\n                                                                size=\"xs\"\n                                                                onClick={() => setDisableModalEntity(entity)}\n                                                            >\n                                                                Deshabilitar\n                                                            </Button>\n                                                        )\n                                                    ) : (\n                                                        canCreate && (\n                                                            <Button\n                                                                type=\"outline\"\n                                                                size=\"xs\"\n                                                                onClick={() => handleOpenEnableModal(entity)}\n                                                            >\n                                                                Habilitar\n                                                            </Button>\n                                                        )\n                                                    )}\n                                                </div>\n                                            </div>\n                                        );\n                                    })}\n                                </>\n                            )}\n                        </div>\n                    )}\n                </div>\n\n            </div>\n\n            {/* Modal — Nueva Entidad */}\n            {isAddModalOpen && (\n                <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4\">\n                    <div className=\"bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden relative\">\n                        <div className=\"absolute right-4 top-4\">\n                            <Button type=\"plain\" size=\"xs\" iconOnly leftIcon={<svg className=\"w-5 h-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"><path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" /></svg>} onClick={() => setIsAddModalOpen(false)} ariaLabel=\"Cerrar modal\" />\n                        </div>\n\n                        <div className=\"px-6 py-5 border-b border-gray-100\">\n                            <h3 className=\"text-lg font-bold text-gray-900\">Nueva Entidad</h3>\n                        </div>\n\n                        <div className=\"p-6 space-y-5\">\n                            <div className=\"space-y-2\">\n                                <label className=\"text-sm font-medium text-gray-900 flex gap-1\">Código de Entidad <span className=\"text-red-300\">*</span></label>\n                                <Input\n                                    type=\"text\"\n                                    placeholder=\"Ej: DATOS_ADICIONALES\"\n                                    value={newEntityCode}\n                                    onChange={(e) => setNewEntityCode(e.target.value)}\n                                    autoFocus\n                                    inputSize=\"sm\"\n                                />\n                                <p className=\"text-xs text-gray-500\">Un identificador único sin espacios para la base de datos.</p>\n                            </div>\n\n                            <div className=\"space-y-2\">\n                                <label className=\"text-sm font-medium text-gray-900 flex gap-1\">Nombre <span className=\"text-red-300\">*</span></label>\n                                <Input\n                                    type=\"text\"\n                                    placeholder=\"Ej: Información técnica extra\"\n                                    value={newEntityDesc}\n                                    onChange={(e) => setNewEntityDesc(e.target.value)}\n                                    onKeyDown={(e) => {\n                                        if (e.key === 'Enter') handleConfirmAddEntity();\n                                    }}\n                                    inputSize=\"sm\"\n                                />\n                                <p className=\"text-xs text-gray-500\">El nombre visible que se mostrará en las pestañas.</p>\n                            </div>\n\n                            <div className=\"space-y-3 pt-2\">\n                                <label className=\"text-sm font-medium text-gray-900\">Modo de Visualización</label>\n                                <div className=\"grid grid-cols-2 gap-3\">\n                                    <label className={`cursor-pointer border rounded-lg p-3 flex flex-col items-center gap-2 transition-colors ${newEntityRenderMode === 'tab' ? 'bg-[#dbeefe]/30 border-[#0e79fd]' : 'bg-white border-gray-200 hover:bg-gray-50'}`}>\n                                        <input type=\"radio\" name=\"renderMode\" value=\"tab\" className=\"sr-only\" checked={newEntityRenderMode === 'tab'} onChange={() => setNewEntityRenderMode('tab')} />\n                                        <span className={`text-sm font-medium ${newEntityRenderMode === 'tab' ? 'text-[#0e79fd]' : 'text-gray-700'}`}>Pestaña (Tab)</span>\n                                    </label>\n                                    <label className={`cursor-pointer border rounded-lg p-3 flex flex-col items-center gap-2 transition-colors ${newEntityRenderMode === 'inline' ? 'bg-[#dbeefe]/30 border-[#0e79fd]' : 'bg-white border-gray-200 hover:bg-gray-50'}`}>\n                                        <input type=\"radio\" name=\"renderMode\" value=\"inline\" className=\"sr-only\" checked={newEntityRenderMode === 'inline'} onChange={() => setNewEntityRenderMode('inline')} />\n                                        <span className={`text-sm font-medium ${newEntityRenderMode === 'inline' ? 'text-[#0e79fd]' : 'text-gray-700'}`}>En Línea</span>\n                                    </label>\n                                </div>\n                            </div>\n                        </div>\n\n                        <div className=\"px-6 py-4 bg-gray-50 border-t border-gray-100 flex justify-end gap-3 shrink-0\">\n                            <Button type=\"plain\" size=\"sm\" onClick={() => setIsAddModalOpen(false)}>\n                                Cancelar\n                            </Button>\n                            <Button type=\"default\" size=\"sm\" onClick={handleConfirmAddEntity} disabled={!newEntityCode.trim() || loading}>\n                                {loading ? 'Creando...' : 'Guardar'}\n                            </Button>\n                        </div>\n                    </div>\n                </div>\n            )}\n\n            {/* Modal — Habilitar entidad de sistema */}\n            {enableModalEntity && (\n                <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4\">\n                    <AlertDialog\n                        title={`Habilitar \"${enableModalEntity.description || enableModalEntity.code}\"`}\n                        onCancel={() => { setEnableModalEntity(null); setEnableRenderMode('tab'); }}\n                        onConfirm={handleConfirmEnable}\n                        confirmText=\"Habilitar\"\n                        cancelText=\"Cancelar\"\n                        isProcess={isEnabling}\n                    >\n                        <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n                            Selecciona el modo de visualización para esta entidad en el Feature.\n                        </p>\n                        <div className=\"grid grid-cols-2 gap-3 pt-1\">\n                            <label className={`cursor-pointer border rounded-lg p-3 flex flex-col items-center gap-2 transition-colors ${enableRenderMode === 'tab' ? 'bg-[#dbeefe]/30 border-[#0e79fd]' : 'bg-white border-gray-200 hover:bg-gray-50'}`}>\n                                <input\n                                    type=\"radio\"\n                                    name=\"enableRenderMode\"\n                                    value=\"tab\"\n                                    className=\"sr-only\"\n                                    checked={enableRenderMode === 'tab'}\n                                    onChange={() => setEnableRenderMode('tab')}\n                                />\n                                <span className={`text-sm font-medium ${enableRenderMode === 'tab' ? 'text-[#0e79fd]' : 'text-gray-700'}`}>\n                                    Pestaña (Tab)\n                                </span>\n                            </label>\n                            <label className={`cursor-pointer border rounded-lg p-3 flex flex-col items-center gap-2 transition-colors ${enableRenderMode === 'inline' ? 'bg-[#dbeefe]/30 border-[#0e79fd]' : 'bg-white border-gray-200 hover:bg-gray-50'}`}>\n                                <input\n                                    type=\"radio\"\n                                    name=\"enableRenderMode\"\n                                    value=\"inline\"\n                                    className=\"sr-only\"\n                                    checked={enableRenderMode === 'inline'}\n                                    onChange={() => setEnableRenderMode('inline')}\n                                />\n                                <span className={`text-sm font-medium ${enableRenderMode === 'inline' ? 'text-[#0e79fd]' : 'text-gray-700'}`}>\n                                    En Línea\n                                </span>\n                            </label>\n                        </div>\n                    </AlertDialog>\n                </div>\n            )}\n\n            {/* Modal — Deshabilitar entidad de sistema */}\n            {disableModalEntity && (\n                <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4\">\n                    <AlertDialog\n                        title={`¿Deshabilitar \"${disableModalEntity.description || disableModalEntity.code}\"?`}\n                        onCancel={() => setDisableModalEntity(null)}\n                        onConfirm={handleConfirmDisable}\n                        confirmText=\"Deshabilitar\"\n                        cancelText=\"Cancelar\"\n                        isProcess={isDisabling}\n                    >\n                        <p className=\"text-sm leading-5 font-normal text-content-tertiary dark:text-content-tertiary\">\n                            Esta acción eliminará la asociación con el Feature. Los datos EAV capturados no se eliminan.\n                        </p>\n                    </AlertDialog>\n                </div>\n            )}\n\n        </LayoutContent>\n    );\n};\n","import React, { useState, useEffect } from 'react';\nimport {\n    useDynamicEntitiesContext,\n    useDynamicEntitiesFetcher,\n    useDynamicEntitiesPermissions\n} from '../core/DynamicEntitiesProvider';\nimport { Input } from '../../Input/Input';\nimport { Button } from '../../Button/Button';\nimport { InformationCircleIcon, PencilSquareIcon, TrashIcon, ExclamationCircleIcon, XMarkIcon } from '@heroicons/react/24/outline';\n\ninterface GenericListItem {\n    id?: string;\n    value: string;\n    label: string;\n    order: number;\n    active: boolean;\n}\n\ninterface GenericList {\n    id?: string;\n    code: string;\n    description?: string;\n    active: boolean;\n    items: GenericListItem[];\n}\n\nexport const CatalogManager: React.FC = () => {\n    const { baseUrl, onError } = useDynamicEntitiesContext();\n    const http = useDynamicEntitiesFetcher();\n    const { canCreate, canUpdate, canDelete } = useDynamicEntitiesPermissions();\n    const [lists, setLists] = useState<GenericList[]>([]);\n    const [loading, setLoading] = useState(true);\n    const [loadError, setLoadError] = useState<Error | null>(null);\n    const [editingList, setEditingList] = useState<GenericList | null>(null);\n\n    const loadLists = async () => {\n        setLoading(true);\n        setLoadError(null);\n        try {\n            const res = await http(`${baseUrl}/dynamic-entities/catalogs`);\n            if (!res.ok) throw new Error(`Failed to fetch catalogs: ${res.status} ${res.statusText}`);\n            const data = await res.json();\n            setLists(data);\n        } catch (err) {\n            console.error(err);\n            setLists([]);\n            setLoadError(err as Error);\n            onError?.(err as Error);\n        } finally {\n            setLoading(false);\n        }\n    };\n\n    useEffect(() => {\n        loadLists();\n    }, [baseUrl, http]);\n\n    const handleSave = async () => {\n        if (!editingList) return;\n        const method = editingList.id ? 'PUT' : 'POST';\n        const url = editingList.id\n            ? `${baseUrl}/dynamic-entities/catalogs/${editingList.id}`\n            : `${baseUrl}/dynamic-entities/catalogs`;\n\n        try {\n            const res = await http(url, {\n                method,\n                headers: { 'Content-Type': 'application/json' },\n                body: JSON.stringify(editingList)\n            });\n            if (!res.ok) throw new Error(`Failed to save catalog: ${res.status} ${res.statusText}`);\n            setEditingList(null);\n            loadLists();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n            alert('Error al guardar catálogo');\n        }\n    };\n\n    const handleDelete = async (id: string) => {\n        if (!confirm('¿Eliminar catálogo?')) return;\n        try {\n            const res = await http(`${baseUrl}/dynamic-entities/catalogs/${id}`, { method: 'DELETE' });\n            if (!res.ok) throw new Error(`Failed to delete catalog: ${res.status} ${res.statusText}`);\n            loadLists();\n        } catch (err) {\n            console.error(err);\n            onError?.(err as Error);\n        }\n    };\n\n    return (\n        <div className=\"flex flex-col w-full\">\n            <div className=\"flex justify-between items-center mb-6\">\n                <div className=\"bg-[#cffafe] border border-[#67e8f9] flex items-center gap-2 px-4 py-2 rounded-lg\">\n                    <InformationCircleIcon className=\"w-6 h-6 text-[#0e7490]\" />\n                    <span className=\"text-sm text-[#0e7490]\">Crea un listado de opciones</span>\n                </div>\n                {canCreate && (\n                    <Button\n                        type=\"outline\"\n                        onClick={() => setEditingList({ code: '', active: true, items: [] })}\n                    >\n                        Nuevo catálogo\n                    </Button>\n                )}\n            </div>\n\n            {loading ? (\n                <div className=\"text-gray-500 py-4\">Cargando catálogos...</div>\n            ) : loadError ? (\n                <div\n                    role=\"alert\"\n                    className=\"flex items-start gap-3 rounded-lg border border-red-200 bg-red-50 px-4 py-3\"\n                >\n                    <ExclamationCircleIcon className=\"w-5 h-5 text-red-600 shrink-0 mt-0.5\" />\n                    <div className=\"flex flex-col gap-1\">\n                        <p className=\"text-sm font-medium text-red-700\">\n                            No se pudieron cargar los catálogos.\n                        </p>\n                        <p className=\"text-sm text-red-600\">{loadError.message}</p>\n                    </div>\n                </div>\n            ) : (\n                <div className=\"w-full overflow-x-auto\">\n                    <table className=\"w-full text-left border-collapse\">\n                        <thead>\n                            <tr>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200\">Código</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200\">Nombre</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200\">Opciones</th>\n                                <th className=\"px-5 py-4 text-sm font-medium text-gray-400 border-b border-gray-200 text-center w-[100px]\">Acciones</th>\n                            </tr>\n                        </thead>\n                        <tbody>\n                            {lists.length === 0 && (\n                                <tr>\n                                    <td colSpan={4} className=\"px-5 py-6 text-center text-gray-500\">\n                                        No has creado catálogos aún. Los catálogos son necesarios para campos de tipo Radio y Select.\n                                    </td>\n                                </tr>\n                            )}\n                            {lists.map(list => (\n                                <tr key={list.id} className=\"group\">\n                                    <td className=\"px-5 py-4 text-sm text-gray-900 border-b border-gray-200\">\n                                        {list.code}\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm text-gray-900 border-b border-gray-200\">\n                                        {list.description || 'Sin descripción'}\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm border-b border-gray-200\">\n                                        <span className=\"inline-flex items-center px-2 py-0.5 rounded-md text-xs font-normal bg-[#dbeefe] text-[#0e79fd]\">\n                                            {list.items?.length || 0} {list.items?.length === 1 ? 'Campo adicional' : 'Campos adicionales'}\n                                        </span>\n                                    </td>\n                                    <td className=\"px-5 py-4 text-sm border-b border-gray-200 text-center\">\n                                        <div className=\"flex items-center justify-center gap-2\">\n                                            {canUpdate && (\n                                                <Button\n                                                    type=\"plain\"\n                                                    iconOnly\n                                                    leftIcon={<PencilSquareIcon className=\"h-5 w-5\" />}\n                                                    ariaLabel=\"Editar\"\n                                                    onClick={() => setEditingList(list)}\n                                                />\n                                            )}\n                                            {canDelete && (\n                                                <Button\n                                                    type=\"plain\"\n                                                    iconOnly\n                                                    leftIcon={<TrashIcon className=\"h-5 w-5\" />}\n                                                    ariaLabel=\"Eliminar\"\n                                                    className=\"text-red-500\"\n                                                    onClick={() => list.id && handleDelete(list.id)}\n                                                />\n                                            )}\n                                        </div>\n                                    </td>\n                                </tr>\n                            ))}\n                        </tbody>\n                    </table>\n                </div>\n            )}\n\n            {/* Modal de Creación / Edición */}\n            {editingList && (\n                <div className=\"fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4\">\n                    <div className=\"bg-white rounded-xl shadow-2xl border border-gray-200 relative w-full max-w-4xl flex flex-col max-h-[90vh] overflow-hidden\">\n                        {/* Close Button */}\n                        <div className=\"absolute right-5 top-5 z-10\">\n                            <Button\n                                type=\"plain\"\n                                size=\"xs\"\n                                iconOnly\n                                leftIcon={<XMarkIcon className=\"w-5 h-5\" />}\n                                ariaLabel=\"Cerrar modal\"\n                                onClick={() => setEditingList(null)}\n                            />\n                        </div>\n\n                        {/* Modal Content Scrollable */}\n                        <div className=\"p-6 flex flex-col gap-6 overflow-y-auto\">\n                            {/* Header */}\n                            <div className=\"flex items-center gap-4\">\n                                <div className=\"bg-[#fcedc9] w-10 h-10 rounded-full flex items-center justify-center shrink-0\">\n                                    <ExclamationCircleIcon className=\"w-6 h-6 text-yellow-700\" />\n                                </div>\n                                <h2 className=\"text-xl font-bold text-gray-900 tracking-tight\">\n                                    {editingList.id ? 'Editar catálogo' : 'Nuevo catálogo'}\n                                </h2>\n                            </div>\n\n                            {/* Form Inputs */}\n                            <div className=\"flex gap-5\">\n                                <div className=\"flex flex-col gap-2 w-64\">\n                                    <label className=\"text-sm font-medium text-gray-900 flex gap-1\">\n                                        Código <span className=\"text-red-300\">*</span>\n                                    </label>\n                                    <input\n                                        type=\"text\"\n                                        value={editingList.code}\n                                        onChange={e => setEditingList({ ...editingList, code: e.target.value })}\n                                        disabled={!!editingList.id}\n                                        placeholder=\"Ej: 91289421\"\n                                        className=\"border border-gray-200 rounded-md px-3 py-1.5 text-sm text-gray-700 focus:outline-none focus:border-blue-500 disabled:bg-gray-50\"\n                                    />\n                                </div>\n                                <div className=\"flex flex-col gap-2 w-64\">\n                                    <label className=\"text-sm font-medium text-gray-900 flex gap-1\">\n                                        Nombre <span className=\"text-red-300\">*</span>\n                                    </label>\n                                    <input\n                                        type=\"text\"\n                                        value={editingList.description || ''}\n                                        onChange={e => setEditingList({ ...editingList, description: e.target.value })}\n                                        placeholder=\"Ej: Estado del producto\"\n                                        className=\"border border-gray-200 rounded-md px-3 py-1.5 text-sm text-gray-700 focus:outline-none focus:border-blue-500\"\n                                    />\n                                </div>\n                            </div>\n\n                            {/* Dynamic Table Area */}\n                            <div className=\"flex flex-col items-end gap-5\">\n                                <Button\n                                    type=\"outline\"\n                                    size=\"sm\"\n                                    onClick={() => {\n                                        const newItems = [...editingList.items, { value: '', label: '', order: editingList.items.length, active: true }];\n                                        setEditingList({ ...editingList, items: newItems });\n                                    }}\n                                >\n                                    Nuevo\n                                </Button>\n\n                                <div className=\"w-full\">\n                                    {/* Table Header */}\n                                    <div className=\"flex w-full border-b border-gray-200 min-h-[36px]\">\n                                        <div className=\"flex-1 px-4 py-2 text-sm font-medium text-gray-400 flex items-center\">Valor ID</div>\n                                        <div className=\"flex-1 px-4 py-2 text-sm font-medium text-gray-400 flex items-center\">Etiqueta</div>\n                                        <div className=\"w-[100px] px-4 py-2 text-sm font-medium text-gray-400 flex items-center justify-center\">Acciones</div>\n                                    </div>\n\n                                    {/* Table Body */}\n                                    {editingList.items.map((item, index) => (\n                                        <div key={index} className=\"flex w-full border-b border-gray-200 py-2 items-center\">\n                                            <div className=\"flex-1 px-4\">\n                                                <input\n                                                    type=\"text\"\n                                                    value={item.value}\n                                                    onChange={e => {\n                                                        const items = [...editingList.items];\n                                                        items[index].value = e.target.value;\n                                                        setEditingList({ ...editingList, items });\n                                                    }}\n                                                    className=\"w-full border border-gray-200 rounded-md px-3 py-1.5 text-sm text-gray-700 focus:outline-none focus:border-blue-500\"\n                                                    placeholder=\"Ej: john_smith\"\n                                                />\n                                            </div>\n                                            <div className=\"flex-1 px-4\">\n                                                <input\n                                                    type=\"text\"\n                                                    value={item.label}\n                                                    onChange={e => {\n                                                        const items = [...editingList.items];\n                                                        items[index].label = e.target.value;\n                                                        setEditingList({ ...editingList, items });\n                                                    }}\n                                                    className=\"w-full border border-gray-200 rounded-md px-3 py-1.5 text-sm text-gray-700 focus:outline-none focus:border-blue-500\"\n                                                    placeholder=\"Ej: John Smith\"\n                                                />\n                                            </div>\n                                            <div className=\"w-[100px] px-4 flex items-center justify-center\">\n                                                <Button\n                                                    type=\"plain\"\n                                                    size=\"sm\"\n                                                    iconOnly\n                                                    leftIcon={<TrashIcon className=\"w-5 h-5\" />}\n                                                    ariaLabel=\"Eliminar opción\"\n                                                    className=\"text-red-500\"\n                                                    onClick={() => {\n                                                        const items = editingList.items.filter((_, i) => i !== index);\n                                                        setEditingList({ ...editingList, items });\n                                                    }}\n                                                />\n                                            </div>\n                                        </div>\n                                    ))}\n                                    {editingList.items.length === 0 && (\n                                        <div className=\"w-full py-8 text-center text-sm text-gray-400 border-b border-gray-200\">\n                                            No hay opciones agregadas. Haz clic en \"Nuevo\" para comenzar.\n                                        </div>\n                                    )}\n                                </div>\n                            </div>\n                        </div>\n\n                        {/* Footer Actions */}\n                        <div className=\"px-6 py-4 flex justify-end gap-3 w-full border-t border-gray-100 bg-gray-50 shrink-0\">\n                            <Button\n                                type=\"default\"\n                                onClick={handleSave}\n                            >\n                                Guardar\n                            </Button>\n                        </div>\n                    </div>\n                </div>\n            )}\n        </div>\n    );\n};\n","import { EntityEditor } from \"./EntityEditor\";\nimport { useFeatureService } from \"./services/useFeatureService\";\nimport { useDynamicEntitiesContext, useDynamicEntitiesPermissions } from \"../core/DynamicEntitiesProvider\";\nimport React, { useState } from 'react';\nimport { LayoutContent } from '../../LayoutContent';\nimport { FeatureList } from './FeatureList';\nimport { FeatureEditor } from './FeatureEditor';\nimport { Input } from '../../Input/Input';\nimport { MagnifyingGlassIcon } from '@heroicons/react/24/outline';\n\nexport const DynamicEntitiesAdmin: React.FC = () => {\n    const { onError } = useDynamicEntitiesContext();\n    const { canCreate } = useDynamicEntitiesPermissions();\n    const service = useFeatureService();\n    const [selectedFeatureId, setSelectedFeatureId] = useState<string | null>(null);\n    const [selectedPlansAndCriteriaEntityId, setSelectedPlansAndCriteriaEntityId] = useState<string | null>(null);\n    const [selectedPlansAndCriteriaFeatureEntityId, setSelectedPlansAndCriteriaFeatureEntityId] = useState<string | null>(null);\n    const [selectedPlansAndCriteriaRenderMode, setSelectedPlansAndCriteriaRenderMode] = useState<'tab' | 'inline' | 'modal'>('tab');\n    const [searchTerm, setSearchTerm] = useState('');\n\n    const handleCreatePlansAndCriteria = async (feature: any) => {\n        try {\n            const code = `${feature.code}_planes_criterios`.toUpperCase();\n\n            // Refetch feature to get full feature entities just in case\n            const fullFeature = await service.getById(feature.id);\n            const existingEntity = fullFeature.featureEntities?.find((fe: any) => fe.dynamicEntity?.code === code || fe.dynamicEntity?.isPlansAndCriteria);\n\n            if (existingEntity) {\n                setSelectedFeatureId(feature.id);\n                setSelectedPlansAndCriteriaEntityId(existingEntity.dynamicEntityId);\n                setSelectedPlansAndCriteriaFeatureEntityId(existingEntity.id);\n                setSelectedPlansAndCriteriaRenderMode(existingEntity.renderMode || 'tab');\n            } else {\n                const newEntity = await service.createEntity({\n                    code: code,\n                    description: `Planes y Criterios para ${feature.name}`,\n                    multiRecord: false,\n                    isReadonly: false,\n                    isDisabled: false,\n                    isPlansAndCriteria: true\n                });\n\n                const featureEntity = await service.addFeatureEntity(feature.id, {\n                    featureId: feature.id,\n                    dynamicEntityId: newEntity.id,\n                    renderMode: 'tab',\n                    order: 0\n                });\n\n                setSelectedFeatureId(feature.id);\n                setSelectedPlansAndCriteriaEntityId(newEntity.id);\n                setSelectedPlansAndCriteriaFeatureEntityId(featureEntity.id);\n                setSelectedPlansAndCriteriaRenderMode('tab'); // New entities default to tab\n            }\n        } catch (error) {\n            console.error('Error creating plans and criteria entity:', error);\n            onError?.(error as Error);\n            alert('Error al crear o abrir la entidad de planes y criterios. Revisa la consola.');\n        }\n    };\n\n    if (selectedPlansAndCriteriaEntityId && selectedFeatureId) {\n        return (\n                    <EntityEditor\n                entityId={selectedPlansAndCriteriaEntityId}\n                featureId={selectedFeatureId}\n                featureEntityId={selectedPlansAndCriteriaFeatureEntityId || undefined}\n                initialRenderMode={selectedPlansAndCriteriaRenderMode}\n                onBack={() => {\n                    setSelectedPlansAndCriteriaEntityId(null);\n                    setSelectedPlansAndCriteriaFeatureEntityId(null);\n                    setSelectedPlansAndCriteriaRenderMode('tab');\n                    setSelectedFeatureId(null);\n                }}\n            />\n        );\n    }\n\n    // If editing a specific feature, the toolbar should reflect that context\n    if (selectedFeatureId) {\n        // We render FeatureEditor which handles its own internal layout logic,\n        // or we could wrap it in LayoutContent here if preferred. \n        // For now, let's just render the editor directly and we can refactor FeatureEditor next.\n        return (\n            <FeatureEditor\n                featureId={selectedFeatureId}\n                onBack={() => setSelectedFeatureId(null)}\n            />\n        );\n    }\n\n    return (\n        <LayoutContent\n            title=\"Opciones del sistema\"\n            toolbarEndContent={\n                <div className=\"w-full sm:w-64\">\n                    <Input\n                        inputSize=\"sm\"\n                        placeholder=\"Buscar por código o nombre...\"\n                        value={searchTerm}\n                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}\n                        startIcon={<MagnifyingGlassIcon className=\"h-5 w-5 text-gray-400\" />}\n                    />\n                </div>\n            }\n        >\n            <div className=\"flex flex-col w-full\">\n                <FeatureList\n                    onSelectFeature={setSelectedFeatureId}\n                    onCreatePlansAndCriteria={canCreate ? handleCreatePlansAndCriteria : undefined}\n                    searchTerm={searchTerm}\n                />\n            </div>\n        </LayoutContent>\n    );\n};\n","import React, { useState, useEffect } from 'react';\nimport { XMarkIcon, TrashIcon, InformationCircleIcon } from '@heroicons/react/24/outline';\nimport { Button } from '../Button/Button';\nimport { Input } from '../Input/Input';\nimport type { GenericEntity, GenericEntityItem } from './GenericEntities.types';\n\nexport interface GenericEntityModalProps {\n    isOpen: boolean;\n    mode: 'create' | 'edit';\n    entity?: GenericEntity | null;\n    initialItems?: GenericEntityItem[];\n    onClose: () => void;\n    onSave: (entity: Partial<GenericEntity>, items: GenericEntityItem[]) => void;\n    isLoading?: boolean;\n}\n\nexport const GenericEntityModal: React.FC<GenericEntityModalProps> = ({\n    isOpen,\n    mode,\n    entity,\n    initialItems = [],\n    onClose,\n    onSave,\n    isLoading = false,\n}) => {\n    const [code, setCode] = useState('');\n    const [description, setDescription] = useState('');\n    const [items, setItems] = useState<GenericEntityItem[]>([]);\n\n    useEffect(() => {\n        if (isOpen) {\n            if (mode === 'edit' && entity) {\n                setCode(entity.code);\n                setDescription(entity.description);\n                setItems(initialItems);\n            } else {\n                setCode('');\n                setDescription('');\n                setItems([]);\n            }\n        }\n    }, [isOpen, mode, entity, initialItems]);\n\n    if (!isOpen) return null;\n\n    const isEdit = mode === 'edit';\n    const title = isEdit ? `Editar : ${entity?.description || ''}` : 'Nueva Entidad Genérica';\n\n    const handleAddItem = () => {\n        setItems([\n            ...items,\n            {\n                id: Math.random().toString(), // ID temporal\n                genericEntityId: entity?.id || '',\n                code: '',\n                value: '',\n                sortOrder: items.length,\n                isActive: true,\n            },\n        ]);\n    };\n\n    const handleUpdateItem = (index: number, field: keyof GenericEntityItem, val: any) => {\n        const newItems = [...items];\n        newItems[index] = { ...newItems[index], [field]: val };\n        setItems(newItems);\n    };\n\n    const handleRemoveItem = (index: number) => {\n        const newItems = items.filter((_, i) => i !== index);\n        setItems(newItems);\n    };\n\n    const isValid = code.trim() !== '' && description.trim() !== '';\n\n    const handleSave = () => {\n        if (!isValid) return;\n        onSave(\n            {\n                ...(entity || {}),\n                code,\n                description,\n                isActive: entity ? entity.isActive : true,\n            },\n            items\n        );\n    };\n\n    return (\n        <div className=\"fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4\">\n            <div className=\"bg-white dark:bg-dark-bg-primary rounded-2xl shadow-xl border border-border-primary dark:border-dark-border-primary relative w-full max-w-4xl flex flex-col max-h-[90vh]\">\n                {/* Header */}\n                <div className=\"bg-gray-100 dark:bg-dark-bg-secondary flex justify-between items-center px-5 py-4 border-b border-border-primary dark:border-dark-border-primary rounded-t-2xl\">\n                    <h2 className=\"text-xl font-bold text-gray-900 dark:text-dark-content-primary\">\n                        {title}\n                    </h2>\n                    <Button\n                        type=\"plain\"\n                        size=\"xs\"\n                        iconOnly\n                        leftIcon={<XMarkIcon className=\"w-4 h-4 text-content-primary dark:text-dark-content-primary\" />}\n                        ariaLabel=\"Cerrar\"\n                        onClick={onClose}\n                        disabled={isLoading}\n                        className=\"border border-border-custom-primary !p-2\"\n                    />\n                </div>\n\n                {/* Body */}\n                <div className=\"p-5 flex flex-col gap-5 overflow-y-auto\">\n                    {/* Main Fields */}\n                    <div className=\"flex gap-5\">\n                        <div className=\"flex w-[265px] flex-col gap-2\">\n                            <label className=\"text-sm font-medium text-gray-900 dark:text-dark-content-primary flex gap-1\">\n                                Código <span className=\"text-red-300\">*</span>\n                            </label>\n                            <Input\n                                value={code}\n                                onChange={e => setCode(e.target.value)}\n                                disabled={isEdit} \n                            />\n                        </div>\n                        <div className=\"flex w-[265px] flex-col gap-2\">\n                            <label className=\"text-sm font-medium text-gray-900 dark:text-dark-content-primary flex gap-1\">\n                                Nombre <span className=\"text-red-300\">*</span>\n                            </label>\n                            <Input\n                                value={description}\n                                onChange={e => setDescription(e.target.value)}\n                            />\n                        </div>\n                    </div>\n\n                    {/* Options (Variables) */}\n                    <div className=\"flex flex-col gap-5 items-end\">\n                        <div className=\"flex justify-between items-center w-full\">\n                            <div className=\"bg-cyan-100 dark:bg-cyan-900/30 border border-cyan-400 dark:border-cyan-700 flex gap-2 items-center px-4 py-2 rounded-lg\">\n                                <InformationCircleIcon className=\"w-6 h-6 text-cyan-700 dark:text-cyan-400\" />\n                                <span className=\"text-sm text-cyan-700 dark:text-cyan-400\">\n                                    Es el listado de opciones que veras\n                                </span>\n                            </div>\n                            <Button onClick={handleAddItem} type=\"outline\" size=\"sm\" className=\"font-medium\">\n                                Nuevo\n                            </Button>\n                        </div>\n\n                        <div className=\"flex flex-col w-full\">\n                            <div className=\"flex h-9 border-b border-border-primary dark:border-dark-border-primary\">\n                                <div className=\"flex-1 flex items-center px-4 py-2 border-b border-border-primary dark:border-dark-border-primary\">\n                                    <span className=\"text-sm font-medium text-content-secondary dark:text-dark-content-secondary\">\n                                        Valor ID\n                                    </span>\n                                </div>\n                                <div className=\"flex-1 flex items-center px-4 py-2 border-b border-border-primary dark:border-dark-border-primary\">\n                                    <span className=\"text-sm font-medium text-content-secondary dark:text-dark-content-secondary\">\n                                        Etiqueta\n                                    </span>\n                                </div>\n                                <div className=\"w-[100px] flex items-center px-4 py-2 border-b border-border-primary dark:border-dark-border-primary\">\n                                    <span className=\"text-sm font-medium text-content-secondary dark:text-dark-content-secondary\">\n                                        Acciones\n                                    </span>\n                                </div>\n                            </div>\n\n                            {items.length === 0 ? (\n                                <div className=\"p-8 text-center text-sm text-content-secondary dark:text-dark-content-secondary\">\n                                    No se han agregado opciones. Haz clic en \"Nuevo\" para comenzar.\n                                </div>\n                            ) : (\n                                <div className=\"max-h-[300px] overflow-y-auto\">\n                                    {items.map((item, index) => (\n                                        <div key={item.id} className=\"flex items-start gap-5 py-2 border-b border-border-secondary dark:border-dark-border-secondary w-full\">\n                                            <div className=\"flex-1 flex flex-col gap-2\">\n                                                <Input value={item.code} onChange={e => handleUpdateItem(index, 'code', e.target.value)} />\n                                            </div>\n                                            <div className=\"flex-1 flex flex-col gap-2\">\n                                                <Input value={item.value} onChange={e => handleUpdateItem(index, 'value', e.target.value)} />\n                                            </div>\n                                            <div className=\"w-[100px] h-8 flex justify-center items-center px-4\">\n                                                <Button type=\"plain\" iconOnly leftIcon={<TrashIcon className=\"w-4 h-4 text-red-500\" />} onClick={() => handleRemoveItem(index)} />\n                                            </div>\n                                        </div>\n                                    ))}\n                                </div>\n                            )}\n                        </div>\n                    </div>\n                </div>\n\n                {/* Footer */}\n                <div className=\"bg-gray-100 dark:bg-dark-bg-secondary flex justify-end px-5 py-4 border-t border-gray-100 dark:border-dark-border-primary rounded-b-2xl\">\n                     <Button\n                        type=\"default\"\n                        disabled={!isValid || isLoading}\n                        onClick={handleSave}\n                        className=\"bg-[#0e79fd] hover:bg-blue-600 text-white font-medium px-4 py-2 rounded-md shadow-[inset_0px_2px_0px_0px_rgba(255,255,255,0.15)] border border-[#3c9bf6]\"\n                    >\n                        {isLoading ? 'Guardando...' : 'Guardar'}\n                    </Button>\n                </div>\n            </div>\n        </div>\n    );\n};\n","import React, { useState } from 'react';\nimport { PencilSquareIcon } from '@heroicons/react/24/outline';\nimport type { GenericEntitiesProps, GenericEntity, GenericEntityItem } from './GenericEntities.types';\nimport { Button } from '../Button';\nimport { Table } from '../Table';\nimport { Input } from '../Input';\nimport { LayoutContent } from '../LayoutContent';\nimport { MagnifyingGlassIcon } from '@heroicons/react/24/outline';\nimport type { TableColumn } from '../Table/Table.types';\nimport { GenericEntityModal } from './GenericEntityModal';\n\ninterface ModalState {\n    isOpen: boolean;\n    mode: 'create' | 'edit';\n    entity?: GenericEntity | null;\n    items: GenericEntityItem[];\n}\n\nexport const GenericEntities: React.FC<GenericEntitiesProps> = ({\n    title = 'Entidades Genéricas',\n    entities = [],\n    isLoading = false,\n    onSelectEntity,\n    onCreateEntity,\n    onSaveEntity,\n    onLoadItems,\n    className = '',\n}) => {\n    const [searchTerm, setSearchTerm] = useState('');\n    \n    // Unificamos el estado del modal de creación/edición\n    const [modalState, setModalState] = useState<ModalState>({\n        isOpen: false,\n        mode: 'create',\n        entity: null,\n        items: []\n    });\n    \n    const [isLoadingItems, setIsLoadingItems] = useState(false);\n\n    const handleCreateClick = () => {\n        setModalState({\n            isOpen: true,\n            mode: 'create',\n            entity: null,\n            items: []\n        });\n    };\n\n    const handleSelectForEdit = async (entity: GenericEntity) => {\n        if (onSelectEntity) onSelectEntity(entity);\n\n        let loadedItems: GenericEntityItem[] = [];\n        if (onLoadItems) {\n            setIsLoadingItems(true);\n            try {\n                loadedItems = await onLoadItems(entity);\n            } catch (err) {\n                console.error('Error loading items:', err);\n                loadedItems = [];\n            } finally {\n                setIsLoadingItems(false);\n            }\n        }\n\n        setModalState({\n            isOpen: true,\n            mode: 'edit',\n            entity,\n            items: loadedItems\n        });\n    };\n\n    const handleCloseModal = () => {\n        setModalState(prev => ({ ...prev, isOpen: false }));\n    };\n\n    const handleSaveModal = (entityData: Partial<GenericEntity>, itemsData: GenericEntityItem[]) => {\n        if (modalState.mode === 'create') {\n            if (onCreateEntity) {\n                // En modo creación asume que la interfaz de quien lo consume puede lidiar con las opciones\n                // si la interfaz lo permite, o bien lo guarda todo en `onCreateEntity` o hace otra lógica.\n                // Como `onCreateEntity` solo recibe Partial<GenericEntity> en los props actuales,\n                // idealmente el consumidor debería tener una forma de recibir ambos, o nosotros llamamos a onSaveEntity si está creado.\n                // Ajustamos para usar onSaveEntity si se provee, o onCreateEntity como estaba.\n                if (onSaveEntity && entityData.id) {\n                     onSaveEntity(entityData as GenericEntity, itemsData);\n                } else if (onCreateEntity) {\n                     onCreateEntity(entityData, itemsData);\n                     // Nota: Si se requiere guardar items en creacion, onSaveEntity es más apropiado, \n                     // pero mantenemos la compatibilidad del prop.\n                }\n            }\n        } else {\n            if (onSaveEntity && entityData.id) {\n                onSaveEntity(entityData as GenericEntity, itemsData);\n            }\n        }\n        setModalState(prev => ({ ...prev, isOpen: false }));\n    };\n\n    const filtered = entities.filter(e =>\n        e.code.toLowerCase().includes(searchTerm.toLowerCase()) ||\n        e.description.toLowerCase().includes(searchTerm.toLowerCase())\n    );\n\n    const columns: TableColumn<GenericEntity>[] = [\n        { header: 'Código', accessor: 'code', sortable: true },\n        { header: 'Descripción', accessor: 'description', sortable: true },\n        {\n            header: 'Estado',\n            accessor: 'isActive',\n            render: (val: boolean) => (\n                <span className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-normal ${val ? 'bg-[#dbeefe] text-[#0e79fd]' : 'bg-red-50 text-red-600'}`}>\n                    {val ? 'Activo' : 'Inactivo'}\n                </span>\n            )\n        },\n        {\n            header: 'Acciones',\n            accessor: 'id',\n            align: 'center',\n            render: (_, row: GenericEntity) => (\n                <button\n                    onClick={(e) => {\n                        e.stopPropagation();\n                        handleSelectForEdit(row);\n                    }}\n                    className=\"inline-flex items-center justify-center text-[#0e79fd] hover:text-blue-800 transition-colors\"\n                    title=\"Editar\"\n                    disabled={isLoadingItems}\n                >\n                    <PencilSquareIcon className=\"h-5 w-5\" />\n                </button>\n            )\n        }\n    ];\n\n    return (\n        <LayoutContent\n            title={title}\n            toolbarEndContent={\n                <div className=\"flex w-full sm:w-auto items-center gap-3\">\n                    <div className=\"w-full sm:w-64\">\n                        <Input\n                            placeholder=\"Buscar entidad...\"\n                            value={searchTerm}\n                            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}\n                            startIcon={<MagnifyingGlassIcon className=\"h-5 w-5 text-gray-400\" />}\n                        />\n                    </div>\n                    <Button onClick={handleCreateClick} variant=\"default\">\n                        Nueva Entidad\n                    </Button>\n                </div>\n            }\n        >\n            <div className={`w-full h-full flex flex-col gap-4 ${className}`}>\n                <Table\n                    columns={columns}\n                    data={filtered}\n                    loading={isLoading || isLoadingItems}\n                />\n            </div>\n\n            <GenericEntityModal\n                isOpen={modalState.isOpen}\n                mode={modalState.mode}\n                entity={modalState.entity}\n                initialItems={modalState.items}\n                onClose={handleCloseModal}\n                onSave={handleSaveModal}\n                isLoading={isLoading}\n            />\n        </LayoutContent>\n    );\n};\n","import type { ContactTranslations } from './translations.types'\n\nexport const defaultTranslations: ContactTranslations = {\n  schema: {\n    name: {\n      required: 'El nombre es obligatorio',\n      maxLength: 'El nombre no puede exceder 200 caracteres',\n    },\n    email: {\n      invalidFormat: 'El formato del correo electrónico no es válido',\n      maxLength: 'El correo no puede exceder 256 caracteres',\n    },\n    address: {\n      maxLength: 'La dirección no puede exceder 500 caracteres',\n    },\n    phone: {\n      countryRequired: 'El país es obligatorio',\n      areaCodeMaxLength: 'El área no puede exceder 3 caracteres',\n      numberRequired: 'El número de teléfono es obligatorio',\n      numberMaxLength: 'El número no puede exceder 10 caracteres',\n      extensionMaxLength: 'La extensión no puede exceder 3 caracteres',\n    },\n    socialNetwork: {\n      typeRequired: 'Debe seleccionar un tipo de red social',\n      urlRequired: 'La URL del perfil es obligatoria',\n      urlMaxLength: 'La URL no puede exceder 2048 caracteres',\n    },\n    useFor: {\n      required: 'El contacto debe tener al menos un uso',\n    },\n  },\n  modal: {\n    titlePrefix: 'Contacto',\n    actionBadge: {\n      creating: 'Creando',\n      editing: 'Editando',\n    },\n    description: 'Formulario de contacto',\n    button: {\n      save: 'Guardar',\n      update: 'Actualizar',\n      cancel: 'Cancelar',\n      close: 'Cerrar',\n      addPhone: 'Agregar teléfono',\n      addSocialNetwork: 'Agregar red social',\n    },\n    label: {\n      name: 'Nombre',\n      email: 'Email',\n      address: 'Dirección',\n      description: 'Descripción',\n      useFor: 'Usar para',\n      country: 'País',\n      state: 'Estado/Departamento',\n      city: 'Ciudad',\n      neighborhood: 'Barrio',\n      category: 'Categoría',\n      phoneNumber: 'Número',\n      socialType: 'Red social',\n      socialUrl: 'URL',\n    },\n    placeholder: {\n      name: 'Nombre del contacto',\n      address: 'Dirección del contacto',\n      description: 'Descripción del contacto',\n      select: '\\u2014 Seleccionar \\u2014',\n      loading: 'Cargando...',\n      socialUrl: 'https://...',\n    },\n    tab: {\n      basicData: 'Datos básicos',\n      location: 'Ubicación',\n      phone: 'Teléfono',\n      socialNetwork: 'Redes sociales',\n    },\n    section: {\n      location: 'Ubicación',\n      phones: 'Teléfonos',\n      socialNetworks: 'Redes Sociales',\n    },\n    error: {\n      preventRemoval: 'Debe existir al menos un contacto Predeterminado',\n      transferBlocked: 'No se puede transferir. El contacto predeterminado actual no tiene otros usos y quedaría sin ninguno.',\n      neighborhoodMismatch: 'El barrio seleccionado no pertenece a la ciudad indicada',\n      catalogsPhone: 'Error al cargar catálogos. Las opciones de país pueden no estar disponibles.',\n      catalogsSocial: 'Error al cargar catálogos. Los tipos de red social pueden no estar disponibles.',\n    },\n    aria: {\n      phoneCategory: (index: number) => `Categoría del teléfono ${index + 1}`,\n      phoneCountry: (index: number) => `País del teléfono ${index + 1}`,\n      removePhone: (index: number) => `Eliminar teléfono ${index + 1}`,\n      socialType: (index: number) => `Tipo de red social ${index + 1}`,\n      socialUrl: (index: number) => `URL de red social ${index + 1}`,\n      removeSocial: (index: number) => `Eliminar red social ${index + 1}`,\n      country: 'País',\n      state: 'Estado/Departamento',\n      city: 'Ciudad',\n      neighborhood: 'Barrio',\n    },\n    defaultCategory: 'Móvil',\n    emptyState: {\n      phone: 'No hay registros. Haz clic en \"Agregar teléfono\"',\n      socialNetwork: 'No hay registros. Haz clic en \"Agregar red social\"',\n    },\n    column: {\n      actions: 'Acciones',\n    },\n  },\n  grid: {\n    title: 'Contacto',\n    button: { addContact: 'Agregar contacto' },\n    aria: { table: 'Tabla de contactos' },\n    column: {\n      name: 'Nombre',\n      email: 'Email',\n      useFor: 'Usar para',\n      phone: 'Teléfono',\n      socialNetworks: 'Redes sociales',\n      actions: 'Acciones',\n    },\n    pagination: {\n      previous: 'Anterior',\n      next: 'Siguiente',\n    },\n    emptyBanner: 'No hay registros. Haz clic en \\u201CAgregar contacto\\u201D',\n    socialNetworkNotEnabled: 'Red social no habilitada',\n  },\n  actions: {\n    pendingDelete: 'Pendiente de eliminación',\n    undo: 'Deshacer',\n    viewDetail: 'Ver Detalle',\n    edit: 'Editar',\n    delete: 'Eliminar',\n  },\n  emptyState: {\n    noContacts: 'No hay contactos registrados.',\n    addHint: \" Haz clic en 'Agregar Contacto' para comenzar.\",\n    addButton: 'Agregar Contacto',\n  },\n  pillEmail: {\n    error: {\n      invalidFormat: 'El formato del correo electrónico no es válido',\n      duplicate: 'Este correo ya fue agregado',\n    },\n    placeholder: 'Ingrese correo y presione Enter...',\n    aria: {\n      list: 'Correos electrónicos',\n      emailLabel: (email: string) => `Correo: ${email}`,\n      removeEmail: (email: string) => `Eliminar ${email}`,\n      addEmail: 'Agregar correo electrónico',\n    },\n  },\n  phoneInput: {\n    placeholder: {\n      area: 'Área',\n      number: 'Número de teléfono',\n      extension: 'Ext.',\n    },\n    aria: {\n      group: 'Número de teléfono: área, número, extensión',\n      areaCode: 'Código de área',\n      number: 'Número',\n      extension: 'Extensión',\n    },\n  },\n  tagSelector: {\n    selectAll: 'Usar para todo',\n    aria: {\n      group: 'Usar para',\n      option: (label: string) => `Usar para: ${label}`,\n    },\n  },\n  manager: {\n    defaultLabel: 'Predeterminado',\n  },\n  dialog: {\n    default: {\n      title: 'Cambiar contacto predeterminado',\n      newContactFallback: 'el nuevo contacto',\n      message: (currentName: string, newName: string) =>\n        `El contacto \\u201C${currentName}\\u201D ya está marcado como Predeterminado. ¿Desea transferir el predeterminado a \\u201C${newName}\\u201D?`,\n      cancel: 'Cancelar',\n      confirm: 'Confirmar',\n    },\n    delete: {\n      title: 'Eliminar',\n      message: '¿Estás seguro de eliminar el registro?',\n      cancel: 'Cancelar',\n      confirm: 'Confirmar',\n    },\n    deleteDefault: {\n      title: 'Eliminar contacto predeterminado',\n      message: (defaultName: string, newDefaultName: string) =>\n        `El contacto \\u201C${defaultName}\\u201D es el predeterminado. Al eliminarlo, el predeterminado se transferirá a \\u201C${newDefaultName}\\u201D. ¿Desea continuar?`,\n      cancel: 'Cancelar',\n      confirm: 'Confirmar',\n    },\n  },\n  skeleton: {\n    column: {\n      name: 'Nombre',\n      email: 'Email',\n      phone: 'Teléfono',\n      actions: 'Acciones',\n    },\n  },\n  enums: {\n    useFor: { 0: 'Predeterminado' },\n    phoneCategory: { 0: 'Móvil' },\n  },\n}\n","import type { ContactTranslations } from './translations.types'\n\nexport type DeepPartial<T> = {\n  [K in keyof T]?: T[K] extends (...args: infer A) => infer R\n    ? (...args: A) => R\n    : T[K] extends object\n      ? DeepPartial<T[K]>\n      : T[K]\n}\n\nexport type PartialTranslations = DeepPartial<ContactTranslations>\n\nexport function mergeTranslations(\n  defaults: ContactTranslations,\n  overrides?: PartialTranslations,\n): ContactTranslations {\n  if (!overrides) return defaults\n\n  function deepMerge(\n    base: Record<string, unknown>,\n    partial: Record<string, unknown>,\n  ): Record<string, unknown> {\n    const result: Record<string, unknown> = { ...base }\n    for (const key of Object.keys(partial)) {\n      const override = partial[key]\n      if (override === undefined) continue\n      const baseVal = base[key]\n      if (typeof override === 'function' || typeof baseVal !== 'object' || baseVal === null) {\n        result[key] = override\n      } else {\n        result[key] = deepMerge(\n          baseVal as Record<string, unknown>,\n          override as Record<string, unknown>,\n        )\n      }\n    }\n    return result\n  }\n\n  return deepMerge(\n    defaults as unknown as Record<string, unknown>,\n    overrides as unknown as Record<string, unknown>,\n  ) as unknown as ContactTranslations\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react'\nimport type { IContactServiceAdapter } from '../types/adapter.types'\nimport type { ContactTranslations } from '../i18n/translations.types'\nimport type { PartialTranslations } from '../i18n/mergeTranslations'\nimport { defaultTranslations } from '../i18n/defaultTranslations'\nimport { mergeTranslations } from '../i18n/mergeTranslations'\n\nconst ContactServiceContext = createContext<IContactServiceAdapter | null>(null)\nconst TranslationsContext = createContext<ContactTranslations>(defaultTranslations)\n\nexport function useContactServiceAdapter(): IContactServiceAdapter {\n  const adapter = useContext(ContactServiceContext)\n  if (!adapter) {\n    throw new Error('useContactServiceAdapter must be used within a ContactServiceProvider')\n  }\n  return adapter\n}\n\nexport function useTranslations(): ContactTranslations {\n  return useContext(TranslationsContext)\n}\n\ninterface ContactServiceProviderProps {\n  adapter: IContactServiceAdapter\n  translations?: PartialTranslations\n  children: ReactNode\n}\n\nexport function ContactServiceProvider({ adapter, translations, children }: ContactServiceProviderProps) {\n  const merged = useMemo(\n    () => mergeTranslations(defaultTranslations, translations),\n    [translations],\n  )\n\n  return (\n    <ContactServiceContext.Provider value={adapter}>\n      <TranslationsContext.Provider value={merged}>\n        {children}\n      </TranslationsContext.Provider>\n    </ContactServiceContext.Provider>\n  )\n}\n","export const DEFAULT_VALUE = 0\n\nexport interface EnumOption {\n  value: number\n  label: string\n}\n\n/** Build EnumOption[] from a Record<number, string> translation map. */\nexport function buildEnumOptions(map: Record<number, string>): EnumOption[] {\n  return Object.entries(map).map(([key, label]) => ({ value: Number(key), label }))\n}\n","import { create } from 'zustand'\nimport type { Contact } from '../types/contact.types'\nimport { DEFAULT_VALUE } from '../types/enum.types'\n\nexport interface PendingChangesPayload {\n  recordId: string\n  contacts: Contact[]\n  maxContacts: number\n}\n\nexport interface ContactStoreState {\n  recordId: string\n  contacts: Contact[]\n  pendingAdds: Contact[]\n  pendingEdits: Map<string, Contact>\n  pendingDeletes: Set<string>\n  maxContacts: number\n}\n\nexport interface ContactStoreActions {\n  loadContacts: (recordId: string, contacts: Contact[]) => void\n  addContact: (contact: Omit<Contact, 'id'>) => void\n  editContact: (id: string, data: Partial<Contact>) => void\n  deleteContact: (id: string) => void\n  restoreContact: (id: string) => void\n  getPendingChanges: () => PendingChangesPayload | null\n  resetChanges: () => void\n  reset: () => void\n  setMaxContacts: (max: number) => void\n}\n\nconst initialState: ContactStoreState = {\n  recordId: '',\n  contacts: [],\n  pendingAdds: [],\n  pendingEdits: new Map(),\n  pendingDeletes: new Set(),\n  maxContacts: 10,\n}\n\nexport const useContactStore = create<ContactStoreState & ContactStoreActions>()(\n  (set, get) => ({\n    ...initialState,\n\n    loadContacts: (recordId, contacts) => {\n      set({\n        recordId,\n        contacts,\n        pendingAdds: [],\n        pendingEdits: new Map(),\n        pendingDeletes: new Set(),\n      })\n    },\n\n    addContact: (contactData) => {\n      const contact: Contact = {\n        ...contactData,\n        id: crypto.randomUUID(),\n      }\n      set((state) => ({\n        contacts: [...state.contacts, contact],\n        pendingAdds: [...state.pendingAdds, contact],\n      }))\n    },\n\n    editContact: (id, data) => {\n      set((state) => {\n        const updatedContacts = state.contacts.map((c) =>\n          c.id === id ? { ...c, ...data } : c,\n        )\n        const updatedContact = updatedContacts.find((c) => c.id === id)\n        if (!updatedContact) return state\n\n        const newPendingEdits = new Map(state.pendingEdits)\n        newPendingEdits.set(id, updatedContact)\n\n        return {\n          contacts: updatedContacts,\n          pendingEdits: newPendingEdits,\n        }\n      })\n    },\n\n    deleteContact: (id) => {\n      set((state) => {\n        const newPendingDeletes = new Set(state.pendingDeletes)\n        newPendingDeletes.add(id)\n\n        // AC4: Auto-reassign default when deleting the default contact\n        const deletedContact = state.contacts.find((c) => c.id === id)\n        if (deletedContact?.useFor.includes(DEFAULT_VALUE)) {\n          const firstRemaining = state.contacts.find(\n            (c) => c.id !== id && !newPendingDeletes.has(c.id ?? ''),\n          )\n          if (firstRemaining?.id) {\n            const newPendingEdits = new Map(state.pendingEdits)\n            const updated = {\n              ...firstRemaining,\n              useFor: firstRemaining.useFor.includes(DEFAULT_VALUE)\n                ? firstRemaining.useFor\n                : [DEFAULT_VALUE, ...firstRemaining.useFor],\n              isDefault: true,\n            }\n            newPendingEdits.set(firstRemaining.id, updated)\n            return {\n              contacts: state.contacts.map((c) =>\n                c.id === firstRemaining.id ? updated : c,\n              ),\n              pendingDeletes: newPendingDeletes,\n              pendingEdits: newPendingEdits,\n            }\n          }\n        }\n\n        return { pendingDeletes: newPendingDeletes }\n      })\n    },\n\n    restoreContact: (id) => {\n      set((state) => {\n        const newPendingDeletes = new Set(state.pendingDeletes)\n        newPendingDeletes.delete(id)\n\n        const restoredContact = state.contacts.find((c) => c.id === id)\n        if (restoredContact?.useFor.includes(DEFAULT_VALUE)) {\n          // Reverse the auto-reassignment: remove default from whoever currently has it\n          const currentDefault = state.contacts.find(\n            (c) =>\n              c.id !== id &&\n              !newPendingDeletes.has(c.id ?? '') &&\n              c.useFor.includes(DEFAULT_VALUE),\n          )\n          if (currentDefault?.id) {\n            const newPendingEdits = new Map(state.pendingEdits)\n            const updated = {\n              ...currentDefault,\n              useFor: currentDefault.useFor.filter((u) => u !== DEFAULT_VALUE),\n              isDefault: false,\n            }\n            newPendingEdits.set(currentDefault.id, updated)\n            return {\n              contacts: state.contacts.map((c) =>\n                c.id === currentDefault.id ? updated : c,\n              ),\n              pendingDeletes: newPendingDeletes,\n              pendingEdits: newPendingEdits,\n            }\n          }\n        }\n\n        return { pendingDeletes: newPendingDeletes }\n      })\n    },\n\n    getPendingChanges: () => {\n      const state = get()\n      const hasPendingAdds = state.pendingAdds.length > 0\n      const hasPendingEdits = state.pendingEdits.size > 0\n      const hasPendingDeletes = state.pendingDeletes.size > 0\n\n      if (!hasPendingAdds && !hasPendingEdits && !hasPendingDeletes) {\n        return null\n      }\n\n      const pendingAddIds = new Set(state.pendingAdds.map((c) => c.id))\n\n      const contacts = state.contacts\n        .filter((c) => c.id == null || !state.pendingDeletes.has(c.id))\n        .map((c) => {\n          if (pendingAddIds.has(c.id)) {\n            return { ...c, id: null }\n          }\n          return c\n        })\n\n      return {\n        recordId: state.recordId,\n        contacts,\n        maxContacts: state.maxContacts,\n      }\n    },\n\n    resetChanges: () => {\n      set({\n        pendingAdds: [],\n        pendingEdits: new Map(),\n        pendingDeletes: new Set(),\n      })\n    },\n\n    // Unlike resetChanges (which only clears the pending-change trackers, leaving `contacts` as\n    // the just-persisted truth — correct right after an EDIT save), this also blanks `contacts`\n    // and `recordId` back to their initial values. Call this after a CREATE succeeds: the 'new'\n    // bucket's content now belongs to a real record elsewhere, so leaving it here would leak into\n    // the next unrelated \"start creating a new record\" session under that same 'new' recordId —\n    // ContactManager's own mount effect only re-fetches when `recordId` prop actually CHANGES\n    // value, which never happens between two separate creation sessions (both are literally\n    // 'new'), so a stale `contacts` array is otherwise never cleared on its own.\n    reset: () => {\n      set({\n        recordId: '',\n        contacts: [],\n        pendingAdds: [],\n        pendingEdits: new Map(),\n        pendingDeletes: new Set(),\n      })\n    },\n\n    setMaxContacts: (max) => {\n      set({ maxContacts: max })\n    },\n  }),\n)\n","import { useState, useEffect } from 'react'\n\nexport function useMediaQuery(query: string): boolean {\n  const [matches, setMatches] = useState(() => {\n    if (typeof window === 'undefined') return false\n    return window.matchMedia(query).matches\n  })\n\n  useEffect(() => {\n    const mediaQuery = window.matchMedia(query)\n    const handler = (event: MediaQueryListEvent) => setMatches(event.matches)\n\n    mediaQuery.addEventListener('change', handler)\n    setMatches(mediaQuery.matches)\n\n    return () => mediaQuery.removeEventListener('change', handler)\n  }, [query])\n\n  return matches\n}\n","export interface TagColor {\n  bg: string\n  text: string\n  border: string\n  darkBg: string\n  darkText: string\n  darkBorder: string\n}\n\nexport const TAG_COLORS: TagColor[] = [\n  { bg: 'bg-primary-100', text: 'text-primary-600', border: 'border-primary-300', darkBg: 'dark:bg-blue-900', darkText: 'dark:text-blue-200', darkBorder: 'dark:border-blue-700' },\n  { bg: 'bg-green-100', text: 'text-green-800', border: 'border-green-300', darkBg: 'dark:bg-green-900', darkText: 'dark:text-green-200', darkBorder: 'dark:border-green-700' },\n  { bg: 'bg-amber-100', text: 'text-amber-800', border: 'border-amber-300', darkBg: 'dark:bg-amber-900', darkText: 'dark:text-amber-200', darkBorder: 'dark:border-amber-700' },\n  { bg: 'bg-purple-100', text: 'text-purple-800', border: 'border-purple-300', darkBg: 'dark:bg-purple-900', darkText: 'dark:text-purple-200', darkBorder: 'dark:border-purple-700' },\n  { bg: 'bg-cyan-100', text: 'text-cyan-800', border: 'border-cyan-300', darkBg: 'dark:bg-cyan-900', darkText: 'dark:text-cyan-200', darkBorder: 'dark:border-cyan-700' },\n  { bg: 'bg-red-100', text: 'text-red-800', border: 'border-red-300', darkBg: 'dark:bg-red-900', darkText: 'dark:text-red-200', darkBorder: 'dark:border-red-700' },\n]\n\nexport function getColorForIndex(index: number): TagColor {\n  return TAG_COLORS[index % TAG_COLORS.length]\n}\n","import type { Contact, ContactPhone, ContactSocialNetwork } from '../types/contact.types'\n\nexport type ContactState = 'new' | 'modified' | 'deleted' | null\n\nexport const STATE_SHADOW_STYLE: Record<string, string> = {\n  new: 'shadow-[inset_4px_0_0_0_var(--color-primary-400)]',\n  modified: 'shadow-[inset_4px_0_0_0_var(--color-amber-400)]',\n  deleted: 'shadow-[inset_4px_0_0_0_var(--color-red-400)]',\n}\n\nexport function getContactState(\n  contact: Contact,\n  pendingAdds: Contact[],\n  pendingEdits: Map<string, Contact>,\n  pendingDeletes: Set<string>,\n): ContactState {\n  if (contact.id != null && pendingDeletes.has(contact.id)) return 'deleted'\n  if (pendingAdds.some((c) => c.id === contact.id)) return 'new'\n  if (contact.id != null && pendingEdits.has(contact.id)) return 'modified'\n  return null\n}\n\nexport function formatPhoneForGrid(phone: ContactPhone, categoryLabelMap?: Map<number, string>): string {\n  let result = categoryLabelMap?.get(phone.category) ?? String(phone.category)\n  if (phone.areaCode) {\n    result += ` ${phone.areaCode}-${phone.number}`\n  } else {\n    result += ` ${phone.number}`\n  }\n  if (phone.extension) result += ` ext ${phone.extension}`\n  return result\n}\n\nexport function formatSocialForGrid(\n  sn: ContactSocialNetwork,\n  socialNetworkLabelMap: Map<string, string> | undefined,\n  notEnabledLabel: string,\n): string {\n  const url = sn.url.length > 40 ? `${sn.url.substring(0, 37)}...` : sn.url\n  // A map that exists but doesn't contain this network's id means the company's own\n  // lookup search (now company-scoped, see contactAdapter.ts) never returned it — the\n  // network isn't enabled for the active company, so its raw GUID would otherwise leak\n  // into the grid instead of a name. No map at all (no company context) falls back to\n  // the id, same as before — there's nothing to say it's \"not enabled\" against.\n  const label = socialNetworkLabelMap\n    ? socialNetworkLabelMap.get(sn.socialNetworkTypeId) ?? notEnabledLabel\n    : sn.socialNetworkTypeId\n  return `${label}: ${url}`\n}\n\nexport const DEFAULT_PAGE_SIZE = 5\n","import Skeleton from 'react-loading-skeleton'\nimport 'react-loading-skeleton/dist/skeleton.css'\nimport '../contact-manager.css'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\nconst SKELETON_ROWS = 3\n\ninterface ContactGridSkeletonProps {\n  layout?: 'table' | 'card'\n}\n\nexport function ContactGridSkeleton({ layout = 'table' }: ContactGridSkeletonProps) {\n  const t = useTranslations()\n\n  if (layout === 'card') {\n    return (\n      <div className=\"contact-grid-skeleton flex flex-col gap-3\">\n        {Array.from({ length: SKELETON_ROWS }).map((_, i) => (\n          <div key={i} className=\"rounded-md bg-white p-4 shadow-sm dark:bg-slate-900\">\n            <Skeleton width={160} height={16} />\n            <Skeleton width={200} height={14} className=\"mt-1\" />\n            <Skeleton width={120} height={12} className=\"mt-1\" />\n          </div>\n        ))}\n      </div>\n    )\n  }\n\n  return (\n    <table className=\"contact-grid-skeleton w-full\">\n      <thead>\n        {/* Same header color/weight as ContactGrid's own loaded table (text-content-primary,\n            font-semibold) — this used to be text-slate-500, a washed-out gray that stayed\n            visible only for the brief loading flash, but read as inconsistent with the real\n            headers that replace it right after. */}\n        <tr className=\"border-b border-border-primary dark:border-dark-border-primary\">\n          <th className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary\">{t.skeleton.column.name}</th>\n          <th className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary\">{t.skeleton.column.email}</th>\n          <th className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary\">{t.skeleton.column.phone}</th>\n          <th className=\"py-3 px-4 text-right text-sm font-semibold text-content-primary dark:text-dark-content-primary\">{t.skeleton.column.actions}</th>\n        </tr>\n      </thead>\n      <tbody>\n        {Array.from({ length: SKELETON_ROWS }).map((_, i) => (\n          <tr key={i} className=\"border-b border-border-secondary dark:border-dark-border-primary\">\n            <td className=\"py-3 px-4\"><Skeleton width={140} /></td>\n            <td className=\"py-3 px-4\"><Skeleton width={180} /></td>\n            <td className=\"py-3 px-4\"><Skeleton width={120} /></td>\n            <td className=\"py-3 px-4 text-right\"><Skeleton width={80} /></td>\n          </tr>\n        ))}\n      </tbody>\n    </table>\n  )\n}\n","import { Info } from 'lucide-react'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\n// The \"Agregar contacto\" action lives ONLY in ContactGrid's header now (top-right, same spot\n// and same button regardless of whether there are contacts yet) — this used to render its own\n// second copy here, bottom-centered, so an empty record showed two differently-styled buttons\n// for the same action.\nexport function ContactGridEmptyState() {\n  const t = useTranslations()\n\n  return (\n    <div className=\"flex flex-col items-center gap-4\">\n      <div className=\"flex w-full items-center gap-3 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 dark:border-blue-800/50 dark:bg-blue-950/30\">\n        <Info className=\"h-5 w-5 shrink-0 text-blue-600 dark:text-blue-400\" />\n        <p className=\"text-sm text-blue-800 dark:text-blue-200\">\n          {t.grid.emptyBanner}\n        </p>\n      </div>\n    </div>\n  )\n}\n","import { Pencil, Trash2, Eye } from 'lucide-react'\nimport { Button } from '@components/Button/Button'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\ninterface ContactRowActionsProps {\n  contactId: string\n  mode: 'edit' | 'view'\n  isPendingDelete: boolean\n  onEdit: (id: string) => void\n  onView: (id: string) => void\n  onDelete: (id: string) => void\n  onRestore: (id: string) => void\n}\n\nexport function ContactRowActions({\n  contactId,\n  mode,\n  isPendingDelete,\n  onEdit,\n  onView,\n  onDelete,\n  onRestore,\n}: ContactRowActionsProps) {\n  const t = useTranslations()\n\n  // AC6: Deleted row — only \"Deshacer\" outline button. Centered (not justify-end) so it\n  // lines up under the now-centered \"Acciones\" header label.\n  if (isPendingDelete) {\n    return (\n      <div className=\"flex items-center justify-center\">\n        <Button\n          type=\"outline\"\n          size=\"xs\"\n          onClick={() => onRestore(contactId)}\n        >\n          {t.actions.undo}\n        </Button>\n      </div>\n    )\n  }\n\n  // AC5: Actions always visible — no hover behavior\n  if (mode === 'view') {\n    return (\n      <div className=\"flex items-center justify-center gap-1.5\">\n        <Button\n          type=\"outline\"\n          size=\"xs\"\n          iconOnly\n          leftIcon={<Eye className=\"h-4 w-4\" />}\n          onClick={() => onView(contactId)}\n          ariaLabel={t.actions.viewDetail}\n        />\n      </div>\n    )\n  }\n\n  return (\n    <div className=\"flex items-center justify-center gap-1.5\">\n      <Button\n        type=\"outline\"\n        size=\"xs\"\n        iconOnly\n        leftIcon={<Pencil className=\"h-4 w-4\" />}\n        onClick={() => onEdit(contactId)}\n        ariaLabel={t.actions.edit}\n      />\n      <Button\n        type=\"outline\"\n        size=\"xs\"\n        iconOnly\n        leftIcon={<Eye className=\"h-4 w-4\" />}\n        onClick={() => onView(contactId)}\n        ariaLabel={t.actions.viewDetail}\n      />\n      <Button\n        type=\"outline\"\n        size=\"xs\"\n        iconOnly\n        leftIcon={<Trash2 className=\"h-4 w-4 text-content-extensions-red\" />}\n        onClick={() => onDelete(contactId)}\n        ariaLabel={t.actions.delete}\n      />\n    </div>\n  )\n}\n","import { useMemo } from 'react'\nimport type { Contact } from '../types/contact.types'\nimport type { EnumOption } from '../types/enum.types'\nimport type { CatalogItem } from '../types/adapter.types'\nimport type { ContactState } from './contactGridUtils'\nimport { STATE_SHADOW_STYLE, formatPhoneForGrid, formatSocialForGrid } from './contactGridUtils'\nimport { getColorForIndex } from '../utils/tagColors'\nimport { ContactRowActions } from './ContactRowActions'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\ninterface ResponsiveContactCardProps {\n  contact: Contact\n  state: ContactState\n  mode: 'edit' | 'view'\n  useForOptions?: EnumOption[]\n  phoneCategoryOptions?: EnumOption[]\n  socialNetworkTypes?: CatalogItem[]\n  onEdit: (id: string) => void\n  onView: (id: string) => void\n  onDelete: (id: string) => void\n  onRestore: (id: string) => void\n}\n\nexport function ResponsiveContactCard({\n  contact,\n  state,\n  mode,\n  useForOptions,\n  phoneCategoryOptions,\n  socialNetworkTypes,\n  onEdit,\n  onView,\n  onDelete,\n  onRestore,\n}: ResponsiveContactCardProps) {\n  const t = useTranslations()\n  const stateStyle = state ? STATE_SHADOW_STYLE[state] : ''\n  const isDeleted = state === 'deleted'\n  const showClassification = (useForOptions?.length ?? 0) > 1\n\n  const socialNetworkLabelMap = useMemo(() => {\n    if (!socialNetworkTypes) return undefined\n    return new Map(socialNetworkTypes.map((snt) => [snt.id, snt.name]))\n  }, [socialNetworkTypes])\n\n  const categoryLabelMap = useMemo(() => {\n    if (!phoneCategoryOptions) return undefined\n    return new Map(phoneCategoryOptions.map((o) => [o.value, o.label]))\n  }, [phoneCategoryOptions])\n\n  return (\n    <div className={`rounded-lg bg-bg-primary p-4 shadow-xs border border-border-secondary dark:bg-dark-bg-primary dark:border-dark-border-primary ${stateStyle} ${isDeleted ? 'opacity-60' : ''}`}>\n      <div className=\"flex items-start justify-between\">\n        <div className=\"min-w-0 flex-1\">\n          <p className={`text-sm font-medium text-content-primary dark:text-dark-content-primary ${isDeleted ? 'line-through' : ''}`}>\n            {contact.name}\n          </p>\n          {showClassification && contact.useFor.length > 0 && (\n            <div className=\"mt-1 flex flex-wrap gap-1\">\n              {contact.useFor.map((useForValue) => {\n                const option = useForOptions!.find((o) => o.value === useForValue)\n                const colorIndex = useForOptions!.findIndex((o) => o.value === useForValue)\n                const color = getColorForIndex(colorIndex >= 0 ? colorIndex : 0)\n                return (\n                  <span\n                    key={useForValue}\n                    className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium ${color.bg} ${color.text} ${color.darkBg} ${color.darkText}`}\n                  >\n                    {option?.label ?? String(useForValue)}\n                  </span>\n                )\n              })}\n            </div>\n          )}\n          {contact.emails.length > 0 && (\n            <div className=\"mt-1 flex items-center gap-1\">\n              <span className=\"inline-block max-w-[180px] truncate rounded-full bg-slate-100 px-2 py-0.5 text-xs text-content-primary dark:bg-slate-800 dark:text-dark-content-primary\">\n                {contact.emails[0]}\n              </span>\n              {contact.emails.length > 1 && (\n                <span className=\"inline-block rounded-full bg-primary-100 px-1.5 py-0.5 text-xs font-medium text-primary-600\">\n                  +{contact.emails.length - 1}\n                </span>\n              )}\n            </div>\n          )}\n          {contact.phones.length > 0 && (\n            <div className=\"mt-2 space-y-0.5\">\n              {contact.phones.map((phone, i) => (\n                <p key={i} className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">\n                  {formatPhoneForGrid(phone, categoryLabelMap)}\n                </p>\n              ))}\n            </div>\n          )}\n          {contact.socialNetworks.length > 0 && (\n            <div className=\"mt-1 space-y-0.5\">\n              {contact.socialNetworks.map((sn, i) => (\n                <p key={i} className=\"text-xs text-content-tertiary dark:text-dark-content-tertiary\">\n                  {formatSocialForGrid(sn, socialNetworkLabelMap, t.grid.socialNetworkNotEnabled)}\n                </p>\n              ))}\n            </div>\n          )}\n        </div>\n        <div className=\"ml-4 flex-shrink-0\">\n          {contact.id != null && (\n            <ContactRowActions\n              contactId={contact.id}\n              mode={mode}\n              isPendingDelete={isDeleted}\n              onEdit={onEdit}\n              onView={onView}\n              onDelete={onDelete}\n              onRestore={onRestore}\n            />\n          )}\n        </div>\n      </div>\n    </div>\n  )\n}\n","import { useMemo, useState } from 'react'\nimport { Plus } from 'lucide-react'\nimport { Button } from '@components/Button/Button'\nimport { Badge } from '@components/Badge/Badge'\nimport { Pagination } from '@components/Pagination/Pagination'\nimport { useContactStore } from '../store/useContactStore'\nimport { useMediaQuery } from '../hooks/useMediaQuery'\nimport { getColorForIndex } from '../utils/tagColors'\nimport { getContactState, formatPhoneForGrid, formatSocialForGrid, STATE_SHADOW_STYLE, DEFAULT_PAGE_SIZE } from './contactGridUtils'\nimport { ContactGridSkeleton } from './ContactGridSkeleton'\nimport { ContactGridEmptyState } from './ContactGridEmptyState'\nimport { ContactRowActions } from './ContactRowActions'\nimport { ResponsiveContactCard } from './ResponsiveContactCard'\nimport type { EnumOption } from '../types/enum.types'\nimport type { CatalogItem } from '../types/adapter.types'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\ninterface ContactGridProps {\n  recordId: string\n  mode: 'edit' | 'view'\n  useForOptions?: EnumOption[]\n  phoneCategoryOptions?: EnumOption[]\n  socialNetworkTypes?: CatalogItem[]\n  isLoading?: boolean\n  onAddContact: () => void\n  onEditContact: (id: string) => void\n  onViewContact: (id: string) => void\n  onDeleteContact: (id: string) => void\n  onRestoreContact: (id: string) => void\n}\n\nfunction EmailPills({ emails }: { emails: string[] }) {\n  if (emails.length === 0) return <span>—</span>\n  return (\n    <span className=\"inline-flex items-center gap-1\">\n      <span className=\"inline-block max-w-[180px] truncate rounded-full bg-slate-100 px-2 py-0.5 text-xs text-content-primary dark:bg-slate-800 dark:text-dark-content-primary\">\n        {emails[0]}\n      </span>\n      {emails.length > 1 && (\n        <Badge color=\"blue\" label={`+${emails.length - 1}`} />\n      )}\n    </span>\n  )\n}\n\nfunction ClassificationBadges({ useFor, useForOptions }: { useFor: number[]; useForOptions: EnumOption[] }) {\n  if (useFor.length === 0) return <span>—</span>\n  const sorted = [...useFor].sort((a, b) => {\n    const idxA = useForOptions.findIndex((o) => o.value === a)\n    const idxB = useForOptions.findIndex((o) => o.value === b)\n    return idxA - idxB\n  })\n  return (\n    <span className=\"flex flex-wrap gap-1\">\n      {sorted.map((useForValue) => {\n        const option = useForOptions.find((o) => o.value === useForValue)\n        const colorIndex = useForOptions.findIndex((o) => o.value === useForValue)\n        const color = getColorForIndex(colorIndex >= 0 ? colorIndex : 0)\n        return (\n          <span\n            key={useForValue}\n            className={`inline-block whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium ${color.bg} ${color.text} ${color.darkBg} ${color.darkText}`}\n          >\n            {option?.label ?? String(useForValue)}\n          </span>\n        )\n      })}\n    </span>\n  )\n}\n\nfunction PhoneCell({ phones, categoryLabelMap }: { phones: { category: number; countryId: string; areaCode: string; number: string; extension: string }[]; categoryLabelMap?: Map<number, string> }) {\n  if (phones.length === 0) return <span>—</span>\n  return (\n    <span className=\"inline-flex items-center gap-1\">\n      <span className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary\">\n        {formatPhoneForGrid(phones[0], categoryLabelMap)}\n      </span>\n      {phones.length > 1 && (\n        <Badge color=\"blue\" label={`+${phones.length - 1}`} />\n      )}\n    </span>\n  )\n}\n\nfunction SocialCell({ socialNetworks, socialNetworkLabelMap, notEnabledLabel }: { socialNetworks: { socialNetworkTypeId: string; url: string }[]; socialNetworkLabelMap?: Map<string, string>; notEnabledLabel: string }) {\n  if (socialNetworks.length === 0) return <span>—</span>\n  return (\n    <span className=\"inline-flex items-center gap-1\">\n      <span className=\"text-sm text-content-tertiary dark:text-dark-content-tertiary\">\n        {formatSocialForGrid(socialNetworks[0], socialNetworkLabelMap, notEnabledLabel)}\n      </span>\n      {socialNetworks.length > 1 && (\n        <Badge color=\"blue\" label={`+${socialNetworks.length - 1}`} />\n      )}\n    </span>\n  )\n}\n\nexport function ContactGrid({\n  recordId,\n  mode,\n  useForOptions,\n  phoneCategoryOptions,\n  socialNetworkTypes,\n  isLoading = false,\n  onAddContact,\n  onEditContact,\n  onViewContact,\n  onDeleteContact,\n  onRestoreContact,\n}: ContactGridProps) {\n  const contacts = useContactStore((s) => s.contacts)\n  const pendingAdds = useContactStore((s) => s.pendingAdds)\n  const pendingEdits = useContactStore((s) => s.pendingEdits)\n  const pendingDeletes = useContactStore((s) => s.pendingDeletes)\n  const t = useTranslations()\n\n  const isTabletOrAbove = useMediaQuery('(min-width: 768px)')\n\n  const showClassification = (useForOptions?.length ?? 0) > 1\n\n  // Pagination state\n  const [currentPage, setCurrentPage] = useState(1)\n  const totalPages = Math.max(1, Math.ceil(contacts.length / DEFAULT_PAGE_SIZE))\n  const paginatedContacts = useMemo(() => {\n    const start = (currentPage - 1) * DEFAULT_PAGE_SIZE\n    return contacts.slice(start, start + DEFAULT_PAGE_SIZE)\n  }, [contacts, currentPage])\n\n  // Reset to page 1 if current page becomes invalid\n  if (currentPage > totalPages && totalPages > 0) {\n    setCurrentPage(1)\n  }\n\n  const socialNetworkLabelMap = useMemo(() => {\n    if (!socialNetworkTypes) return undefined\n    return new Map(socialNetworkTypes.map((snt) => [snt.id, snt.name]))\n  }, [socialNetworkTypes])\n\n  const categoryLabelMap = useMemo(() => {\n    if (!phoneCategoryOptions) return undefined\n    return new Map(phoneCategoryOptions.map((o) => [o.value, o.label]))\n  }, [phoneCategoryOptions])\n\n  return (\n    <div>\n      {/* Header: Add button only — the \"Contacto\" section title was redundant with the tab/page\n          heading the consumer already shows above this component. */}\n      <div className=\"flex items-center justify-end mb-3\">\n        {mode === 'edit' && (\n          <Button\n            type=\"default\"\n            leftIcon={<Plus size={16} />}\n            onClick={onAddContact}\n            disabled={isLoading}\n          >\n            {t.grid.button.addContact}\n          </Button>\n        )}\n      </div>\n\n      {/* Loading state */}\n      {isLoading && <ContactGridSkeleton layout={isTabletOrAbove ? 'table' : 'card'} />}\n\n      {/* Empty state */}\n      {!isLoading && contacts.length === 0 && (\n        <ContactGridEmptyState />\n      )}\n\n      {/* Contact list */}\n      {!isLoading && contacts.length > 0 && (\n        <>\n          {isTabletOrAbove ? (\n            <div className=\"overflow-x-auto\">\n              <table className=\"w-full min-w-[900px]\" aria-label={t.grid.aria.table}>\n                <thead>\n                  {/* text-content-primary — same header color the shared Table component uses\n                      (TableHeader's own span, e.g. ContactModal's phone/social tables). The\n                      previous text-content-secondary (#a1a1aa) read as washed-out/low-contrast. */}\n                  <tr className=\"border-b border-border-primary dark:border-dark-border-primary\">\n                    {showClassification && (\n                      <th scope=\"col\" className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary min-w-[240px]\">{t.grid.column.useFor}</th>\n                    )}\n                    <th scope=\"col\" className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary min-w-[130px]\">{t.grid.column.name}</th>\n                    <th scope=\"col\" className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary min-w-[160px]\">{t.grid.column.email}</th>\n                    <th scope=\"col\" className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary min-w-[180px] whitespace-nowrap\">{t.grid.column.phone}</th>\n                    <th scope=\"col\" className=\"py-3 px-4 text-left text-sm font-semibold text-content-primary dark:text-dark-content-primary min-w-[180px]\">{t.grid.column.socialNetworks}</th>\n                    {/* px-2 (not px-4) + the buttons' own gap-1 (ContactRowActions) — tighter\n                        than before so the column's real rendered width (driven by its 3-icon\n                        row, the widest case) sits close to min-w instead of padding it out\n                        another 16px per side, which is what pushed the row's buttons away\n                        from a now-centered label. */}\n                    <th scope=\"col\" className=\"py-3 px-2 text-center text-sm font-semibold text-content-primary dark:text-dark-content-primary sticky right-0 bg-white dark:bg-dark-bg-primary z-10 min-w-[92px]\">{t.grid.column.actions}</th>\n                  </tr>\n                </thead>\n                <tbody>\n                  {paginatedContacts.map((contact, contactIndex) => {\n                    const state = getContactState(contact, pendingAdds, pendingEdits, pendingDeletes)\n                    const stateStyle = state ? STATE_SHADOW_STYLE[state] : ''\n                    const isDeleted = state === 'deleted'\n                    const groupBg = contactIndex % 2 === 0\n                      ? 'bg-bg-primary dark:bg-dark-bg-primary'\n                      : 'bg-slate-50 dark:bg-slate-900'\n\n                    return (\n                      <tr\n                        key={contact.id ?? contactIndex}\n                        className={`border-b border-border-secondary dark:border-dark-border-primary ${stateStyle} ${groupBg} ${isDeleted ? 'opacity-60' : ''}`}\n                      >\n                        {showClassification && (\n                          <td className=\"py-3 px-4 text-sm\">\n                            <ClassificationBadges useFor={contact.useFor} useForOptions={useForOptions!} />\n                          </td>\n                        )}\n                        <td className={`py-3 px-4 text-sm text-content-primary dark:text-dark-content-primary ${isDeleted ? 'line-through text-content-tertiary dark:text-dark-content-tertiary' : ''}`}>\n                          {contact.name}\n                        </td>\n                        <td className={`py-3 px-4 text-sm text-content-tertiary dark:text-dark-content-tertiary ${isDeleted ? 'line-through' : ''}`}>\n                          <EmailPills emails={contact.emails} />\n                        </td>\n                        <td className={`py-3 px-4 text-sm whitespace-nowrap ${isDeleted ? 'line-through' : ''}`}>\n                          <PhoneCell phones={contact.phones} categoryLabelMap={categoryLabelMap} />\n                        </td>\n                        <td className={`py-3 px-4 text-sm whitespace-nowrap ${isDeleted ? 'line-through' : ''}`}>\n                          <SocialCell socialNetworks={contact.socialNetworks} socialNetworkLabelMap={socialNetworkLabelMap} notEnabledLabel={t.grid.socialNetworkNotEnabled} />\n                        </td>\n                        <td className=\"py-3 px-2 text-center sticky right-0 bg-inherit z-10 shadow-[-2px_0_4px_rgba(0,0,0,0.05)]\">\n                          {contact.id != null && (\n                            <ContactRowActions\n                              contactId={contact.id}\n                              mode={mode}\n                              isPendingDelete={isDeleted}\n                              onEdit={onEditContact}\n                              onView={onViewContact}\n                              onDelete={onDeleteContact}\n                              onRestore={onRestoreContact}\n                            />\n                          )}\n                        </td>\n                      </tr>\n                    )\n                  })}\n                </tbody>\n              </table>\n            </div>\n          ) : (\n            <div className=\"flex flex-col gap-3\">\n              {paginatedContacts.map((contact, index) => {\n                const state = getContactState(contact, pendingAdds, pendingEdits, pendingDeletes)\n                return (\n                  <ResponsiveContactCard\n                    key={contact.id ?? index}\n                    contact={contact}\n                    state={state}\n                    mode={mode}\n                    useForOptions={useForOptions}\n                    phoneCategoryOptions={phoneCategoryOptions}\n                    socialNetworkTypes={socialNetworkTypes}\n                    onEdit={onEditContact}\n                    onView={onViewContact}\n                    onDelete={onDeleteContact}\n                    onRestore={onRestoreContact}\n                  />\n                )\n              })}\n            </div>\n          )}\n\n          {/* Pagination — only worth showing once there's a second page to go to\n              (more than DEFAULT_PAGE_SIZE contacts); a single page of results doesn't need it. */}\n          {totalPages > 1 && (\n            <div className=\"mt-4\">\n              <Pagination\n                currentPage={currentPage}\n                totalPages={totalPages}\n                onPageChange={setCurrentPage}\n                backText={t.grid.pagination.previous}\n                nextText={t.grid.pagination.next}\n                className=\"w-full\"\n              />\n            </div>\n          )}\n        </>\n      )}\n    </div>\n  )\n}\n","import { z } from 'zod'\nimport type { ContactTranslations } from '../i18n/translations.types'\nimport { defaultTranslations } from '../i18n/defaultTranslations'\n\nexport function createContactPhoneSchema(t: ContactTranslations['schema']) {\n  return z.object({\n    category: z.number(),\n    countryId: z.string().min(1, t.phone.countryRequired),\n    areaCode: z.string().max(3, t.phone.areaCodeMaxLength),\n    number: z.string().trim().min(1, t.phone.numberRequired).max(10, t.phone.numberMaxLength),\n    extension: z.string().max(3, t.phone.extensionMaxLength),\n  })\n}\n\nexport function createContactSocialNetworkSchema(t: ContactTranslations['schema']) {\n  return z.object({\n    socialNetworkTypeId: z.string().min(1, t.socialNetwork.typeRequired),\n    url: z.string().trim().min(1, t.socialNetwork.urlRequired).max(2048, t.socialNetwork.urlMaxLength),\n  })\n}\n\nexport function createContactSchema(t: ContactTranslations['schema'], options?: { requireClassification?: boolean }) {\n  const emailItemSchema = z\n    .string()\n    .email(t.email.invalidFormat)\n    .max(256, t.email.maxLength)\n\n  const useForSchema = options?.requireClassification\n    ? z.array(z.number()).min(1, t.useFor.required)\n    : z.array(z.number())\n\n  return z.object({\n    name: z.string().trim().min(1, t.name.required).max(200, t.name.maxLength),\n    emails: z.array(emailItemSchema),\n    address: z.string().max(500, t.address.maxLength).nullable(),\n    description: z.string().nullable(),\n    cityId: z.string().nullable().optional(),\n    neighborhoodId: z.string().nullable().optional(),\n    useFor: useForSchema,\n    phones: z.array(createContactPhoneSchema(t)),\n    socialNetworks: z.array(createContactSocialNetworkSchema(t)),\n  })\n}\n\n// Backward-compatible module-level exports (default Spanish)\nconst _defaultSchema = defaultTranslations.schema\nexport const contactPhoneSchema = createContactPhoneSchema(_defaultSchema)\nexport const contactSocialNetworkSchema = createContactSocialNetworkSchema(_defaultSchema)\nexport const contactSchema = createContactSchema(_defaultSchema)\nexport type ContactFormData = z.infer<typeof contactSchema>\n","// packages/react/use-escape-keydown/src/use-escape-keydown.tsx\nimport * as React from \"react\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nfunction useEscapeKeydown(onEscapeKeyDownProp, ownerDocument = globalThis?.document) {\n  const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp);\n  React.useEffect(() => {\n    const handleKeyDown = (event) => {\n      if (event.key === \"Escape\") {\n        onEscapeKeyDown(event);\n      }\n    };\n    ownerDocument.addEventListener(\"keydown\", handleKeyDown, { capture: true });\n    return () => ownerDocument.removeEventListener(\"keydown\", handleKeyDown, { capture: true });\n  }, [onEscapeKeyDown, ownerDocument]);\n}\nexport {\n  useEscapeKeydown\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/dismissable-layer.tsx\nimport * as React from \"react\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { Primitive, dispatchDiscreteCustomEvent } from \"@radix-ui/react-primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { jsx } from \"react/jsx-runtime\";\nvar DISMISSABLE_LAYER_NAME = \"DismissableLayer\";\nvar CONTEXT_UPDATE = \"dismissableLayer.update\";\nvar POINTER_DOWN_OUTSIDE = \"dismissableLayer.pointerDownOutside\";\nvar FOCUS_OUTSIDE = \"dismissableLayer.focusOutside\";\nvar originalBodyPointerEvents;\nvar DismissableLayerContext = React.createContext({\n  layers: /* @__PURE__ */ new Set(),\n  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),\n  branches: /* @__PURE__ */ new Set()\n});\nvar DismissableLayer = React.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      disableOutsidePointerEvents = false,\n      onEscapeKeyDown,\n      onPointerDownOutside,\n      onFocusOutside,\n      onInteractOutside,\n      onDismiss,\n      ...layerProps\n    } = props;\n    const context = React.useContext(DismissableLayerContext);\n    const [node, setNode] = React.useState(null);\n    const ownerDocument = node?.ownerDocument ?? globalThis?.document;\n    const [, force] = React.useState({});\n    const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2));\n    const layers = Array.from(context.layers);\n    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);\n    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);\n    const index = node ? layers.indexOf(node) : -1;\n    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;\n    const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex;\n    const pointerDownOutside = usePointerDownOutside((event) => {\n      const target = event.target;\n      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));\n      if (!isPointerEventsEnabled || isPointerDownOnBranch) return;\n      onPointerDownOutside?.(event);\n      onInteractOutside?.(event);\n      if (!event.defaultPrevented) onDismiss?.();\n    }, ownerDocument);\n    const focusOutside = useFocusOutside((event) => {\n      const target = event.target;\n      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));\n      if (isFocusInBranch) return;\n      onFocusOutside?.(event);\n      onInteractOutside?.(event);\n      if (!event.defaultPrevented) onDismiss?.();\n    }, ownerDocument);\n    useEscapeKeydown((event) => {\n      const isHighestLayer = index === context.layers.size - 1;\n      if (!isHighestLayer) return;\n      onEscapeKeyDown?.(event);\n      if (!event.defaultPrevented && onDismiss) {\n        event.preventDefault();\n        onDismiss();\n      }\n    }, ownerDocument);\n    React.useEffect(() => {\n      if (!node) return;\n      if (disableOutsidePointerEvents) {\n        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {\n          originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;\n          ownerDocument.body.style.pointerEvents = \"none\";\n        }\n        context.layersWithOutsidePointerEventsDisabled.add(node);\n      }\n      context.layers.add(node);\n      dispatchUpdate();\n      return () => {\n        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {\n          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents;\n        }\n      };\n    }, [node, ownerDocument, disableOutsidePointerEvents, context]);\n    React.useEffect(() => {\n      return () => {\n        if (!node) return;\n        context.layers.delete(node);\n        context.layersWithOutsidePointerEventsDisabled.delete(node);\n        dispatchUpdate();\n      };\n    }, [node, context]);\n    React.useEffect(() => {\n      const handleUpdate = () => force({});\n      document.addEventListener(CONTEXT_UPDATE, handleUpdate);\n      return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate);\n    }, []);\n    return /* @__PURE__ */ jsx(\n      Primitive.div,\n      {\n        ...layerProps,\n        ref: composedRefs,\n        style: {\n          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? \"auto\" : \"none\" : void 0,\n          ...props.style\n        },\n        onFocusCapture: composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture),\n        onBlurCapture: composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture),\n        onPointerDownCapture: composeEventHandlers(\n          props.onPointerDownCapture,\n          pointerDownOutside.onPointerDownCapture\n        )\n      }\n    );\n  }\n);\nDismissableLayer.displayName = DISMISSABLE_LAYER_NAME;\nvar BRANCH_NAME = \"DismissableLayerBranch\";\nvar DismissableLayerBranch = React.forwardRef((props, forwardedRef) => {\n  const context = React.useContext(DismissableLayerContext);\n  const ref = React.useRef(null);\n  const composedRefs = useComposedRefs(forwardedRef, ref);\n  React.useEffect(() => {\n    const node = ref.current;\n    if (node) {\n      context.branches.add(node);\n      return () => {\n        context.branches.delete(node);\n      };\n    }\n  }, [context.branches]);\n  return /* @__PURE__ */ jsx(Primitive.div, { ...props, ref: composedRefs });\n});\nDismissableLayerBranch.displayName = BRANCH_NAME;\nfunction usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis?.document) {\n  const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);\n  const isPointerInsideReactTreeRef = React.useRef(false);\n  const handleClickRef = React.useRef(() => {\n  });\n  React.useEffect(() => {\n    const handlePointerDown = (event) => {\n      if (event.target && !isPointerInsideReactTreeRef.current) {\n        let handleAndDispatchPointerDownOutsideEvent2 = function() {\n          handleAndDispatchCustomEvent(\n            POINTER_DOWN_OUTSIDE,\n            handlePointerDownOutside,\n            eventDetail,\n            { discrete: true }\n          );\n        };\n        var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2;\n        const eventDetail = { originalEvent: event };\n        if (event.pointerType === \"touch\") {\n          ownerDocument.removeEventListener(\"click\", handleClickRef.current);\n          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;\n          ownerDocument.addEventListener(\"click\", handleClickRef.current, { once: true });\n        } else {\n          handleAndDispatchPointerDownOutsideEvent2();\n        }\n      } else {\n        ownerDocument.removeEventListener(\"click\", handleClickRef.current);\n      }\n      isPointerInsideReactTreeRef.current = false;\n    };\n    const timerId = window.setTimeout(() => {\n      ownerDocument.addEventListener(\"pointerdown\", handlePointerDown);\n    }, 0);\n    return () => {\n      window.clearTimeout(timerId);\n      ownerDocument.removeEventListener(\"pointerdown\", handlePointerDown);\n      ownerDocument.removeEventListener(\"click\", handleClickRef.current);\n    };\n  }, [ownerDocument, handlePointerDownOutside]);\n  return {\n    // ensures we check React component tree (not just DOM tree)\n    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true\n  };\n}\nfunction useFocusOutside(onFocusOutside, ownerDocument = globalThis?.document) {\n  const handleFocusOutside = useCallbackRef(onFocusOutside);\n  const isFocusInsideReactTreeRef = React.useRef(false);\n  React.useEffect(() => {\n    const handleFocus = (event) => {\n      if (event.target && !isFocusInsideReactTreeRef.current) {\n        const eventDetail = { originalEvent: event };\n        handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {\n          discrete: false\n        });\n      }\n    };\n    ownerDocument.addEventListener(\"focusin\", handleFocus);\n    return () => ownerDocument.removeEventListener(\"focusin\", handleFocus);\n  }, [ownerDocument, handleFocusOutside]);\n  return {\n    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,\n    onBlurCapture: () => isFocusInsideReactTreeRef.current = false\n  };\n}\nfunction dispatchUpdate() {\n  const event = new CustomEvent(CONTEXT_UPDATE);\n  document.dispatchEvent(event);\n}\nfunction handleAndDispatchCustomEvent(name, handler, detail, { discrete }) {\n  const target = detail.originalEvent.target;\n  const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });\n  if (handler) target.addEventListener(name, handler, { once: true });\n  if (discrete) {\n    dispatchDiscreteCustomEvent(target, event);\n  } else {\n    target.dispatchEvent(event);\n  }\n}\nvar Root = DismissableLayer;\nvar Branch = DismissableLayerBranch;\nexport {\n  Branch,\n  DismissableLayer,\n  DismissableLayerBranch,\n  Root\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/focus-scope.tsx\nimport * as React from \"react\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { jsx } from \"react/jsx-runtime\";\nvar AUTOFOCUS_ON_MOUNT = \"focusScope.autoFocusOnMount\";\nvar AUTOFOCUS_ON_UNMOUNT = \"focusScope.autoFocusOnUnmount\";\nvar EVENT_OPTIONS = { bubbles: false, cancelable: true };\nvar FOCUS_SCOPE_NAME = \"FocusScope\";\nvar FocusScope = React.forwardRef((props, forwardedRef) => {\n  const {\n    loop = false,\n    trapped = false,\n    onMountAutoFocus: onMountAutoFocusProp,\n    onUnmountAutoFocus: onUnmountAutoFocusProp,\n    ...scopeProps\n  } = props;\n  const [container, setContainer] = React.useState(null);\n  const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n  const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n  const lastFocusedElementRef = React.useRef(null);\n  const composedRefs = useComposedRefs(forwardedRef, (node) => setContainer(node));\n  const focusScope = React.useRef({\n    paused: false,\n    pause() {\n      this.paused = true;\n    },\n    resume() {\n      this.paused = false;\n    }\n  }).current;\n  React.useEffect(() => {\n    if (trapped) {\n      let handleFocusIn2 = function(event) {\n        if (focusScope.paused || !container) return;\n        const target = event.target;\n        if (container.contains(target)) {\n          lastFocusedElementRef.current = target;\n        } else {\n          focus(lastFocusedElementRef.current, { select: true });\n        }\n      }, handleFocusOut2 = function(event) {\n        if (focusScope.paused || !container) return;\n        const relatedTarget = event.relatedTarget;\n        if (relatedTarget === null) return;\n        if (!container.contains(relatedTarget)) {\n          focus(lastFocusedElementRef.current, { select: true });\n        }\n      }, handleMutations2 = function(mutations) {\n        const focusedElement = document.activeElement;\n        if (focusedElement !== document.body) return;\n        for (const mutation of mutations) {\n          if (mutation.removedNodes.length > 0) focus(container);\n        }\n      };\n      var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;\n      document.addEventListener(\"focusin\", handleFocusIn2);\n      document.addEventListener(\"focusout\", handleFocusOut2);\n      const mutationObserver = new MutationObserver(handleMutations2);\n      if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n      return () => {\n        document.removeEventListener(\"focusin\", handleFocusIn2);\n        document.removeEventListener(\"focusout\", handleFocusOut2);\n        mutationObserver.disconnect();\n      };\n    }\n  }, [trapped, container, focusScope.paused]);\n  React.useEffect(() => {\n    if (container) {\n      focusScopesStack.add(focusScope);\n      const previouslyFocusedElement = document.activeElement;\n      const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n      if (!hasFocusedCandidate) {\n        const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n        container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n        container.dispatchEvent(mountEvent);\n        if (!mountEvent.defaultPrevented) {\n          focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n          if (document.activeElement === previouslyFocusedElement) {\n            focus(container);\n          }\n        }\n      }\n      return () => {\n        container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n        setTimeout(() => {\n          const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n          container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n          container.dispatchEvent(unmountEvent);\n          if (!unmountEvent.defaultPrevented) {\n            focus(previouslyFocusedElement ?? document.body, { select: true });\n          }\n          container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n          focusScopesStack.remove(focusScope);\n        }, 0);\n      };\n    }\n  }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n  const handleKeyDown = React.useCallback(\n    (event) => {\n      if (!loop && !trapped) return;\n      if (focusScope.paused) return;\n      const isTabKey = event.key === \"Tab\" && !event.altKey && !event.ctrlKey && !event.metaKey;\n      const focusedElement = document.activeElement;\n      if (isTabKey && focusedElement) {\n        const container2 = event.currentTarget;\n        const [first, last] = getTabbableEdges(container2);\n        const hasTabbableElementsInside = first && last;\n        if (!hasTabbableElementsInside) {\n          if (focusedElement === container2) event.preventDefault();\n        } else {\n          if (!event.shiftKey && focusedElement === last) {\n            event.preventDefault();\n            if (loop) focus(first, { select: true });\n          } else if (event.shiftKey && focusedElement === first) {\n            event.preventDefault();\n            if (loop) focus(last, { select: true });\n          }\n        }\n      }\n    },\n    [loop, trapped, focusScope.paused]\n  );\n  return /* @__PURE__ */ jsx(Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });\n});\nFocusScope.displayName = FOCUS_SCOPE_NAME;\nfunction focusFirst(candidates, { select = false } = {}) {\n  const previouslyFocusedElement = document.activeElement;\n  for (const candidate of candidates) {\n    focus(candidate, { select });\n    if (document.activeElement !== previouslyFocusedElement) return;\n  }\n}\nfunction getTabbableEdges(container) {\n  const candidates = getTabbableCandidates(container);\n  const first = findVisible(candidates, container);\n  const last = findVisible(candidates.reverse(), container);\n  return [first, last];\n}\nfunction getTabbableCandidates(container) {\n  const nodes = [];\n  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n    acceptNode: (node) => {\n      const isHiddenInput = node.tagName === \"INPUT\" && node.type === \"hidden\";\n      if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;\n      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;\n    }\n  });\n  while (walker.nextNode()) nodes.push(walker.currentNode);\n  return nodes;\n}\nfunction findVisible(elements, container) {\n  for (const element of elements) {\n    if (!isHidden(element, { upTo: container })) return element;\n  }\n}\nfunction isHidden(node, { upTo }) {\n  if (getComputedStyle(node).visibility === \"hidden\") return true;\n  while (node) {\n    if (upTo !== void 0 && node === upTo) return false;\n    if (getComputedStyle(node).display === \"none\") return true;\n    node = node.parentElement;\n  }\n  return false;\n}\nfunction isSelectableInput(element) {\n  return element instanceof HTMLInputElement && \"select\" in element;\n}\nfunction focus(element, { select = false } = {}) {\n  if (element && element.focus) {\n    const previouslyFocusedElement = document.activeElement;\n    element.focus({ preventScroll: true });\n    if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n      element.select();\n  }\n}\nvar focusScopesStack = createFocusScopesStack();\nfunction createFocusScopesStack() {\n  let stack = [];\n  return {\n    add(focusScope) {\n      const activeFocusScope = stack[0];\n      if (focusScope !== activeFocusScope) {\n        activeFocusScope?.pause();\n      }\n      stack = arrayRemove(stack, focusScope);\n      stack.unshift(focusScope);\n    },\n    remove(focusScope) {\n      stack = arrayRemove(stack, focusScope);\n      stack[0]?.resume();\n    }\n  };\n}\nfunction arrayRemove(array, item) {\n  const updatedArray = [...array];\n  const index = updatedArray.indexOf(item);\n  if (index !== -1) {\n    updatedArray.splice(index, 1);\n  }\n  return updatedArray;\n}\nfunction removeLinks(items) {\n  return items.filter((item) => item.tagName !== \"A\");\n}\nvar Root = FocusScope;\nexport {\n  FocusScope,\n  Root\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/portal.tsx\nimport * as React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { useLayoutEffect } from \"@radix-ui/react-use-layout-effect\";\nimport { jsx } from \"react/jsx-runtime\";\nvar PORTAL_NAME = \"Portal\";\nvar Portal = React.forwardRef((props, forwardedRef) => {\n  const { container: containerProp, ...portalProps } = props;\n  const [mounted, setMounted] = React.useState(false);\n  useLayoutEffect(() => setMounted(true), []);\n  const container = containerProp || mounted && globalThis?.document?.body;\n  return container ? ReactDOM.createPortal(/* @__PURE__ */ jsx(Primitive.div, { ...portalProps, ref: forwardedRef }), container) : null;\n});\nPortal.displayName = PORTAL_NAME;\nvar Root = Portal;\nexport {\n  Portal,\n  Root\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/focus-guards.tsx\nimport * as React from \"react\";\nvar count = 0;\nfunction FocusGuards(props) {\n  useFocusGuards();\n  return props.children;\n}\nfunction useFocusGuards() {\n  React.useEffect(() => {\n    const edgeGuards = document.querySelectorAll(\"[data-radix-focus-guard]\");\n    document.body.insertAdjacentElement(\"afterbegin\", edgeGuards[0] ?? createFocusGuard());\n    document.body.insertAdjacentElement(\"beforeend\", edgeGuards[1] ?? createFocusGuard());\n    count++;\n    return () => {\n      if (count === 1) {\n        document.querySelectorAll(\"[data-radix-focus-guard]\").forEach((node) => node.remove());\n      }\n      count--;\n    };\n  }, []);\n}\nfunction createFocusGuard() {\n  const element = document.createElement(\"span\");\n  element.setAttribute(\"data-radix-focus-guard\", \"\");\n  element.tabIndex = 0;\n  element.style.outline = \"none\";\n  element.style.opacity = \"0\";\n  element.style.position = \"fixed\";\n  element.style.pointerEvents = \"none\";\n  return element;\n}\nexport {\n  FocusGuards,\n  FocusGuards as Root,\n  useFocusGuards\n};\n//# sourceMappingURL=index.mjs.map\n","export var zeroRightClassName = 'right-scroll-bar-position';\nexport var fullWidthClassName = 'width-before-scroll-bar';\nexport var noScrollbarsClassName = 'with-scroll-bars-hidden';\n/**\n * Name of a CSS variable containing the amount of \"hidden\" scrollbar\n * ! might be undefined ! use will fallback!\n */\nexport var removedBarSizeVariable = '--removed-body-scroll-bar-size';\n","/**\n * Assigns a value for a given ref, no matter of the ref format\n * @param {RefObject} ref - a callback function or ref object\n * @param value - a new value\n *\n * @see https://github.com/theKashey/use-callback-ref#assignref\n * @example\n * const refObject = useRef();\n * const refFn = (ref) => {....}\n *\n * assignRef(refObject, \"refValue\");\n * assignRef(refFn, \"refValue\");\n */\nexport function assignRef(ref, value) {\n    if (typeof ref === 'function') {\n        ref(value);\n    }\n    else if (ref) {\n        ref.current = value;\n    }\n    return ref;\n}\n","import { useState } from 'react';\n/**\n * creates a MutableRef with ref change callback\n * @param initialValue - initial ref value\n * @param {Function} callback - a callback to run when value changes\n *\n * @example\n * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue);\n * ref.current = 1;\n * // prints 0 -> 1\n *\n * @see https://reactjs.org/docs/hooks-reference.html#useref\n * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref\n * @returns {MutableRefObject}\n */\nexport function useCallbackRef(initialValue, callback) {\n    var ref = useState(function () { return ({\n        // value\n        value: initialValue,\n        // last callback\n        callback: callback,\n        // \"memoized\" public interface\n        facade: {\n            get current() {\n                return ref.value;\n            },\n            set current(value) {\n                var last = ref.value;\n                if (last !== value) {\n                    ref.value = value;\n                    ref.callback(value, last);\n                }\n            },\n        },\n    }); })[0];\n    // update callback\n    ref.callback = callback;\n    return ref.facade;\n}\n","import * as React from 'react';\nimport { assignRef } from './assignRef';\nimport { useCallbackRef } from './useRef';\nvar useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\nvar currentValues = new WeakMap();\n/**\n * Merges two or more refs together providing a single interface to set their value\n * @param {RefObject|Ref} refs\n * @returns {MutableRefObject} - a new ref, which translates all changes to {refs}\n *\n * @see {@link mergeRefs} a version without buit-in memoization\n * @see https://github.com/theKashey/use-callback-ref#usemergerefs\n * @example\n * const Component = React.forwardRef((props, ref) => {\n *   const ownRef = useRef();\n *   const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together\n *   return <div ref={domRef}>...</div>\n * }\n */\nexport function useMergeRefs(refs, defaultValue) {\n    var callbackRef = useCallbackRef(defaultValue || null, function (newValue) {\n        return refs.forEach(function (ref) { return assignRef(ref, newValue); });\n    });\n    // handle refs changes - added or removed\n    useIsomorphicLayoutEffect(function () {\n        var oldValue = currentValues.get(callbackRef);\n        if (oldValue) {\n            var prevRefs_1 = new Set(oldValue);\n            var nextRefs_1 = new Set(refs);\n            var current_1 = callbackRef.current;\n            prevRefs_1.forEach(function (ref) {\n                if (!nextRefs_1.has(ref)) {\n                    assignRef(ref, null);\n                }\n            });\n            nextRefs_1.forEach(function (ref) {\n                if (!prevRefs_1.has(ref)) {\n                    assignRef(ref, current_1);\n                }\n            });\n        }\n        currentValues.set(callbackRef, refs);\n    }, [refs]);\n    return callbackRef;\n}\n","import { __assign } from \"tslib\";\nfunction ItoI(a) {\n    return a;\n}\nfunction innerCreateMedium(defaults, middleware) {\n    if (middleware === void 0) { middleware = ItoI; }\n    var buffer = [];\n    var assigned = false;\n    var medium = {\n        read: function () {\n            if (assigned) {\n                throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.');\n            }\n            if (buffer.length) {\n                return buffer[buffer.length - 1];\n            }\n            return defaults;\n        },\n        useMedium: function (data) {\n            var item = middleware(data, assigned);\n            buffer.push(item);\n            return function () {\n                buffer = buffer.filter(function (x) { return x !== item; });\n            };\n        },\n        assignSyncMedium: function (cb) {\n            assigned = true;\n            while (buffer.length) {\n                var cbs = buffer;\n                buffer = [];\n                cbs.forEach(cb);\n            }\n            buffer = {\n                push: function (x) { return cb(x); },\n                filter: function () { return buffer; },\n            };\n        },\n        assignMedium: function (cb) {\n            assigned = true;\n            var pendingQueue = [];\n            if (buffer.length) {\n                var cbs = buffer;\n                buffer = [];\n                cbs.forEach(cb);\n                pendingQueue = buffer;\n            }\n            var executeQueue = function () {\n                var cbs = pendingQueue;\n                pendingQueue = [];\n                cbs.forEach(cb);\n            };\n            var cycle = function () { return Promise.resolve().then(executeQueue); };\n            cycle();\n            buffer = {\n                push: function (x) {\n                    pendingQueue.push(x);\n                    cycle();\n                },\n                filter: function (filter) {\n                    pendingQueue = pendingQueue.filter(filter);\n                    return buffer;\n                },\n            };\n        },\n    };\n    return medium;\n}\nexport function createMedium(defaults, middleware) {\n    if (middleware === void 0) { middleware = ItoI; }\n    return innerCreateMedium(defaults, middleware);\n}\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function createSidecarMedium(options) {\n    if (options === void 0) { options = {}; }\n    var medium = innerCreateMedium(null);\n    medium.options = __assign({ async: true, ssr: false }, options);\n    return medium;\n}\n","import { __assign, __rest } from \"tslib\";\nimport * as React from 'react';\nvar SideCar = function (_a) {\n    var sideCar = _a.sideCar, rest = __rest(_a, [\"sideCar\"]);\n    if (!sideCar) {\n        throw new Error('Sidecar: please provide `sideCar` property to import the right car');\n    }\n    var Target = sideCar.read();\n    if (!Target) {\n        throw new Error('Sidecar medium not found');\n    }\n    return React.createElement(Target, __assign({}, rest));\n};\nSideCar.isSideCarExport = true;\nexport function exportSidecar(medium, exported) {\n    medium.useMedium(exported);\n    return SideCar;\n}\n","import { createSidecarMedium } from 'use-sidecar';\nexport var effectCar = createSidecarMedium();\n","import { __assign, __rest } from \"tslib\";\nimport * as React from 'react';\nimport { fullWidthClassName, zeroRightClassName } from 'react-remove-scroll-bar/constants';\nimport { useMergeRefs } from 'use-callback-ref';\nimport { effectCar } from './medium';\nvar nothing = function () {\n    return;\n};\n/**\n * Removes scrollbar from the page and contain the scroll within the Lock\n */\nvar RemoveScroll = React.forwardRef(function (props, parentRef) {\n    var ref = React.useRef(null);\n    var _a = React.useState({\n        onScrollCapture: nothing,\n        onWheelCapture: nothing,\n        onTouchMoveCapture: nothing,\n    }), callbacks = _a[0], setCallbacks = _a[1];\n    var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noRelative = props.noRelative, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? 'div' : _b, gapMode = props.gapMode, rest = __rest(props, [\"forwardProps\", \"children\", \"className\", \"removeScrollBar\", \"enabled\", \"shards\", \"sideCar\", \"noRelative\", \"noIsolation\", \"inert\", \"allowPinchZoom\", \"as\", \"gapMode\"]);\n    var SideCar = sideCar;\n    var containerRef = useMergeRefs([ref, parentRef]);\n    var containerProps = __assign(__assign({}, rest), callbacks);\n    return (React.createElement(React.Fragment, null,\n        enabled && (React.createElement(SideCar, { sideCar: effectCar, removeScrollBar: removeScrollBar, shards: shards, noRelative: noRelative, noIsolation: noIsolation, inert: inert, setCallbacks: setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode: gapMode })),\n        forwardProps ? (React.cloneElement(React.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef }))) : (React.createElement(Container, __assign({}, containerProps, { className: className, ref: containerRef }), children))));\n});\nRemoveScroll.defaultProps = {\n    enabled: true,\n    removeScrollBar: true,\n    inert: false,\n};\nRemoveScroll.classNames = {\n    fullWidth: fullWidthClassName,\n    zeroRight: zeroRightClassName,\n};\nexport { RemoveScroll };\n","var currentNonce;\nexport var setNonce = function (nonce) {\n    currentNonce = nonce;\n};\nexport var getNonce = function () {\n    if (currentNonce) {\n        return currentNonce;\n    }\n    if (typeof __webpack_nonce__ !== 'undefined') {\n        return __webpack_nonce__;\n    }\n    return undefined;\n};\n","import { getNonce } from 'get-nonce';\nfunction makeStyleTag() {\n    if (!document)\n        return null;\n    var tag = document.createElement('style');\n    tag.type = 'text/css';\n    var nonce = getNonce();\n    if (nonce) {\n        tag.setAttribute('nonce', nonce);\n    }\n    return tag;\n}\nfunction injectStyles(tag, css) {\n    // @ts-ignore\n    if (tag.styleSheet) {\n        // @ts-ignore\n        tag.styleSheet.cssText = css;\n    }\n    else {\n        tag.appendChild(document.createTextNode(css));\n    }\n}\nfunction insertStyleTag(tag) {\n    var head = document.head || document.getElementsByTagName('head')[0];\n    head.appendChild(tag);\n}\nexport var stylesheetSingleton = function () {\n    var counter = 0;\n    var stylesheet = null;\n    return {\n        add: function (style) {\n            if (counter == 0) {\n                if ((stylesheet = makeStyleTag())) {\n                    injectStyles(stylesheet, style);\n                    insertStyleTag(stylesheet);\n                }\n            }\n            counter++;\n        },\n        remove: function () {\n            counter--;\n            if (!counter && stylesheet) {\n                stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);\n                stylesheet = null;\n            }\n        },\n    };\n};\n","import * as React from 'react';\nimport { stylesheetSingleton } from './singleton';\n/**\n * creates a hook to control style singleton\n * @see {@link styleSingleton} for a safer component version\n * @example\n * ```tsx\n * const useStyle = styleHookSingleton();\n * ///\n * useStyle('body { overflow: hidden}');\n */\nexport var styleHookSingleton = function () {\n    var sheet = stylesheetSingleton();\n    return function (styles, isDynamic) {\n        React.useEffect(function () {\n            sheet.add(styles);\n            return function () {\n                sheet.remove();\n            };\n        }, [styles && isDynamic]);\n    };\n};\n","import { styleHookSingleton } from './hook';\n/**\n * create a Component to add styles on demand\n * - styles are added when first instance is mounted\n * - styles are removed when the last instance is unmounted\n * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior\n */\nexport var styleSingleton = function () {\n    var useStyle = styleHookSingleton();\n    var Sheet = function (_a) {\n        var styles = _a.styles, dynamic = _a.dynamic;\n        useStyle(styles, dynamic);\n        return null;\n    };\n    return Sheet;\n};\n","export var zeroGap = {\n    left: 0,\n    top: 0,\n    right: 0,\n    gap: 0,\n};\nvar parse = function (x) { return parseInt(x || '', 10) || 0; };\nvar getOffset = function (gapMode) {\n    var cs = window.getComputedStyle(document.body);\n    var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft'];\n    var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop'];\n    var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight'];\n    return [parse(left), parse(top), parse(right)];\n};\nexport var getGapWidth = function (gapMode) {\n    if (gapMode === void 0) { gapMode = 'margin'; }\n    if (typeof window === 'undefined') {\n        return zeroGap;\n    }\n    var offsets = getOffset(gapMode);\n    var documentWidth = document.documentElement.clientWidth;\n    var windowWidth = window.innerWidth;\n    return {\n        left: offsets[0],\n        top: offsets[1],\n        right: offsets[2],\n        gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]),\n    };\n};\n","import * as React from 'react';\nimport { styleSingleton } from 'react-style-singleton';\nimport { fullWidthClassName, zeroRightClassName, noScrollbarsClassName, removedBarSizeVariable } from './constants';\nimport { getGapWidth } from './utils';\nvar Style = styleSingleton();\nexport var lockAttribute = 'data-scroll-locked';\n// important tip - once we measure scrollBar width and remove them\n// we could not repeat this operation\n// thus we are using style-singleton - only the first \"yet correct\" style will be applied.\nvar getStyles = function (_a, allowRelative, gapMode, important) {\n    var left = _a.left, top = _a.top, right = _a.right, gap = _a.gap;\n    if (gapMode === void 0) { gapMode = 'margin'; }\n    return \"\\n  .\".concat(noScrollbarsClassName, \" {\\n   overflow: hidden \").concat(important, \";\\n   padding-right: \").concat(gap, \"px \").concat(important, \";\\n  }\\n  body[\").concat(lockAttribute, \"] {\\n    overflow: hidden \").concat(important, \";\\n    overscroll-behavior: contain;\\n    \").concat([\n        allowRelative && \"position: relative \".concat(important, \";\"),\n        gapMode === 'margin' &&\n            \"\\n    padding-left: \".concat(left, \"px;\\n    padding-top: \").concat(top, \"px;\\n    padding-right: \").concat(right, \"px;\\n    margin-left:0;\\n    margin-top:0;\\n    margin-right: \").concat(gap, \"px \").concat(important, \";\\n    \"),\n        gapMode === 'padding' && \"padding-right: \".concat(gap, \"px \").concat(important, \";\"),\n    ]\n        .filter(Boolean)\n        .join(''), \"\\n  }\\n  \\n  .\").concat(zeroRightClassName, \" {\\n    right: \").concat(gap, \"px \").concat(important, \";\\n  }\\n  \\n  .\").concat(fullWidthClassName, \" {\\n    margin-right: \").concat(gap, \"px \").concat(important, \";\\n  }\\n  \\n  .\").concat(zeroRightClassName, \" .\").concat(zeroRightClassName, \" {\\n    right: 0 \").concat(important, \";\\n  }\\n  \\n  .\").concat(fullWidthClassName, \" .\").concat(fullWidthClassName, \" {\\n    margin-right: 0 \").concat(important, \";\\n  }\\n  \\n  body[\").concat(lockAttribute, \"] {\\n    \").concat(removedBarSizeVariable, \": \").concat(gap, \"px;\\n  }\\n\");\n};\nvar getCurrentUseCounter = function () {\n    var counter = parseInt(document.body.getAttribute(lockAttribute) || '0', 10);\n    return isFinite(counter) ? counter : 0;\n};\nexport var useLockAttribute = function () {\n    React.useEffect(function () {\n        document.body.setAttribute(lockAttribute, (getCurrentUseCounter() + 1).toString());\n        return function () {\n            var newCounter = getCurrentUseCounter() - 1;\n            if (newCounter <= 0) {\n                document.body.removeAttribute(lockAttribute);\n            }\n            else {\n                document.body.setAttribute(lockAttribute, newCounter.toString());\n            }\n        };\n    }, []);\n};\n/**\n * Removes page scrollbar and blocks page scroll when mounted\n */\nexport var RemoveScrollBar = function (_a) {\n    var noRelative = _a.noRelative, noImportant = _a.noImportant, _b = _a.gapMode, gapMode = _b === void 0 ? 'margin' : _b;\n    useLockAttribute();\n    /*\n     gap will be measured on every component mount\n     however it will be used only by the \"first\" invocation\n     due to singleton nature of <Style\n     */\n    var gap = React.useMemo(function () { return getGapWidth(gapMode); }, [gapMode]);\n    return React.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') });\n};\n","var passiveSupported = false;\nif (typeof window !== 'undefined') {\n    try {\n        var options = Object.defineProperty({}, 'passive', {\n            get: function () {\n                passiveSupported = true;\n                return true;\n            },\n        });\n        // @ts-ignore\n        window.addEventListener('test', options, options);\n        // @ts-ignore\n        window.removeEventListener('test', options, options);\n    }\n    catch (err) {\n        passiveSupported = false;\n    }\n}\nexport var nonPassive = passiveSupported ? { passive: false } : false;\n","var alwaysContainsScroll = function (node) {\n    // textarea will always _contain_ scroll inside self. It only can be hidden\n    return node.tagName === 'TEXTAREA';\n};\nvar elementCanBeScrolled = function (node, overflow) {\n    if (!(node instanceof Element)) {\n        return false;\n    }\n    var styles = window.getComputedStyle(node);\n    return (\n    // not-not-scrollable\n    styles[overflow] !== 'hidden' &&\n        // contains scroll inside self\n        !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible'));\n};\nvar elementCouldBeVScrolled = function (node) { return elementCanBeScrolled(node, 'overflowY'); };\nvar elementCouldBeHScrolled = function (node) { return elementCanBeScrolled(node, 'overflowX'); };\nexport var locationCouldBeScrolled = function (axis, node) {\n    var ownerDocument = node.ownerDocument;\n    var current = node;\n    do {\n        // Skip over shadow root\n        if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) {\n            current = current.host;\n        }\n        var isScrollable = elementCouldBeScrolled(axis, current);\n        if (isScrollable) {\n            var _a = getScrollVariables(axis, current), scrollHeight = _a[1], clientHeight = _a[2];\n            if (scrollHeight > clientHeight) {\n                return true;\n            }\n        }\n        current = current.parentNode;\n    } while (current && current !== ownerDocument.body);\n    return false;\n};\nvar getVScrollVariables = function (_a) {\n    var scrollTop = _a.scrollTop, scrollHeight = _a.scrollHeight, clientHeight = _a.clientHeight;\n    return [\n        scrollTop,\n        scrollHeight,\n        clientHeight,\n    ];\n};\nvar getHScrollVariables = function (_a) {\n    var scrollLeft = _a.scrollLeft, scrollWidth = _a.scrollWidth, clientWidth = _a.clientWidth;\n    return [\n        scrollLeft,\n        scrollWidth,\n        clientWidth,\n    ];\n};\nvar elementCouldBeScrolled = function (axis, node) {\n    return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node);\n};\nvar getScrollVariables = function (axis, node) {\n    return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node);\n};\nvar getDirectionFactor = function (axis, direction) {\n    /**\n     * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position,\n     * and then increasingly negative as you scroll towards the end of the content.\n     * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft\n     */\n    return axis === 'h' && direction === 'rtl' ? -1 : 1;\n};\nexport var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) {\n    var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction);\n    var delta = directionFactor * sourceDelta;\n    // find scrollable target\n    var target = event.target;\n    var targetInLock = endTarget.contains(target);\n    var shouldCancelScroll = false;\n    var isDeltaPositive = delta > 0;\n    var availableScroll = 0;\n    var availableScrollTop = 0;\n    do {\n        if (!target) {\n            break;\n        }\n        var _a = getScrollVariables(axis, target), position = _a[0], scroll_1 = _a[1], capacity = _a[2];\n        var elementScroll = scroll_1 - capacity - directionFactor * position;\n        if (position || elementScroll) {\n            if (elementCouldBeScrolled(axis, target)) {\n                availableScroll += elementScroll;\n                availableScrollTop += position;\n            }\n        }\n        var parent_1 = target.parentNode;\n        // we will \"bubble\" from ShadowDom in case we are, or just to the parent in normal case\n        // this is the same logic used in focus-lock\n        target = (parent_1 && parent_1.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? parent_1.host : parent_1);\n    } while (\n    // portaled content\n    (!targetInLock && target !== document.body) ||\n        // self content\n        (targetInLock && (endTarget.contains(target) || endTarget === target)));\n    // handle epsilon around 0 (non standard zoom levels)\n    if (isDeltaPositive &&\n        ((noOverscroll && Math.abs(availableScroll) < 1) || (!noOverscroll && delta > availableScroll))) {\n        shouldCancelScroll = true;\n    }\n    else if (!isDeltaPositive &&\n        ((noOverscroll && Math.abs(availableScrollTop) < 1) || (!noOverscroll && -delta > availableScrollTop))) {\n        shouldCancelScroll = true;\n    }\n    return shouldCancelScroll;\n};\n","import { __spreadArray } from \"tslib\";\nimport * as React from 'react';\nimport { RemoveScrollBar } from 'react-remove-scroll-bar';\nimport { styleSingleton } from 'react-style-singleton';\nimport { nonPassive } from './aggresiveCapture';\nimport { handleScroll, locationCouldBeScrolled } from './handleScroll';\nexport var getTouchXY = function (event) {\n    return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];\n};\nexport var getDeltaXY = function (event) { return [event.deltaX, event.deltaY]; };\nvar extractRef = function (ref) {\n    return ref && 'current' in ref ? ref.current : ref;\n};\nvar deltaCompare = function (x, y) { return x[0] === y[0] && x[1] === y[1]; };\nvar generateStyle = function (id) { return \"\\n  .block-interactivity-\".concat(id, \" {pointer-events: none;}\\n  .allow-interactivity-\").concat(id, \" {pointer-events: all;}\\n\"); };\nvar idCounter = 0;\nvar lockStack = [];\nexport function RemoveScrollSideCar(props) {\n    var shouldPreventQueue = React.useRef([]);\n    var touchStartRef = React.useRef([0, 0]);\n    var activeAxis = React.useRef();\n    var id = React.useState(idCounter++)[0];\n    var Style = React.useState(styleSingleton)[0];\n    var lastProps = React.useRef(props);\n    React.useEffect(function () {\n        lastProps.current = props;\n    }, [props]);\n    React.useEffect(function () {\n        if (props.inert) {\n            document.body.classList.add(\"block-interactivity-\".concat(id));\n            var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean);\n            allow_1.forEach(function (el) { return el.classList.add(\"allow-interactivity-\".concat(id)); });\n            return function () {\n                document.body.classList.remove(\"block-interactivity-\".concat(id));\n                allow_1.forEach(function (el) { return el.classList.remove(\"allow-interactivity-\".concat(id)); });\n            };\n        }\n        return;\n    }, [props.inert, props.lockRef.current, props.shards]);\n    var shouldCancelEvent = React.useCallback(function (event, parent) {\n        if (('touches' in event && event.touches.length === 2) || (event.type === 'wheel' && event.ctrlKey)) {\n            return !lastProps.current.allowPinchZoom;\n        }\n        var touch = getTouchXY(event);\n        var touchStart = touchStartRef.current;\n        var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0];\n        var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1];\n        var currentAxis;\n        var target = event.target;\n        var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v';\n        // allow horizontal touch move on Range inputs. They will not cause any scroll\n        if ('touches' in event && moveDirection === 'h' && target.type === 'range') {\n            return false;\n        }\n        // allow drag selection (iOS); check if selection's anchorNode is the same as target or contains target\n        var selection = window.getSelection();\n        var anchorNode = selection && selection.anchorNode;\n        var isTouchingSelection = anchorNode ? anchorNode === target || anchorNode.contains(target) : false;\n        if (isTouchingSelection) {\n            return false;\n        }\n        var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);\n        if (!canBeScrolledInMainDirection) {\n            return true;\n        }\n        if (canBeScrolledInMainDirection) {\n            currentAxis = moveDirection;\n        }\n        else {\n            currentAxis = moveDirection === 'v' ? 'h' : 'v';\n            canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);\n            // other axis might be not scrollable\n        }\n        if (!canBeScrolledInMainDirection) {\n            return false;\n        }\n        if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) {\n            activeAxis.current = currentAxis;\n        }\n        if (!currentAxis) {\n            return true;\n        }\n        var cancelingAxis = activeAxis.current || currentAxis;\n        return handleScroll(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true);\n    }, []);\n    var shouldPrevent = React.useCallback(function (_event) {\n        var event = _event;\n        if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) {\n            // not the last active\n            return;\n        }\n        var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event);\n        var sourceEvent = shouldPreventQueue.current.filter(function (e) { return e.name === event.type && (e.target === event.target || event.target === e.shadowParent) && deltaCompare(e.delta, delta); })[0];\n        // self event, and should be canceled\n        if (sourceEvent && sourceEvent.should) {\n            if (event.cancelable) {\n                event.preventDefault();\n            }\n            return;\n        }\n        // outside or shard event\n        if (!sourceEvent) {\n            var shardNodes = (lastProps.current.shards || [])\n                .map(extractRef)\n                .filter(Boolean)\n                .filter(function (node) { return node.contains(event.target); });\n            var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;\n            if (shouldStop) {\n                if (event.cancelable) {\n                    event.preventDefault();\n                }\n            }\n        }\n    }, []);\n    var shouldCancel = React.useCallback(function (name, delta, target, should) {\n        var event = { name: name, delta: delta, target: target, should: should, shadowParent: getOutermostShadowParent(target) };\n        shouldPreventQueue.current.push(event);\n        setTimeout(function () {\n            shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { return e !== event; });\n        }, 1);\n    }, []);\n    var scrollTouchStart = React.useCallback(function (event) {\n        touchStartRef.current = getTouchXY(event);\n        activeAxis.current = undefined;\n    }, []);\n    var scrollWheel = React.useCallback(function (event) {\n        shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));\n    }, []);\n    var scrollTouchMove = React.useCallback(function (event) {\n        shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));\n    }, []);\n    React.useEffect(function () {\n        lockStack.push(Style);\n        props.setCallbacks({\n            onScrollCapture: scrollWheel,\n            onWheelCapture: scrollWheel,\n            onTouchMoveCapture: scrollTouchMove,\n        });\n        document.addEventListener('wheel', shouldPrevent, nonPassive);\n        document.addEventListener('touchmove', shouldPrevent, nonPassive);\n        document.addEventListener('touchstart', scrollTouchStart, nonPassive);\n        return function () {\n            lockStack = lockStack.filter(function (inst) { return inst !== Style; });\n            document.removeEventListener('wheel', shouldPrevent, nonPassive);\n            document.removeEventListener('touchmove', shouldPrevent, nonPassive);\n            document.removeEventListener('touchstart', scrollTouchStart, nonPassive);\n        };\n    }, []);\n    var removeScrollBar = props.removeScrollBar, inert = props.inert;\n    return (React.createElement(React.Fragment, null,\n        inert ? React.createElement(Style, { styles: generateStyle(id) }) : null,\n        removeScrollBar ? React.createElement(RemoveScrollBar, { noRelative: props.noRelative, gapMode: props.gapMode }) : null));\n}\nfunction getOutermostShadowParent(node) {\n    var shadowParent = null;\n    while (node !== null) {\n        if (node instanceof ShadowRoot) {\n            shadowParent = node.host;\n            node = node.host;\n        }\n        node = node.parentNode;\n    }\n    return shadowParent;\n}\n","import { exportSidecar } from 'use-sidecar';\nimport { RemoveScrollSideCar } from './SideEffect';\nimport { effectCar } from './medium';\nexport default exportSidecar(effectCar, RemoveScrollSideCar);\n","import { __assign } from \"tslib\";\nimport * as React from 'react';\nimport { RemoveScroll } from './UI';\nimport SideCar from './sidecar';\nvar ReactRemoveScroll = React.forwardRef(function (props, ref) { return (React.createElement(RemoveScroll, __assign({}, props, { ref: ref, sideCar: SideCar }))); });\nReactRemoveScroll.classNames = RemoveScroll.classNames;\nexport default ReactRemoveScroll;\n","var getDefaultParent = function (originalTarget) {\n    if (typeof document === 'undefined') {\n        return null;\n    }\n    var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;\n    return sampleTarget.ownerDocument.body;\n};\nvar counterMap = new WeakMap();\nvar uncontrolledNodes = new WeakMap();\nvar markerMap = {};\nvar lockCount = 0;\nvar unwrapHost = function (node) {\n    return node && (node.host || unwrapHost(node.parentNode));\n};\nvar correctTargets = function (parent, targets) {\n    return targets\n        .map(function (target) {\n        if (parent.contains(target)) {\n            return target;\n        }\n        var correctedTarget = unwrapHost(target);\n        if (correctedTarget && parent.contains(correctedTarget)) {\n            return correctedTarget;\n        }\n        console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing');\n        return null;\n    })\n        .filter(function (x) { return Boolean(x); });\n};\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @param {String} [controlAttribute] - html Attribute to control\n * @return {Undo} undo command\n */\nvar applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) {\n    var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n    if (!markerMap[markerName]) {\n        markerMap[markerName] = new WeakMap();\n    }\n    var markerCounter = markerMap[markerName];\n    var hiddenNodes = [];\n    var elementsToKeep = new Set();\n    var elementsToStop = new Set(targets);\n    var keep = function (el) {\n        if (!el || elementsToKeep.has(el)) {\n            return;\n        }\n        elementsToKeep.add(el);\n        keep(el.parentNode);\n    };\n    targets.forEach(keep);\n    var deep = function (parent) {\n        if (!parent || elementsToStop.has(parent)) {\n            return;\n        }\n        Array.prototype.forEach.call(parent.children, function (node) {\n            if (elementsToKeep.has(node)) {\n                deep(node);\n            }\n            else {\n                try {\n                    var attr = node.getAttribute(controlAttribute);\n                    var alreadyHidden = attr !== null && attr !== 'false';\n                    var counterValue = (counterMap.get(node) || 0) + 1;\n                    var markerValue = (markerCounter.get(node) || 0) + 1;\n                    counterMap.set(node, counterValue);\n                    markerCounter.set(node, markerValue);\n                    hiddenNodes.push(node);\n                    if (counterValue === 1 && alreadyHidden) {\n                        uncontrolledNodes.set(node, true);\n                    }\n                    if (markerValue === 1) {\n                        node.setAttribute(markerName, 'true');\n                    }\n                    if (!alreadyHidden) {\n                        node.setAttribute(controlAttribute, 'true');\n                    }\n                }\n                catch (e) {\n                    console.error('aria-hidden: cannot operate on ', node, e);\n                }\n            }\n        });\n    };\n    deep(parentNode);\n    elementsToKeep.clear();\n    lockCount++;\n    return function () {\n        hiddenNodes.forEach(function (node) {\n            var counterValue = counterMap.get(node) - 1;\n            var markerValue = markerCounter.get(node) - 1;\n            counterMap.set(node, counterValue);\n            markerCounter.set(node, markerValue);\n            if (!counterValue) {\n                if (!uncontrolledNodes.has(node)) {\n                    node.removeAttribute(controlAttribute);\n                }\n                uncontrolledNodes.delete(node);\n            }\n            if (!markerValue) {\n                node.removeAttribute(markerName);\n            }\n        });\n        lockCount--;\n        if (!lockCount) {\n            // clear\n            counterMap = new WeakMap();\n            counterMap = new WeakMap();\n            uncontrolledNodes = new WeakMap();\n            markerMap = {};\n        }\n    };\n};\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nexport var hideOthers = function (originalTarget, parentNode, markerName) {\n    if (markerName === void 0) { markerName = 'data-aria-hidden'; }\n    var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n    var activeParentNode = parentNode || getDefaultParent(originalTarget);\n    if (!activeParentNode) {\n        return function () { return null; };\n    }\n    // we should not hide aria-live elements - https://github.com/theKashey/aria-hidden/issues/10\n    // and script elements, as they have no impact on accessibility.\n    targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live], script')));\n    return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden');\n};\n/**\n * Marks everything except given node(or nodes) as inert\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nexport var inertOthers = function (originalTarget, parentNode, markerName) {\n    if (markerName === void 0) { markerName = 'data-inert-ed'; }\n    var activeParentNode = parentNode || getDefaultParent(originalTarget);\n    if (!activeParentNode) {\n        return function () { return null; };\n    }\n    return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert');\n};\n/**\n * @returns if current browser supports inert\n */\nexport var supportsInert = function () {\n    return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert');\n};\n/**\n * Automatic function to \"suppress\" DOM elements - _hide_ or _inert_ in the best possible way\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nexport var suppressOthers = function (originalTarget, parentNode, markerName) {\n    if (markerName === void 0) { markerName = 'data-suppressed'; }\n    return (supportsInert() ? inertOthers : hideOthers)(originalTarget, parentNode, markerName);\n};\n","// src/slot.tsx\nimport * as React from \"react\";\nimport { composeRefs } from \"@radix-ui/react-compose-refs\";\nimport { Fragment as Fragment2, jsx } from \"react/jsx-runtime\";\n// @__NO_SIDE_EFFECTS__\nfunction createSlot(ownerName) {\n  const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);\n  const Slot2 = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    const childrenArray = React.Children.toArray(children);\n    const slottable = childrenArray.find(isSlottable);\n    if (slottable) {\n      const newElement = slottable.props.children;\n      const newChildren = childrenArray.map((child) => {\n        if (child === slottable) {\n          if (React.Children.count(newElement) > 1) return React.Children.only(null);\n          return React.isValidElement(newElement) ? newElement.props.children : null;\n        } else {\n          return child;\n        }\n      });\n      return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: React.isValidElement(newElement) ? React.cloneElement(newElement, void 0, newChildren) : null });\n    }\n    return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });\n  });\n  Slot2.displayName = `${ownerName}.Slot`;\n  return Slot2;\n}\nvar Slot = /* @__PURE__ */ createSlot(\"Slot\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlotClone(ownerName) {\n  const SlotClone = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    if (React.isValidElement(children)) {\n      const childrenRef = getElementRef(children);\n      const props2 = mergeProps(slotProps, children.props);\n      if (children.type !== React.Fragment) {\n        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n      }\n      return React.cloneElement(children, props2);\n    }\n    return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n  });\n  SlotClone.displayName = `${ownerName}.SlotClone`;\n  return SlotClone;\n}\nvar SLOTTABLE_IDENTIFIER = Symbol(\"radix.slottable\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlottable(ownerName) {\n  const Slottable2 = ({ children }) => {\n    return /* @__PURE__ */ jsx(Fragment2, { children });\n  };\n  Slottable2.displayName = `${ownerName}.Slottable`;\n  Slottable2.__radixId = SLOTTABLE_IDENTIFIER;\n  return Slottable2;\n}\nvar Slottable = /* @__PURE__ */ createSlottable(\"Slottable\");\nfunction isSlottable(child) {\n  return React.isValidElement(child) && typeof child.type === \"function\" && \"__radixId\" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;\n}\nfunction mergeProps(slotProps, childProps) {\n  const overrideProps = { ...childProps };\n  for (const propName in childProps) {\n    const slotPropValue = slotProps[propName];\n    const childPropValue = childProps[propName];\n    const isHandler = /^on[A-Z]/.test(propName);\n    if (isHandler) {\n      if (slotPropValue && childPropValue) {\n        overrideProps[propName] = (...args) => {\n          const result = childPropValue(...args);\n          slotPropValue(...args);\n          return result;\n        };\n      } else if (slotPropValue) {\n        overrideProps[propName] = slotPropValue;\n      }\n    } else if (propName === \"style\") {\n      overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n    } else if (propName === \"className\") {\n      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(\" \");\n    }\n  }\n  return { ...slotProps, ...overrideProps };\n}\nfunction getElementRef(element) {\n  let getter = Object.getOwnPropertyDescriptor(element.props, \"ref\")?.get;\n  let mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.ref;\n  }\n  getter = Object.getOwnPropertyDescriptor(element, \"ref\")?.get;\n  mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.props.ref;\n  }\n  return element.props.ref || element.ref;\n}\nexport {\n  Slot as Root,\n  Slot,\n  Slottable,\n  createSlot,\n  createSlottable\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/dialog.tsx\nimport * as React from \"react\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createContext, createContextScope } from \"@radix-ui/react-context\";\nimport { useId } from \"@radix-ui/react-id\";\nimport { useControllableState } from \"@radix-ui/react-use-controllable-state\";\nimport { DismissableLayer } from \"@radix-ui/react-dismissable-layer\";\nimport { FocusScope } from \"@radix-ui/react-focus-scope\";\nimport { Portal as PortalPrimitive } from \"@radix-ui/react-portal\";\nimport { Presence } from \"@radix-ui/react-presence\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { useFocusGuards } from \"@radix-ui/react-focus-guards\";\nimport { RemoveScroll } from \"react-remove-scroll\";\nimport { hideOthers } from \"aria-hidden\";\nimport { createSlot } from \"@radix-ui/react-slot\";\nimport { Fragment, jsx, jsxs } from \"react/jsx-runtime\";\nvar DIALOG_NAME = \"Dialog\";\nvar [createDialogContext, createDialogScope] = createContextScope(DIALOG_NAME);\nvar [DialogProvider, useDialogContext] = createDialogContext(DIALOG_NAME);\nvar Dialog = (props) => {\n  const {\n    __scopeDialog,\n    children,\n    open: openProp,\n    defaultOpen,\n    onOpenChange,\n    modal = true\n  } = props;\n  const triggerRef = React.useRef(null);\n  const contentRef = React.useRef(null);\n  const [open, setOpen] = useControllableState({\n    prop: openProp,\n    defaultProp: defaultOpen ?? false,\n    onChange: onOpenChange,\n    caller: DIALOG_NAME\n  });\n  return /* @__PURE__ */ jsx(\n    DialogProvider,\n    {\n      scope: __scopeDialog,\n      triggerRef,\n      contentRef,\n      contentId: useId(),\n      titleId: useId(),\n      descriptionId: useId(),\n      open,\n      onOpenChange: setOpen,\n      onOpenToggle: React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),\n      modal,\n      children\n    }\n  );\n};\nDialog.displayName = DIALOG_NAME;\nvar TRIGGER_NAME = \"DialogTrigger\";\nvar DialogTrigger = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeDialog, ...triggerProps } = props;\n    const context = useDialogContext(TRIGGER_NAME, __scopeDialog);\n    const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);\n    return /* @__PURE__ */ jsx(\n      Primitive.button,\n      {\n        type: \"button\",\n        \"aria-haspopup\": \"dialog\",\n        \"aria-expanded\": context.open,\n        \"aria-controls\": context.contentId,\n        \"data-state\": getState(context.open),\n        ...triggerProps,\n        ref: composedTriggerRef,\n        onClick: composeEventHandlers(props.onClick, context.onOpenToggle)\n      }\n    );\n  }\n);\nDialogTrigger.displayName = TRIGGER_NAME;\nvar PORTAL_NAME = \"DialogPortal\";\nvar [PortalProvider, usePortalContext] = createDialogContext(PORTAL_NAME, {\n  forceMount: void 0\n});\nvar DialogPortal = (props) => {\n  const { __scopeDialog, forceMount, children, container } = props;\n  const context = useDialogContext(PORTAL_NAME, __scopeDialog);\n  return /* @__PURE__ */ jsx(PortalProvider, { scope: __scopeDialog, forceMount, children: React.Children.map(children, (child) => /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsx(PortalPrimitive, { asChild: true, container, children: child }) })) });\n};\nDialogPortal.displayName = PORTAL_NAME;\nvar OVERLAY_NAME = \"DialogOverlay\";\nvar DialogOverlay = React.forwardRef(\n  (props, forwardedRef) => {\n    const portalContext = usePortalContext(OVERLAY_NAME, props.__scopeDialog);\n    const { forceMount = portalContext.forceMount, ...overlayProps } = props;\n    const context = useDialogContext(OVERLAY_NAME, props.__scopeDialog);\n    return context.modal ? /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsx(DialogOverlayImpl, { ...overlayProps, ref: forwardedRef }) }) : null;\n  }\n);\nDialogOverlay.displayName = OVERLAY_NAME;\nvar Slot = createSlot(\"DialogOverlay.RemoveScroll\");\nvar DialogOverlayImpl = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeDialog, ...overlayProps } = props;\n    const context = useDialogContext(OVERLAY_NAME, __scopeDialog);\n    return (\n      // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll`\n      // ie. when `Overlay` and `Content` are siblings\n      /* @__PURE__ */ jsx(RemoveScroll, { as: Slot, allowPinchZoom: true, shards: [context.contentRef], children: /* @__PURE__ */ jsx(\n        Primitive.div,\n        {\n          \"data-state\": getState(context.open),\n          ...overlayProps,\n          ref: forwardedRef,\n          style: { pointerEvents: \"auto\", ...overlayProps.style }\n        }\n      ) })\n    );\n  }\n);\nvar CONTENT_NAME = \"DialogContent\";\nvar DialogContent = React.forwardRef(\n  (props, forwardedRef) => {\n    const portalContext = usePortalContext(CONTENT_NAME, props.__scopeDialog);\n    const { forceMount = portalContext.forceMount, ...contentProps } = props;\n    const context = useDialogContext(CONTENT_NAME, props.__scopeDialog);\n    return /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ jsx(DialogContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ jsx(DialogContentNonModal, { ...contentProps, ref: forwardedRef }) });\n  }\n);\nDialogContent.displayName = CONTENT_NAME;\nvar DialogContentModal = React.forwardRef(\n  (props, forwardedRef) => {\n    const context = useDialogContext(CONTENT_NAME, props.__scopeDialog);\n    const contentRef = React.useRef(null);\n    const composedRefs = useComposedRefs(forwardedRef, context.contentRef, contentRef);\n    React.useEffect(() => {\n      const content = contentRef.current;\n      if (content) return hideOthers(content);\n    }, []);\n    return /* @__PURE__ */ jsx(\n      DialogContentImpl,\n      {\n        ...props,\n        ref: composedRefs,\n        trapFocus: context.open,\n        disableOutsidePointerEvents: true,\n        onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => {\n          event.preventDefault();\n          context.triggerRef.current?.focus();\n        }),\n        onPointerDownOutside: composeEventHandlers(props.onPointerDownOutside, (event) => {\n          const originalEvent = event.detail.originalEvent;\n          const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n          const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n          if (isRightClick) event.preventDefault();\n        }),\n        onFocusOutside: composeEventHandlers(\n          props.onFocusOutside,\n          (event) => event.preventDefault()\n        )\n      }\n    );\n  }\n);\nvar DialogContentNonModal = React.forwardRef(\n  (props, forwardedRef) => {\n    const context = useDialogContext(CONTENT_NAME, props.__scopeDialog);\n    const hasInteractedOutsideRef = React.useRef(false);\n    const hasPointerDownOutsideRef = React.useRef(false);\n    return /* @__PURE__ */ jsx(\n      DialogContentImpl,\n      {\n        ...props,\n        ref: forwardedRef,\n        trapFocus: false,\n        disableOutsidePointerEvents: false,\n        onCloseAutoFocus: (event) => {\n          props.onCloseAutoFocus?.(event);\n          if (!event.defaultPrevented) {\n            if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();\n            event.preventDefault();\n          }\n          hasInteractedOutsideRef.current = false;\n          hasPointerDownOutsideRef.current = false;\n        },\n        onInteractOutside: (event) => {\n          props.onInteractOutside?.(event);\n          if (!event.defaultPrevented) {\n            hasInteractedOutsideRef.current = true;\n            if (event.detail.originalEvent.type === \"pointerdown\") {\n              hasPointerDownOutsideRef.current = true;\n            }\n          }\n          const target = event.target;\n          const targetIsTrigger = context.triggerRef.current?.contains(target);\n          if (targetIsTrigger) event.preventDefault();\n          if (event.detail.originalEvent.type === \"focusin\" && hasPointerDownOutsideRef.current) {\n            event.preventDefault();\n          }\n        }\n      }\n    );\n  }\n);\nvar DialogContentImpl = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeDialog, trapFocus, onOpenAutoFocus, onCloseAutoFocus, ...contentProps } = props;\n    const context = useDialogContext(CONTENT_NAME, __scopeDialog);\n    const contentRef = React.useRef(null);\n    const composedRefs = useComposedRefs(forwardedRef, contentRef);\n    useFocusGuards();\n    return /* @__PURE__ */ jsxs(Fragment, { children: [\n      /* @__PURE__ */ jsx(\n        FocusScope,\n        {\n          asChild: true,\n          loop: true,\n          trapped: trapFocus,\n          onMountAutoFocus: onOpenAutoFocus,\n          onUnmountAutoFocus: onCloseAutoFocus,\n          children: /* @__PURE__ */ jsx(\n            DismissableLayer,\n            {\n              role: \"dialog\",\n              id: context.contentId,\n              \"aria-describedby\": context.descriptionId,\n              \"aria-labelledby\": context.titleId,\n              \"data-state\": getState(context.open),\n              ...contentProps,\n              ref: composedRefs,\n              onDismiss: () => context.onOpenChange(false)\n            }\n          )\n        }\n      ),\n      /* @__PURE__ */ jsxs(Fragment, { children: [\n        /* @__PURE__ */ jsx(TitleWarning, { titleId: context.titleId }),\n        /* @__PURE__ */ jsx(DescriptionWarning, { contentRef, descriptionId: context.descriptionId })\n      ] })\n    ] });\n  }\n);\nvar TITLE_NAME = \"DialogTitle\";\nvar DialogTitle = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeDialog, ...titleProps } = props;\n    const context = useDialogContext(TITLE_NAME, __scopeDialog);\n    return /* @__PURE__ */ jsx(Primitive.h2, { id: context.titleId, ...titleProps, ref: forwardedRef });\n  }\n);\nDialogTitle.displayName = TITLE_NAME;\nvar DESCRIPTION_NAME = \"DialogDescription\";\nvar DialogDescription = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeDialog, ...descriptionProps } = props;\n    const context = useDialogContext(DESCRIPTION_NAME, __scopeDialog);\n    return /* @__PURE__ */ jsx(Primitive.p, { id: context.descriptionId, ...descriptionProps, ref: forwardedRef });\n  }\n);\nDialogDescription.displayName = DESCRIPTION_NAME;\nvar CLOSE_NAME = \"DialogClose\";\nvar DialogClose = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeDialog, ...closeProps } = props;\n    const context = useDialogContext(CLOSE_NAME, __scopeDialog);\n    return /* @__PURE__ */ jsx(\n      Primitive.button,\n      {\n        type: \"button\",\n        ...closeProps,\n        ref: forwardedRef,\n        onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false))\n      }\n    );\n  }\n);\nDialogClose.displayName = CLOSE_NAME;\nfunction getState(open) {\n  return open ? \"open\" : \"closed\";\n}\nvar TITLE_WARNING_NAME = \"DialogTitleWarning\";\nvar [WarningProvider, useWarningContext] = createContext(TITLE_WARNING_NAME, {\n  contentName: CONTENT_NAME,\n  titleName: TITLE_NAME,\n  docsSlug: \"dialog\"\n});\nvar TitleWarning = ({ titleId }) => {\n  const titleWarningContext = useWarningContext(TITLE_WARNING_NAME);\n  const MESSAGE = `\\`${titleWarningContext.contentName}\\` requires a \\`${titleWarningContext.titleName}\\` for the component to be accessible for screen reader users.\n\nIf you want to hide the \\`${titleWarningContext.titleName}\\`, you can wrap it with our VisuallyHidden component.\n\nFor more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`;\n  React.useEffect(() => {\n    if (titleId) {\n      const hasTitle = document.getElementById(titleId);\n      if (!hasTitle) console.error(MESSAGE);\n    }\n  }, [MESSAGE, titleId]);\n  return null;\n};\nvar DESCRIPTION_WARNING_NAME = \"DialogDescriptionWarning\";\nvar DescriptionWarning = ({ contentRef, descriptionId }) => {\n  const descriptionWarningContext = useWarningContext(DESCRIPTION_WARNING_NAME);\n  const MESSAGE = `Warning: Missing \\`Description\\` or \\`aria-describedby={undefined}\\` for {${descriptionWarningContext.contentName}}.`;\n  React.useEffect(() => {\n    const describedById = contentRef.current?.getAttribute(\"aria-describedby\");\n    if (descriptionId && describedById) {\n      const hasDescription = document.getElementById(descriptionId);\n      if (!hasDescription) console.warn(MESSAGE);\n    }\n  }, [MESSAGE, contentRef, descriptionId]);\n  return null;\n};\nvar Root = Dialog;\nvar Trigger = DialogTrigger;\nvar Portal = DialogPortal;\nvar Overlay = DialogOverlay;\nvar Content = DialogContent;\nvar Title = DialogTitle;\nvar Description = DialogDescription;\nvar Close = DialogClose;\nexport {\n  Close,\n  Content,\n  Description,\n  Dialog,\n  DialogClose,\n  DialogContent,\n  DialogDescription,\n  DialogOverlay,\n  DialogPortal,\n  DialogTitle,\n  DialogTrigger,\n  Overlay,\n  Portal,\n  Root,\n  Title,\n  Trigger,\n  WarningProvider,\n  createDialogScope\n};\n//# sourceMappingURL=index.mjs.map\n","// src/slot.tsx\nimport * as React from \"react\";\nimport { composeRefs } from \"@radix-ui/react-compose-refs\";\nimport { Fragment as Fragment2, jsx } from \"react/jsx-runtime\";\n// @__NO_SIDE_EFFECTS__\nfunction createSlot(ownerName) {\n  const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);\n  const Slot2 = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    const childrenArray = React.Children.toArray(children);\n    const slottable = childrenArray.find(isSlottable);\n    if (slottable) {\n      const newElement = slottable.props.children;\n      const newChildren = childrenArray.map((child) => {\n        if (child === slottable) {\n          if (React.Children.count(newElement) > 1) return React.Children.only(null);\n          return React.isValidElement(newElement) ? newElement.props.children : null;\n        } else {\n          return child;\n        }\n      });\n      return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: React.isValidElement(newElement) ? React.cloneElement(newElement, void 0, newChildren) : null });\n    }\n    return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });\n  });\n  Slot2.displayName = `${ownerName}.Slot`;\n  return Slot2;\n}\nvar Slot = /* @__PURE__ */ createSlot(\"Slot\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlotClone(ownerName) {\n  const SlotClone = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    if (React.isValidElement(children)) {\n      const childrenRef = getElementRef(children);\n      const props2 = mergeProps(slotProps, children.props);\n      if (children.type !== React.Fragment) {\n        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n      }\n      return React.cloneElement(children, props2);\n    }\n    return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n  });\n  SlotClone.displayName = `${ownerName}.SlotClone`;\n  return SlotClone;\n}\nvar SLOTTABLE_IDENTIFIER = Symbol(\"radix.slottable\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlottable(ownerName) {\n  const Slottable2 = ({ children }) => {\n    return /* @__PURE__ */ jsx(Fragment2, { children });\n  };\n  Slottable2.displayName = `${ownerName}.Slottable`;\n  Slottable2.__radixId = SLOTTABLE_IDENTIFIER;\n  return Slottable2;\n}\nvar Slottable = /* @__PURE__ */ createSlottable(\"Slottable\");\nfunction isSlottable(child) {\n  return React.isValidElement(child) && typeof child.type === \"function\" && \"__radixId\" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;\n}\nfunction mergeProps(slotProps, childProps) {\n  const overrideProps = { ...childProps };\n  for (const propName in childProps) {\n    const slotPropValue = slotProps[propName];\n    const childPropValue = childProps[propName];\n    const isHandler = /^on[A-Z]/.test(propName);\n    if (isHandler) {\n      if (slotPropValue && childPropValue) {\n        overrideProps[propName] = (...args) => {\n          const result = childPropValue(...args);\n          slotPropValue(...args);\n          return result;\n        };\n      } else if (slotPropValue) {\n        overrideProps[propName] = slotPropValue;\n      }\n    } else if (propName === \"style\") {\n      overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n    } else if (propName === \"className\") {\n      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(\" \");\n    }\n  }\n  return { ...slotProps, ...overrideProps };\n}\nfunction getElementRef(element) {\n  let getter = Object.getOwnPropertyDescriptor(element.props, \"ref\")?.get;\n  let mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.ref;\n  }\n  getter = Object.getOwnPropertyDescriptor(element, \"ref\")?.get;\n  mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.props.ref;\n  }\n  return element.props.ref || element.ref;\n}\nexport {\n  Slot as Root,\n  Slot,\n  Slottable,\n  createSlot,\n  createSlottable\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/alert-dialog.tsx\nimport * as React from \"react\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\";\nimport { createDialogScope } from \"@radix-ui/react-dialog\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { createSlottable } from \"@radix-ui/react-slot\";\nimport { jsx, jsxs } from \"react/jsx-runtime\";\nvar ROOT_NAME = \"AlertDialog\";\nvar [createAlertDialogContext, createAlertDialogScope] = createContextScope(ROOT_NAME, [\n  createDialogScope\n]);\nvar useDialogScope = createDialogScope();\nvar AlertDialog = (props) => {\n  const { __scopeAlertDialog, ...alertDialogProps } = props;\n  const dialogScope = useDialogScope(__scopeAlertDialog);\n  return /* @__PURE__ */ jsx(DialogPrimitive.Root, { ...dialogScope, ...alertDialogProps, modal: true });\n};\nAlertDialog.displayName = ROOT_NAME;\nvar TRIGGER_NAME = \"AlertDialogTrigger\";\nvar AlertDialogTrigger = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeAlertDialog, ...triggerProps } = props;\n    const dialogScope = useDialogScope(__scopeAlertDialog);\n    return /* @__PURE__ */ jsx(DialogPrimitive.Trigger, { ...dialogScope, ...triggerProps, ref: forwardedRef });\n  }\n);\nAlertDialogTrigger.displayName = TRIGGER_NAME;\nvar PORTAL_NAME = \"AlertDialogPortal\";\nvar AlertDialogPortal = (props) => {\n  const { __scopeAlertDialog, ...portalProps } = props;\n  const dialogScope = useDialogScope(__scopeAlertDialog);\n  return /* @__PURE__ */ jsx(DialogPrimitive.Portal, { ...dialogScope, ...portalProps });\n};\nAlertDialogPortal.displayName = PORTAL_NAME;\nvar OVERLAY_NAME = \"AlertDialogOverlay\";\nvar AlertDialogOverlay = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeAlertDialog, ...overlayProps } = props;\n    const dialogScope = useDialogScope(__scopeAlertDialog);\n    return /* @__PURE__ */ jsx(DialogPrimitive.Overlay, { ...dialogScope, ...overlayProps, ref: forwardedRef });\n  }\n);\nAlertDialogOverlay.displayName = OVERLAY_NAME;\nvar CONTENT_NAME = \"AlertDialogContent\";\nvar [AlertDialogContentProvider, useAlertDialogContentContext] = createAlertDialogContext(CONTENT_NAME);\nvar Slottable = createSlottable(\"AlertDialogContent\");\nvar AlertDialogContent = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeAlertDialog, children, ...contentProps } = props;\n    const dialogScope = useDialogScope(__scopeAlertDialog);\n    const contentRef = React.useRef(null);\n    const composedRefs = useComposedRefs(forwardedRef, contentRef);\n    const cancelRef = React.useRef(null);\n    return /* @__PURE__ */ jsx(\n      DialogPrimitive.WarningProvider,\n      {\n        contentName: CONTENT_NAME,\n        titleName: TITLE_NAME,\n        docsSlug: \"alert-dialog\",\n        children: /* @__PURE__ */ jsx(AlertDialogContentProvider, { scope: __scopeAlertDialog, cancelRef, children: /* @__PURE__ */ jsxs(\n          DialogPrimitive.Content,\n          {\n            role: \"alertdialog\",\n            ...dialogScope,\n            ...contentProps,\n            ref: composedRefs,\n            onOpenAutoFocus: composeEventHandlers(contentProps.onOpenAutoFocus, (event) => {\n              event.preventDefault();\n              cancelRef.current?.focus({ preventScroll: true });\n            }),\n            onPointerDownOutside: (event) => event.preventDefault(),\n            onInteractOutside: (event) => event.preventDefault(),\n            children: [\n              /* @__PURE__ */ jsx(Slottable, { children }),\n              /* @__PURE__ */ jsx(DescriptionWarning, { contentRef })\n            ]\n          }\n        ) })\n      }\n    );\n  }\n);\nAlertDialogContent.displayName = CONTENT_NAME;\nvar TITLE_NAME = \"AlertDialogTitle\";\nvar AlertDialogTitle = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeAlertDialog, ...titleProps } = props;\n    const dialogScope = useDialogScope(__scopeAlertDialog);\n    return /* @__PURE__ */ jsx(DialogPrimitive.Title, { ...dialogScope, ...titleProps, ref: forwardedRef });\n  }\n);\nAlertDialogTitle.displayName = TITLE_NAME;\nvar DESCRIPTION_NAME = \"AlertDialogDescription\";\nvar AlertDialogDescription = React.forwardRef((props, forwardedRef) => {\n  const { __scopeAlertDialog, ...descriptionProps } = props;\n  const dialogScope = useDialogScope(__scopeAlertDialog);\n  return /* @__PURE__ */ jsx(DialogPrimitive.Description, { ...dialogScope, ...descriptionProps, ref: forwardedRef });\n});\nAlertDialogDescription.displayName = DESCRIPTION_NAME;\nvar ACTION_NAME = \"AlertDialogAction\";\nvar AlertDialogAction = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeAlertDialog, ...actionProps } = props;\n    const dialogScope = useDialogScope(__scopeAlertDialog);\n    return /* @__PURE__ */ jsx(DialogPrimitive.Close, { ...dialogScope, ...actionProps, ref: forwardedRef });\n  }\n);\nAlertDialogAction.displayName = ACTION_NAME;\nvar CANCEL_NAME = \"AlertDialogCancel\";\nvar AlertDialogCancel = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopeAlertDialog, ...cancelProps } = props;\n    const { cancelRef } = useAlertDialogContentContext(CANCEL_NAME, __scopeAlertDialog);\n    const dialogScope = useDialogScope(__scopeAlertDialog);\n    const ref = useComposedRefs(forwardedRef, cancelRef);\n    return /* @__PURE__ */ jsx(DialogPrimitive.Close, { ...dialogScope, ...cancelProps, ref });\n  }\n);\nAlertDialogCancel.displayName = CANCEL_NAME;\nvar DescriptionWarning = ({ contentRef }) => {\n  const MESSAGE = `\\`${CONTENT_NAME}\\` requires a description for the component to be accessible for screen reader users.\n\nYou can add a description to the \\`${CONTENT_NAME}\\` by passing a \\`${DESCRIPTION_NAME}\\` component as a child, which also benefits sighted users by adding visible context to the dialog.\n\nAlternatively, you can use your own component as a description by assigning it an \\`id\\` and passing the same value to the \\`aria-describedby\\` prop in \\`${CONTENT_NAME}\\`. If the description is confusing or duplicative for sighted users, you can use the \\`@radix-ui/react-visually-hidden\\` primitive as a wrapper around your description component.\n\nFor more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;\n  React.useEffect(() => {\n    const hasDescription = document.getElementById(\n      contentRef.current?.getAttribute(\"aria-describedby\")\n    );\n    if (!hasDescription) console.warn(MESSAGE);\n  }, [MESSAGE, contentRef]);\n  return null;\n};\nvar Root2 = AlertDialog;\nvar Trigger2 = AlertDialogTrigger;\nvar Portal2 = AlertDialogPortal;\nvar Overlay2 = AlertDialogOverlay;\nvar Content2 = AlertDialogContent;\nvar Action = AlertDialogAction;\nvar Cancel = AlertDialogCancel;\nvar Title2 = AlertDialogTitle;\nvar Description2 = AlertDialogDescription;\nexport {\n  Action,\n  AlertDialog,\n  AlertDialogAction,\n  AlertDialogCancel,\n  AlertDialogContent,\n  AlertDialogDescription,\n  AlertDialogOverlay,\n  AlertDialogPortal,\n  AlertDialogTitle,\n  AlertDialogTrigger,\n  Cancel,\n  Content2 as Content,\n  Description2 as Description,\n  Overlay2 as Overlay,\n  Portal2 as Portal,\n  Root2 as Root,\n  Title2 as Title,\n  Trigger2 as Trigger,\n  createAlertDialogScope\n};\n//# sourceMappingURL=index.mjs.map\n","// src/arrow.tsx\nimport * as React from \"react\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { jsx } from \"react/jsx-runtime\";\nvar NAME = \"Arrow\";\nvar Arrow = React.forwardRef((props, forwardedRef) => {\n  const { children, width = 10, height = 5, ...arrowProps } = props;\n  return /* @__PURE__ */ jsx(\n    Primitive.svg,\n    {\n      ...arrowProps,\n      ref: forwardedRef,\n      width,\n      height,\n      viewBox: \"0 0 30 10\",\n      preserveAspectRatio: \"none\",\n      children: props.asChild ? children : /* @__PURE__ */ jsx(\"polygon\", { points: \"0,0 30,0 15,10\" })\n    }\n  );\n});\nArrow.displayName = NAME;\nvar Root = Arrow;\nexport {\n  Arrow,\n  Root\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/popper.tsx\nimport * as React from \"react\";\nimport {\n  useFloating,\n  autoUpdate,\n  offset,\n  shift,\n  limitShift,\n  hide,\n  arrow as floatingUIarrow,\n  flip,\n  size\n} from \"@floating-ui/react-dom\";\nimport * as ArrowPrimitive from \"@radix-ui/react-arrow\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useLayoutEffect } from \"@radix-ui/react-use-layout-effect\";\nimport { useSize } from \"@radix-ui/react-use-size\";\nimport { jsx } from \"react/jsx-runtime\";\nvar SIDE_OPTIONS = [\"top\", \"right\", \"bottom\", \"left\"];\nvar ALIGN_OPTIONS = [\"start\", \"center\", \"end\"];\nvar POPPER_NAME = \"Popper\";\nvar [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME);\nvar [PopperProvider, usePopperContext] = createPopperContext(POPPER_NAME);\nvar Popper = (props) => {\n  const { __scopePopper, children } = props;\n  const [anchor, setAnchor] = React.useState(null);\n  return /* @__PURE__ */ jsx(PopperProvider, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, children });\n};\nPopper.displayName = POPPER_NAME;\nvar ANCHOR_NAME = \"PopperAnchor\";\nvar PopperAnchor = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopePopper, virtualRef, ...anchorProps } = props;\n    const context = usePopperContext(ANCHOR_NAME, __scopePopper);\n    const ref = React.useRef(null);\n    const composedRefs = useComposedRefs(forwardedRef, ref);\n    const anchorRef = React.useRef(null);\n    React.useEffect(() => {\n      const previousAnchor = anchorRef.current;\n      anchorRef.current = virtualRef?.current || ref.current;\n      if (previousAnchor !== anchorRef.current) {\n        context.onAnchorChange(anchorRef.current);\n      }\n    });\n    return virtualRef ? null : /* @__PURE__ */ jsx(Primitive.div, { ...anchorProps, ref: composedRefs });\n  }\n);\nPopperAnchor.displayName = ANCHOR_NAME;\nvar CONTENT_NAME = \"PopperContent\";\nvar [PopperContentProvider, useContentContext] = createPopperContext(CONTENT_NAME);\nvar PopperContent = React.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      __scopePopper,\n      side = \"bottom\",\n      sideOffset = 0,\n      align = \"center\",\n      alignOffset = 0,\n      arrowPadding = 0,\n      avoidCollisions = true,\n      collisionBoundary = [],\n      collisionPadding: collisionPaddingProp = 0,\n      sticky = \"partial\",\n      hideWhenDetached = false,\n      updatePositionStrategy = \"optimized\",\n      onPlaced,\n      ...contentProps\n    } = props;\n    const context = usePopperContext(CONTENT_NAME, __scopePopper);\n    const [content, setContent] = React.useState(null);\n    const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));\n    const [arrow, setArrow] = React.useState(null);\n    const arrowSize = useSize(arrow);\n    const arrowWidth = arrowSize?.width ?? 0;\n    const arrowHeight = arrowSize?.height ?? 0;\n    const desiredPlacement = side + (align !== \"center\" ? \"-\" + align : \"\");\n    const collisionPadding = typeof collisionPaddingProp === \"number\" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };\n    const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];\n    const hasExplicitBoundaries = boundary.length > 0;\n    const detectOverflowOptions = {\n      padding: collisionPadding,\n      boundary: boundary.filter(isNotNull),\n      // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries\n      altBoundary: hasExplicitBoundaries\n    };\n    const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({\n      // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues\n      strategy: \"fixed\",\n      placement: desiredPlacement,\n      whileElementsMounted: (...args) => {\n        const cleanup = autoUpdate(...args, {\n          animationFrame: updatePositionStrategy === \"always\"\n        });\n        return cleanup;\n      },\n      elements: {\n        reference: context.anchor\n      },\n      middleware: [\n        offset({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),\n        avoidCollisions && shift({\n          mainAxis: true,\n          crossAxis: false,\n          limiter: sticky === \"partial\" ? limitShift() : void 0,\n          ...detectOverflowOptions\n        }),\n        avoidCollisions && flip({ ...detectOverflowOptions }),\n        size({\n          ...detectOverflowOptions,\n          apply: ({ elements, rects, availableWidth, availableHeight }) => {\n            const { width: anchorWidth, height: anchorHeight } = rects.reference;\n            const contentStyle = elements.floating.style;\n            contentStyle.setProperty(\"--radix-popper-available-width\", `${availableWidth}px`);\n            contentStyle.setProperty(\"--radix-popper-available-height\", `${availableHeight}px`);\n            contentStyle.setProperty(\"--radix-popper-anchor-width\", `${anchorWidth}px`);\n            contentStyle.setProperty(\"--radix-popper-anchor-height\", `${anchorHeight}px`);\n          }\n        }),\n        arrow && floatingUIarrow({ element: arrow, padding: arrowPadding }),\n        transformOrigin({ arrowWidth, arrowHeight }),\n        hideWhenDetached && hide({ strategy: \"referenceHidden\", ...detectOverflowOptions })\n      ]\n    });\n    const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);\n    const handlePlaced = useCallbackRef(onPlaced);\n    useLayoutEffect(() => {\n      if (isPositioned) {\n        handlePlaced?.();\n      }\n    }, [isPositioned, handlePlaced]);\n    const arrowX = middlewareData.arrow?.x;\n    const arrowY = middlewareData.arrow?.y;\n    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;\n    const [contentZIndex, setContentZIndex] = React.useState();\n    useLayoutEffect(() => {\n      if (content) setContentZIndex(window.getComputedStyle(content).zIndex);\n    }, [content]);\n    return /* @__PURE__ */ jsx(\n      \"div\",\n      {\n        ref: refs.setFloating,\n        \"data-radix-popper-content-wrapper\": \"\",\n        style: {\n          ...floatingStyles,\n          transform: isPositioned ? floatingStyles.transform : \"translate(0, -200%)\",\n          // keep off the page when measuring\n          minWidth: \"max-content\",\n          zIndex: contentZIndex,\n          [\"--radix-popper-transform-origin\"]: [\n            middlewareData.transformOrigin?.x,\n            middlewareData.transformOrigin?.y\n          ].join(\" \"),\n          // hide the content if using the hide middleware and should be hidden\n          // set visibility to hidden and disable pointer events so the UI behaves\n          // as if the PopperContent isn't there at all\n          ...middlewareData.hide?.referenceHidden && {\n            visibility: \"hidden\",\n            pointerEvents: \"none\"\n          }\n        },\n        dir: props.dir,\n        children: /* @__PURE__ */ jsx(\n          PopperContentProvider,\n          {\n            scope: __scopePopper,\n            placedSide,\n            onArrowChange: setArrow,\n            arrowX,\n            arrowY,\n            shouldHideArrow: cannotCenterArrow,\n            children: /* @__PURE__ */ jsx(\n              Primitive.div,\n              {\n                \"data-side\": placedSide,\n                \"data-align\": placedAlign,\n                ...contentProps,\n                ref: composedRefs,\n                style: {\n                  ...contentProps.style,\n                  // if the PopperContent hasn't been placed yet (not all measurements done)\n                  // we prevent animations so that users's animation don't kick in too early referring wrong sides\n                  animation: !isPositioned ? \"none\" : void 0\n                }\n              }\n            )\n          }\n        )\n      }\n    );\n  }\n);\nPopperContent.displayName = CONTENT_NAME;\nvar ARROW_NAME = \"PopperArrow\";\nvar OPPOSITE_SIDE = {\n  top: \"bottom\",\n  right: \"left\",\n  bottom: \"top\",\n  left: \"right\"\n};\nvar PopperArrow = React.forwardRef(function PopperArrow2(props, forwardedRef) {\n  const { __scopePopper, ...arrowProps } = props;\n  const contentContext = useContentContext(ARROW_NAME, __scopePopper);\n  const baseSide = OPPOSITE_SIDE[contentContext.placedSide];\n  return (\n    // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)\n    // doesn't report size as we'd expect on SVG elements.\n    // it reports their bounding box which is effectively the largest path inside the SVG.\n    /* @__PURE__ */ jsx(\n      \"span\",\n      {\n        ref: contentContext.onArrowChange,\n        style: {\n          position: \"absolute\",\n          left: contentContext.arrowX,\n          top: contentContext.arrowY,\n          [baseSide]: 0,\n          transformOrigin: {\n            top: \"\",\n            right: \"0 0\",\n            bottom: \"center 0\",\n            left: \"100% 0\"\n          }[contentContext.placedSide],\n          transform: {\n            top: \"translateY(100%)\",\n            right: \"translateY(50%) rotate(90deg) translateX(-50%)\",\n            bottom: `rotate(180deg)`,\n            left: \"translateY(50%) rotate(-90deg) translateX(50%)\"\n          }[contentContext.placedSide],\n          visibility: contentContext.shouldHideArrow ? \"hidden\" : void 0\n        },\n        children: /* @__PURE__ */ jsx(\n          ArrowPrimitive.Root,\n          {\n            ...arrowProps,\n            ref: forwardedRef,\n            style: {\n              ...arrowProps.style,\n              // ensures the element can be measured correctly (mostly for if SVG)\n              display: \"block\"\n            }\n          }\n        )\n      }\n    )\n  );\n});\nPopperArrow.displayName = ARROW_NAME;\nfunction isNotNull(value) {\n  return value !== null;\n}\nvar transformOrigin = (options) => ({\n  name: \"transformOrigin\",\n  options,\n  fn(data) {\n    const { placement, rects, middlewareData } = data;\n    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;\n    const isArrowHidden = cannotCenterArrow;\n    const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;\n    const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;\n    const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);\n    const noArrowAlign = { start: \"0%\", center: \"50%\", end: \"100%\" }[placedAlign];\n    const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;\n    const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;\n    let x = \"\";\n    let y = \"\";\n    if (placedSide === \"bottom\") {\n      x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;\n      y = `${-arrowHeight}px`;\n    } else if (placedSide === \"top\") {\n      x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;\n      y = `${rects.floating.height + arrowHeight}px`;\n    } else if (placedSide === \"right\") {\n      x = `${-arrowHeight}px`;\n      y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;\n    } else if (placedSide === \"left\") {\n      x = `${rects.floating.width + arrowHeight}px`;\n      y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;\n    }\n    return { data: { x, y } };\n  }\n});\nfunction getSideAndAlignFromPlacement(placement) {\n  const [side, align = \"center\"] = placement.split(\"-\");\n  return [side, align];\n}\nvar Root2 = Popper;\nvar Anchor = PopperAnchor;\nvar Content = PopperContent;\nvar Arrow = PopperArrow;\nexport {\n  ALIGN_OPTIONS,\n  Anchor,\n  Arrow,\n  Content,\n  Popper,\n  PopperAnchor,\n  PopperArrow,\n  PopperContent,\n  Root2 as Root,\n  SIDE_OPTIONS,\n  createPopperScope\n};\n//# sourceMappingURL=index.mjs.map\n","// src/slot.tsx\nimport * as React from \"react\";\nimport { composeRefs } from \"@radix-ui/react-compose-refs\";\nimport { Fragment as Fragment2, jsx } from \"react/jsx-runtime\";\n// @__NO_SIDE_EFFECTS__\nfunction createSlot(ownerName) {\n  const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);\n  const Slot2 = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    const childrenArray = React.Children.toArray(children);\n    const slottable = childrenArray.find(isSlottable);\n    if (slottable) {\n      const newElement = slottable.props.children;\n      const newChildren = childrenArray.map((child) => {\n        if (child === slottable) {\n          if (React.Children.count(newElement) > 1) return React.Children.only(null);\n          return React.isValidElement(newElement) ? newElement.props.children : null;\n        } else {\n          return child;\n        }\n      });\n      return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: React.isValidElement(newElement) ? React.cloneElement(newElement, void 0, newChildren) : null });\n    }\n    return /* @__PURE__ */ jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });\n  });\n  Slot2.displayName = `${ownerName}.Slot`;\n  return Slot2;\n}\nvar Slot = /* @__PURE__ */ createSlot(\"Slot\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlotClone(ownerName) {\n  const SlotClone = React.forwardRef((props, forwardedRef) => {\n    const { children, ...slotProps } = props;\n    if (React.isValidElement(children)) {\n      const childrenRef = getElementRef(children);\n      const props2 = mergeProps(slotProps, children.props);\n      if (children.type !== React.Fragment) {\n        props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n      }\n      return React.cloneElement(children, props2);\n    }\n    return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n  });\n  SlotClone.displayName = `${ownerName}.SlotClone`;\n  return SlotClone;\n}\nvar SLOTTABLE_IDENTIFIER = Symbol(\"radix.slottable\");\n// @__NO_SIDE_EFFECTS__\nfunction createSlottable(ownerName) {\n  const Slottable2 = ({ children }) => {\n    return /* @__PURE__ */ jsx(Fragment2, { children });\n  };\n  Slottable2.displayName = `${ownerName}.Slottable`;\n  Slottable2.__radixId = SLOTTABLE_IDENTIFIER;\n  return Slottable2;\n}\nvar Slottable = /* @__PURE__ */ createSlottable(\"Slottable\");\nfunction isSlottable(child) {\n  return React.isValidElement(child) && typeof child.type === \"function\" && \"__radixId\" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;\n}\nfunction mergeProps(slotProps, childProps) {\n  const overrideProps = { ...childProps };\n  for (const propName in childProps) {\n    const slotPropValue = slotProps[propName];\n    const childPropValue = childProps[propName];\n    const isHandler = /^on[A-Z]/.test(propName);\n    if (isHandler) {\n      if (slotPropValue && childPropValue) {\n        overrideProps[propName] = (...args) => {\n          const result = childPropValue(...args);\n          slotPropValue(...args);\n          return result;\n        };\n      } else if (slotPropValue) {\n        overrideProps[propName] = slotPropValue;\n      }\n    } else if (propName === \"style\") {\n      overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n    } else if (propName === \"className\") {\n      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(\" \");\n    }\n  }\n  return { ...slotProps, ...overrideProps };\n}\nfunction getElementRef(element) {\n  let getter = Object.getOwnPropertyDescriptor(element.props, \"ref\")?.get;\n  let mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.ref;\n  }\n  getter = Object.getOwnPropertyDescriptor(element, \"ref\")?.get;\n  mayWarn = getter && \"isReactWarning\" in getter && getter.isReactWarning;\n  if (mayWarn) {\n    return element.props.ref;\n  }\n  return element.props.ref || element.ref;\n}\nexport {\n  Slot as Root,\n  Slot,\n  Slottable,\n  createSlot,\n  createSlottable\n};\n//# sourceMappingURL=index.mjs.map\n","\"use client\";\n\n// src/popover.tsx\nimport * as React from \"react\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { createContextScope } from \"@radix-ui/react-context\";\nimport { DismissableLayer } from \"@radix-ui/react-dismissable-layer\";\nimport { useFocusGuards } from \"@radix-ui/react-focus-guards\";\nimport { FocusScope } from \"@radix-ui/react-focus-scope\";\nimport { useId } from \"@radix-ui/react-id\";\nimport * as PopperPrimitive from \"@radix-ui/react-popper\";\nimport { createPopperScope } from \"@radix-ui/react-popper\";\nimport { Portal as PortalPrimitive } from \"@radix-ui/react-portal\";\nimport { Presence } from \"@radix-ui/react-presence\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { createSlot } from \"@radix-ui/react-slot\";\nimport { useControllableState } from \"@radix-ui/react-use-controllable-state\";\nimport { hideOthers } from \"aria-hidden\";\nimport { RemoveScroll } from \"react-remove-scroll\";\nimport { jsx } from \"react/jsx-runtime\";\nvar POPOVER_NAME = \"Popover\";\nvar [createPopoverContext, createPopoverScope] = createContextScope(POPOVER_NAME, [\n  createPopperScope\n]);\nvar usePopperScope = createPopperScope();\nvar [PopoverProvider, usePopoverContext] = createPopoverContext(POPOVER_NAME);\nvar Popover = (props) => {\n  const {\n    __scopePopover,\n    children,\n    open: openProp,\n    defaultOpen,\n    onOpenChange,\n    modal = false\n  } = props;\n  const popperScope = usePopperScope(__scopePopover);\n  const triggerRef = React.useRef(null);\n  const [hasCustomAnchor, setHasCustomAnchor] = React.useState(false);\n  const [open, setOpen] = useControllableState({\n    prop: openProp,\n    defaultProp: defaultOpen ?? false,\n    onChange: onOpenChange,\n    caller: POPOVER_NAME\n  });\n  return /* @__PURE__ */ jsx(PopperPrimitive.Root, { ...popperScope, children: /* @__PURE__ */ jsx(\n    PopoverProvider,\n    {\n      scope: __scopePopover,\n      contentId: useId(),\n      triggerRef,\n      open,\n      onOpenChange: setOpen,\n      onOpenToggle: React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),\n      hasCustomAnchor,\n      onCustomAnchorAdd: React.useCallback(() => setHasCustomAnchor(true), []),\n      onCustomAnchorRemove: React.useCallback(() => setHasCustomAnchor(false), []),\n      modal,\n      children\n    }\n  ) });\n};\nPopover.displayName = POPOVER_NAME;\nvar ANCHOR_NAME = \"PopoverAnchor\";\nvar PopoverAnchor = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopePopover, ...anchorProps } = props;\n    const context = usePopoverContext(ANCHOR_NAME, __scopePopover);\n    const popperScope = usePopperScope(__scopePopover);\n    const { onCustomAnchorAdd, onCustomAnchorRemove } = context;\n    React.useEffect(() => {\n      onCustomAnchorAdd();\n      return () => onCustomAnchorRemove();\n    }, [onCustomAnchorAdd, onCustomAnchorRemove]);\n    return /* @__PURE__ */ jsx(PopperPrimitive.Anchor, { ...popperScope, ...anchorProps, ref: forwardedRef });\n  }\n);\nPopoverAnchor.displayName = ANCHOR_NAME;\nvar TRIGGER_NAME = \"PopoverTrigger\";\nvar PopoverTrigger = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopePopover, ...triggerProps } = props;\n    const context = usePopoverContext(TRIGGER_NAME, __scopePopover);\n    const popperScope = usePopperScope(__scopePopover);\n    const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);\n    const trigger = /* @__PURE__ */ jsx(\n      Primitive.button,\n      {\n        type: \"button\",\n        \"aria-haspopup\": \"dialog\",\n        \"aria-expanded\": context.open,\n        \"aria-controls\": context.contentId,\n        \"data-state\": getState(context.open),\n        ...triggerProps,\n        ref: composedTriggerRef,\n        onClick: composeEventHandlers(props.onClick, context.onOpenToggle)\n      }\n    );\n    return context.hasCustomAnchor ? trigger : /* @__PURE__ */ jsx(PopperPrimitive.Anchor, { asChild: true, ...popperScope, children: trigger });\n  }\n);\nPopoverTrigger.displayName = TRIGGER_NAME;\nvar PORTAL_NAME = \"PopoverPortal\";\nvar [PortalProvider, usePortalContext] = createPopoverContext(PORTAL_NAME, {\n  forceMount: void 0\n});\nvar PopoverPortal = (props) => {\n  const { __scopePopover, forceMount, children, container } = props;\n  const context = usePopoverContext(PORTAL_NAME, __scopePopover);\n  return /* @__PURE__ */ jsx(PortalProvider, { scope: __scopePopover, forceMount, children: /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsx(PortalPrimitive, { asChild: true, container, children }) }) });\n};\nPopoverPortal.displayName = PORTAL_NAME;\nvar CONTENT_NAME = \"PopoverContent\";\nvar PopoverContent = React.forwardRef(\n  (props, forwardedRef) => {\n    const portalContext = usePortalContext(CONTENT_NAME, props.__scopePopover);\n    const { forceMount = portalContext.forceMount, ...contentProps } = props;\n    const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);\n    return /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ jsx(PopoverContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ jsx(PopoverContentNonModal, { ...contentProps, ref: forwardedRef }) });\n  }\n);\nPopoverContent.displayName = CONTENT_NAME;\nvar Slot = createSlot(\"PopoverContent.RemoveScroll\");\nvar PopoverContentModal = React.forwardRef(\n  (props, forwardedRef) => {\n    const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);\n    const contentRef = React.useRef(null);\n    const composedRefs = useComposedRefs(forwardedRef, contentRef);\n    const isRightClickOutsideRef = React.useRef(false);\n    React.useEffect(() => {\n      const content = contentRef.current;\n      if (content) return hideOthers(content);\n    }, []);\n    return /* @__PURE__ */ jsx(RemoveScroll, { as: Slot, allowPinchZoom: true, children: /* @__PURE__ */ jsx(\n      PopoverContentImpl,\n      {\n        ...props,\n        ref: composedRefs,\n        trapFocus: context.open,\n        disableOutsidePointerEvents: true,\n        onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => {\n          event.preventDefault();\n          if (!isRightClickOutsideRef.current) context.triggerRef.current?.focus();\n        }),\n        onPointerDownOutside: composeEventHandlers(\n          props.onPointerDownOutside,\n          (event) => {\n            const originalEvent = event.detail.originalEvent;\n            const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n            const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n            isRightClickOutsideRef.current = isRightClick;\n          },\n          { checkForDefaultPrevented: false }\n        ),\n        onFocusOutside: composeEventHandlers(\n          props.onFocusOutside,\n          (event) => event.preventDefault(),\n          { checkForDefaultPrevented: false }\n        )\n      }\n    ) });\n  }\n);\nvar PopoverContentNonModal = React.forwardRef(\n  (props, forwardedRef) => {\n    const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);\n    const hasInteractedOutsideRef = React.useRef(false);\n    const hasPointerDownOutsideRef = React.useRef(false);\n    return /* @__PURE__ */ jsx(\n      PopoverContentImpl,\n      {\n        ...props,\n        ref: forwardedRef,\n        trapFocus: false,\n        disableOutsidePointerEvents: false,\n        onCloseAutoFocus: (event) => {\n          props.onCloseAutoFocus?.(event);\n          if (!event.defaultPrevented) {\n            if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();\n            event.preventDefault();\n          }\n          hasInteractedOutsideRef.current = false;\n          hasPointerDownOutsideRef.current = false;\n        },\n        onInteractOutside: (event) => {\n          props.onInteractOutside?.(event);\n          if (!event.defaultPrevented) {\n            hasInteractedOutsideRef.current = true;\n            if (event.detail.originalEvent.type === \"pointerdown\") {\n              hasPointerDownOutsideRef.current = true;\n            }\n          }\n          const target = event.target;\n          const targetIsTrigger = context.triggerRef.current?.contains(target);\n          if (targetIsTrigger) event.preventDefault();\n          if (event.detail.originalEvent.type === \"focusin\" && hasPointerDownOutsideRef.current) {\n            event.preventDefault();\n          }\n        }\n      }\n    );\n  }\n);\nvar PopoverContentImpl = React.forwardRef(\n  (props, forwardedRef) => {\n    const {\n      __scopePopover,\n      trapFocus,\n      onOpenAutoFocus,\n      onCloseAutoFocus,\n      disableOutsidePointerEvents,\n      onEscapeKeyDown,\n      onPointerDownOutside,\n      onFocusOutside,\n      onInteractOutside,\n      ...contentProps\n    } = props;\n    const context = usePopoverContext(CONTENT_NAME, __scopePopover);\n    const popperScope = usePopperScope(__scopePopover);\n    useFocusGuards();\n    return /* @__PURE__ */ jsx(\n      FocusScope,\n      {\n        asChild: true,\n        loop: true,\n        trapped: trapFocus,\n        onMountAutoFocus: onOpenAutoFocus,\n        onUnmountAutoFocus: onCloseAutoFocus,\n        children: /* @__PURE__ */ jsx(\n          DismissableLayer,\n          {\n            asChild: true,\n            disableOutsidePointerEvents,\n            onInteractOutside,\n            onEscapeKeyDown,\n            onPointerDownOutside,\n            onFocusOutside,\n            onDismiss: () => context.onOpenChange(false),\n            children: /* @__PURE__ */ jsx(\n              PopperPrimitive.Content,\n              {\n                \"data-state\": getState(context.open),\n                role: \"dialog\",\n                id: context.contentId,\n                ...popperScope,\n                ...contentProps,\n                ref: forwardedRef,\n                style: {\n                  ...contentProps.style,\n                  // re-namespace exposed content custom properties\n                  ...{\n                    \"--radix-popover-content-transform-origin\": \"var(--radix-popper-transform-origin)\",\n                    \"--radix-popover-content-available-width\": \"var(--radix-popper-available-width)\",\n                    \"--radix-popover-content-available-height\": \"var(--radix-popper-available-height)\",\n                    \"--radix-popover-trigger-width\": \"var(--radix-popper-anchor-width)\",\n                    \"--radix-popover-trigger-height\": \"var(--radix-popper-anchor-height)\"\n                  }\n                }\n              }\n            )\n          }\n        )\n      }\n    );\n  }\n);\nvar CLOSE_NAME = \"PopoverClose\";\nvar PopoverClose = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopePopover, ...closeProps } = props;\n    const context = usePopoverContext(CLOSE_NAME, __scopePopover);\n    return /* @__PURE__ */ jsx(\n      Primitive.button,\n      {\n        type: \"button\",\n        ...closeProps,\n        ref: forwardedRef,\n        onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false))\n      }\n    );\n  }\n);\nPopoverClose.displayName = CLOSE_NAME;\nvar ARROW_NAME = \"PopoverArrow\";\nvar PopoverArrow = React.forwardRef(\n  (props, forwardedRef) => {\n    const { __scopePopover, ...arrowProps } = props;\n    const popperScope = usePopperScope(__scopePopover);\n    return /* @__PURE__ */ jsx(PopperPrimitive.Arrow, { ...popperScope, ...arrowProps, ref: forwardedRef });\n  }\n);\nPopoverArrow.displayName = ARROW_NAME;\nfunction getState(open) {\n  return open ? \"open\" : \"closed\";\n}\nvar Root2 = Popover;\nvar Anchor2 = PopoverAnchor;\nvar Trigger = PopoverTrigger;\nvar Portal = PopoverPortal;\nvar Content2 = PopoverContent;\nvar Close = PopoverClose;\nvar Arrow2 = PopoverArrow;\nexport {\n  Anchor2 as Anchor,\n  Arrow2 as Arrow,\n  Close,\n  Content2 as Content,\n  Popover,\n  PopoverAnchor,\n  PopoverArrow,\n  PopoverClose,\n  PopoverContent,\n  PopoverPortal,\n  PopoverTrigger,\n  Portal,\n  Root2 as Root,\n  Trigger,\n  createPopoverScope\n};\n//# sourceMappingURL=index.mjs.map\n","import { type ClassValue, clsx } from 'clsx'\nimport { twMerge } from 'tailwind-merge'\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n","import * as React from \"react\"\nimport { XIcon } from \"lucide-react\"\nimport { Dialog as DialogPrimitive } from \"radix-ui\"\n\nimport { cn } from \"../utils/cn\"\nimport { Button } from \"@components/Button/Button\"\n\nfunction Dialog({\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root>) {\n  return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n  return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n  return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Close>) {\n  return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n  className,\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n  return (\n    <DialogPrimitive.Overlay\n      data-slot=\"dialog-overlay\"\n      className={cn(\n        \"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction DialogContent({\n  className,\n  children,\n  showCloseButton = true,\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content> & {\n  showCloseButton?: boolean\n}) {\n  return (\n    <DialogPortal data-slot=\"dialog-portal\">\n      <div data-slot=\"dialog-overlay\" className=\"fixed inset-0 z-50 bg-black/50\" />\n      <DialogPrimitive.Content\n        data-slot=\"dialog-content\"\n        className={cn(\n          \"bg-white dark:bg-dark-bg-primary 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg\",\n          className\n        )}\n        onPointerDownOutside={(e) => e.preventDefault()}\n        onInteractOutside={(e) => e.preventDefault()}\n        {...props}\n      >\n        {children}\n        {showCloseButton && (\n          <DialogPrimitive.Close\n            data-slot=\"dialog-close\"\n            className=\"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n          >\n            <XIcon />\n            <span className=\"sr-only\">Cerrar</span>\n          </DialogPrimitive.Close>\n        )}\n      </DialogPrimitive.Content>\n    </DialogPortal>\n  )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"dialog-header\"\n      className={cn(\"flex flex-col gap-2 text-center sm:text-left\", className)}\n      {...props}\n    />\n  )\n}\n\nfunction DialogFooter({\n  className,\n  showCloseButton = false,\n  children,\n  ...props\n}: React.ComponentProps<\"div\"> & {\n  showCloseButton?: boolean\n}) {\n  return (\n    <div\n      data-slot=\"dialog-footer\"\n      className={cn(\n        \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n        className\n      )}\n      {...props}\n    >\n      {children}\n      {showCloseButton && (\n        <DialogPrimitive.Close asChild>\n          <Button variant=\"outline\">Cerrar</Button>\n        </DialogPrimitive.Close>\n      )}\n    </div>\n  )\n}\n\nfunction DialogTitle({\n  className,\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Title>) {\n  return (\n    <DialogPrimitive.Title\n      data-slot=\"dialog-title\"\n      className={cn(\"text-lg leading-none font-semibold\", className)}\n      {...props}\n    />\n  )\n}\n\nfunction DialogDescription({\n  className,\n  ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n  return (\n    <DialogPrimitive.Description\n      data-slot=\"dialog-description\"\n      className={cn(\"text-muted-foreground text-sm\", className)}\n      {...props}\n    />\n  )\n}\n\nexport {\n  Dialog,\n  DialogClose,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogOverlay,\n  DialogPortal,\n  DialogTitle,\n  DialogTrigger,\n}\n","import { useState, useRef, useCallback, type KeyboardEvent } from 'react'\nimport { X } from 'lucide-react'\nimport { cn } from '../utils/cn'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\nexport interface PillEmailInputProps {\n  value: string[]\n  onChange: (emails: string[]) => void\n  disabled?: boolean\n  hasError?: boolean\n  id?: string\n  'aria-invalid'?: boolean\n  'aria-describedby'?: string\n}\n\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nexport function PillEmailInput({\n  value,\n  onChange,\n  disabled = false,\n  hasError = false,\n  id,\n  'aria-invalid': ariaInvalid,\n  'aria-describedby': ariaDescribedBy,\n}: PillEmailInputProps) {\n  const [inputValue, setInputValue] = useState('')\n  const [error, setError] = useState<string | null>(null)\n  const inputRef = useRef<HTMLInputElement>(null)\n  const t = useTranslations()\n\n  const addEmail = useCallback(\n    (raw: string) => {\n      const email = raw.trim().toLowerCase()\n      if (!email) return\n\n      if (!EMAIL_REGEX.test(email)) {\n        setError(t.pillEmail.error.invalidFormat)\n        return\n      }\n\n      if (value.includes(email)) {\n        setError(t.pillEmail.error.duplicate)\n        return\n      }\n\n      setError(null)\n      setInputValue('')\n      onChange([...value, email])\n    },\n    [value, onChange, t],\n  )\n\n  const removeEmail = useCallback(\n    (index: number) => {\n      onChange(value.filter((_, i) => i !== index))\n    },\n    [value, onChange],\n  )\n\n  const handleKeyDown = useCallback(\n    (e: KeyboardEvent<HTMLInputElement>) => {\n      if (e.key === 'Enter' || e.key === ',' || e.key === ';') {\n        e.preventDefault()\n        addEmail(inputValue)\n      } else if (e.key === 'Backspace' && inputValue === '' && value.length > 0) {\n        removeEmail(value.length - 1)\n      }\n    },\n    [inputValue, value, addEmail, removeEmail],\n  )\n\n  const handleBlur = useCallback(() => {\n    if (inputValue.trim()) {\n      addEmail(inputValue)\n    }\n  }, [inputValue, addEmail])\n\n  if (disabled) {\n    return (\n      <div\n        role=\"listbox\"\n        aria-label={t.pillEmail.aria.list}\n        aria-invalid={ariaInvalid}\n        aria-describedby={ariaDescribedBy}\n        className=\"flex min-h-[2.5rem] flex-wrap gap-1.5 rounded-lg border border-border-primary bg-bg-secondary px-3 py-2 text-sm text-content-tertiary cursor-not-allowed dark:border-dark-border-primary dark:bg-dark-bg-secondary dark:text-dark-content-tertiary\"\n        id={id}\n      >\n        {value.length > 0 ? (\n          value.map((email, i) => (\n            <span\n              key={email}\n              role=\"option\"\n              aria-selected\n              aria-label={t.pillEmail.aria.emailLabel(email)}\n              className=\"inline-flex items-center rounded-full bg-primary-100 px-2.5 py-0.5 text-xs font-medium text-primary-600 dark:bg-dark-bg-custom dark:text-dark-content-custom\"\n            >\n              {email}\n            </span>\n          ))\n        ) : (\n          <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">&mdash;</span>\n        )}\n      </div>\n    )\n  }\n\n  return (\n    <div>\n      <div\n        role=\"listbox\"\n        aria-label={t.pillEmail.aria.list}\n        aria-invalid={ariaInvalid}\n        aria-describedby={ariaDescribedBy}\n        className={cn(\n          'flex min-h-[2.5rem] flex-wrap items-center gap-1.5 rounded-lg border bg-bg-primary px-3 py-1.5 text-sm text-content-primary transition-all duration-150',\n          'focus-within:ring-2 focus-within:ring-[#329cff] dark:focus-within:ring-[#329cff]',\n          'dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary',\n          hasError || error\n            ? 'border-red-500 focus-within:ring-red-500'\n            : 'border-border-primary',\n        )}\n        onClick={() => inputRef.current?.focus()}\n      >\n        {value.map((email, i) => (\n          <span\n            key={email}\n            role=\"option\"\n            aria-selected\n            aria-label={t.pillEmail.aria.emailLabel(email)}\n            className=\"inline-flex items-center gap-1 rounded-full bg-primary-100 px-2.5 py-0.5 text-xs font-medium text-primary-600 dark:bg-dark-bg-custom dark:text-dark-content-custom\"\n          >\n            {email}\n            <button\n              type=\"button\"\n              onClick={(e) => {\n                e.stopPropagation()\n                removeEmail(i)\n              }}\n              className=\"ml-0.5 inline-flex h-3.5 w-3.5 items-center justify-center rounded-full hover:bg-primary-200 dark:hover:bg-dark-bg-custom/50\"\n              aria-label={t.pillEmail.aria.removeEmail(email)}\n            >\n              <X className=\"h-2.5 w-2.5\" />\n            </button>\n          </span>\n        ))}\n        <input\n          ref={inputRef}\n          type=\"email\"\n          value={inputValue}\n          onChange={(e) => {\n            setInputValue(e.target.value)\n            if (error) setError(null)\n          }}\n          onKeyDown={handleKeyDown}\n          onBlur={handleBlur}\n          maxLength={256}\n          placeholder={value.length === 0 ? t.pillEmail.placeholder : ''}\n          aria-label={t.pillEmail.aria.addEmail}\n          className=\"min-w-[120px] flex-1 bg-transparent outline-hidden border-none shadow-none text-content-primary placeholder:text-content-tertiary dark:text-dark-content-primary dark:placeholder:text-dark-content-tertiary focus:outline-hidden focus:ring-0\"\n          id={id}\n        />\n      </div>\n      {error && (\n        <p className=\"mt-1 text-xs text-content-extensions-red\" role=\"alert\">\n          {error}\n        </p>\n      )}\n    </div>\n  )\n}\n","import { useState, useRef } from 'react'\nimport { Dropdown } from '@components/Dropdown/Dropdown'\nimport { Checkbox } from '@components/Checkbox/Checkbox'\nimport { ChevronsUpDown } from 'lucide-react'\nimport type { EnumOption } from '../types/enum.types'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\ninterface UseForDropdownProps {\n  value: number[]\n  options: EnumOption[]\n  /** Return true to keep dropdown open, false to close it */\n  onChange: (selected: number[]) => boolean\n  disabled?: boolean\n}\n\nexport function UseForDropdown({\n  value,\n  options,\n  onChange,\n  disabled = false,\n}: UseForDropdownProps) {\n  const t = useTranslations()\n  const [isOpen, setIsOpen] = useState(false)\n  const itemClickedRef = useRef(false)\n\n  // Keep a ref to the latest value to avoid stale closures in double-fire scenarios\n  const valueRef = useRef(value)\n  valueRef.current = value\n\n  // AC4: Auto-hide when only one option or fewer\n  if (options.length <= 1) return null\n\n  // AC5: View mode — read-only display\n  if (disabled) {\n    const selectedLabels = options\n      .filter((o) => value.includes(o.value))\n      .map((o) => o.label)\n\n    return (\n      <div\n        className=\"text-sm text-content-primary dark:text-dark-content-primary\"\n        aria-label={t.tagSelector.aria.group}\n      >\n        {selectedLabels.length > 0 ? selectedLabels.join(', ') : '\\u2014'}\n      </div>\n    )\n  }\n\n  const handleToggle = (optionValue: number) => {\n    itemClickedRef.current = true\n    const current = valueRef.current\n    const result = current.includes(optionValue)\n      ? onChange(current.filter((v) => v !== optionValue))\n      : onChange([...current, optionValue])\n    if (result === false) itemClickedRef.current = false\n  }\n\n  const handleOpenChange = (open: boolean) => {\n    if (!open && itemClickedRef.current) {\n      itemClickedRef.current = false\n      return // item was clicked, keep dropdown open\n    }\n    setIsOpen(open)\n  }\n\n  const selectedLabels = options\n    .filter((o) => value.includes(o.value))\n    .map((o) => o.label)\n\n  const displayText = selectedLabels.length > 0\n    ? selectedLabels.join(', ')\n    : t.modal.placeholder.select\n\n  // pointer-events-none on Checkbox prevents the label's programmatic click on the\n  // hidden input from bubbling a second click event to the DropdownItem button.\n  // The DropdownItem <button> handles all click logic; Checkbox is purely visual.\n  //\n  // No \"select all\" entry: this dropdown's real-world use is transferring the single\n  // \"Predeterminado\" classification to one contact (see ContactModal's transfer flow),\n  // not bulk-assigning every classification at once — a mass toggle doesn't map to that\n  // flow and risked tripping the default-transfer/blocked logic by accident.\n  const items = options.map((option) => ({\n    children: (\n      <Checkbox\n        label={option.label}\n        checked={value.includes(option.value)}\n        onChange={() => {}}\n        className=\"pointer-events-none\"\n      />\n    ),\n    onClick: () => handleToggle(option.value),\n  }))\n\n  return (\n    <div className=\"block w-full\">\n      <Dropdown\n        // Dropdown only stretches its trigger wrapper to 100% when its OWN `className`\n        // contains `w-full` (see Dropdown.tsx's `isFullWidth` check) — the trigger button's\n        // own `w-full` below was already there but had no effect, since its `inline-flex`\n        // parent (the wrapper Dropdown renders around `renderTrigger`) was sizing to content.\n        className=\"w-full\"\n        open={isOpen}\n        onOpenChange={handleOpenChange}\n        items={items}\n        ariaLabel={t.tagSelector.aria.group}\n        renderTrigger={() => (\n          <button\n            type=\"button\"\n            className=\"inline-flex items-center justify-between gap-3 w-full px-3 py-2 text-sm font-normal leading-5 rounded-lg border transition-all duration-150 bg-bg-primary border-border-primary text-content-primary dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary hover:border-[#f9f9f9] dark:hover:border-[#3a3a3f] focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary\"\n          >\n            <span className={`truncate ${selectedLabels.length > 0 ? '' : 'text-content-secondary dark:text-content-secondary'}`}>\n              {displayText}\n            </span>\n            <ChevronsUpDown className={`shrink-0 w-4 h-4 transition-transform duration-150 text-content-secondary dark:text-content-secondary ${isOpen ? 'rotate-180' : ''}`} />\n          </button>\n        )}\n      />\n    </div>\n  )\n}\n","import * as React from \"react\"\nimport { AlertDialog as AlertDialogPrimitive } from \"radix-ui\"\n\nimport { cn } from \"../utils/cn\"\n\nfunction AlertDialog({\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {\n  return <AlertDialogPrimitive.Root data-slot=\"alert-dialog\" {...props} />\n}\n\nfunction AlertDialogTrigger({\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {\n  return <AlertDialogPrimitive.Trigger data-slot=\"alert-dialog-trigger\" {...props} />\n}\n\nfunction AlertDialogPortal({\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {\n  return <AlertDialogPrimitive.Portal data-slot=\"alert-dialog-portal\" {...props} />\n}\n\nfunction AlertDialogOverlay({\n  className,\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {\n  return (\n    <AlertDialogPrimitive.Overlay\n      data-slot=\"alert-dialog-overlay\"\n      className={cn(\n        \"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction AlertDialogContent({\n  className,\n  children,\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {\n  return (\n    <AlertDialogPortal>\n      <AlertDialogOverlay />\n      <AlertDialogPrimitive.Content\n        data-slot=\"alert-dialog-content\"\n        className={cn(\n          \"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-md\",\n          className\n        )}\n        {...props}\n      >\n        {children}\n      </AlertDialogPrimitive.Content>\n    </AlertDialogPortal>\n  )\n}\n\nfunction AlertDialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"alert-dialog-header\"\n      className={cn(\"flex flex-col gap-2 text-center sm:text-left\", className)}\n      {...props}\n    />\n  )\n}\n\nfunction AlertDialogFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"alert-dialog-footer\"\n      className={cn(\"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\", className)}\n      {...props}\n    />\n  )\n}\n\nfunction AlertDialogTitle({\n  className,\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n  return (\n    <AlertDialogPrimitive.Title\n      data-slot=\"alert-dialog-title\"\n      className={cn(\"text-lg leading-none font-semibold\", className)}\n      {...props}\n    />\n  )\n}\n\nfunction AlertDialogDescription({\n  className,\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n  return (\n    <AlertDialogPrimitive.Description\n      data-slot=\"alert-dialog-description\"\n      className={cn(\"text-sm text-content-secondary dark:text-dark-content-secondary\", className)}\n      {...props}\n    />\n  )\n}\n\nfunction AlertDialogAction({\n  className,\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {\n  return (\n    <AlertDialogPrimitive.Action\n      data-slot=\"alert-dialog-action\"\n      className={cn(\n        \"inline-flex h-9 items-center justify-center rounded-lg bg-primary-600 px-4 text-sm font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-[#329cff] focus:ring-offset-2 dark:bg-primary-600 dark:hover:bg-primary-500\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction AlertDialogCancel({\n  className,\n  ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {\n  return (\n    <AlertDialogPrimitive.Cancel\n      data-slot=\"alert-dialog-cancel\"\n      className={cn(\n        \"inline-flex h-9 items-center justify-center rounded-lg border border-border-primary bg-bg-primary px-4 text-sm font-medium text-content-primary hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#329cff] focus:ring-offset-2 dark:border-dark-border-primary dark:bg-dark-bg-primary dark:text-dark-content-primary dark:hover:bg-gray-800\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\nexport {\n  AlertDialog,\n  AlertDialogAction,\n  AlertDialogCancel,\n  AlertDialogContent,\n  AlertDialogDescription,\n  AlertDialogFooter,\n  AlertDialogHeader,\n  AlertDialogOverlay,\n  AlertDialogPortal,\n  AlertDialogTitle,\n  AlertDialogTrigger,\n}\n","import { AlertTriangle } from 'lucide-react'\nimport {\n  AlertDialog,\n  AlertDialogAction,\n  AlertDialogCancel,\n  AlertDialogContent,\n  AlertDialogDescription,\n  AlertDialogFooter,\n  AlertDialogHeader,\n  AlertDialogTitle,\n} from '../ui/alert-dialog'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\nexport interface DefaultConfirmationDialogProps {\n  open: boolean\n  currentDefaultName: string\n  newDefaultName: string\n  onConfirm: () => void\n  onCancel: () => void\n}\n\nexport function DefaultConfirmationDialog({\n  open,\n  currentDefaultName,\n  newDefaultName,\n  onConfirm,\n  onCancel,\n}: DefaultConfirmationDialogProps) {\n  const t = useTranslations()\n\n  return (\n    <AlertDialog open={open} onOpenChange={(isOpen) => { if (!isOpen) onCancel() }}>\n      <AlertDialogContent>\n        <AlertDialogHeader>\n          <div className=\"flex items-center gap-3\">\n            <div className=\"flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900\">\n              <AlertTriangle className=\"h-5 w-5 text-amber-500\" />\n            </div>\n            <AlertDialogTitle className=\"text-content-primary dark:text-dark-content-primary\">\n              {t.dialog.default.title}\n            </AlertDialogTitle>\n          </div>\n          <AlertDialogDescription>\n            {t.dialog.default.message(currentDefaultName, newDefaultName)}\n          </AlertDialogDescription>\n        </AlertDialogHeader>\n        <AlertDialogFooter>\n          <AlertDialogCancel>{t.dialog.default.cancel}</AlertDialogCancel>\n          <AlertDialogAction onClick={onConfirm}>{t.dialog.default.confirm}</AlertDialogAction>\n        </AlertDialogFooter>\n      </AlertDialogContent>\n    </AlertDialog>\n  )\n}\n","import { useRef, useCallback, type KeyboardEvent, type ChangeEvent } from 'react'\nimport { cn } from '../utils/cn'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\nexport interface UnifiedPhoneInputProps {\n  value: { areaCode: string; number: string; extension: string }\n  onChange: (value: { areaCode: string; number: string; extension: string }) => void\n  disabled?: boolean\n  hasError?: boolean\n  id?: string\n  'aria-describedby'?: string\n}\n\nconst AREA_MAX = 3\nconst NUMBER_MAX = 10\nconst EXTENSION_MAX = 3\n\nexport function UnifiedPhoneInput({\n  value,\n  onChange,\n  disabled = false,\n  hasError = false,\n  id,\n  'aria-describedby': ariaDescribedBy,\n}: UnifiedPhoneInputProps) {\n  const areaRef = useRef<HTMLInputElement>(null)\n  const numberRef = useRef<HTMLInputElement>(null)\n  const extensionRef = useRef<HTMLInputElement>(null)\n  const t = useTranslations()\n\n  const handleAreaChange = useCallback(\n    (e: ChangeEvent<HTMLInputElement>) => {\n      const val = e.target.value.replace(/\\D/g, '').slice(0, AREA_MAX)\n      onChange({ ...value, areaCode: val })\n      if (val.length === AREA_MAX) {\n        numberRef.current?.focus()\n      }\n    },\n    [value, onChange],\n  )\n\n  const handleNumberChange = useCallback(\n    (e: ChangeEvent<HTMLInputElement>) => {\n      const val = e.target.value.replace(/\\D/g, '').slice(0, NUMBER_MAX)\n      onChange({ ...value, number: val })\n      if (val.length === NUMBER_MAX) {\n        extensionRef.current?.focus()\n      }\n    },\n    [value, onChange],\n  )\n\n  const handleExtensionChange = useCallback(\n    (e: ChangeEvent<HTMLInputElement>) => {\n      const val = e.target.value.replace(/\\D/g, '').slice(0, EXTENSION_MAX)\n      onChange({ ...value, extension: val })\n    },\n    [value, onChange],\n  )\n\n  const handleKeyDown = useCallback(\n    (segment: 'area' | 'number' | 'extension') =>\n      (e: KeyboardEvent<HTMLInputElement>) => {\n        const target = e.currentTarget\n        const atStart = target.selectionStart === 0 && target.selectionEnd === 0\n        const atEnd =\n          target.selectionStart === target.value.length &&\n          target.selectionEnd === target.value.length\n\n        if (e.key === 'Backspace' && atStart) {\n          e.preventDefault()\n          if (segment === 'number') {\n            areaRef.current?.focus()\n          } else if (segment === 'extension') {\n            numberRef.current?.focus()\n          }\n        }\n\n        if (e.key === 'ArrowLeft' && atStart) {\n          e.preventDefault()\n          if (segment === 'number' && areaRef.current) {\n            areaRef.current.focus()\n            const len = areaRef.current.value.length\n            areaRef.current.setSelectionRange(len, len)\n          } else if (segment === 'extension' && numberRef.current) {\n            numberRef.current.focus()\n            const len = numberRef.current.value.length\n            numberRef.current.setSelectionRange(len, len)\n          }\n        }\n\n        if (e.key === 'ArrowRight' && atEnd) {\n          e.preventDefault()\n          if (segment === 'area' && numberRef.current) {\n            numberRef.current.focus()\n            numberRef.current.setSelectionRange(0, 0)\n          } else if (segment === 'number' && extensionRef.current) {\n            extensionRef.current.focus()\n            extensionRef.current.setSelectionRange(0, 0)\n          }\n        }\n      },\n    [],\n  )\n\n  if (disabled) {\n    const display = [value.areaCode, value.number, value.extension]\n      .filter(Boolean)\n      .join(' - ')\n    return (\n      <div\n        role=\"group\"\n        aria-label={t.phoneInput.aria.group}\n        aria-disabled=\"true\"\n        className=\"flex min-h-[2.5rem] items-center rounded-lg border border-border-primary bg-bg-secondary px-3 py-2 text-sm text-content-tertiary cursor-not-allowed dark:border-dark-border-primary dark:bg-dark-bg-secondary dark:text-dark-content-tertiary\"\n        id={id}\n      >\n        {display || '\\u2014'}\n      </div>\n    )\n  }\n\n  return (\n    <div\n      role=\"group\"\n      aria-label={t.phoneInput.aria.group}\n      className={cn(\n        'flex items-center rounded-lg border bg-bg-primary text-sm text-content-primary transition-all duration-150',\n        'focus-within:ring-2 focus-within:ring-[#329cff] dark:focus-within:ring-[#329cff]',\n        'dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary',\n        hasError\n          ? 'border-red-500 focus-within:ring-red-500'\n          : 'border-border-primary',\n      )}\n      id={id}\n      aria-describedby={ariaDescribedBy}\n    >\n      <input\n        ref={areaRef}\n        type=\"text\"\n        inputMode=\"numeric\"\n        value={value.areaCode}\n        onChange={handleAreaChange}\n        onKeyDown={handleKeyDown('area')}\n        placeholder={t.phoneInput.placeholder.area}\n        maxLength={AREA_MAX}\n        aria-label={t.phoneInput.aria.areaCode}\n        className=\"w-16 bg-transparent py-2.5 pl-3 pr-1 outline-none placeholder:text-content-tertiary/60 dark:placeholder:text-dark-content-tertiary/60\"\n      />\n      <input\n        ref={numberRef}\n        type=\"text\"\n        inputMode=\"numeric\"\n        value={value.number}\n        onChange={handleNumberChange}\n        onKeyDown={handleKeyDown('number')}\n        placeholder={t.phoneInput.placeholder.number}\n        maxLength={NUMBER_MAX}\n        aria-label={t.phoneInput.aria.number}\n        className=\"flex-1 min-w-0 bg-transparent py-2.5 px-1 outline-none placeholder:text-content-tertiary/60 dark:placeholder:text-dark-content-tertiary/60\"\n      />\n      <input\n        ref={extensionRef}\n        type=\"text\"\n        inputMode=\"numeric\"\n        value={value.extension}\n        onChange={handleExtensionChange}\n        onKeyDown={handleKeyDown('extension')}\n        placeholder={t.phoneInput.placeholder.extension}\n        maxLength={EXTENSION_MAX}\n        aria-label={t.phoneInput.aria.extension}\n        className=\"w-14 bg-transparent py-2.5 pl-1 pr-3 outline-none placeholder:text-content-tertiary/60 dark:placeholder:text-dark-content-tertiary/60\"\n      />\n    </div>\n  )\n}\n","import { useEffect, useState, useMemo } from 'react'\nimport { useForm, useFieldArray, type FieldErrors } from 'react-hook-form'\nimport { standardSchemaResolver } from '@hookform/resolvers/standard-schema'\nimport { Info, Trash2, X as XIcon, Save, Plus, Pencil } from 'lucide-react'\nimport { Input } from '@components/Input/Input'\nimport { Textarea } from '@components/Textarea/Textarea'\nimport { Button } from '@components/Button/Button'\nimport { Badge } from '@components/Badge/Badge'\nimport { LookupField } from '@components/LookupField'\nimport { Table } from '@components/Table/Table'\nimport type { TableColumn } from '@components/Table/Table.types'\nimport { Select } from '@components/Select/Select'\nimport { toast } from '@components/Toast'\nimport { createContactSchema } from '../schemas/contact.schema'\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogHeader,\n  DialogTitle,\n} from '../ui/dialog'\nimport { PillEmailInput } from './PillEmailInput'\nimport { UseForDropdown } from './UseForDropdown'\nimport { DefaultConfirmationDialog } from './DefaultConfirmationDialog'\nimport { UnifiedPhoneInput } from './UnifiedPhoneInput'\nimport { useMediaQuery } from '../hooks/useMediaQuery'\nimport { cn } from '../utils/cn'\nimport { useTranslations } from '../providers/ContactServiceProvider'\nimport type { Contact, ContactSocialNetwork } from '../types/contact.types'\nimport type { LookupConfig } from '../types/adapter.types'\nimport type { EnumOption } from '../types/enum.types'\nimport { DEFAULT_VALUE } from '../types/enum.types'\nimport type { z } from 'zod'\n\nexport type ContactModalMode = 'create' | 'edit' | 'view'\n\nexport interface ContactModalProps {\n  open: boolean\n  mode: ContactModalMode\n  contact: Contact | null\n  lookupConfig: LookupConfig\n  useForOptions?: EnumOption[]\n  phoneCategoryOptions?: EnumOption[]\n  isFirstContact?: boolean\n  currentDefaultContactName?: string\n  isOnlyDefault?: boolean\n  currentDefaultOnlyHasDefault?: boolean\n  onSave: (data: ContactModalFormData) => void\n  onClose: () => void\n}\n\nconst DEFAULT_SOCIAL_NETWORK: ContactSocialNetwork = {\n  socialNetworkTypeId: '',\n  url: '',\n}\n\nconst TAB_BASIC_DATA = 'basic-data'\nconst TAB_LOCATION = 'location'\nconst TAB_PHONE = 'phone'\nconst TAB_SOCIAL = 'social-network'\n\n/** Maps a form field name to the tab that contains it */\nfunction getTabForField(fieldName: string): string {\n  if (fieldName.startsWith('phones')) return TAB_PHONE\n  if (fieldName.startsWith('socialNetworks')) return TAB_SOCIAL\n  if (fieldName === 'cityId' || fieldName === 'neighborhoodId' || fieldName === 'address') return TAB_LOCATION\n  return TAB_BASIC_DATA\n}\n\nexport type ContactModalFormData = z.infer<ReturnType<typeof createContactSchema>>\n\nexport function ContactModal({\n  open,\n  mode,\n  contact,\n  lookupConfig,\n  useForOptions,\n  phoneCategoryOptions,\n  isFirstContact,\n  currentDefaultContactName,\n  isOnlyDefault,\n  currentDefaultOnlyHasDefault,\n  onSave,\n  onClose,\n}: ContactModalProps) {\n  const isMobile = useMediaQuery('(max-width: 767px)')\n  const isViewMode = mode === 'view'\n  const t = useTranslations()\n\n  const [activeTab, setActiveTab] = useState(TAB_BASIC_DATA)\n\n  const requireClassification = mode === 'edit' || isFirstContact === false\n  const modalFormSchema = useMemo(() => {\n    const full = createContactSchema(t.schema, { requireClassification })\n    return full.pick({\n      name: true,\n      emails: true,\n      address: true,\n      description: true,\n      cityId: true,\n      neighborhoodId: true,\n      useFor: true,\n      phones: true,\n      socialNetworks: true,\n    })\n  }, [t.schema, requireClassification])\n\n  const categories = phoneCategoryOptions && phoneCategoryOptions.length > 0\n    ? phoneCategoryOptions\n    : [{ value: 0, label: t.enums.phoneCategory[0] ?? t.modal.defaultCategory }] as EnumOption[]\n\n  const getCategoryLabel = (categoryValue: number): string => {\n    return categories.find((c) => c.value === categoryValue)?.label ?? String(categoryValue)\n  }\n\n  // LookupField capability detection (presence of config enables the section)\n  const hasCities = !!lookupConfig.cities\n  const hasNeighborhoods = !!lookupConfig.neighborhoods\n  const hasAnyGeoConfig = hasCities || hasNeighborhoods\n\n  // Default transfer confirmation dialog state\n  const [transferDialogOpen, setTransferDialogOpen] = useState(false)\n  const [pendingUseFor, setPendingUseFor] = useState<number[] | null>(null)\n  const [preventRemovalError, setPreventRemovalError] = useState(false)\n\n  const {\n    register,\n    handleSubmit,\n    setValue,\n    watch,\n    reset,\n    setFocus,\n    trigger,\n    control,\n    formState: { errors },\n  } = useForm<ContactModalFormData>({\n    resolver: standardSchemaResolver(modalFormSchema),\n    defaultValues: {\n      name: '',\n      emails: [],\n      address: null,\n      description: null,\n      cityId: null,\n      neighborhoodId: null,\n      useFor: [],\n      phones: [],\n      socialNetworks: [],\n    },\n  })\n\n  const { fields: phoneFields, prepend: prependPhone, remove: removePhone } = useFieldArray({\n    control,\n    name: 'phones',\n  })\n\n  const { fields: socialNetworkFields, prepend: prependSocialNetwork, remove: removeSocialNetwork } = useFieldArray({\n    control,\n    name: 'socialNetworks',\n  })\n\n  useEffect(() => {\n    if (open) {\n      setPreventRemovalError(false)\n      setTransferDialogOpen(false)\n      setPendingUseFor(null)\n      setActiveTab(TAB_BASIC_DATA)\n      if (mode === 'create') {\n        reset({ name: '', emails: [], address: null, description: null, cityId: null, neighborhoodId: null, useFor: [], phones: [], socialNetworks: [] })\n      } else if (contact) {\n        reset({\n          name: contact.name,\n          emails: contact.emails,\n          address: contact.address,\n          description: contact.description,\n          cityId: contact.cityId,\n          neighborhoodId: contact.neighborhoodId,\n          useFor: contact.useFor,\n          phones: contact.phones.length > 0 ? contact.phones : [],\n          socialNetworks: contact.socialNetworks.length > 0 ? contact.socialNetworks : [],\n        })\n      }\n    }\n  }, [open, mode, contact, reset])\n\n  const emails = watch('emails')\n  const nameValue = watch('name')\n\n  const handleCityChange = (record: Record<string, unknown> | null) => {\n    const id = record ? String(record['Id'] ?? record['id'] ?? '') : null\n    setValue('cityId', id)\n    setValue('neighborhoodId', null)\n  }\n\n  const handleNeighborhoodChange = (record: Record<string, unknown> | null) => {\n    const id = record ? String(record['Id'] ?? record['id'] ?? '') : null\n    setValue('neighborhoodId', id)\n  }\n\n  const onSubmit = (data: ContactModalFormData) => {\n    onSave(data)\n  }\n\n  const onError = (formErrors: FieldErrors<ContactModalFormData>) => {\n    // Cross-tab validation: navigate to the tab with the first error\n    const firstErrorField = Object.keys(formErrors)[0] as keyof ContactModalFormData | undefined\n    if (firstErrorField) {\n      const targetTab = getTabForField(firstErrorField)\n      setActiveTab(targetTab)\n      if (firstErrorField !== 'emails' && firstErrorField !== 'phones' && firstErrorField !== 'socialNetworks') {\n        setTimeout(() => setFocus(firstErrorField), 0)\n      }\n    }\n  }\n\n  const handleAddPhone = async () => {\n    const phones = watch('phones')\n    if (phones.length > 0) {\n      const valid = await trigger('phones.0')\n      if (!valid) return\n    }\n    prependPhone({\n      category: categories[0].value,\n      countryId: '',\n      areaCode: '',\n      number: '',\n      extension: '',\n    })\n    setTimeout(() => setFocus('phones.0.number'), 0)\n  }\n\n  /** Returns true if dropdown should stay open, false if it should close */\n  const handleUseForChange = (selected: number[]): boolean => {\n    const currentUseFor = watch('useFor')\n    const wasAdded = selected.includes(DEFAULT_VALUE) && !currentUseFor.includes(DEFAULT_VALUE)\n    const wasRemoved = !selected.includes(DEFAULT_VALUE) && currentUseFor.includes(DEFAULT_VALUE)\n\n    // Clear stale errors on every call\n    setPreventRemovalError(false)\n\n    if (wasAdded && currentDefaultContactName) {\n      if (currentDefaultOnlyHasDefault) {\n        // Block — old default would be left with no classification. A toast (not an inline\n        // field message) because this is a rejected click, not a persistent validation state —\n        // the dropdown selection itself doesn't change, so there's nothing left under the field\n        // to annotate.\n        toast.error(t.modal.error.transferBlocked)\n        return false\n      }\n      // Transfer needed — show confirmation dialog, close dropdown\n      setPendingUseFor(selected)\n      setTransferDialogOpen(true)\n      return false\n    }\n\n    if (wasRemoved && isOnlyDefault) {\n      // Cannot remove only default — show error\n      setPreventRemovalError(true)\n      return true\n    }\n\n    setValue('useFor', selected)\n    return true\n  }\n\n  const handleTransferConfirm = () => {\n    if (pendingUseFor) {\n      setValue('useFor', pendingUseFor)\n    }\n    setPendingUseFor(null)\n    setTransferDialogOpen(false)\n  }\n\n  const handleTransferCancel = () => {\n    setPendingUseFor(null)\n    setTransferDialogOpen(false)\n  }\n\n  const tabItems = [\n    { id: TAB_BASIC_DATA, label: t.modal.tab.basicData },\n    { id: TAB_LOCATION, label: t.modal.tab.location },\n    { id: TAB_PHONE, label: t.modal.tab.phone },\n    { id: TAB_SOCIAL, label: t.modal.tab.socialNetwork },\n  ]\n\n  const handleAddSocialNetwork = async () => {\n    const socialNetworks = watch('socialNetworks')\n    if (socialNetworks.length > 0) {\n      const valid = await trigger('socialNetworks.0')\n      if (!valid) return\n    }\n    prependSocialNetwork({ ...DEFAULT_SOCIAL_NETWORK })\n    setTimeout(() => setFocus('socialNetworks.0.url'), 0)\n  }\n\n  const phoneTableColumns: TableColumn<Record<string, unknown>>[] = [\n    {\n      header: t.modal.label.category,\n      accessor: 'category',\n      width: '130px',\n      render: (_value, _row, index) =>\n        isViewMode ? (\n          <span className=\"text-sm text-content-primary dark:text-dark-content-primary\">\n            {getCategoryLabel(Number((contact?.phones ?? [])[index]?.category ?? 0))}\n          </span>\n        ) : (\n          <Select\n            options={categories.map((c) => ({ value: c.value, label: c.label }))}\n            value={watch(`phones.${index}.category`)}\n            onChange={(val) => setValue(`phones.${index}.category`, Number(val))}\n            ariaLabel={t.modal.aria.phoneCategory(index)}\n          />\n        ),\n    },\n    {\n      header: t.modal.label.country,\n      accessor: 'countryId',\n      // Wide enough that the LookupField trigger and its floating dropdown share the\n      // same width — narrower than this and the dropdown (driven by its own search box\n      // + operator toggle content) grows past the trigger and visually spills into the\n      // \"Teléfono\" column next to it. fixedWidth: without it, Table treats `width` as a\n      // MINIMUM (minmax(260px, 1fr)) and still lets the column grow/shrink with content\n      // (e.g. narrower once cleared) — fixedWidth pins it at exactly 260px always.\n      width: '260px',\n      fixedWidth: true,\n      render: (_value, _row, index) => {\n        const phoneCountryId = isViewMode\n          ? ((contact?.phones ?? [])[index]?.countryId || null)\n          : (watch(`phones.${index}.countryId`) || null)\n        return (\n          // w-full: this cell's wrapper is a flex container (Table.tsx), so without an\n          // explicit width this div — and LookupField inside it — shrinks to fit its own\n          // content (e.g. narrower for \"Select...\" than for \"57 - Colombia\") instead of\n          // filling the fixedWidth column. That's what made the field visibly grow/shrink.\n          <div className=\"w-full\">\n            <LookupField\n              key={phoneFields[index]?.id}\n              entity={lookupConfig.countries.entity}\n              label=\"\"\n              // Empty label still occupies a row-gap slot in LookupField's own flex-col\n              // layout even with zero height, pushing the trigger a few px below sibling\n              // controls (input, buttons) in the same table row — this class removes it\n              // from layout entirely instead of just hiding its (empty) text.\n              className=\"lookup-field--label-hidden\"\n              displayFields={lookupConfig.countries.displayFields}\n              displayTemplate={lookupConfig.countries.displayTemplate}\n              value={phoneCountryId}\n              onChange={isViewMode ? () => {} : (record) => {\n                const id = record ? String(record['Id'] ?? record['id'] ?? '') : ''\n                setValue(`phones.${index}.countryId`, id)\n              }}\n              fetcher={lookupConfig.fetcher}\n              readOnly={isViewMode}\n              disabled={isViewMode}\n              error={!isViewMode && !!errors.phones?.[index]?.countryId}\n              errorText={errors.phones?.[index]?.countryId?.message}\n              onCreateNew={lookupConfig.countries.onCreateNew}\n              createButtonLabel={lookupConfig.countries.createButtonLabel}\n              createTitle={lookupConfig.countries.createTitle}\n              createShowHeader={lookupConfig.countries.createShowHeader}\n              createWidth={lookupConfig.countries.createWidth}\n              createHeight={lookupConfig.countries.createHeight}\n            />\n          </div>\n        )\n      },\n    },\n    {\n      header: t.modal.tab.phone,\n      accessor: 'number',\n      render: (_value, _row, index) => {\n        const phoneData = isViewMode\n          ? (contact?.phones ?? [])[index]\n          : undefined\n        return (\n          <div>\n            <UnifiedPhoneInput\n              value={isViewMode\n                ? { areaCode: phoneData?.areaCode ?? '', number: phoneData?.number ?? '', extension: phoneData?.extension ?? '' }\n                : {\n                    areaCode: watch(`phones.${index}.areaCode`) ?? '',\n                    number: watch(`phones.${index}.number`) ?? '',\n                    extension: watch(`phones.${index}.extension`) ?? '',\n                  }\n              }\n              onChange={isViewMode ? () => {} : (phoneVal) => {\n                setValue(`phones.${index}.areaCode`, phoneVal.areaCode)\n                setValue(`phones.${index}.number`, phoneVal.number)\n                setValue(`phones.${index}.extension`, phoneVal.extension)\n              }}\n              disabled={isViewMode}\n              hasError={!isViewMode && (!!errors.phones?.[index]?.number || !!errors.phones?.[index]?.areaCode || !!errors.phones?.[index]?.extension)}\n            />\n            {!isViewMode && errors.phones?.[index]?.number && (\n              <p id={`phone-${index}-number-error`} className=\"mt-1 text-xs text-red-600\" role=\"alert\">\n                {errors.phones[index].number.message}\n              </p>\n            )}\n            {!isViewMode && errors.phones?.[index]?.areaCode && (\n              <p id={`phone-${index}-area-error`} className=\"mt-1 text-xs text-red-600\" role=\"alert\">\n                {errors.phones[index].areaCode.message}\n              </p>\n            )}\n            {!isViewMode && errors.phones?.[index]?.extension && (\n              <p id={`phone-${index}-ext-error`} className=\"mt-1 text-xs text-red-600\" role=\"alert\">\n                {errors.phones[index].extension.message}\n              </p>\n            )}\n          </div>\n        )\n      },\n    },\n    ...(!isViewMode ? [{\n      header: t.modal.column.actions,\n      accessor: 'id' as const,\n      // Narrower than the other columns' widths — this one only ever holds a single icon-only\n      // delete button, not free-form content, so it doesn't need their room. Still wide enough\n      // for the \"Acciones\" header text itself to render in full (56px clipped it to \"A...\").\n      // fixedWidth (unlike Table's minmax(width, 1fr) default) pins it here instead of\n      // stretching into any leftover row space.\n      width: '100px',\n      fixedWidth: true,\n      stickyRight: true,\n      render: (_value: unknown, _row: Record<string, unknown>, index: number) => (\n        <Button\n          type=\"plain\"\n          size=\"xs\"\n          iconOnly\n          leftIcon={<Trash2 className=\"h-4 w-4 text-content-extensions-red\" />}\n          onClick={() => removePhone(index)}\n          ariaLabel={t.modal.aria.removePhone(index)}\n        />\n      ),\n    }] as TableColumn<Record<string, unknown>>[] : []),\n  ]\n\n  const socialTableColumns: TableColumn<Record<string, unknown>>[] = [\n    {\n      header: t.modal.label.socialType,\n      accessor: 'socialNetworkTypeId',\n      // Same reasoning as the phone table's \"País\" column — wide enough that the\n      // dropdown doesn't grow past its own trigger and spill into the \"URL\" column,\n      // and pinned with fixedWidth so it doesn't grow/shrink with content either.\n      width: '260px',\n      fixedWidth: true,\n      render: (_value, _row, index) => {\n        const snTypeId = isViewMode\n          ? ((contact?.socialNetworks ?? [])[index]?.socialNetworkTypeId || null)\n          : (watch(`socialNetworks.${index}.socialNetworkTypeId`) || null)\n        return (\n          // w-full — same reasoning as the phone table's \"País\" cell above.\n          <div className=\"w-full\">\n            <LookupField\n              key={socialNetworkFields[index]?.id}\n              entity={lookupConfig.socialNetworkTypes.entity}\n              label=\"\"\n              // Empty label still occupies a row-gap slot in LookupField's own flex-col\n              // layout even with zero height, pushing the trigger a few px below sibling\n              // controls (input, buttons) in the same table row — this class removes it\n              // from layout entirely instead of just hiding its (empty) text.\n              className=\"lookup-field--label-hidden\"\n              displayFields={lookupConfig.socialNetworkTypes.displayFields}\n              value={snTypeId}\n              onChange={isViewMode ? () => {} : (record) => {\n                const id = record ? String(record['Id'] ?? record['id'] ?? '') : ''\n                setValue(`socialNetworks.${index}.socialNetworkTypeId`, id)\n              }}\n              fetcher={lookupConfig.fetcher}\n              readOnly={isViewMode}\n              disabled={isViewMode}\n              error={!isViewMode && !!errors.socialNetworks?.[index]?.socialNetworkTypeId}\n              errorText={errors.socialNetworks?.[index]?.socialNetworkTypeId?.message}\n              onCreateNew={lookupConfig.socialNetworkTypes.onCreateNew}\n              createButtonLabel={lookupConfig.socialNetworkTypes.createButtonLabel}\n              createTitle={lookupConfig.socialNetworkTypes.createTitle}\n              createShowHeader={lookupConfig.socialNetworkTypes.createShowHeader}\n              createWidth={lookupConfig.socialNetworkTypes.createWidth}\n              createHeight={lookupConfig.socialNetworkTypes.createHeight}\n            />\n          </div>\n        )\n      },\n    },\n    {\n      header: t.modal.label.socialUrl,\n      accessor: 'url',\n      // No width before this ('1fr' default) let the column shrink enough to truncate\n      // the URL text. A sane minimum keeps it readable without a horizontal scroll.\n      width: '320px',\n      render: (_value, _row, index) => {\n        if (isViewMode) {\n          const sn = (contact?.socialNetworks ?? [])[index]\n          return (\n            <span className=\"text-sm text-content-primary dark:text-dark-content-primary truncate\">\n              {sn?.url || '—'}\n            </span>\n          )\n        }\n        return (\n          // w-full — same reasoning as the \"País\"/\"Red social\" lookup cells above: this\n          // cell's wrapper is a flex container (Table.tsx), so without an explicit width\n          // this div shrinks to fit its own content instead of filling the column.\n          <div className=\"w-full\">\n            <Input\n              {...(register(`socialNetworks.${index}.url`) as any)}\n              type=\"url\"\n              maxLength={2048}\n              placeholder={t.modal.placeholder.socialUrl}\n              className={errors.socialNetworks?.[index]?.url ? 'border-red-500' : ''}\n              aria-label={t.modal.aria.socialUrl(index)}\n              aria-invalid={!!errors.socialNetworks?.[index]?.url}\n              aria-describedby={errors.socialNetworks?.[index]?.url ? `sn-${index}-url-error` : undefined}\n              fullWidth\n            />\n            {errors.socialNetworks?.[index]?.url && (\n              <p id={`sn-${index}-url-error`} className=\"mt-1 text-xs text-red-600\" role=\"alert\">\n                {errors.socialNetworks[index].url.message}\n              </p>\n            )}\n          </div>\n        )\n      },\n    },\n    ...(!isViewMode ? [{\n      header: t.modal.column.actions,\n      accessor: 'id' as const,\n      // 100px (not 56px) — narrow enough that it only ever fits the single icon-only delete\n      // button, but wide enough for the \"Acciones\" header text to render in full.\n      width: '100px',\n      fixedWidth: true,\n      stickyRight: true,\n      render: (_value: unknown, _row: Record<string, unknown>, index: number) => (\n        <Button\n          type=\"plain\"\n          size=\"xs\"\n          iconOnly\n          leftIcon={<Trash2 className=\"h-4 w-4 text-content-extensions-red\" />}\n          onClick={() => removeSocialNetwork(index)}\n          ariaLabel={t.modal.aria.removeSocial(index)}\n        />\n      ),\n    }] as TableColumn<Record<string, unknown>>[] : []),\n  ]\n\n  return (\n    <Dialog modal={false} open={open} onOpenChange={(isOpen) => { if (!isOpen) onClose() }}>\n      <DialogContent\n        showCloseButton={false}\n        className={cn(\n          'flex flex-col overflow-hidden',\n          isMobile && 'w-full h-full max-w-full rounded-none translate-x-0 translate-y-0 top-0 left-0',\n          !isMobile && 'sm:max-w-[1000px] max-h-[90vh]',\n        )}\n        onOpenAutoFocus={(e) => {\n          if (!isViewMode) {\n            e.preventDefault()\n            setTimeout(() => setFocus('name'), 0)\n          }\n        }}\n      >\n        <form onSubmit={handleSubmit(onSubmit, onError)} noValidate className=\"flex flex-col flex-1 min-h-0\">\n          {/* Title on the left, Cancelar/Guardar (or just Cerrar in view mode) top-right — no\n              separate \"X\" close button anymore (showCloseButton={false} above), Cancelar/Cerrar\n              already close the modal. Matches BranchDetailModal's header (BranchPanel.tsx). */}\n          <DialogHeader className=\"shrink-0 pb-4 flex-row items-center justify-between gap-4 space-y-0\">\n            <div className=\"flex flex-col gap-2\">\n              {/* Same blue as BranchDetailModal's title (BranchPanel.tsx, text-[#1355b7]),\n                  traced live from the main Tercero form. Live-updates from the \"Nombre\" field\n                  while typing, same as the contact's own name would once saved. */}\n              <DialogTitle className=\"text-xl font-semibold text-[#1355b7] tracking-tight leading-7\">\n                {t.modal.titlePrefix}{nameValue ? `: ${nameValue}` : ''}\n              </DialogTitle>\n              <DialogDescription className=\"sr-only\">\n                {t.modal.description}\n              </DialogDescription>\n              {!isViewMode && (\n                <Badge\n                  label={mode === 'create' ? t.modal.actionBadge.creating : t.modal.actionBadge.editing}\n                  color=\"yellow\"\n                  leftIcon={<Pencil size={12} />}\n                />\n              )}\n            </div>\n            <div className=\"flex items-center gap-3 shrink-0\">\n              {isViewMode ? (\n                <Button type=\"outline\" htmlType=\"button\" leftIcon={<XIcon size={16} />} onClick={onClose}>\n                  {t.modal.button.close}\n                </Button>\n              ) : (\n                <>\n                  <Button type=\"outline\" htmlType=\"button\" leftIcon={<XIcon size={16} />} onClick={onClose}>\n                    {t.modal.button.cancel}\n                  </Button>\n                  <Button type=\"default\" htmlType=\"submit\" leftIcon={<Save size={16} />}>\n                    {mode === 'create' ? t.modal.button.save : t.modal.button.update}\n                  </Button>\n                </>\n              )}\n            </div>\n          </DialogHeader>\n\n          {/* Tabs + content share one bordered/rounded frame — matches BranchDetailModal's\n              card exactly (BranchPanel.tsx, traced live from MasterPatternView's own TabBar). */}\n          <div className=\"flex-1 flex flex-col min-h-0 rounded-xl border border-neutral-200 dark:border-dark-border-primary overflow-hidden\">\n            <div role=\"tablist\" aria-label={t.modal.description} className=\"flex flex-shrink-0 gap-1 px-3 pt-2\">\n              {tabItems.map((tab) => {\n                const isTabActive = tab.id === activeTab\n                return (\n                  <button\n                    key={tab.id}\n                    type=\"button\"\n                    role=\"tab\"\n                    aria-selected={isTabActive}\n                    onClick={() => setActiveTab(tab.id)}\n                    className={cn(\n                      'relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap cursor-pointer rounded-t-lg bg-[#f8f9fc] transition-colors',\n                      isTabActive ? 'text-blue-600' : 'text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100',\n                    )}\n                  >\n                    {tab.label}\n                    {isTabActive && (\n                      <div className=\"absolute inset-x-0 bottom-0 h-0.5 rounded-full bg-blue-600\" />\n                    )}\n                  </button>\n                )\n              })}\n            </div>\n\n          <div className=\"flex-1 flex flex-col min-h-0 p-4\">\n            {/* Tab: Basic Data */}\n            <div className={activeTab === TAB_BASIC_DATA ? 'flex flex-col flex-1 min-h-0' : 'hidden'}>\n              <div className=\"space-y-4 overflow-y-auto flex-1 min-h-0\">\n                {/* UseFor + Nombre on same row — but only when \"Usar para\" actually renders;\n                    otherwise Nombre must fill the full row instead of sitting in a lone,\n                    half-width grid cell next to nothing. */}\n                <div className={cn('grid grid-cols-1 gap-4', useForOptions && useForOptions.length > 1 && 'sm:grid-cols-2')}>\n                  {/* Usar para */}\n                  {useForOptions && useForOptions.length > 1 && (\n                    <div className=\"space-y-3\">\n                      {/* Nombre's label comes from Input's own labelVariants (text-base,\n                          8px gap) — this custom label is text-sm (4px shorter) with its\n                          own gap, so space-y-3 (vs. the visually-matched-looking 1.5)\n                          makes up the difference and keeps both controls' top edge level. */}\n                      <label className=\"block text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n                        {t.modal.label.useFor} {requireClassification && <span className=\"text-destructive ml-1\">*</span>}\n                      </label>\n                      <UseForDropdown\n                        value={watch('useFor')}\n                        options={useForOptions}\n                        onChange={handleUseForChange}\n                        disabled={isViewMode}\n                      />\n                      {/* transferBlockedError (blocked double-\"Predeterminado\") no longer renders\n                          inline here — it's a one-off, transient notice about a click that was\n                          just rejected, not a persistent field validation state, so it now fires\n                          as a toast (see handleUseForChange) instead of competing for this same\n                          line with preventRemoval/schema errors. */}\n                      {preventRemovalError && (\n                        <p className=\"text-xs text-red-600\" role=\"alert\">\n                          {t.modal.error.preventRemoval}\n                        </p>\n                      )}\n                      {errors.useFor && !preventRemovalError && (\n                        <p className=\"text-xs text-red-600\" role=\"alert\">\n                          {errors.useFor.message}\n                        </p>\n                      )}\n                    </div>\n                  )}\n                  {/* Nombre */}\n                  <div>\n                    {isViewMode ? (\n                      <Input\n                        label={t.modal.label.name}\n                        value={contact?.name || '—'}\n                        disabled\n                        readOnly\n                        onChange={() => {}}\n                      />\n                    ) : (\n                      <Input\n                        label={t.modal.label.name}\n                        required\n                        placeholder={t.modal.placeholder.name}\n                        {...(register('name') as any)}\n                        error={!!errors.name}\n                        errorMessage={errors.name?.message}\n                        aria-invalid={!!errors.name}\n                        fullWidth\n                      />\n                    )}\n                  </div>\n                </div>\n                {errors.useFor && !(useForOptions && useForOptions.length > 1) && (\n                  <p className=\"text-xs text-red-600\" role=\"alert\">\n                    {errors.useFor.message}\n                  </p>\n                )}\n\n                {/* Email */}\n                <div className=\"space-y-1.5\">\n                  <label className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n                    {t.modal.label.email}\n                  </label>\n                  <PillEmailInput\n                    id=\"contact-emails\"\n                    value={emails}\n                    onChange={(newEmails) => setValue('emails', newEmails, { shouldValidate: false })}\n                    disabled={isViewMode}\n                    hasError={!!errors.emails}\n                    aria-invalid={!!errors.emails}\n                    aria-describedby={errors.emails ? 'contact-emails-error' : undefined}\n                  />\n                  {errors.emails && (\n                    <p id=\"contact-emails-error\" className=\"text-xs text-red-600\" role=\"alert\">\n                      {errors.emails.message || errors.emails.root?.message}\n                    </p>\n                  )}\n                </div>\n\n                {/* Descripción */}\n                {isViewMode ? (\n                  <Textarea\n                    label={t.modal.label.description}\n                    value={contact?.description || '—'}\n                    disabled\n                    fullWidth\n                    readOnly\n                  />\n                ) : (\n                  <Textarea\n                    label={t.modal.label.description}\n                    placeholder={t.modal.placeholder.description}\n                    {...register('description')}\n                    rows={3}\n                    fullWidth\n                  />\n                )}\n              </div>\n            </div>\n\n            {/* Tab: Location */}\n            <div className={activeTab === TAB_LOCATION ? 'flex flex-col flex-1 min-h-0' : 'hidden'}>\n              <div className=\"space-y-4 overflow-y-auto flex-1 min-h-0\">\n                {/* Ciudad + Barrio */}\n                {hasAnyGeoConfig && (\n                  <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-4\">\n                    {hasCities && (\n                      <LookupField\n                        entity={lookupConfig.cities!.entity}\n                        label={t.modal.label.city}\n                        displayFields={lookupConfig.cities!.displayFields}\n                        value={watch('cityId') ?? null}\n                        onChange={handleCityChange}\n                        fetcher={lookupConfig.fetcher}\n                        disabled={isViewMode}\n                        readOnly={isViewMode}\n                        onCreateNew={lookupConfig.cities!.onCreateNew}\n                        createButtonLabel={lookupConfig.cities!.createButtonLabel}\n                        createTitle={lookupConfig.cities!.createTitle}\n                        createShowHeader={lookupConfig.cities!.createShowHeader}\n                        createWidth={lookupConfig.cities!.createWidth}\n                        createHeight={lookupConfig.cities!.createHeight}\n                      />\n                    )}\n                    {hasNeighborhoods && (\n                      <LookupField\n                        entity={lookupConfig.neighborhoods!.entity}\n                        label={t.modal.label.neighborhood}\n                        displayFields={lookupConfig.neighborhoods!.displayFields}\n                        value={watch('neighborhoodId') ?? null}\n                        onChange={handleNeighborhoodChange}\n                        fetcher={lookupConfig.fetcher}\n                        getFilters={() => ({ CityId: watch('cityId') ?? '' })}\n                        dependencies={[watch('cityId')]}\n                        disabled={isViewMode || !watch('cityId')}\n                        readOnly={isViewMode}\n                        onCreateNew={lookupConfig.neighborhoods!.onCreateNew}\n                        createButtonLabel={lookupConfig.neighborhoods!.createButtonLabel}\n                        createTitle={lookupConfig.neighborhoods!.createTitle}\n                        createShowHeader={lookupConfig.neighborhoods!.createShowHeader}\n                        createWidth={lookupConfig.neighborhoods!.createWidth}\n                        createHeight={lookupConfig.neighborhoods!.createHeight}\n                      />\n                    )}\n                  </div>\n                )}\n\n                {/* Dirección */}\n                {isViewMode ? (\n                  <Input\n                    label={t.modal.label.address}\n                    value={contact?.address || '—'}\n                    disabled\n                    readOnly\n                    onChange={() => {}}\n                  />\n                ) : (\n                  <Input\n                    label={t.modal.label.address}\n                    placeholder={t.modal.placeholder.address}\n                    {...(register('address') as any)}\n                    error={!!errors.address}\n                    errorMessage={errors.address?.message}\n                    fullWidth\n                  />\n                )}\n              </div>\n            </div>\n\n            {/* Tab: Phone */}\n            <div className={activeTab === TAB_PHONE ? 'flex flex-col flex-1 min-h-0' : 'hidden'}>\n              <div className=\"flex flex-col gap-4 flex-1 min-h-0\">\n                {(isViewMode ? (contact?.phones ?? []) : phoneFields).length === 0 ? (\n                  <>\n                    {!isViewMode && (\n                      <div className=\"flex justify-end shrink-0\">\n                        <Button type=\"outline\" htmlType=\"button\" leftIcon={<Plus size={16} />} onClick={handleAddPhone}>\n                          {t.modal.button.addPhone}\n                        </Button>\n                      </div>\n                    )}\n                    {/* Same blue banner as ContactGridEmptyState (the component's own\n                        \"No hay registros\" banner) — consistent color standard across\n                        every empty-state notice in ContactManager. */}\n                    <div className=\"flex items-center gap-3 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 dark:border-blue-800/50 dark:bg-blue-950/30\">\n                      <Info className=\"h-5 w-5 shrink-0 text-blue-600 dark:text-blue-400\" />\n                      <p className=\"text-sm text-blue-800 dark:text-blue-200\">\n                        {t.modal.emptyState.phone}\n                      </p>\n                    </div>\n                  </>\n                ) : (\n                  <>\n                    {!isViewMode && (\n                      <div className=\"flex justify-end shrink-0\">\n                        <Button type=\"outline\" htmlType=\"button\" leftIcon={<Plus size={16} />} onClick={handleAddPhone}>\n                          {t.modal.button.addPhone}\n                        </Button>\n                      </div>\n                    )}\n                    <div className=\"overflow-auto flex-1 min-h-0\">\n                      <Table\n                        columns={phoneTableColumns}\n                        data={(isViewMode ? (contact?.phones ?? []) : phoneFields) as unknown as Record<string, unknown>[]}\n                        showBorder={false}\n                        showShadow={false}\n                        showPadding={false}\n                        fullWidth\n                      />\n                    </div>\n                  </>\n                )}\n                {errors.phones && !Array.isArray(errors.phones) && errors.phones.message && (\n                  <p className=\"text-xs text-red-600\" role=\"alert\">\n                    {errors.phones.message}\n                  </p>\n                )}\n              </div>\n            </div>\n\n            {/* Tab: Social Network */}\n            <div className={activeTab === TAB_SOCIAL ? 'flex flex-col flex-1 min-h-0' : 'hidden'}>\n              <div className=\"flex flex-col gap-4 flex-1 min-h-0\">\n                {(isViewMode ? (contact?.socialNetworks ?? []) : socialNetworkFields).length === 0 ? (\n                  <>\n                    {!isViewMode && (\n                      <div className=\"flex justify-end shrink-0\">\n                        <Button type=\"outline\" htmlType=\"button\" leftIcon={<Plus size={16} />} onClick={handleAddSocialNetwork}>\n                          {t.modal.button.addSocialNetwork}\n                        </Button>\n                      </div>\n                    )}\n                    {/* Same blue banner as ContactGridEmptyState — see the phone tab's\n                        identical empty-state banner above for the rationale. */}\n                    <div className=\"flex items-center gap-3 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 dark:border-blue-800/50 dark:bg-blue-950/30\">\n                      <Info className=\"h-5 w-5 shrink-0 text-blue-600 dark:text-blue-400\" />\n                      <p className=\"text-sm text-blue-800 dark:text-blue-200\">\n                        {t.modal.emptyState.socialNetwork}\n                      </p>\n                    </div>\n                  </>\n                ) : (\n                  <>\n                    {!isViewMode && (\n                      <div className=\"flex justify-end shrink-0\">\n                        <Button type=\"outline\" htmlType=\"button\" leftIcon={<Plus size={16} />} onClick={handleAddSocialNetwork}>\n                          {t.modal.button.addSocialNetwork}\n                        </Button>\n                      </div>\n                    )}\n                    <div className=\"overflow-auto flex-1 min-h-0\">\n                      <Table\n                        columns={socialTableColumns}\n                        data={(isViewMode ? (contact?.socialNetworks ?? []) : socialNetworkFields) as unknown as Record<string, unknown>[]}\n                        showBorder={false}\n                        showShadow={false}\n                        showPadding={false}\n                        fullWidth\n                      />\n                    </div>\n                  </>\n                )}\n                {errors.socialNetworks && !Array.isArray(errors.socialNetworks) && errors.socialNetworks.message && (\n                  <p className=\"text-xs text-red-600\" role=\"alert\">\n                    {errors.socialNetworks.message}\n                  </p>\n                )}\n              </div>\n            </div>\n          </div>\n          </div>\n        </form>\n      </DialogContent>\n      {currentDefaultContactName && (\n        <DefaultConfirmationDialog\n          open={transferDialogOpen}\n          currentDefaultName={currentDefaultContactName}\n          newDefaultName={watch('name') || contact?.name || t.dialog.default.newContactFallback}\n          onConfirm={handleTransferConfirm}\n          onCancel={handleTransferCancel}\n        />\n      )}\n    </Dialog>\n  )\n}\n","import { AlertTriangle } from 'lucide-react'\nimport {\n  AlertDialog,\n  AlertDialogAction,\n  AlertDialogCancel,\n  AlertDialogContent,\n  AlertDialogDescription,\n  AlertDialogFooter,\n  AlertDialogHeader,\n  AlertDialogTitle,\n} from '../ui/alert-dialog'\nimport { useTranslations } from '../providers/ContactServiceProvider'\n\nexport interface DeleteDefaultConfirmationDialogProps {\n  open: boolean\n  /** When true, shows the default-contact variant with dynamic names */\n  isDefaultDelete?: boolean\n  defaultContactName?: string\n  newDefaultName?: string\n  onConfirm: () => void\n  onCancel: () => void\n}\n\nexport function DeleteDefaultConfirmationDialog({\n  open,\n  isDefaultDelete = false,\n  defaultContactName = '',\n  newDefaultName = '',\n  onConfirm,\n  onCancel,\n}: DeleteDefaultConfirmationDialogProps) {\n  const t = useTranslations()\n\n  const title = isDefaultDelete ? t.dialog.deleteDefault.title : t.dialog.delete.title\n  const message = isDefaultDelete\n    ? t.dialog.deleteDefault.message(defaultContactName, newDefaultName)\n    : t.dialog.delete.message\n  const cancelLabel = isDefaultDelete ? t.dialog.deleteDefault.cancel : t.dialog.delete.cancel\n  const confirmLabel = isDefaultDelete ? t.dialog.deleteDefault.confirm : t.dialog.delete.confirm\n\n  return (\n    <AlertDialog open={open} onOpenChange={(isOpen) => { if (!isOpen) onCancel() }}>\n      <AlertDialogContent>\n        <AlertDialogHeader>\n          <div className=\"flex flex-col items-center gap-3 text-center\">\n            <div className=\"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900\">\n              <AlertTriangle className=\"h-6 w-6 text-amber-500\" />\n            </div>\n            <AlertDialogTitle className=\"text-content-primary dark:text-dark-content-primary\">\n              {title}\n            </AlertDialogTitle>\n          </div>\n          <AlertDialogDescription className=\"text-center\">\n            {message}\n          </AlertDialogDescription>\n        </AlertDialogHeader>\n        <AlertDialogFooter className=\"flex justify-center gap-3 sm:justify-center\">\n          <AlertDialogCancel className=\"text-primary-600 hover:text-primary-700 dark:text-dark-content-custom\">\n            {cancelLabel}\n          </AlertDialogCancel>\n          <AlertDialogAction\n            onClick={onConfirm}\n            className=\"bg-red-600 text-white hover:bg-red-700 dark:bg-red-600 dark:hover:bg-red-700\"\n          >\n            {confirmLabel}\n          </AlertDialogAction>\n        </AlertDialogFooter>\n      </AlertDialogContent>\n    </AlertDialog>\n  )\n}\n","import { useEffect, useState, useCallback, useRef, useMemo } from 'react'\nimport { useContactServiceAdapter, useTranslations } from './providers/ContactServiceProvider'\nimport { useContactStore } from './store/useContactStore'\nimport { ContactGrid } from './parts/ContactGrid'\nimport { ContactModal, type ContactModalMode, type ContactModalFormData } from './parts/ContactModal'\nimport { DeleteDefaultConfirmationDialog } from './parts/DeleteDefaultConfirmationDialog'\nimport type { ContactManagerProps } from './types/component.types'\nimport type { Contact } from './types/contact.types'\nimport type { CatalogItem } from './types/adapter.types'\nimport { DEFAULT_VALUE, buildEnumOptions } from './types/enum.types'\n\ninterface ModalState {\n  isOpen: boolean\n  mode: ContactModalMode\n  contact: Contact | null\n}\n\nexport function ContactManager({\n  recordId,\n  mode = 'edit',\n  useForOptions: useForOptionsProp,\n  phoneCategoryOptions,\n  onContactsChange,\n}: ContactManagerProps) {\n  const adapter = useContactServiceAdapter()\n  const t = useTranslations()\n\n  // Determine if consumer extended enum labels via translations\n  const consumerExtendedUseFor = Object.keys(t.enums.useFor).length > 1\n  const consumerExtendedPhoneCat = Object.keys(t.enums.phoneCategory).length > 1\n\n  // Fetch classification values from backend (only when no prop AND no translation extension)\n  const [fetchedValues, setFetchedValues] = useState<number[] | null>(null)\n\n  useEffect(() => {\n    if (useForOptionsProp || consumerExtendedUseFor || !adapter.getClassifications) return\n    let cancelled = false\n    adapter.getClassifications().then((result) => {\n      if (!cancelled) setFetchedValues(result)\n    }).catch(() => {})\n    return () => { cancelled = true }\n  }, [adapter, useForOptionsProp, consumerExtendedUseFor])\n\n  // UseFor resolution: prop > translation-extended > backend-fetched > fallback\n  const resolvedOptions = useForOptionsProp\n    ?? (consumerExtendedUseFor ? buildEnumOptions(t.enums.useFor) : undefined)\n    ?? fetchedValues?.map((v) => ({\n      value: v,\n      label: t.enums.useFor[v] ?? String(v),\n    }))\n    ?? buildEnumOptions(t.enums.useFor)\n\n  // PhoneCategory resolution: prop > translation-extended > fallback\n  const resolvedPhoneCategoryOptions = phoneCategoryOptions\n    ?? (consumerExtendedPhoneCat ? buildEnumOptions(t.enums.phoneCategory) : undefined)\n    ?? buildEnumOptions(t.enums.phoneCategory)\n\n  // AC3: Inject default classification if not present in consumer options\n  const normalizedUseForOptions = useMemo(() => {\n    return resolvedOptions.some((o) => o.value === DEFAULT_VALUE)\n      ? resolvedOptions\n      : [{ value: DEFAULT_VALUE, label: t.enums.useFor[0] ?? t.manager.defaultLabel }, ...resolvedOptions]\n  }, [resolvedOptions, t.enums.useFor, t.manager.defaultLabel])\n  // Social network types — loaded once via fetcher for grid label resolution\n  const [socialNetworkTypes, setSocialNetworkTypes] = useState<CatalogItem[]>([])\n\n  useEffect(() => {\n    let cancelled = false\n    const snConfig = adapter.lookupConfig.socialNetworkTypes\n    adapter.lookupConfig.fetcher(snConfig.entity, { fields: ['Id', ...snConfig.displayFields], page: 1, pageSize: 500 })\n      .then((res) => {\n        if (!cancelled) {\n          setSocialNetworkTypes(\n            res.data.map((r: Record<string, unknown>) => ({\n              id: String(r['Id'] ?? r['id'] ?? ''),\n              name: snConfig.displayFields.map((f) => String(r[f] ?? '')).filter(Boolean).join(' - '),\n            })),\n          )\n        }\n      }).catch(() => {})\n    return () => { cancelled = true }\n  }, [adapter])\n\n  const loadContacts = useContactStore((s) => s.loadContacts)\n  const contacts = useContactStore((s) => s.contacts)\n  const pendingAdds = useContactStore((s) => s.pendingAdds)\n  const pendingEdits = useContactStore((s) => s.pendingEdits)\n  const pendingDeletes = useContactStore((s) => s.pendingDeletes)\n  const addContact = useContactStore((s) => s.addContact)\n  const editContact = useContactStore((s) => s.editContact)\n  const deleteContact = useContactStore((s) => s.deleteContact)\n  const restoreContact = useContactStore((s) => s.restoreContact)\n  const [isLoading, setIsLoading] = useState(true)\n\n  // Delete default confirmation dialog state\n  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)\n  const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null)\n\n  const [modalState, setModalState] = useState<ModalState>({\n    isOpen: false,\n    mode: 'create',\n    contact: null,\n  })\n\n  const modalStateRef = useRef(modalState)\n  modalStateRef.current = modalState\n\n  // Notify parent of pending changes\n  useEffect(() => {\n    const hasChanges = pendingAdds.length > 0 || pendingEdits.size > 0 || pendingDeletes.size > 0\n    onContactsChange?.(hasChanges)\n  }, [pendingAdds, pendingEdits, pendingDeletes, onContactsChange])\n\n  useEffect(() => {\n    let cancelled = false\n    setIsLoading(true)\n    adapter.getByRecordId(recordId).then((loaded) => {\n      if (!cancelled) {\n        loadContacts(recordId, loaded)\n        setIsLoading(false)\n      }\n    }).catch(() => {\n      if (!cancelled) {\n        setIsLoading(false)\n      }\n    })\n    return () => { cancelled = true }\n  }, [recordId, adapter, loadContacts])\n\n  const handleAdd = useCallback(() => {\n    setModalState({ isOpen: true, mode: 'create', contact: null })\n  }, [])\n\n  const handleEdit = useCallback((id: string) => {\n    const found = contacts.find((c) => c.id === id) ?? null\n    if (found) {\n      setModalState({ isOpen: true, mode: 'edit', contact: found })\n    }\n  }, [contacts])\n\n  const handleView = useCallback((id: string) => {\n    const found = contacts.find((c) => c.id === id) ?? null\n    if (found) {\n      setModalState({ isOpen: true, mode: 'view', contact: found })\n    }\n  }, [contacts])\n\n  const handleClose = useCallback(() => {\n    setModalState((prev) => ({ ...prev, isOpen: false }))\n  }, [])\n\n  // Compute if next created contact would be the first\n  const isFirstContact = useMemo(() => {\n    const activeContacts = contacts.filter((c) => !pendingDeletes.has(c.id ?? ''))\n    return activeContacts.length === 0\n  }, [contacts, pendingDeletes])\n\n  // AC1/AC2: Compute current default contact for transfer detection\n  const currentDefaultContact = useMemo(\n    () => contacts.find((c) => c.useFor.includes(DEFAULT_VALUE) && !pendingDeletes.has(c.id ?? '')) ?? null,\n    [contacts, pendingDeletes],\n  )\n\n  // AC: current default would be left with empty useFor if we transfer\n  const currentDefaultOnlyHasDefault = useMemo(() => {\n    if (!currentDefaultContact) return false\n    return currentDefaultContact.useFor.length === 1 && currentDefaultContact.useFor[0] === DEFAULT_VALUE\n  }, [currentDefaultContact])\n\n  const isOnlyDefault = useMemo(() => {\n    if (!modalState.contact) return false\n    return modalState.contact.useFor.includes(DEFAULT_VALUE)\n      && contacts.filter((c) => c.useFor.includes(DEFAULT_VALUE) && !pendingDeletes.has(c.id ?? '')).length === 1\n  }, [modalState.contact, contacts, pendingDeletes])\n\n  const handleSave = useCallback((data: ContactModalFormData) => {\n    const { mode: currentMode, contact: currentContact } = modalStateRef.current\n    const useFor = data.useFor ?? []\n\n    if (currentMode === 'create') {\n      // AC1: Auto-ensure default on first contact\n      const activeContacts = contacts.filter((c) => !pendingDeletes.has(c.id ?? ''))\n      const ensuredUseFor = activeContacts.length === 0 && !useFor.includes(DEFAULT_VALUE)\n        ? [DEFAULT_VALUE, ...useFor]\n        : useFor\n\n      addContact({\n        recordId,\n        name: data.name,\n        emails: data.emails,\n        address: data.address ?? null,\n        description: data.description ?? null,\n        cityId: data.cityId ?? null,\n        neighborhoodId: data.neighborhoodId ?? null,\n        useFor: ensuredUseFor,\n        phones: data.phones ?? [],\n        socialNetworks: data.socialNetworks ?? [],\n        isDefault: ensuredUseFor.includes(DEFAULT_VALUE),\n      })\n\n      // AC2: Transfer — remove default from old default if new contact has it\n      if (ensuredUseFor.includes(DEFAULT_VALUE)) {\n        const oldDefault = contacts.find((c) => c.useFor.includes(DEFAULT_VALUE) && !pendingDeletes.has(c.id ?? ''))\n        if (oldDefault?.id) {\n          const newUseFor = oldDefault.useFor.filter((u) => u !== DEFAULT_VALUE)\n          // Safety: never leave old default with empty classification\n          if (newUseFor.length > 0) {\n            editContact(oldDefault.id, {\n              useFor: newUseFor,\n              isDefault: false,\n            })\n          }\n        }\n      }\n    } else if (currentMode === 'edit' && currentContact?.id) {\n      // AC2: Transfer — remove default from old default if transfer happened\n      if (useFor.includes(DEFAULT_VALUE) && currentDefaultContact && currentDefaultContact.id !== currentContact.id) {\n        const newUseFor = currentDefaultContact.useFor.filter((u) => u !== DEFAULT_VALUE)\n        // Safety: never leave old default with empty classification\n        if (newUseFor.length > 0 && currentDefaultContact.id) {\n          editContact(currentDefaultContact.id, {\n            useFor: newUseFor,\n            isDefault: false,\n          })\n        }\n      }\n\n      editContact(currentContact.id, {\n        name: data.name,\n        emails: data.emails,\n        address: data.address ?? null,\n        description: data.description ?? null,\n        cityId: data.cityId ?? null,\n        neighborhoodId: data.neighborhoodId ?? null,\n        useFor,\n        phones: data.phones ?? [],\n        socialNetworks: data.socialNetworks ?? [],\n        isDefault: useFor.includes(DEFAULT_VALUE),\n      })\n    }\n    handleClose()\n  }, [recordId, contacts, pendingDeletes, currentDefaultContact, addContact, editContact, handleClose])\n\n  // Delete handler — ALL deletes trigger confirmation dialog\n  const handleDelete = useCallback((id: string) => {\n    const contact = contacts.find((c) => c.id === id)\n    if (!contact) return\n\n    setPendingDeleteId(id)\n    setDeleteDialogOpen(true)\n  }, [contacts])\n\n  const handleDeleteConfirm = useCallback(() => {\n    if (pendingDeleteId) {\n      deleteContact(pendingDeleteId)\n    }\n    setPendingDeleteId(null)\n    setDeleteDialogOpen(false)\n  }, [pendingDeleteId, deleteContact])\n\n  const handleDeleteCancel = useCallback(() => {\n    setPendingDeleteId(null)\n    setDeleteDialogOpen(false)\n  }, [])\n\n  // Compute names for the delete confirmation dialog\n  const deleteDialogContact = pendingDeleteId ? contacts.find((c) => c.id === pendingDeleteId) : null\n  const deleteDialogNewDefault = pendingDeleteId\n    ? contacts.find((c) => c.id !== pendingDeleteId && !pendingDeletes.has(c.id ?? ''))\n    : null\n\n  return (\n    <>\n      <ContactGrid\n        recordId={recordId}\n        mode={mode}\n        useForOptions={normalizedUseForOptions}\n        phoneCategoryOptions={resolvedPhoneCategoryOptions}\n        socialNetworkTypes={socialNetworkTypes}\n        isLoading={isLoading}\n        onAddContact={handleAdd}\n        onEditContact={handleEdit}\n        onViewContact={handleView}\n        onDeleteContact={handleDelete}\n        onRestoreContact={restoreContact}\n      />\n      <DeleteDefaultConfirmationDialog\n        open={deleteDialogOpen}\n        isDefaultDelete={!!deleteDialogContact?.useFor.includes(DEFAULT_VALUE) && !!deleteDialogNewDefault}\n        defaultContactName={deleteDialogContact?.name ?? ''}\n        newDefaultName={deleteDialogNewDefault?.name ?? ''}\n        onConfirm={handleDeleteConfirm}\n        onCancel={handleDeleteCancel}\n      />\n      <ContactModal\n        open={modalState.isOpen}\n        mode={modalState.mode}\n        contact={modalState.contact}\n        lookupConfig={adapter.lookupConfig}\n        useForOptions={normalizedUseForOptions}\n        phoneCategoryOptions={resolvedPhoneCategoryOptions}\n        isFirstContact={isFirstContact}\n        currentDefaultContactName={\n          currentDefaultContact && currentDefaultContact.id !== modalState.contact?.id\n            ? currentDefaultContact.name\n            : undefined\n        }\n        isOnlyDefault={isOnlyDefault}\n        currentDefaultOnlyHasDefault={currentDefaultOnlyHasDefault}\n        onSave={handleSave}\n        onClose={handleClose}\n      />\n    </>\n  )\n}\n","import type { ContactTranslations } from './translations.types'\n\nexport const englishTranslations: ContactTranslations = {\n  schema: {\n    name: {\n      required: 'Name is required',\n      maxLength: 'Name cannot exceed 200 characters',\n    },\n    email: {\n      invalidFormat: 'Invalid email format',\n      maxLength: 'Email cannot exceed 256 characters',\n    },\n    address: {\n      maxLength: 'Address cannot exceed 500 characters',\n    },\n    phone: {\n      countryRequired: 'Country is required',\n      areaCodeMaxLength: 'Area code cannot exceed 3 digits',\n      numberRequired: 'Phone number is required',\n      numberMaxLength: 'Phone number cannot exceed 10 digits',\n      extensionMaxLength: 'Extension cannot exceed 3 digits',\n    },\n    socialNetwork: {\n      typeRequired: 'Please select a social network type',\n      urlRequired: 'Profile URL is required',\n      urlMaxLength: 'URL cannot exceed 2048 characters',\n    },\n    useFor: {\n      required: 'The contact must have at least one use',\n    },\n  },\n  modal: {\n    titlePrefix: 'Contact',\n    actionBadge: {\n      creating: 'Creating',\n      editing: 'Editing',\n    },\n    description: 'Contact form',\n    button: {\n      save: 'Save',\n      update: 'Update',\n      cancel: 'Cancel',\n      close: 'Close',\n      addPhone: 'Add phone',\n      addSocialNetwork: 'Add social network',\n    },\n    label: {\n      name: 'Name',\n      email: 'Email',\n      address: 'Address',\n      description: 'Description',\n      useFor: 'Use for',\n      country: 'Country',\n      state: 'State/Department',\n      city: 'City',\n      neighborhood: 'Neighborhood',\n      category: 'Category',\n      phoneNumber: 'Number',\n      socialType: 'Social network',\n      socialUrl: 'URL',\n    },\n    placeholder: {\n      name: 'Contact name',\n      address: 'Contact address',\n      description: 'Contact description',\n      select: '\\u2014 Select \\u2014',\n      loading: 'Loading...',\n      socialUrl: 'https://...',\n    },\n    tab: {\n      basicData: 'Basic data',\n      location: 'Location',\n      phone: 'Phone',\n      socialNetwork: 'Social networks',\n    },\n    section: {\n      location: 'Location',\n      phones: 'Phones',\n      socialNetworks: 'Social Networks',\n    },\n    error: {\n      preventRemoval: 'There must be at least one Default contact',\n      transferBlocked: 'Cannot transfer. The current default contact has no other uses and would be left without any.',\n      neighborhoodMismatch: 'The selected neighborhood does not belong to the indicated city',\n      catalogsPhone: 'Error loading catalogs. Country options may not be available.',\n      catalogsSocial: 'Error loading catalogs. Social network types may not be available.',\n    },\n    aria: {\n      phoneCategory: (index: number) => `Phone ${index + 1} category`,\n      phoneCountry: (index: number) => `Phone ${index + 1} country`,\n      removePhone: (index: number) => `Remove phone ${index + 1}`,\n      socialType: (index: number) => `Social network ${index + 1} type`,\n      socialUrl: (index: number) => `Social network ${index + 1} URL`,\n      removeSocial: (index: number) => `Remove social network ${index + 1}`,\n      country: 'Country',\n      state: 'State/Department',\n      city: 'City',\n      neighborhood: 'Neighborhood',\n    },\n    defaultCategory: 'Mobile',\n    emptyState: {\n      phone: 'No records. Click \"Add phone\" to get started.',\n      socialNetwork: 'No records. Click \"Add social network\" to get started.',\n    },\n    column: {\n      actions: 'Actions',\n    },\n  },\n  grid: {\n    title: 'Contact',\n    button: { addContact: 'Add contact' },\n    aria: { table: 'Contacts table' },\n    column: {\n      name: 'Name',\n      email: 'Email',\n      useFor: 'Use for',\n      phone: 'Phone',\n      socialNetworks: 'Social networks',\n      actions: 'Actions',\n    },\n    pagination: {\n      previous: 'Previous',\n      next: 'Next',\n    },\n    emptyBanner: \"No records. Click 'Add contact' to get started.\",\n    socialNetworkNotEnabled: 'Social network not enabled',\n  },\n  actions: {\n    pendingDelete: 'Pending deletion',\n    undo: 'Undo',\n    viewDetail: 'View Detail',\n    edit: 'Edit',\n    delete: 'Delete',\n  },\n  emptyState: {\n    noContacts: 'No contacts registered.',\n    addHint: \" Click 'Add Contact' to get started.\",\n    addButton: 'Add Contact',\n  },\n  pillEmail: {\n    error: {\n      invalidFormat: 'Invalid email format',\n      duplicate: 'This email has already been added',\n    },\n    placeholder: 'Enter email and press Enter...',\n    aria: {\n      list: 'Email addresses',\n      emailLabel: (email: string) => `Email: ${email}`,\n      removeEmail: (email: string) => `Remove ${email}`,\n      addEmail: 'Add email address',\n    },\n  },\n  phoneInput: {\n    placeholder: {\n      area: 'Area',\n      number: 'Phone number',\n      extension: 'Ext.',\n    },\n    aria: {\n      group: 'Phone number: area, number, extension',\n      areaCode: 'Area code',\n      number: 'Number',\n      extension: 'Extension',\n    },\n  },\n  tagSelector: {\n    selectAll: 'Use for all',\n    aria: {\n      group: 'Use for',\n      option: (label: string) => `Use for: ${label}`,\n    },\n  },\n  manager: {\n    defaultLabel: 'Default',\n  },\n  dialog: {\n    default: {\n      title: 'Change default contact',\n      newContactFallback: 'the new contact',\n      message: (currentName: string, newName: string) =>\n        `Contact \\u201C${currentName}\\u201D is already marked as Default. Do you want to transfer the default to \\u201C${newName}\\u201D?`,\n      cancel: 'Cancel',\n      confirm: 'Confirm',\n    },\n    delete: {\n      title: 'Delete',\n      message: 'Are you sure you want to delete this record?',\n      cancel: 'Cancel',\n      confirm: 'Confirm',\n    },\n    deleteDefault: {\n      title: 'Delete default contact',\n      message: (defaultName: string, newDefaultName: string) =>\n        `Contact \\u201C${defaultName}\\u201D is the default. Deleting it will transfer the default to \\u201C${newDefaultName}\\u201D. Do you want to continue?`,\n      cancel: 'Cancel',\n      confirm: 'Confirm',\n    },\n  },\n  skeleton: {\n    column: {\n      name: 'Name',\n      email: 'Email',\n      phone: 'Phone',\n      actions: 'Actions',\n    },\n  },\n  enums: {\n    useFor: { 0: 'Default' },\n    phoneCategory: { 0: 'Mobile' },\n  },\n}\n","/**\n * @typedef Options\n *   Configuration for `stringify`.\n * @property {boolean} [padLeft=true]\n *   Whether to pad a space before a token.\n * @property {boolean} [padRight=false]\n *   Whether to pad a space after a token.\n */\n\n/**\n * @typedef {Options} StringifyOptions\n *   Please use `StringifyOptions` instead.\n */\n\n/**\n * Parse comma-separated tokens to an array.\n *\n * @param {string} value\n *   Comma-separated tokens.\n * @returns {Array<string>}\n *   List of tokens.\n */\nexport function parse(value) {\n  /** @type {Array<string>} */\n  const tokens = []\n  const input = String(value || '')\n  let index = input.indexOf(',')\n  let start = 0\n  /** @type {boolean} */\n  let end = false\n\n  while (!end) {\n    if (index === -1) {\n      index = input.length\n      end = true\n    }\n\n    const token = input.slice(start, index).trim()\n\n    if (token || !end) {\n      tokens.push(token)\n    }\n\n    start = index + 1\n    index = input.indexOf(',', start)\n  }\n\n  return tokens\n}\n\n/**\n * Serialize an array of strings or numbers to comma-separated tokens.\n *\n * @param {Array<string|number>} values\n *   List of tokens.\n * @param {Options} [options]\n *   Configuration for `stringify` (optional).\n * @returns {string}\n *   Comma-separated tokens.\n */\nexport function stringify(values, options) {\n  const settings = options || {}\n\n  // Ensure the last empty entry is seen.\n  const input = values[values.length - 1] === '' ? [...values, ''] : values\n\n  return input\n    .join(\n      (settings.padRight ? ' ' : '') +\n        ',' +\n        (settings.padLeft === false ? '' : ' ')\n    )\n    .trim()\n}\n","/**\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [jsx=false]\n *   Support JSX identifiers (default: `false`).\n */\n\nconst startRe = /[$_\\p{ID_Start}]/u\nconst contRe = /[$_\\u{200C}\\u{200D}\\p{ID_Continue}]/u\nconst contReJsx = /[-$_\\u{200C}\\u{200D}\\p{ID_Continue}]/u\nconst nameRe = /^[$_\\p{ID_Start}][$_\\u{200C}\\u{200D}\\p{ID_Continue}]*$/u\nconst nameReJsx = /^[$_\\p{ID_Start}][-$_\\u{200C}\\u{200D}\\p{ID_Continue}]*$/u\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Checks if the given code point can start an identifier.\n *\n * @param {number | undefined} code\n *   Code point to check.\n * @returns {boolean}\n *   Whether `code` can start an identifier.\n */\n// Note: `undefined` is supported so you can pass the result from `''.codePointAt`.\nexport function start(code) {\n  return code ? startRe.test(String.fromCodePoint(code)) : false\n}\n\n/**\n * Checks if the given code point can continue an identifier.\n *\n * @param {number | undefined} code\n *   Code point to check.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {boolean}\n *   Whether `code` can continue an identifier.\n */\n// Note: `undefined` is supported so you can pass the result from `''.codePointAt`.\nexport function cont(code, options) {\n  const settings = options || emptyOptions\n  const re = settings.jsx ? contReJsx : contRe\n  return code ? re.test(String.fromCodePoint(code)) : false\n}\n\n/**\n * Checks if the given value is a valid identifier name.\n *\n * @param {string} name\n *   Identifier to check.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {boolean}\n *   Whether `name` can be an identifier.\n */\nexport function name(name, options) {\n  const settings = options || emptyOptions\n  const re = settings.jsx ? nameReJsx : nameRe\n  return re.test(name)\n}\n","/**\n * @typedef {import('hast').Nodes} Nodes\n */\n\n// HTML whitespace expression.\n// See <https://infra.spec.whatwg.org/#ascii-whitespace>.\nconst re = /[ \\t\\n\\f\\r]/g\n\n/**\n * Check if the given value is *inter-element whitespace*.\n *\n * @param {Nodes | string} thing\n *   Thing to check (`Node` or `string`).\n * @returns {boolean}\n *   Whether the `value` is inter-element whitespace (`boolean`): consisting of\n *   zero or more of space, tab (`\\t`), line feed (`\\n`), carriage return\n *   (`\\r`), or form feed (`\\f`); if a node is passed it must be a `Text` node,\n *   whose `value` field is checked.\n */\nexport function whitespace(thing) {\n  return typeof thing === 'object'\n    ? thing.type === 'text'\n      ? empty(thing.value)\n      : false\n    : empty(thing)\n}\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nfunction empty(value) {\n  return value.replace(re, '') === ''\n}\n","/**\n * @import {Schema as SchemaType, Space} from 'property-information'\n */\n\n/** @type {SchemaType} */\nexport class Schema {\n  /**\n   * @param {SchemaType['property']} property\n   *   Property.\n   * @param {SchemaType['normal']} normal\n   *   Normal.\n   * @param {Space | undefined} [space]\n   *   Space.\n   * @returns\n   *   Schema.\n   */\n  constructor(property, normal, space) {\n    this.normal = normal\n    this.property = property\n\n    if (space) {\n      this.space = space\n    }\n  }\n}\n\nSchema.prototype.normal = {}\nSchema.prototype.property = {}\nSchema.prototype.space = undefined\n","/**\n * @import {Info, Space} from 'property-information'\n */\n\nimport {Schema} from './schema.js'\n\n/**\n * @param {ReadonlyArray<Schema>} definitions\n *   Definitions.\n * @param {Space | undefined} [space]\n *   Space.\n * @returns {Schema}\n *   Schema.\n */\nexport function merge(definitions, space) {\n  /** @type {Record<string, Info>} */\n  const property = {}\n  /** @type {Record<string, string>} */\n  const normal = {}\n\n  for (const definition of definitions) {\n    Object.assign(property, definition.property)\n    Object.assign(normal, definition.normal)\n  }\n\n  return new Schema(property, normal, space)\n}\n","/**\n * Get the cleaned case insensitive form of an attribute or property.\n *\n * @param {string} value\n *   An attribute-like or property-like name.\n * @returns {string}\n *   Value that can be used to look up the properly cased property on a\n *   `Schema`.\n */\nexport function normalize(value) {\n  return value.toLowerCase()\n}\n","/**\n * @import {Info as InfoType} from 'property-information'\n */\n\n/** @type {InfoType} */\nexport class Info {\n  /**\n   * @param {string} property\n   *   Property.\n   * @param {string} attribute\n   *   Attribute.\n   * @returns\n   *   Info.\n   */\n  constructor(property, attribute) {\n    this.attribute = attribute\n    this.property = property\n  }\n}\n\nInfo.prototype.attribute = ''\nInfo.prototype.booleanish = false\nInfo.prototype.boolean = false\nInfo.prototype.commaOrSpaceSeparated = false\nInfo.prototype.commaSeparated = false\nInfo.prototype.defined = false\nInfo.prototype.mustUseProperty = false\nInfo.prototype.number = false\nInfo.prototype.overloadedBoolean = false\nInfo.prototype.property = ''\nInfo.prototype.spaceSeparated = false\nInfo.prototype.space = undefined\n","let powers = 0\n\nexport const boolean = increment()\nexport const booleanish = increment()\nexport const overloadedBoolean = increment()\nexport const number = increment()\nexport const spaceSeparated = increment()\nexport const commaSeparated = increment()\nexport const commaOrSpaceSeparated = increment()\n\nfunction increment() {\n  return 2 ** ++powers\n}\n","/**\n * @import {Space} from 'property-information'\n */\n\nimport {Info} from './info.js'\nimport * as types from './types.js'\n\nconst checks = /** @type {ReadonlyArray<keyof typeof types>} */ (\n  Object.keys(types)\n)\n\nexport class DefinedInfo extends Info {\n  /**\n   * @constructor\n   * @param {string} property\n   *   Property.\n   * @param {string} attribute\n   *   Attribute.\n   * @param {number | null | undefined} [mask]\n   *   Mask.\n   * @param {Space | undefined} [space]\n   *   Space.\n   * @returns\n   *   Info.\n   */\n  constructor(property, attribute, mask, space) {\n    let index = -1\n\n    super(property, attribute)\n\n    mark(this, 'space', space)\n\n    if (typeof mask === 'number') {\n      while (++index < checks.length) {\n        const check = checks[index]\n        mark(this, checks[index], (mask & types[check]) === types[check])\n      }\n    }\n  }\n}\n\nDefinedInfo.prototype.defined = true\n\n/**\n * @template {keyof DefinedInfo} Key\n *   Key type.\n * @param {DefinedInfo} values\n *   Info.\n * @param {Key} key\n *   Key.\n * @param {DefinedInfo[Key]} value\n *   Value.\n * @returns {undefined}\n *   Nothing.\n */\nfunction mark(values, key, value) {\n  if (value) {\n    values[key] = value\n  }\n}\n","/**\n * @import {Info, Space} from 'property-information'\n */\n\n/**\n * @typedef Definition\n *   Definition of a schema.\n * @property {Record<string, string> | undefined} [attributes]\n *   Normalzed names to special attribute case.\n * @property {ReadonlyArray<string> | undefined} [mustUseProperty]\n *   Normalized names that must be set as properties.\n * @property {Record<string, number | null>} properties\n *   Property names to their types.\n * @property {Space | undefined} [space]\n *   Space.\n * @property {Transform} transform\n *   Transform a property name.\n */\n\n/**\n * @callback Transform\n *   Transform.\n * @param {Record<string, string>} attributes\n *   Attributes.\n * @param {string} property\n *   Property.\n * @returns {string}\n *   Attribute.\n */\n\nimport {normalize} from '../normalize.js'\nimport {DefinedInfo} from './defined-info.js'\nimport {Schema} from './schema.js'\n\n/**\n * @param {Definition} definition\n *   Definition.\n * @returns {Schema}\n *   Schema.\n */\nexport function create(definition) {\n  /** @type {Record<string, Info>} */\n  const properties = {}\n  /** @type {Record<string, string>} */\n  const normals = {}\n\n  for (const [property, value] of Object.entries(definition.properties)) {\n    const info = new DefinedInfo(\n      property,\n      definition.transform(definition.attributes || {}, property),\n      value,\n      definition.space\n    )\n\n    if (\n      definition.mustUseProperty &&\n      definition.mustUseProperty.includes(property)\n    ) {\n      info.mustUseProperty = true\n    }\n\n    properties[property] = info\n\n    normals[normalize(property)] = property\n    normals[normalize(info.attribute)] = property\n  }\n\n  return new Schema(properties, normals, definition.space)\n}\n","import {create} from './util/create.js'\nimport {booleanish, number, spaceSeparated} from './util/types.js'\n\nexport const aria = create({\n  properties: {\n    ariaActiveDescendant: null,\n    ariaAtomic: booleanish,\n    ariaAutoComplete: null,\n    ariaBusy: booleanish,\n    ariaChecked: booleanish,\n    ariaColCount: number,\n    ariaColIndex: number,\n    ariaColSpan: number,\n    ariaControls: spaceSeparated,\n    ariaCurrent: null,\n    ariaDescribedBy: spaceSeparated,\n    ariaDetails: null,\n    ariaDisabled: booleanish,\n    ariaDropEffect: spaceSeparated,\n    ariaErrorMessage: null,\n    ariaExpanded: booleanish,\n    ariaFlowTo: spaceSeparated,\n    ariaGrabbed: booleanish,\n    ariaHasPopup: null,\n    ariaHidden: booleanish,\n    ariaInvalid: null,\n    ariaKeyShortcuts: null,\n    ariaLabel: null,\n    ariaLabelledBy: spaceSeparated,\n    ariaLevel: number,\n    ariaLive: null,\n    ariaModal: booleanish,\n    ariaMultiLine: booleanish,\n    ariaMultiSelectable: booleanish,\n    ariaOrientation: null,\n    ariaOwns: spaceSeparated,\n    ariaPlaceholder: null,\n    ariaPosInSet: number,\n    ariaPressed: booleanish,\n    ariaReadOnly: booleanish,\n    ariaRelevant: null,\n    ariaRequired: booleanish,\n    ariaRoleDescription: spaceSeparated,\n    ariaRowCount: number,\n    ariaRowIndex: number,\n    ariaRowSpan: number,\n    ariaSelected: booleanish,\n    ariaSetSize: number,\n    ariaSort: null,\n    ariaValueMax: number,\n    ariaValueMin: number,\n    ariaValueNow: number,\n    ariaValueText: null,\n    role: null\n  },\n  transform(_, property) {\n    return property === 'role'\n      ? property\n      : 'aria-' + property.slice(4).toLowerCase()\n  }\n})\n","/**\n * @param {Record<string, string>} attributes\n *   Attributes.\n * @param {string} attribute\n *   Attribute.\n * @returns {string}\n *   Transformed attribute.\n */\nexport function caseSensitiveTransform(attributes, attribute) {\n  return attribute in attributes ? attributes[attribute] : attribute\n}\n","import {caseSensitiveTransform} from './case-sensitive-transform.js'\n\n/**\n * @param {Record<string, string>} attributes\n *   Attributes.\n * @param {string} property\n *   Property.\n * @returns {string}\n *   Transformed property.\n */\nexport function caseInsensitiveTransform(attributes, property) {\n  return caseSensitiveTransform(attributes, property.toLowerCase())\n}\n","import {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\nimport {create} from './util/create.js'\nimport {\n  booleanish,\n  boolean,\n  commaSeparated,\n  number,\n  overloadedBoolean,\n  spaceSeparated\n} from './util/types.js'\n\nexport const html = create({\n  attributes: {\n    acceptcharset: 'accept-charset',\n    classname: 'class',\n    htmlfor: 'for',\n    httpequiv: 'http-equiv'\n  },\n  mustUseProperty: ['checked', 'multiple', 'muted', 'selected'],\n  properties: {\n    // Standard Properties.\n    abbr: null,\n    accept: commaSeparated,\n    acceptCharset: spaceSeparated,\n    accessKey: spaceSeparated,\n    action: null,\n    allow: null,\n    allowFullScreen: boolean,\n    allowPaymentRequest: boolean,\n    allowUserMedia: boolean,\n    alt: null,\n    as: null,\n    async: boolean,\n    autoCapitalize: null,\n    autoComplete: spaceSeparated,\n    autoFocus: boolean,\n    autoPlay: boolean,\n    blocking: spaceSeparated,\n    capture: null,\n    charSet: null,\n    checked: boolean,\n    cite: null,\n    className: spaceSeparated,\n    cols: number,\n    colSpan: null,\n    content: null,\n    contentEditable: booleanish,\n    controls: boolean,\n    controlsList: spaceSeparated,\n    coords: number | commaSeparated,\n    crossOrigin: null,\n    data: null,\n    dateTime: null,\n    decoding: null,\n    default: boolean,\n    defer: boolean,\n    dir: null,\n    dirName: null,\n    disabled: boolean,\n    download: overloadedBoolean,\n    draggable: booleanish,\n    encType: null,\n    enterKeyHint: null,\n    fetchPriority: null,\n    form: null,\n    formAction: null,\n    formEncType: null,\n    formMethod: null,\n    formNoValidate: boolean,\n    formTarget: null,\n    headers: spaceSeparated,\n    height: number,\n    hidden: overloadedBoolean,\n    high: number,\n    href: null,\n    hrefLang: null,\n    htmlFor: spaceSeparated,\n    httpEquiv: spaceSeparated,\n    id: null,\n    imageSizes: null,\n    imageSrcSet: null,\n    inert: boolean,\n    inputMode: null,\n    integrity: null,\n    is: null,\n    isMap: boolean,\n    itemId: null,\n    itemProp: spaceSeparated,\n    itemRef: spaceSeparated,\n    itemScope: boolean,\n    itemType: spaceSeparated,\n    kind: null,\n    label: null,\n    lang: null,\n    language: null,\n    list: null,\n    loading: null,\n    loop: boolean,\n    low: number,\n    manifest: null,\n    max: null,\n    maxLength: number,\n    media: null,\n    method: null,\n    min: null,\n    minLength: number,\n    multiple: boolean,\n    muted: boolean,\n    name: null,\n    nonce: null,\n    noModule: boolean,\n    noValidate: boolean,\n    onAbort: null,\n    onAfterPrint: null,\n    onAuxClick: null,\n    onBeforeMatch: null,\n    onBeforePrint: null,\n    onBeforeToggle: null,\n    onBeforeUnload: null,\n    onBlur: null,\n    onCancel: null,\n    onCanPlay: null,\n    onCanPlayThrough: null,\n    onChange: null,\n    onClick: null,\n    onClose: null,\n    onContextLost: null,\n    onContextMenu: null,\n    onContextRestored: null,\n    onCopy: null,\n    onCueChange: null,\n    onCut: null,\n    onDblClick: null,\n    onDrag: null,\n    onDragEnd: null,\n    onDragEnter: null,\n    onDragExit: null,\n    onDragLeave: null,\n    onDragOver: null,\n    onDragStart: null,\n    onDrop: null,\n    onDurationChange: null,\n    onEmptied: null,\n    onEnded: null,\n    onError: null,\n    onFocus: null,\n    onFormData: null,\n    onHashChange: null,\n    onInput: null,\n    onInvalid: null,\n    onKeyDown: null,\n    onKeyPress: null,\n    onKeyUp: null,\n    onLanguageChange: null,\n    onLoad: null,\n    onLoadedData: null,\n    onLoadedMetadata: null,\n    onLoadEnd: null,\n    onLoadStart: null,\n    onMessage: null,\n    onMessageError: null,\n    onMouseDown: null,\n    onMouseEnter: null,\n    onMouseLeave: null,\n    onMouseMove: null,\n    onMouseOut: null,\n    onMouseOver: null,\n    onMouseUp: null,\n    onOffline: null,\n    onOnline: null,\n    onPageHide: null,\n    onPageShow: null,\n    onPaste: null,\n    onPause: null,\n    onPlay: null,\n    onPlaying: null,\n    onPopState: null,\n    onProgress: null,\n    onRateChange: null,\n    onRejectionHandled: null,\n    onReset: null,\n    onResize: null,\n    onScroll: null,\n    onScrollEnd: null,\n    onSecurityPolicyViolation: null,\n    onSeeked: null,\n    onSeeking: null,\n    onSelect: null,\n    onSlotChange: null,\n    onStalled: null,\n    onStorage: null,\n    onSubmit: null,\n    onSuspend: null,\n    onTimeUpdate: null,\n    onToggle: null,\n    onUnhandledRejection: null,\n    onUnload: null,\n    onVolumeChange: null,\n    onWaiting: null,\n    onWheel: null,\n    open: boolean,\n    optimum: number,\n    pattern: null,\n    ping: spaceSeparated,\n    placeholder: null,\n    playsInline: boolean,\n    popover: null,\n    popoverTarget: null,\n    popoverTargetAction: null,\n    poster: null,\n    preload: null,\n    readOnly: boolean,\n    referrerPolicy: null,\n    rel: spaceSeparated,\n    required: boolean,\n    reversed: boolean,\n    rows: number,\n    rowSpan: number,\n    sandbox: spaceSeparated,\n    scope: null,\n    scoped: boolean,\n    seamless: boolean,\n    selected: boolean,\n    shadowRootClonable: boolean,\n    shadowRootDelegatesFocus: boolean,\n    shadowRootMode: null,\n    shape: null,\n    size: number,\n    sizes: null,\n    slot: null,\n    span: number,\n    spellCheck: booleanish,\n    src: null,\n    srcDoc: null,\n    srcLang: null,\n    srcSet: null,\n    start: number,\n    step: null,\n    style: null,\n    tabIndex: number,\n    target: null,\n    title: null,\n    translate: null,\n    type: null,\n    typeMustMatch: boolean,\n    useMap: null,\n    value: booleanish,\n    width: number,\n    wrap: null,\n    writingSuggestions: null,\n\n    // Legacy.\n    // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis\n    align: null, // Several. Use CSS `text-align` instead,\n    aLink: null, // `<body>`. Use CSS `a:active {color}` instead\n    archive: spaceSeparated, // `<object>`. List of URIs to archives\n    axis: null, // `<td>` and `<th>`. Use `scope` on `<th>`\n    background: null, // `<body>`. Use CSS `background-image` instead\n    bgColor: null, // `<body>` and table elements. Use CSS `background-color` instead\n    border: number, // `<table>`. Use CSS `border-width` instead,\n    borderColor: null, // `<table>`. Use CSS `border-color` instead,\n    bottomMargin: number, // `<body>`\n    cellPadding: null, // `<table>`\n    cellSpacing: null, // `<table>`\n    char: null, // Several table elements. When `align=char`, sets the character to align on\n    charOff: null, // Several table elements. When `char`, offsets the alignment\n    classId: null, // `<object>`\n    clear: null, // `<br>`. Use CSS `clear` instead\n    code: null, // `<object>`\n    codeBase: null, // `<object>`\n    codeType: null, // `<object>`\n    color: null, // `<font>` and `<hr>`. Use CSS instead\n    compact: boolean, // Lists. Use CSS to reduce space between items instead\n    declare: boolean, // `<object>`\n    event: null, // `<script>`\n    face: null, // `<font>`. Use CSS instead\n    frame: null, // `<table>`\n    frameBorder: null, // `<iframe>`. Use CSS `border` instead\n    hSpace: number, // `<img>` and `<object>`\n    leftMargin: number, // `<body>`\n    link: null, // `<body>`. Use CSS `a:link {color: *}` instead\n    longDesc: null, // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`\n    lowSrc: null, // `<img>`. Use a `<picture>`\n    marginHeight: number, // `<body>`\n    marginWidth: number, // `<body>`\n    noResize: boolean, // `<frame>`\n    noHref: boolean, // `<area>`. Use no href instead of an explicit `nohref`\n    noShade: boolean, // `<hr>`. Use background-color and height instead of borders\n    noWrap: boolean, // `<td>` and `<th>`\n    object: null, // `<applet>`\n    profile: null, // `<head>`\n    prompt: null, // `<isindex>`\n    rev: null, // `<link>`\n    rightMargin: number, // `<body>`\n    rules: null, // `<table>`\n    scheme: null, // `<meta>`\n    scrolling: booleanish, // `<frame>`. Use overflow in the child context\n    standby: null, // `<object>`\n    summary: null, // `<table>`\n    text: null, // `<body>`. Use CSS `color` instead\n    topMargin: number, // `<body>`\n    valueType: null, // `<param>`\n    version: null, // `<html>`. Use a doctype.\n    vAlign: null, // Several. Use CSS `vertical-align` instead\n    vLink: null, // `<body>`. Use CSS `a:visited {color}` instead\n    vSpace: number, // `<img>` and `<object>`\n\n    // Non-standard Properties.\n    allowTransparency: null,\n    autoCorrect: null,\n    autoSave: null,\n    disablePictureInPicture: boolean,\n    disableRemotePlayback: boolean,\n    prefix: null,\n    property: null,\n    results: number,\n    security: null,\n    unselectable: null\n  },\n  space: 'html',\n  transform: caseInsensitiveTransform\n})\n","import {caseSensitiveTransform} from './util/case-sensitive-transform.js'\nimport {create} from './util/create.js'\nimport {\n  boolean,\n  commaOrSpaceSeparated,\n  commaSeparated,\n  number,\n  spaceSeparated\n} from './util/types.js'\n\nexport const svg = create({\n  attributes: {\n    accentHeight: 'accent-height',\n    alignmentBaseline: 'alignment-baseline',\n    arabicForm: 'arabic-form',\n    baselineShift: 'baseline-shift',\n    capHeight: 'cap-height',\n    className: 'class',\n    clipPath: 'clip-path',\n    clipRule: 'clip-rule',\n    colorInterpolation: 'color-interpolation',\n    colorInterpolationFilters: 'color-interpolation-filters',\n    colorProfile: 'color-profile',\n    colorRendering: 'color-rendering',\n    crossOrigin: 'crossorigin',\n    dataType: 'datatype',\n    dominantBaseline: 'dominant-baseline',\n    enableBackground: 'enable-background',\n    fillOpacity: 'fill-opacity',\n    fillRule: 'fill-rule',\n    floodColor: 'flood-color',\n    floodOpacity: 'flood-opacity',\n    fontFamily: 'font-family',\n    fontSize: 'font-size',\n    fontSizeAdjust: 'font-size-adjust',\n    fontStretch: 'font-stretch',\n    fontStyle: 'font-style',\n    fontVariant: 'font-variant',\n    fontWeight: 'font-weight',\n    glyphName: 'glyph-name',\n    glyphOrientationHorizontal: 'glyph-orientation-horizontal',\n    glyphOrientationVertical: 'glyph-orientation-vertical',\n    hrefLang: 'hreflang',\n    horizAdvX: 'horiz-adv-x',\n    horizOriginX: 'horiz-origin-x',\n    horizOriginY: 'horiz-origin-y',\n    imageRendering: 'image-rendering',\n    letterSpacing: 'letter-spacing',\n    lightingColor: 'lighting-color',\n    markerEnd: 'marker-end',\n    markerMid: 'marker-mid',\n    markerStart: 'marker-start',\n    navDown: 'nav-down',\n    navDownLeft: 'nav-down-left',\n    navDownRight: 'nav-down-right',\n    navLeft: 'nav-left',\n    navNext: 'nav-next',\n    navPrev: 'nav-prev',\n    navRight: 'nav-right',\n    navUp: 'nav-up',\n    navUpLeft: 'nav-up-left',\n    navUpRight: 'nav-up-right',\n    onAbort: 'onabort',\n    onActivate: 'onactivate',\n    onAfterPrint: 'onafterprint',\n    onBeforePrint: 'onbeforeprint',\n    onBegin: 'onbegin',\n    onCancel: 'oncancel',\n    onCanPlay: 'oncanplay',\n    onCanPlayThrough: 'oncanplaythrough',\n    onChange: 'onchange',\n    onClick: 'onclick',\n    onClose: 'onclose',\n    onCopy: 'oncopy',\n    onCueChange: 'oncuechange',\n    onCut: 'oncut',\n    onDblClick: 'ondblclick',\n    onDrag: 'ondrag',\n    onDragEnd: 'ondragend',\n    onDragEnter: 'ondragenter',\n    onDragExit: 'ondragexit',\n    onDragLeave: 'ondragleave',\n    onDragOver: 'ondragover',\n    onDragStart: 'ondragstart',\n    onDrop: 'ondrop',\n    onDurationChange: 'ondurationchange',\n    onEmptied: 'onemptied',\n    onEnd: 'onend',\n    onEnded: 'onended',\n    onError: 'onerror',\n    onFocus: 'onfocus',\n    onFocusIn: 'onfocusin',\n    onFocusOut: 'onfocusout',\n    onHashChange: 'onhashchange',\n    onInput: 'oninput',\n    onInvalid: 'oninvalid',\n    onKeyDown: 'onkeydown',\n    onKeyPress: 'onkeypress',\n    onKeyUp: 'onkeyup',\n    onLoad: 'onload',\n    onLoadedData: 'onloadeddata',\n    onLoadedMetadata: 'onloadedmetadata',\n    onLoadStart: 'onloadstart',\n    onMessage: 'onmessage',\n    onMouseDown: 'onmousedown',\n    onMouseEnter: 'onmouseenter',\n    onMouseLeave: 'onmouseleave',\n    onMouseMove: 'onmousemove',\n    onMouseOut: 'onmouseout',\n    onMouseOver: 'onmouseover',\n    onMouseUp: 'onmouseup',\n    onMouseWheel: 'onmousewheel',\n    onOffline: 'onoffline',\n    onOnline: 'ononline',\n    onPageHide: 'onpagehide',\n    onPageShow: 'onpageshow',\n    onPaste: 'onpaste',\n    onPause: 'onpause',\n    onPlay: 'onplay',\n    onPlaying: 'onplaying',\n    onPopState: 'onpopstate',\n    onProgress: 'onprogress',\n    onRateChange: 'onratechange',\n    onRepeat: 'onrepeat',\n    onReset: 'onreset',\n    onResize: 'onresize',\n    onScroll: 'onscroll',\n    onSeeked: 'onseeked',\n    onSeeking: 'onseeking',\n    onSelect: 'onselect',\n    onShow: 'onshow',\n    onStalled: 'onstalled',\n    onStorage: 'onstorage',\n    onSubmit: 'onsubmit',\n    onSuspend: 'onsuspend',\n    onTimeUpdate: 'ontimeupdate',\n    onToggle: 'ontoggle',\n    onUnload: 'onunload',\n    onVolumeChange: 'onvolumechange',\n    onWaiting: 'onwaiting',\n    onZoom: 'onzoom',\n    overlinePosition: 'overline-position',\n    overlineThickness: 'overline-thickness',\n    paintOrder: 'paint-order',\n    panose1: 'panose-1',\n    pointerEvents: 'pointer-events',\n    referrerPolicy: 'referrerpolicy',\n    renderingIntent: 'rendering-intent',\n    shapeRendering: 'shape-rendering',\n    stopColor: 'stop-color',\n    stopOpacity: 'stop-opacity',\n    strikethroughPosition: 'strikethrough-position',\n    strikethroughThickness: 'strikethrough-thickness',\n    strokeDashArray: 'stroke-dasharray',\n    strokeDashOffset: 'stroke-dashoffset',\n    strokeLineCap: 'stroke-linecap',\n    strokeLineJoin: 'stroke-linejoin',\n    strokeMiterLimit: 'stroke-miterlimit',\n    strokeOpacity: 'stroke-opacity',\n    strokeWidth: 'stroke-width',\n    tabIndex: 'tabindex',\n    textAnchor: 'text-anchor',\n    textDecoration: 'text-decoration',\n    textRendering: 'text-rendering',\n    transformOrigin: 'transform-origin',\n    typeOf: 'typeof',\n    underlinePosition: 'underline-position',\n    underlineThickness: 'underline-thickness',\n    unicodeBidi: 'unicode-bidi',\n    unicodeRange: 'unicode-range',\n    unitsPerEm: 'units-per-em',\n    vAlphabetic: 'v-alphabetic',\n    vHanging: 'v-hanging',\n    vIdeographic: 'v-ideographic',\n    vMathematical: 'v-mathematical',\n    vectorEffect: 'vector-effect',\n    vertAdvY: 'vert-adv-y',\n    vertOriginX: 'vert-origin-x',\n    vertOriginY: 'vert-origin-y',\n    wordSpacing: 'word-spacing',\n    writingMode: 'writing-mode',\n    xHeight: 'x-height',\n    // These were camelcased in Tiny. Now lowercased in SVG 2\n    playbackOrder: 'playbackorder',\n    timelineBegin: 'timelinebegin'\n  },\n  properties: {\n    about: commaOrSpaceSeparated,\n    accentHeight: number,\n    accumulate: null,\n    additive: null,\n    alignmentBaseline: null,\n    alphabetic: number,\n    amplitude: number,\n    arabicForm: null,\n    ascent: number,\n    attributeName: null,\n    attributeType: null,\n    azimuth: number,\n    bandwidth: null,\n    baselineShift: null,\n    baseFrequency: null,\n    baseProfile: null,\n    bbox: null,\n    begin: null,\n    bias: number,\n    by: null,\n    calcMode: null,\n    capHeight: number,\n    className: spaceSeparated,\n    clip: null,\n    clipPath: null,\n    clipPathUnits: null,\n    clipRule: null,\n    color: null,\n    colorInterpolation: null,\n    colorInterpolationFilters: null,\n    colorProfile: null,\n    colorRendering: null,\n    content: null,\n    contentScriptType: null,\n    contentStyleType: null,\n    crossOrigin: null,\n    cursor: null,\n    cx: null,\n    cy: null,\n    d: null,\n    dataType: null,\n    defaultAction: null,\n    descent: number,\n    diffuseConstant: number,\n    direction: null,\n    display: null,\n    dur: null,\n    divisor: number,\n    dominantBaseline: null,\n    download: boolean,\n    dx: null,\n    dy: null,\n    edgeMode: null,\n    editable: null,\n    elevation: number,\n    enableBackground: null,\n    end: null,\n    event: null,\n    exponent: number,\n    externalResourcesRequired: null,\n    fill: null,\n    fillOpacity: number,\n    fillRule: null,\n    filter: null,\n    filterRes: null,\n    filterUnits: null,\n    floodColor: null,\n    floodOpacity: null,\n    focusable: null,\n    focusHighlight: null,\n    fontFamily: null,\n    fontSize: null,\n    fontSizeAdjust: null,\n    fontStretch: null,\n    fontStyle: null,\n    fontVariant: null,\n    fontWeight: null,\n    format: null,\n    fr: null,\n    from: null,\n    fx: null,\n    fy: null,\n    g1: commaSeparated,\n    g2: commaSeparated,\n    glyphName: commaSeparated,\n    glyphOrientationHorizontal: null,\n    glyphOrientationVertical: null,\n    glyphRef: null,\n    gradientTransform: null,\n    gradientUnits: null,\n    handler: null,\n    hanging: number,\n    hatchContentUnits: null,\n    hatchUnits: null,\n    height: null,\n    href: null,\n    hrefLang: null,\n    horizAdvX: number,\n    horizOriginX: number,\n    horizOriginY: number,\n    id: null,\n    ideographic: number,\n    imageRendering: null,\n    initialVisibility: null,\n    in: null,\n    in2: null,\n    intercept: number,\n    k: number,\n    k1: number,\n    k2: number,\n    k3: number,\n    k4: number,\n    kernelMatrix: commaOrSpaceSeparated,\n    kernelUnitLength: null,\n    keyPoints: null, // SEMI_COLON_SEPARATED\n    keySplines: null, // SEMI_COLON_SEPARATED\n    keyTimes: null, // SEMI_COLON_SEPARATED\n    kerning: null,\n    lang: null,\n    lengthAdjust: null,\n    letterSpacing: null,\n    lightingColor: null,\n    limitingConeAngle: number,\n    local: null,\n    markerEnd: null,\n    markerMid: null,\n    markerStart: null,\n    markerHeight: null,\n    markerUnits: null,\n    markerWidth: null,\n    mask: null,\n    maskContentUnits: null,\n    maskUnits: null,\n    mathematical: null,\n    max: null,\n    media: null,\n    mediaCharacterEncoding: null,\n    mediaContentEncodings: null,\n    mediaSize: number,\n    mediaTime: null,\n    method: null,\n    min: null,\n    mode: null,\n    name: null,\n    navDown: null,\n    navDownLeft: null,\n    navDownRight: null,\n    navLeft: null,\n    navNext: null,\n    navPrev: null,\n    navRight: null,\n    navUp: null,\n    navUpLeft: null,\n    navUpRight: null,\n    numOctaves: null,\n    observer: null,\n    offset: null,\n    onAbort: null,\n    onActivate: null,\n    onAfterPrint: null,\n    onBeforePrint: null,\n    onBegin: null,\n    onCancel: null,\n    onCanPlay: null,\n    onCanPlayThrough: null,\n    onChange: null,\n    onClick: null,\n    onClose: null,\n    onCopy: null,\n    onCueChange: null,\n    onCut: null,\n    onDblClick: null,\n    onDrag: null,\n    onDragEnd: null,\n    onDragEnter: null,\n    onDragExit: null,\n    onDragLeave: null,\n    onDragOver: null,\n    onDragStart: null,\n    onDrop: null,\n    onDurationChange: null,\n    onEmptied: null,\n    onEnd: null,\n    onEnded: null,\n    onError: null,\n    onFocus: null,\n    onFocusIn: null,\n    onFocusOut: null,\n    onHashChange: null,\n    onInput: null,\n    onInvalid: null,\n    onKeyDown: null,\n    onKeyPress: null,\n    onKeyUp: null,\n    onLoad: null,\n    onLoadedData: null,\n    onLoadedMetadata: null,\n    onLoadStart: null,\n    onMessage: null,\n    onMouseDown: null,\n    onMouseEnter: null,\n    onMouseLeave: null,\n    onMouseMove: null,\n    onMouseOut: null,\n    onMouseOver: null,\n    onMouseUp: null,\n    onMouseWheel: null,\n    onOffline: null,\n    onOnline: null,\n    onPageHide: null,\n    onPageShow: null,\n    onPaste: null,\n    onPause: null,\n    onPlay: null,\n    onPlaying: null,\n    onPopState: null,\n    onProgress: null,\n    onRateChange: null,\n    onRepeat: null,\n    onReset: null,\n    onResize: null,\n    onScroll: null,\n    onSeeked: null,\n    onSeeking: null,\n    onSelect: null,\n    onShow: null,\n    onStalled: null,\n    onStorage: null,\n    onSubmit: null,\n    onSuspend: null,\n    onTimeUpdate: null,\n    onToggle: null,\n    onUnload: null,\n    onVolumeChange: null,\n    onWaiting: null,\n    onZoom: null,\n    opacity: null,\n    operator: null,\n    order: null,\n    orient: null,\n    orientation: null,\n    origin: null,\n    overflow: null,\n    overlay: null,\n    overlinePosition: number,\n    overlineThickness: number,\n    paintOrder: null,\n    panose1: null,\n    path: null,\n    pathLength: number,\n    patternContentUnits: null,\n    patternTransform: null,\n    patternUnits: null,\n    phase: null,\n    ping: spaceSeparated,\n    pitch: null,\n    playbackOrder: null,\n    pointerEvents: null,\n    points: null,\n    pointsAtX: number,\n    pointsAtY: number,\n    pointsAtZ: number,\n    preserveAlpha: null,\n    preserveAspectRatio: null,\n    primitiveUnits: null,\n    propagate: null,\n    property: commaOrSpaceSeparated,\n    r: null,\n    radius: null,\n    referrerPolicy: null,\n    refX: null,\n    refY: null,\n    rel: commaOrSpaceSeparated,\n    rev: commaOrSpaceSeparated,\n    renderingIntent: null,\n    repeatCount: null,\n    repeatDur: null,\n    requiredExtensions: commaOrSpaceSeparated,\n    requiredFeatures: commaOrSpaceSeparated,\n    requiredFonts: commaOrSpaceSeparated,\n    requiredFormats: commaOrSpaceSeparated,\n    resource: null,\n    restart: null,\n    result: null,\n    rotate: null,\n    rx: null,\n    ry: null,\n    scale: null,\n    seed: null,\n    shapeRendering: null,\n    side: null,\n    slope: null,\n    snapshotTime: null,\n    specularConstant: number,\n    specularExponent: number,\n    spreadMethod: null,\n    spacing: null,\n    startOffset: null,\n    stdDeviation: null,\n    stemh: null,\n    stemv: null,\n    stitchTiles: null,\n    stopColor: null,\n    stopOpacity: null,\n    strikethroughPosition: number,\n    strikethroughThickness: number,\n    string: null,\n    stroke: null,\n    strokeDashArray: commaOrSpaceSeparated,\n    strokeDashOffset: null,\n    strokeLineCap: null,\n    strokeLineJoin: null,\n    strokeMiterLimit: number,\n    strokeOpacity: number,\n    strokeWidth: null,\n    style: null,\n    surfaceScale: number,\n    syncBehavior: null,\n    syncBehaviorDefault: null,\n    syncMaster: null,\n    syncTolerance: null,\n    syncToleranceDefault: null,\n    systemLanguage: commaOrSpaceSeparated,\n    tabIndex: number,\n    tableValues: null,\n    target: null,\n    targetX: number,\n    targetY: number,\n    textAnchor: null,\n    textDecoration: null,\n    textRendering: null,\n    textLength: null,\n    timelineBegin: null,\n    title: null,\n    transformBehavior: null,\n    type: null,\n    typeOf: commaOrSpaceSeparated,\n    to: null,\n    transform: null,\n    transformOrigin: null,\n    u1: null,\n    u2: null,\n    underlinePosition: number,\n    underlineThickness: number,\n    unicode: null,\n    unicodeBidi: null,\n    unicodeRange: null,\n    unitsPerEm: number,\n    values: null,\n    vAlphabetic: number,\n    vMathematical: number,\n    vectorEffect: null,\n    vHanging: number,\n    vIdeographic: number,\n    version: null,\n    vertAdvY: number,\n    vertOriginX: number,\n    vertOriginY: number,\n    viewBox: null,\n    viewTarget: null,\n    visibility: null,\n    width: null,\n    widths: null,\n    wordSpacing: null,\n    writingMode: null,\n    x: null,\n    x1: null,\n    x2: null,\n    xChannelSelector: null,\n    xHeight: number,\n    y: null,\n    y1: null,\n    y2: null,\n    yChannelSelector: null,\n    z: null,\n    zoomAndPan: null\n  },\n  space: 'svg',\n  transform: caseSensitiveTransform\n})\n","import {create} from './util/create.js'\n\nexport const xlink = create({\n  properties: {\n    xLinkActuate: null,\n    xLinkArcRole: null,\n    xLinkHref: null,\n    xLinkRole: null,\n    xLinkShow: null,\n    xLinkTitle: null,\n    xLinkType: null\n  },\n  space: 'xlink',\n  transform(_, property) {\n    return 'xlink:' + property.slice(5).toLowerCase()\n  }\n})\n","import {create} from './util/create.js'\nimport {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\n\nexport const xmlns = create({\n  attributes: {xmlnsxlink: 'xmlns:xlink'},\n  properties: {xmlnsXLink: null, xmlns: null},\n  space: 'xmlns',\n  transform: caseInsensitiveTransform\n})\n","import {create} from './util/create.js'\n\nexport const xml = create({\n  properties: {xmlBase: null, xmlLang: null, xmlSpace: null},\n  space: 'xml',\n  transform(_, property) {\n    return 'xml:' + property.slice(3).toLowerCase()\n  }\n})\n","/**\n * Special cases for React (`Record<string, string>`).\n *\n * `hast` is close to `React` but differs in a couple of cases.\n * To get a React property from a hast property,\n * check if it is in `hastToReact`.\n * If it is, use the corresponding value;\n * otherwise, use the hast property.\n *\n * @type {Record<string, string>}\n */\nexport const hastToReact = {\n  classId: 'classID',\n  dataType: 'datatype',\n  itemId: 'itemID',\n  strokeDashArray: 'strokeDasharray',\n  strokeDashOffset: 'strokeDashoffset',\n  strokeLineCap: 'strokeLinecap',\n  strokeLineJoin: 'strokeLinejoin',\n  strokeMiterLimit: 'strokeMiterlimit',\n  typeOf: 'typeof',\n  xLinkActuate: 'xlinkActuate',\n  xLinkArcRole: 'xlinkArcrole',\n  xLinkHref: 'xlinkHref',\n  xLinkRole: 'xlinkRole',\n  xLinkShow: 'xlinkShow',\n  xLinkTitle: 'xlinkTitle',\n  xLinkType: 'xlinkType',\n  xmlnsXLink: 'xmlnsXlink'\n}\n","/**\n * @import {Schema} from 'property-information'\n */\n\nimport {DefinedInfo} from './util/defined-info.js'\nimport {Info} from './util/info.js'\nimport {normalize} from './normalize.js'\n\nconst cap = /[A-Z]/g\nconst dash = /-[a-z]/g\nconst valid = /^data[-\\w.:]+$/i\n\n/**\n * Look up info on a property.\n *\n * In most cases the given `schema` contains info on the property.\n * All standard,\n * most legacy,\n * and some non-standard properties are supported.\n * For these cases,\n * the returned `Info` has hints about the value of the property.\n *\n * `name` can also be a valid data attribute or property,\n * in which case an `Info` object with the correctly cased `attribute` and\n * `property` is returned.\n *\n * `name` can be an unknown attribute,\n * in which case an `Info` object with `attribute` and `property` set to the\n * given name is returned.\n * It is not recommended to provide unsupported legacy or recently specced\n * properties.\n *\n *\n * @param {Schema} schema\n *   Schema;\n *   either the `html` or `svg` export.\n * @param {string} value\n *   An attribute-like or property-like name;\n *   it will be passed through `normalize` to hopefully find the correct info.\n * @returns {Info}\n *   Info.\n */\nexport function find(schema, value) {\n  const normal = normalize(value)\n  let property = value\n  let Type = Info\n\n  if (normal in schema.normal) {\n    return schema.property[schema.normal[normal]]\n  }\n\n  if (normal.length > 4 && normal.slice(0, 4) === 'data' && valid.test(value)) {\n    // Attribute or property.\n    if (value.charAt(4) === '-') {\n      // Turn it into a property.\n      const rest = value.slice(5).replace(dash, camelcase)\n      property = 'data' + rest.charAt(0).toUpperCase() + rest.slice(1)\n    } else {\n      // Turn it into an attribute.\n      const rest = value.slice(4)\n\n      if (!dash.test(rest)) {\n        let dashes = rest.replace(cap, kebab)\n\n        if (dashes.charAt(0) !== '-') {\n          dashes = '-' + dashes\n        }\n\n        value = 'data' + dashes\n      }\n    }\n\n    Type = DefinedInfo\n  }\n\n  return new Type(property, value)\n}\n\n/**\n * @param {string} $0\n *   Value.\n * @returns {string}\n *   Kebab.\n */\nfunction kebab($0) {\n  return '-' + $0.toLowerCase()\n}\n\n/**\n * @param {string} $0\n *   Value.\n * @returns {string}\n *   Camel.\n */\nfunction camelcase($0) {\n  return $0.charAt(1).toUpperCase()\n}\n","// Note: types exposed from `index.d.ts`.\nimport {merge} from './lib/util/merge.js'\nimport {aria} from './lib/aria.js'\nimport {html as htmlBase} from './lib/html.js'\nimport {svg as svgBase} from './lib/svg.js'\nimport {xlink} from './lib/xlink.js'\nimport {xmlns} from './lib/xmlns.js'\nimport {xml} from './lib/xml.js'\n\nexport {hastToReact} from './lib/hast-to-react.js'\n\nexport const html = merge([aria, htmlBase, xlink, xmlns, xml], 'html')\n\nexport {find} from './lib/find.js'\nexport {normalize} from './lib/normalize.js'\n\nexport const svg = merge([aria, svgBase, xlink, xmlns, xml], 'svg')\n","/**\n * Parse space-separated tokens to an array of strings.\n *\n * @param {string} value\n *   Space-separated tokens.\n * @returns {Array<string>}\n *   List of tokens.\n */\nexport function parse(value) {\n  const input = String(value || '').trim()\n  return input ? input.split(/[ \\t\\n\\r\\f]+/g) : []\n}\n\n/**\n * Serialize an array of strings as space separated-tokens.\n *\n * @param {Array<string|number>} values\n *   List of tokens.\n * @returns {string}\n *   Space-separated tokens.\n */\nexport function stringify(values) {\n  return values.join(' ').trim()\n}\n","'use strict';\n\n// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nvar COMMENT_REGEX = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nvar NEWLINE_REGEX = /\\n/g;\nvar WHITESPACE_REGEX = /^\\s*/;\n\n// declaration\nvar PROPERTY_REGEX = /^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/;\nvar COLON_REGEX = /^:\\s*/;\nvar VALUE_REGEX = /^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/;\nvar SEMICOLON_REGEX = /^[;\\s]*/;\n\n// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill\nvar TRIM_REGEX = /^\\s+|\\s+$/g;\n\n// strings\nvar NEWLINE = '\\n';\nvar FORWARD_SLASH = '/';\nvar ASTERISK = '*';\nvar EMPTY_STRING = '';\n\n// types\nvar TYPE_COMMENT = 'comment';\nvar TYPE_DECLARATION = 'declaration';\n\n/**\n * @param {String} style\n * @param {Object} [options]\n * @return {Object[]}\n * @throws {TypeError}\n * @throws {Error}\n */\nfunction index (style, options) {\n  if (typeof style !== 'string') {\n    throw new TypeError('First argument must be a string');\n  }\n\n  if (!style) return [];\n\n  options = options || {};\n\n  /**\n   * Positional.\n   */\n  var lineno = 1;\n  var column = 1;\n\n  /**\n   * Update lineno and column based on `str`.\n   *\n   * @param {String} str\n   */\n  function updatePosition(str) {\n    var lines = str.match(NEWLINE_REGEX);\n    if (lines) lineno += lines.length;\n    var i = str.lastIndexOf(NEWLINE);\n    column = ~i ? str.length - i : column + str.length;\n  }\n\n  /**\n   * Mark position and patch `node.position`.\n   *\n   * @return {Function}\n   */\n  function position() {\n    var start = { line: lineno, column: column };\n    return function (node) {\n      node.position = new Position(start);\n      whitespace();\n      return node;\n    };\n  }\n\n  /**\n   * Store position information for a node.\n   *\n   * @constructor\n   * @property {Object} start\n   * @property {Object} end\n   * @property {undefined|String} source\n   */\n  function Position(start) {\n    this.start = start;\n    this.end = { line: lineno, column: column };\n    this.source = options.source;\n  }\n\n  /**\n   * Non-enumerable source string.\n   */\n  Position.prototype.content = style;\n\n  /**\n   * Error `msg`.\n   *\n   * @param {String} msg\n   * @throws {Error}\n   */\n  function error(msg) {\n    var err = new Error(\n      options.source + ':' + lineno + ':' + column + ': ' + msg\n    );\n    err.reason = msg;\n    err.filename = options.source;\n    err.line = lineno;\n    err.column = column;\n    err.source = style;\n\n    if (options.silent) ; else {\n      throw err;\n    }\n  }\n\n  /**\n   * Match `re` and return captures.\n   *\n   * @param {RegExp} re\n   * @return {undefined|Array}\n   */\n  function match(re) {\n    var m = re.exec(style);\n    if (!m) return;\n    var str = m[0];\n    updatePosition(str);\n    style = style.slice(str.length);\n    return m;\n  }\n\n  /**\n   * Parse whitespace.\n   */\n  function whitespace() {\n    match(WHITESPACE_REGEX);\n  }\n\n  /**\n   * Parse comments.\n   *\n   * @param {Object[]} [rules]\n   * @return {Object[]}\n   */\n  function comments(rules) {\n    var c;\n    rules = rules || [];\n    while ((c = comment())) {\n      if (c !== false) {\n        rules.push(c);\n      }\n    }\n    return rules;\n  }\n\n  /**\n   * Parse comment.\n   *\n   * @return {Object}\n   * @throws {Error}\n   */\n  function comment() {\n    var pos = position();\n    if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;\n\n    var i = 2;\n    while (\n      EMPTY_STRING != style.charAt(i) &&\n      (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))\n    ) {\n      ++i;\n    }\n    i += 2;\n\n    if (EMPTY_STRING === style.charAt(i - 1)) {\n      return error('End of comment missing');\n    }\n\n    var str = style.slice(2, i - 2);\n    column += 2;\n    updatePosition(str);\n    style = style.slice(i);\n    column += 2;\n\n    return pos({\n      type: TYPE_COMMENT,\n      comment: str\n    });\n  }\n\n  /**\n   * Parse declaration.\n   *\n   * @return {Object}\n   * @throws {Error}\n   */\n  function declaration() {\n    var pos = position();\n\n    // prop\n    var prop = match(PROPERTY_REGEX);\n    if (!prop) return;\n    comment();\n\n    // :\n    if (!match(COLON_REGEX)) return error(\"property missing ':'\");\n\n    // val\n    var val = match(VALUE_REGEX);\n\n    var ret = pos({\n      type: TYPE_DECLARATION,\n      property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),\n      value: val\n        ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))\n        : EMPTY_STRING\n    });\n\n    // ;\n    match(SEMICOLON_REGEX);\n\n    return ret;\n  }\n\n  /**\n   * Parse declarations.\n   *\n   * @return {Object[]}\n   */\n  function declarations() {\n    var decls = [];\n\n    comments(decls);\n\n    // declarations\n    var decl;\n    while ((decl = declaration())) {\n      if (decl !== false) {\n        decls.push(decl);\n        comments(decls);\n      }\n    }\n\n    return decls;\n  }\n\n  whitespace();\n  return declarations();\n}\n\n/**\n * Trim `str`.\n *\n * @param {String} str\n * @return {String}\n */\nfunction trim(str) {\n  return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;\n}\n\nmodule.exports = index;\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = StyleToObject;\nconst inline_style_parser_1 = __importDefault(require(\"inline-style-parser\"));\n/**\n * Parses inline style to object.\n *\n * @param style - Inline style.\n * @param iterator - Iterator.\n * @returns - Style object or null.\n *\n * @example Parsing inline style to object:\n *\n * ```js\n * import parse from 'style-to-object';\n * parse('line-height: 42;'); // { 'line-height': '42' }\n * ```\n */\nfunction StyleToObject(style, iterator) {\n    let styleObject = null;\n    if (!style || typeof style !== 'string') {\n        return styleObject;\n    }\n    const declarations = (0, inline_style_parser_1.default)(style);\n    const hasIterator = typeof iterator === 'function';\n    declarations.forEach((declaration) => {\n        if (declaration.type !== 'declaration') {\n            return;\n        }\n        const { property, value } = declaration;\n        if (hasIterator) {\n            iterator(property, value, declaration);\n        }\n        else if (value) {\n            styleObject = styleObject || {};\n            styleObject[property] = value;\n        }\n    });\n    return styleObject;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.camelCase = void 0;\nvar CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/;\nvar HYPHEN_REGEX = /-([a-z])/g;\nvar NO_HYPHEN_REGEX = /^[^-]+$/;\nvar VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/;\nvar MS_VENDOR_PREFIX_REGEX = /^-(ms)-/;\n/**\n * Checks whether to skip camelCase.\n */\nvar skipCamelCase = function (property) {\n    return !property ||\n        NO_HYPHEN_REGEX.test(property) ||\n        CUSTOM_PROPERTY_REGEX.test(property);\n};\n/**\n * Replacer that capitalizes first character.\n */\nvar capitalize = function (match, character) {\n    return character.toUpperCase();\n};\n/**\n * Replacer that removes beginning hyphen of vendor prefix property.\n */\nvar trimHyphen = function (match, prefix) { return \"\".concat(prefix, \"-\"); };\n/**\n * CamelCases a CSS property.\n */\nvar camelCase = function (property, options) {\n    if (options === void 0) { options = {}; }\n    if (skipCamelCase(property)) {\n        return property;\n    }\n    property = property.toLowerCase();\n    if (options.reactCompat) {\n        // `-ms` vendor prefix should not be capitalized\n        property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen);\n    }\n    else {\n        // for non-React, remove first hyphen so vendor prefix is not capitalized\n        property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen);\n    }\n    return property.replace(HYPHEN_REGEX, capitalize);\n};\nexports.camelCase = camelCase;\n//# sourceMappingURL=utilities.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar style_to_object_1 = __importDefault(require(\"style-to-object\"));\nvar utilities_1 = require(\"./utilities\");\n/**\n * Parses CSS inline style to JavaScript object (camelCased).\n */\nfunction StyleToJS(style, options) {\n    var output = {};\n    if (!style || typeof style !== 'string') {\n        return output;\n    }\n    (0, style_to_object_1.default)(style, function (property, value) {\n        // skip CSS comment\n        if (property && value) {\n            output[(0, utilities_1.camelCase)(property, options)] = value;\n        }\n    });\n    return output;\n}\nStyleToJS.default = StyleToJS;\nmodule.exports = StyleToJS;\n//# sourceMappingURL=index.js.map","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Point} Point\n * @typedef {import('unist').Position} Position\n */\n\n/**\n * @typedef NodeLike\n * @property {string} type\n * @property {PositionLike | null | undefined} [position]\n *\n * @typedef PositionLike\n * @property {PointLike | null | undefined} [start]\n * @property {PointLike | null | undefined} [end]\n *\n * @typedef PointLike\n * @property {number | null | undefined} [line]\n * @property {number | null | undefined} [column]\n * @property {number | null | undefined} [offset]\n */\n\n/**\n * Get the ending point of `node`.\n *\n * @param node\n *   Node.\n * @returns\n *   Point.\n */\nexport const pointEnd = point('end')\n\n/**\n * Get the starting point of `node`.\n *\n * @param node\n *   Node.\n * @returns\n *   Point.\n */\nexport const pointStart = point('start')\n\n/**\n * Get the positional info of `node`.\n *\n * @param {'end' | 'start'} type\n *   Side.\n * @returns\n *   Getter.\n */\nfunction point(type) {\n  return point\n\n  /**\n   * Get the point info of `node` at a bound side.\n   *\n   * @param {Node | NodeLike | null | undefined} [node]\n   * @returns {Point | undefined}\n   */\n  function point(node) {\n    const point = (node && node.position && node.position[type]) || {}\n\n    if (\n      typeof point.line === 'number' &&\n      point.line > 0 &&\n      typeof point.column === 'number' &&\n      point.column > 0\n    ) {\n      return {\n        line: point.line,\n        column: point.column,\n        offset:\n          typeof point.offset === 'number' && point.offset > -1\n            ? point.offset\n            : undefined\n      }\n    }\n  }\n}\n\n/**\n * Get the positional info of `node`.\n *\n * @param {Node | NodeLike | null | undefined} [node]\n *   Node.\n * @returns {Position | undefined}\n *   Position.\n */\nexport function position(node) {\n  const start = pointStart(node)\n  const end = pointEnd(node)\n\n  if (start && end) {\n    return {start, end}\n  }\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Point} Point\n * @typedef {import('unist').Position} Position\n */\n\n/**\n * @typedef NodeLike\n * @property {string} type\n * @property {PositionLike | null | undefined} [position]\n *\n * @typedef PointLike\n * @property {number | null | undefined} [line]\n * @property {number | null | undefined} [column]\n * @property {number | null | undefined} [offset]\n *\n * @typedef PositionLike\n * @property {PointLike | null | undefined} [start]\n * @property {PointLike | null | undefined} [end]\n */\n\n/**\n * Serialize the positional info of a point, position (start and end points),\n * or node.\n *\n * @param {Node | NodeLike | Point | PointLike | Position | PositionLike | null | undefined} [value]\n *   Node, position, or point.\n * @returns {string}\n *   Pretty printed positional info of a node (`string`).\n *\n *   In the format of a range `ls:cs-le:ce` (when given `node` or `position`)\n *   or a point `l:c` (when given `point`), where `l` stands for line, `c` for\n *   column, `s` for `start`, and `e` for end.\n *   An empty string (`''`) is returned if the given value is neither `node`,\n *   `position`, nor `point`.\n */\nexport function stringifyPosition(value) {\n  // Nothing.\n  if (!value || typeof value !== 'object') {\n    return ''\n  }\n\n  // Node.\n  if ('position' in value || 'type' in value) {\n    return position(value.position)\n  }\n\n  // Position.\n  if ('start' in value || 'end' in value) {\n    return position(value)\n  }\n\n  // Point.\n  if ('line' in value || 'column' in value) {\n    return point(value)\n  }\n\n  // ?\n  return ''\n}\n\n/**\n * @param {Point | PointLike | null | undefined} point\n * @returns {string}\n */\nfunction point(point) {\n  return index(point && point.line) + ':' + index(point && point.column)\n}\n\n/**\n * @param {Position | PositionLike | null | undefined} pos\n * @returns {string}\n */\nfunction position(pos) {\n  return point(pos && pos.start) + '-' + point(pos && pos.end)\n}\n\n/**\n * @param {number | null | undefined} value\n * @returns {number}\n */\nfunction index(value) {\n  return value && typeof value === 'number' ? value : 1\n}\n","/**\n * @import {Node, Point, Position} from 'unist'\n */\n\n/**\n * @typedef {object & {type: string, position?: Position | undefined}} NodeLike\n *\n * @typedef Options\n *   Configuration.\n * @property {Array<Node> | null | undefined} [ancestors]\n *   Stack of (inclusive) ancestor nodes surrounding the message (optional).\n * @property {Error | null | undefined} [cause]\n *   Original error cause of the message (optional).\n * @property {Point | Position | null | undefined} [place]\n *   Place of message (optional).\n * @property {string | null | undefined} [ruleId]\n *   Category of message (optional, example: `'my-rule'`).\n * @property {string | null | undefined} [source]\n *   Namespace of who sent the message (optional, example: `'my-package'`).\n */\n\nimport {stringifyPosition} from 'unist-util-stringify-position'\n\n/**\n * Message.\n */\nexport class VFileMessage extends Error {\n  /**\n   * Create a message for `reason`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Options | null | undefined} [options]\n   * @returns\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns\n   *   Instance of `VFileMessage`.\n   */\n  // eslint-disable-next-line complexity\n  constructor(causeOrReason, optionsOrParentOrPlace, origin) {\n    super()\n\n    if (typeof optionsOrParentOrPlace === 'string') {\n      origin = optionsOrParentOrPlace\n      optionsOrParentOrPlace = undefined\n    }\n\n    /** @type {string} */\n    let reason = ''\n    /** @type {Options} */\n    let options = {}\n    let legacyCause = false\n\n    if (optionsOrParentOrPlace) {\n      // Point.\n      if (\n        'line' in optionsOrParentOrPlace &&\n        'column' in optionsOrParentOrPlace\n      ) {\n        options = {place: optionsOrParentOrPlace}\n      }\n      // Position.\n      else if (\n        'start' in optionsOrParentOrPlace &&\n        'end' in optionsOrParentOrPlace\n      ) {\n        options = {place: optionsOrParentOrPlace}\n      }\n      // Node.\n      else if ('type' in optionsOrParentOrPlace) {\n        options = {\n          ancestors: [optionsOrParentOrPlace],\n          place: optionsOrParentOrPlace.position\n        }\n      }\n      // Options.\n      else {\n        options = {...optionsOrParentOrPlace}\n      }\n    }\n\n    if (typeof causeOrReason === 'string') {\n      reason = causeOrReason\n    }\n    // Error.\n    else if (!options.cause && causeOrReason) {\n      legacyCause = true\n      reason = causeOrReason.message\n      options.cause = causeOrReason\n    }\n\n    if (!options.ruleId && !options.source && typeof origin === 'string') {\n      const index = origin.indexOf(':')\n\n      if (index === -1) {\n        options.ruleId = origin\n      } else {\n        options.source = origin.slice(0, index)\n        options.ruleId = origin.slice(index + 1)\n      }\n    }\n\n    if (!options.place && options.ancestors && options.ancestors) {\n      const parent = options.ancestors[options.ancestors.length - 1]\n\n      if (parent) {\n        options.place = parent.position\n      }\n    }\n\n    const start =\n      options.place && 'start' in options.place\n        ? options.place.start\n        : options.place\n\n    /**\n     * Stack of ancestor nodes surrounding the message.\n     *\n     * @type {Array<Node> | undefined}\n     */\n    this.ancestors = options.ancestors || undefined\n\n    /**\n     * Original error cause of the message.\n     *\n     * @type {Error | undefined}\n     */\n    this.cause = options.cause || undefined\n\n    /**\n     * Starting column of message.\n     *\n     * @type {number | undefined}\n     */\n    this.column = start ? start.column : undefined\n\n    /**\n     * State of problem.\n     *\n     * * `true` — error, file not usable\n     * * `false` — warning, change may be needed\n     * * `undefined` — change likely not needed\n     *\n     * @type {boolean | null | undefined}\n     */\n    this.fatal = undefined\n\n    /**\n     * Path of a file (used throughout the `VFile` ecosystem).\n     *\n     * @type {string | undefined}\n     */\n    this.file = ''\n\n    // Field from `Error`.\n    /**\n     * Reason for message.\n     *\n     * @type {string}\n     */\n    this.message = reason\n\n    /**\n     * Starting line of error.\n     *\n     * @type {number | undefined}\n     */\n    this.line = start ? start.line : undefined\n\n    // Field from `Error`.\n    /**\n     * Serialized positional info of message.\n     *\n     * On normal errors, this would be something like `ParseError`, buit in\n     * `VFile` messages we use this space to show where an error happened.\n     */\n    this.name = stringifyPosition(options.place) || '1:1'\n\n    /**\n     * Place of message.\n     *\n     * @type {Point | Position | undefined}\n     */\n    this.place = options.place || undefined\n\n    /**\n     * Reason for message, should use markdown.\n     *\n     * @type {string}\n     */\n    this.reason = this.message\n\n    /**\n     * Category of message (example: `'my-rule'`).\n     *\n     * @type {string | undefined}\n     */\n    this.ruleId = options.ruleId || undefined\n\n    /**\n     * Namespace of message (example: `'my-package'`).\n     *\n     * @type {string | undefined}\n     */\n    this.source = options.source || undefined\n\n    // Field from `Error`.\n    /**\n     * Stack of message.\n     *\n     * This is used by normal errors to show where something happened in\n     * programming code, irrelevant for `VFile` messages,\n     *\n     * @type {string}\n     */\n    this.stack =\n      legacyCause && options.cause && typeof options.cause.stack === 'string'\n        ? options.cause.stack\n        : ''\n\n    // The following fields are “well known”.\n    // Not standard.\n    // Feel free to add other non-standard fields to your messages.\n\n    /**\n     * Specify the source value that’s being reported, which is deemed\n     * incorrect.\n     *\n     * @type {string | undefined}\n     */\n    this.actual = undefined\n\n    /**\n     * Suggest acceptable values that can be used instead of `actual`.\n     *\n     * @type {Array<string> | undefined}\n     */\n    this.expected = undefined\n\n    /**\n     * Long form description of the message (you should use markdown).\n     *\n     * @type {string | undefined}\n     */\n    this.note = undefined\n\n    /**\n     * Link to docs for the message.\n     *\n     * > 👉 **Note**: this must be an absolute URL that can be passed as `x`\n     * > to `new URL(x)`.\n     *\n     * @type {string | undefined}\n     */\n    this.url = undefined\n  }\n}\n\nVFileMessage.prototype.file = ''\nVFileMessage.prototype.name = ''\nVFileMessage.prototype.reason = ''\nVFileMessage.prototype.message = ''\nVFileMessage.prototype.stack = ''\nVFileMessage.prototype.column = undefined\nVFileMessage.prototype.line = undefined\nVFileMessage.prototype.ancestors = undefined\nVFileMessage.prototype.cause = undefined\nVFileMessage.prototype.fatal = undefined\nVFileMessage.prototype.place = undefined\nVFileMessage.prototype.ruleId = undefined\nVFileMessage.prototype.source = undefined\n","/**\n * @import {Identifier, Literal, MemberExpression} from 'estree'\n * @import {Jsx, JsxDev, Options, Props} from 'hast-util-to-jsx-runtime'\n * @import {Element, Nodes, Parents, Root, Text} from 'hast'\n * @import {MdxFlowExpressionHast, MdxTextExpressionHast} from 'mdast-util-mdx-expression'\n * @import {MdxJsxFlowElementHast, MdxJsxTextElementHast} from 'mdast-util-mdx-jsx'\n * @import {MdxjsEsmHast} from 'mdast-util-mdxjs-esm'\n * @import {Position} from 'unist'\n * @import {Child, Create, Field, JsxElement, State, Style} from './types.js'\n */\n\nimport {stringify as commas} from 'comma-separated-tokens'\nimport {ok as assert} from 'devlop'\nimport {name as isIdentifierName} from 'estree-util-is-identifier-name'\nimport {whitespace} from 'hast-util-whitespace'\nimport {find, hastToReact, html, svg} from 'property-information'\nimport {stringify as spaces} from 'space-separated-tokens'\nimport styleToJs from 'style-to-js'\nimport {pointStart} from 'unist-util-position'\nimport {VFileMessage} from 'vfile-message'\n\n// To do: next major: `Object.hasOwn`.\nconst own = {}.hasOwnProperty\n\n/** @type {Map<string, number>} */\nconst emptyMap = new Map()\n\nconst cap = /[A-Z]/g\n\n// `react-dom` triggers a warning for *any* white space in tables.\n// To follow GFM, `mdast-util-to-hast` injects line endings between elements.\n// Other tools might do so too, but they don’t do here, so we remove all of\n// that.\n\n// See: <https://github.com/facebook/react/pull/7081>.\n// See: <https://github.com/facebook/react/pull/7515>.\n// See: <https://github.com/remarkjs/remark-react/issues/64>.\n// See: <https://github.com/rehypejs/rehype-react/pull/29>.\n// See: <https://github.com/rehypejs/rehype-react/pull/32>.\n// See: <https://github.com/rehypejs/rehype-react/pull/45>.\nconst tableElements = new Set(['table', 'tbody', 'thead', 'tfoot', 'tr'])\n\nconst tableCellElement = new Set(['td', 'th'])\n\nconst docs = 'https://github.com/syntax-tree/hast-util-to-jsx-runtime'\n\n/**\n * Transform a hast tree to preact, react, solid, svelte, vue, etc.,\n * with an automatic JSX runtime.\n *\n * @param {Nodes} tree\n *   Tree to transform.\n * @param {Options} options\n *   Configuration (required).\n * @returns {JsxElement}\n *   JSX element.\n */\n\nexport function toJsxRuntime(tree, options) {\n  if (!options || options.Fragment === undefined) {\n    throw new TypeError('Expected `Fragment` in options')\n  }\n\n  const filePath = options.filePath || undefined\n  /** @type {Create} */\n  let create\n\n  if (options.development) {\n    if (typeof options.jsxDEV !== 'function') {\n      throw new TypeError(\n        'Expected `jsxDEV` in options when `development: true`'\n      )\n    }\n\n    create = developmentCreate(filePath, options.jsxDEV)\n  } else {\n    if (typeof options.jsx !== 'function') {\n      throw new TypeError('Expected `jsx` in production options')\n    }\n\n    if (typeof options.jsxs !== 'function') {\n      throw new TypeError('Expected `jsxs` in production options')\n    }\n\n    create = productionCreate(filePath, options.jsx, options.jsxs)\n  }\n\n  /** @type {State} */\n  const state = {\n    Fragment: options.Fragment,\n    ancestors: [],\n    components: options.components || {},\n    create,\n    elementAttributeNameCase: options.elementAttributeNameCase || 'react',\n    evaluater: options.createEvaluater ? options.createEvaluater() : undefined,\n    filePath,\n    ignoreInvalidStyle: options.ignoreInvalidStyle || false,\n    passKeys: options.passKeys !== false,\n    passNode: options.passNode || false,\n    schema: options.space === 'svg' ? svg : html,\n    stylePropertyNameCase: options.stylePropertyNameCase || 'dom',\n    tableCellAlignToStyle: options.tableCellAlignToStyle !== false\n  }\n\n  const result = one(state, tree, undefined)\n\n  // JSX element.\n  if (result && typeof result !== 'string') {\n    return result\n  }\n\n  // Text node or something that turned into nothing.\n  return state.create(\n    tree,\n    state.Fragment,\n    {children: result || undefined},\n    undefined\n  )\n}\n\n/**\n * Transform a node.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Nodes} node\n *   Current node.\n * @param {string | undefined} key\n *   Key.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction one(state, node, key) {\n  if (node.type === 'element') {\n    return element(state, node, key)\n  }\n\n  if (node.type === 'mdxFlowExpression' || node.type === 'mdxTextExpression') {\n    return mdxExpression(state, node)\n  }\n\n  if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {\n    return mdxJsxElement(state, node, key)\n  }\n\n  if (node.type === 'mdxjsEsm') {\n    return mdxEsm(state, node)\n  }\n\n  if (node.type === 'root') {\n    return root(state, node, key)\n  }\n\n  if (node.type === 'text') {\n    return text(state, node)\n  }\n}\n\n/**\n * Handle element.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Element} node\n *   Current node.\n * @param {string | undefined} key\n *   Key.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction element(state, node, key) {\n  const parentSchema = state.schema\n  let schema = parentSchema\n\n  if (node.tagName.toLowerCase() === 'svg' && parentSchema.space === 'html') {\n    schema = svg\n    state.schema = schema\n  }\n\n  state.ancestors.push(node)\n\n  const type = findComponentFromName(state, node.tagName, false)\n  const props = createElementProps(state, node)\n  let children = createChildren(state, node)\n\n  if (tableElements.has(node.tagName)) {\n    children = children.filter(function (child) {\n      return typeof child === 'string' ? !whitespace(child) : true\n    })\n  }\n\n  addNode(state, props, type, node)\n  addChildren(props, children)\n\n  // Restore.\n  state.ancestors.pop()\n  state.schema = parentSchema\n\n  return state.create(node, type, props, key)\n}\n\n/**\n * Handle MDX expression.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdxFlowExpressionHast | MdxTextExpressionHast} node\n *   Current node.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction mdxExpression(state, node) {\n  if (node.data && node.data.estree && state.evaluater) {\n    const program = node.data.estree\n    const expression = program.body[0]\n    assert(expression.type === 'ExpressionStatement')\n\n    // Assume result is a child.\n    return /** @type {Child | undefined} */ (\n      state.evaluater.evaluateExpression(expression.expression)\n    )\n  }\n\n  crashEstree(state, node.position)\n}\n\n/**\n * Handle MDX ESM.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdxjsEsmHast} node\n *   Current node.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction mdxEsm(state, node) {\n  if (node.data && node.data.estree && state.evaluater) {\n    // Assume result is a child.\n    return /** @type {Child | undefined} */ (\n      state.evaluater.evaluateProgram(node.data.estree)\n    )\n  }\n\n  crashEstree(state, node.position)\n}\n\n/**\n * Handle MDX JSX.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdxJsxFlowElementHast | MdxJsxTextElementHast} node\n *   Current node.\n * @param {string | undefined} key\n *   Key.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction mdxJsxElement(state, node, key) {\n  const parentSchema = state.schema\n  let schema = parentSchema\n\n  if (node.name === 'svg' && parentSchema.space === 'html') {\n    schema = svg\n    state.schema = schema\n  }\n\n  state.ancestors.push(node)\n\n  const type =\n    node.name === null\n      ? state.Fragment\n      : findComponentFromName(state, node.name, true)\n  const props = createJsxElementProps(state, node)\n  const children = createChildren(state, node)\n\n  addNode(state, props, type, node)\n  addChildren(props, children)\n\n  // Restore.\n  state.ancestors.pop()\n  state.schema = parentSchema\n\n  return state.create(node, type, props, key)\n}\n\n/**\n * Handle root.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Root} node\n *   Current node.\n * @param {string | undefined} key\n *   Key.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction root(state, node, key) {\n  /** @type {Props} */\n  const props = {}\n\n  addChildren(props, createChildren(state, node))\n\n  return state.create(node, state.Fragment, props, key)\n}\n\n/**\n * Handle text.\n *\n * @param {State} _\n *   Info passed around.\n * @param {Text} node\n *   Current node.\n * @returns {Child | undefined}\n *   Child, optional.\n */\nfunction text(_, node) {\n  return node.value\n}\n\n/**\n * Add `node` to props.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Props} props\n *   Props.\n * @param {unknown} type\n *   Type.\n * @param {Element | MdxJsxFlowElementHast | MdxJsxTextElementHast} node\n *   Node.\n * @returns {undefined}\n *   Nothing.\n */\nfunction addNode(state, props, type, node) {\n  // If this is swapped out for a component:\n  if (typeof type !== 'string' && type !== state.Fragment && state.passNode) {\n    props.node = node\n  }\n}\n\n/**\n * Add children to props.\n *\n * @param {Props} props\n *   Props.\n * @param {Array<Child>} children\n *   Children.\n * @returns {undefined}\n *   Nothing.\n */\nfunction addChildren(props, children) {\n  if (children.length > 0) {\n    const value = children.length > 1 ? children : children[0]\n\n    if (value) {\n      props.children = value\n    }\n  }\n}\n\n/**\n * @param {string | undefined} _\n *   Path to file.\n * @param {Jsx} jsx\n *   Dynamic.\n * @param {Jsx} jsxs\n *   Static.\n * @returns {Create}\n *   Create a production element.\n */\nfunction productionCreate(_, jsx, jsxs) {\n  return create\n  /** @type {Create} */\n  function create(_, type, props, key) {\n    // Only an array when there are 2 or more children.\n    const isStaticChildren = Array.isArray(props.children)\n    const fn = isStaticChildren ? jsxs : jsx\n    return key ? fn(type, props, key) : fn(type, props)\n  }\n}\n\n/**\n * @param {string | undefined} filePath\n *   Path to file.\n * @param {JsxDev} jsxDEV\n *   Development.\n * @returns {Create}\n *   Create a development element.\n */\nfunction developmentCreate(filePath, jsxDEV) {\n  return create\n  /** @type {Create} */\n  function create(node, type, props, key) {\n    // Only an array when there are 2 or more children.\n    const isStaticChildren = Array.isArray(props.children)\n    const point = pointStart(node)\n    return jsxDEV(\n      type,\n      props,\n      key,\n      isStaticChildren,\n      {\n        columnNumber: point ? point.column - 1 : undefined,\n        fileName: filePath,\n        lineNumber: point ? point.line : undefined\n      },\n      undefined\n    )\n  }\n}\n\n/**\n * Create props from an element.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Element} node\n *   Current element.\n * @returns {Props}\n *   Props.\n */\nfunction createElementProps(state, node) {\n  /** @type {Props} */\n  const props = {}\n  /** @type {string | undefined} */\n  let alignValue\n  /** @type {string} */\n  let prop\n\n  for (prop in node.properties) {\n    if (prop !== 'children' && own.call(node.properties, prop)) {\n      const result = createProperty(state, prop, node.properties[prop])\n\n      if (result) {\n        const [key, value] = result\n\n        if (\n          state.tableCellAlignToStyle &&\n          key === 'align' &&\n          typeof value === 'string' &&\n          tableCellElement.has(node.tagName)\n        ) {\n          alignValue = value\n        } else {\n          props[key] = value\n        }\n      }\n    }\n  }\n\n  if (alignValue) {\n    // Assume style is an object.\n    const style = /** @type {Style} */ (props.style || (props.style = {}))\n    style[state.stylePropertyNameCase === 'css' ? 'text-align' : 'textAlign'] =\n      alignValue\n  }\n\n  return props\n}\n\n/**\n * Create props from a JSX element.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdxJsxFlowElementHast | MdxJsxTextElementHast} node\n *   Current JSX element.\n * @returns {Props}\n *   Props.\n */\nfunction createJsxElementProps(state, node) {\n  /** @type {Props} */\n  const props = {}\n\n  for (const attribute of node.attributes) {\n    if (attribute.type === 'mdxJsxExpressionAttribute') {\n      if (attribute.data && attribute.data.estree && state.evaluater) {\n        const program = attribute.data.estree\n        const expression = program.body[0]\n        assert(expression.type === 'ExpressionStatement')\n        const objectExpression = expression.expression\n        assert(objectExpression.type === 'ObjectExpression')\n        const property = objectExpression.properties[0]\n        assert(property.type === 'SpreadElement')\n\n        Object.assign(\n          props,\n          state.evaluater.evaluateExpression(property.argument)\n        )\n      } else {\n        crashEstree(state, node.position)\n      }\n    } else {\n      // For JSX, the author is responsible of passing in the correct values.\n      const name = attribute.name\n      /** @type {unknown} */\n      let value\n\n      if (attribute.value && typeof attribute.value === 'object') {\n        if (\n          attribute.value.data &&\n          attribute.value.data.estree &&\n          state.evaluater\n        ) {\n          const program = attribute.value.data.estree\n          const expression = program.body[0]\n          assert(expression.type === 'ExpressionStatement')\n          value = state.evaluater.evaluateExpression(expression.expression)\n        } else {\n          crashEstree(state, node.position)\n        }\n      } else {\n        value = attribute.value === null ? true : attribute.value\n      }\n\n      // Assume a prop.\n      props[name] = /** @type {Props[keyof Props]} */ (value)\n    }\n  }\n\n  return props\n}\n\n/**\n * Create children.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Parents} node\n *   Current element.\n * @returns {Array<Child>}\n *   Children.\n */\nfunction createChildren(state, node) {\n  /** @type {Array<Child>} */\n  const children = []\n  let index = -1\n  /** @type {Map<string, number>} */\n  // Note: test this when Solid doesn’t want to merge my upcoming PR.\n  /* c8 ignore next */\n  const countsByName = state.passKeys ? new Map() : emptyMap\n\n  while (++index < node.children.length) {\n    const child = node.children[index]\n    /** @type {string | undefined} */\n    let key\n\n    if (state.passKeys) {\n      const name =\n        child.type === 'element'\n          ? child.tagName\n          : child.type === 'mdxJsxFlowElement' ||\n              child.type === 'mdxJsxTextElement'\n            ? child.name\n            : undefined\n\n      if (name) {\n        const count = countsByName.get(name) || 0\n        key = name + '-' + count\n        countsByName.set(name, count + 1)\n      }\n    }\n\n    const result = one(state, child, key)\n    if (result !== undefined) children.push(result)\n  }\n\n  return children\n}\n\n/**\n * Handle a property.\n *\n * @param {State} state\n *   Info passed around.\n * @param {string} prop\n *   Key.\n * @param {Array<number | string> | boolean | number | string | null | undefined} value\n *   hast property value.\n * @returns {Field | undefined}\n *   Field for runtime, optional.\n */\nfunction createProperty(state, prop, value) {\n  const info = find(state.schema, prop)\n\n  // Ignore nullish and `NaN` values.\n  if (\n    value === null ||\n    value === undefined ||\n    (typeof value === 'number' && Number.isNaN(value))\n  ) {\n    return\n  }\n\n  if (Array.isArray(value)) {\n    // Accept `array`.\n    // Most props are space-separated.\n    value = info.commaSeparated ? commas(value) : spaces(value)\n  }\n\n  // React only accepts `style` as object.\n  if (info.property === 'style') {\n    let styleObject =\n      typeof value === 'object' ? value : parseStyle(state, String(value))\n\n    if (state.stylePropertyNameCase === 'css') {\n      styleObject = transformStylesToCssCasing(styleObject)\n    }\n\n    return ['style', styleObject]\n  }\n\n  return [\n    state.elementAttributeNameCase === 'react' && info.space\n      ? hastToReact[info.property] || info.property\n      : info.attribute,\n    value\n  ]\n}\n\n/**\n * Parse a CSS declaration to an object.\n *\n * @param {State} state\n *   Info passed around.\n * @param {string} value\n *   CSS declarations.\n * @returns {Style}\n *   Properties.\n * @throws\n *   Throws `VFileMessage` when CSS cannot be parsed.\n */\nfunction parseStyle(state, value) {\n  try {\n    return styleToJs(value, {reactCompat: true})\n  } catch (error) {\n    if (state.ignoreInvalidStyle) {\n      return {}\n    }\n\n    const cause = /** @type {Error} */ (error)\n    const message = new VFileMessage('Cannot parse `style` attribute', {\n      ancestors: state.ancestors,\n      cause,\n      ruleId: 'style',\n      source: 'hast-util-to-jsx-runtime'\n    })\n    message.file = state.filePath || undefined\n    message.url = docs + '#cannot-parse-style-attribute'\n\n    throw message\n  }\n}\n\n/**\n * Create a JSX name from a string.\n *\n * @param {State} state\n *   To do.\n * @param {string} name\n *   Name.\n * @param {boolean} allowExpression\n *   Allow member expressions and identifiers.\n * @returns {unknown}\n *   To do.\n */\nfunction findComponentFromName(state, name, allowExpression) {\n  /** @type {Identifier | Literal | MemberExpression} */\n  let result\n\n  if (!allowExpression) {\n    result = {type: 'Literal', value: name}\n  } else if (name.includes('.')) {\n    const identifiers = name.split('.')\n    let index = -1\n    /** @type {Identifier | Literal | MemberExpression | undefined} */\n    let node\n\n    while (++index < identifiers.length) {\n      /** @type {Identifier | Literal} */\n      const prop = isIdentifierName(identifiers[index])\n        ? {type: 'Identifier', name: identifiers[index]}\n        : {type: 'Literal', value: identifiers[index]}\n      node = node\n        ? {\n            type: 'MemberExpression',\n            object: node,\n            property: prop,\n            computed: Boolean(index && prop.type === 'Literal'),\n            optional: false\n          }\n        : prop\n    }\n\n    assert(node, 'always a result')\n    result = node\n  } else {\n    result =\n      isIdentifierName(name) && !/^[a-z]/.test(name)\n        ? {type: 'Identifier', name}\n        : {type: 'Literal', value: name}\n  }\n\n  // Only literals can be passed in `components` currently.\n  // No identifiers / member expressions.\n  if (result.type === 'Literal') {\n    const name = /** @type {string | number} */ (result.value)\n    return own.call(state.components, name) ? state.components[name] : name\n  }\n\n  // Assume component.\n  if (state.evaluater) {\n    return state.evaluater.evaluateExpression(result)\n  }\n\n  crashEstree(state)\n}\n\n/**\n * @param {State} state\n * @param {Position | undefined} [place]\n * @returns {never}\n */\nfunction crashEstree(state, place) {\n  const message = new VFileMessage(\n    'Cannot handle MDX estrees without `createEvaluater`',\n    {\n      ancestors: state.ancestors,\n      place,\n      ruleId: 'mdx-estree',\n      source: 'hast-util-to-jsx-runtime'\n    }\n  )\n  message.file = state.filePath || undefined\n  message.url = docs + '#cannot-handle-mdx-estrees-without-createevaluater'\n\n  throw message\n}\n\n/**\n * Transform a DOM casing style object to a CSS casing style object.\n *\n * @param {Style} domCasing\n * @returns {Style}\n */\nfunction transformStylesToCssCasing(domCasing) {\n  /** @type {Style} */\n  const cssCasing = {}\n  /** @type {string} */\n  let from\n\n  for (from in domCasing) {\n    if (own.call(domCasing, from)) {\n      cssCasing[transformStyleToCssCasing(from)] = domCasing[from]\n    }\n  }\n\n  return cssCasing\n}\n\n/**\n * Transform a DOM casing style field to a CSS casing style field.\n *\n * @param {string} from\n * @returns {string}\n */\nfunction transformStyleToCssCasing(from) {\n  let to = from.replace(cap, toDash)\n  // Handle `ms-xxx` -> `-ms-xxx`.\n  if (to.slice(0, 3) === 'ms-') to = '-' + to\n  return to\n}\n\n/**\n * Make `$0` dash cased.\n *\n * @param {string} $0\n *   Capitalized ASCII leter.\n * @returns {string}\n *   Dash and lower letter.\n */\nfunction toDash($0) {\n  return '-' + $0.toLowerCase()\n}\n","/**\n * HTML URL properties.\n *\n * Each key is a property name and each value is a list of tag names it applies\n * to or `null` if it applies to all elements.\n *\n * @type {Record<string, Array<string> | null>}\n */\nexport const urlAttributes = {\n  action: ['form'],\n  cite: ['blockquote', 'del', 'ins', 'q'],\n  data: ['object'],\n  formAction: ['button', 'input'],\n  href: ['a', 'area', 'base', 'link'],\n  icon: ['menuitem'],\n  itemId: null,\n  manifest: ['html'],\n  ping: ['a', 'area'],\n  poster: ['video'],\n  src: [\n    'audio',\n    'embed',\n    'iframe',\n    'img',\n    'input',\n    'script',\n    'source',\n    'track',\n    'video'\n  ]\n}\n","/**\n * @typedef {import('mdast').Nodes} Nodes\n *\n * @typedef Options\n *   Configuration (optional).\n * @property {boolean | null | undefined} [includeImageAlt=true]\n *   Whether to use `alt` for `image`s (default: `true`).\n * @property {boolean | null | undefined} [includeHtml=true]\n *   Whether to use `value` of HTML (default: `true`).\n */\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Get the text content of a node or list of nodes.\n *\n * Prefers the node’s plain-text fields, otherwise serializes its children,\n * and if the given value is an array, serialize the nodes in it.\n *\n * @param {unknown} [value]\n *   Thing to serialize, typically `Node`.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Serialized `value`.\n */\nexport function toString(value, options) {\n  const settings = options || emptyOptions\n  const includeImageAlt =\n    typeof settings.includeImageAlt === 'boolean'\n      ? settings.includeImageAlt\n      : true\n  const includeHtml =\n    typeof settings.includeHtml === 'boolean' ? settings.includeHtml : true\n\n  return one(value, includeImageAlt, includeHtml)\n}\n\n/**\n * One node or several nodes.\n *\n * @param {unknown} value\n *   Thing to serialize.\n * @param {boolean} includeImageAlt\n *   Include image `alt`s.\n * @param {boolean} includeHtml\n *   Include HTML.\n * @returns {string}\n *   Serialized node.\n */\nfunction one(value, includeImageAlt, includeHtml) {\n  if (node(value)) {\n    if ('value' in value) {\n      return value.type === 'html' && !includeHtml ? '' : value.value\n    }\n\n    if (includeImageAlt && 'alt' in value && value.alt) {\n      return value.alt\n    }\n\n    if ('children' in value) {\n      return all(value.children, includeImageAlt, includeHtml)\n    }\n  }\n\n  if (Array.isArray(value)) {\n    return all(value, includeImageAlt, includeHtml)\n  }\n\n  return ''\n}\n\n/**\n * Serialize a list of nodes.\n *\n * @param {Array<unknown>} values\n *   Thing to serialize.\n * @param {boolean} includeImageAlt\n *   Include image `alt`s.\n * @param {boolean} includeHtml\n *   Include HTML.\n * @returns {string}\n *   Serialized nodes.\n */\nfunction all(values, includeImageAlt, includeHtml) {\n  /** @type {Array<string>} */\n  const result = []\n  let index = -1\n\n  while (++index < values.length) {\n    result[index] = one(values[index], includeImageAlt, includeHtml)\n  }\n\n  return result.join('')\n}\n\n/**\n * Check if `value` looks like a node.\n *\n * @param {unknown} value\n *   Thing.\n * @returns {value is Nodes}\n *   Whether `value` is a node.\n */\nfunction node(value) {\n  return Boolean(value && typeof value === 'object')\n}\n","/// <reference lib=\"dom\" />\n\n/* global document */\n\nconst element = document.createElement('i')\n\n/**\n * @param {string} value\n * @returns {string | false}\n */\nexport function decodeNamedCharacterReference(value) {\n  const characterReference = '&' + value + ';'\n  element.innerHTML = characterReference\n  const character = element.textContent\n\n  // Some named character references do not require the closing semicolon\n  // (`&not`, for instance), which leads to situations where parsing the assumed\n  // named reference of `&notit;` will result in the string `¬it;`.\n  // When we encounter a trailing semicolon after parsing, and the character\n  // reference to decode was not a semicolon (`&semi;`), we can assume that the\n  // matching was not complete.\n  if (\n    character.charCodeAt(character.length - 1) === 59 /* `;` */ &&\n    value !== 'semi'\n  ) {\n    return false\n  }\n\n  // If the decoded string is equal to the input, the character reference was\n  // not valid.\n  return character === characterReference ? false : character\n}\n","/**\n * Like `Array#splice`, but smarter for giant arrays.\n *\n * `Array#splice` takes all items to be inserted as individual argument which\n * causes a stack overflow in V8 when trying to insert 100k items for instance.\n *\n * Otherwise, this does not return the removed items, and takes `items` as an\n * array instead of rest parameters.\n *\n * @template {unknown} T\n *   Item type.\n * @param {Array<T>} list\n *   List to operate on.\n * @param {number} start\n *   Index to remove/insert at (can be negative).\n * @param {number} remove\n *   Number of items to remove.\n * @param {Array<T>} items\n *   Items to inject into `list`.\n * @returns {undefined}\n *   Nothing.\n */\nexport function splice(list, start, remove, items) {\n  const end = list.length;\n  let chunkStart = 0;\n  /** @type {Array<unknown>} */\n  let parameters;\n\n  // Make start between zero and `end` (included).\n  if (start < 0) {\n    start = -start > end ? 0 : end + start;\n  } else {\n    start = start > end ? end : start;\n  }\n  remove = remove > 0 ? remove : 0;\n\n  // No need to chunk the items if there’s only a couple (10k) items.\n  if (items.length < 10000) {\n    parameters = Array.from(items);\n    parameters.unshift(start, remove);\n    // @ts-expect-error Hush, it’s fine.\n    list.splice(...parameters);\n  } else {\n    // Delete `remove` items starting from `start`\n    if (remove) list.splice(start, remove);\n\n    // Insert the items in chunks to not cause stack overflows.\n    while (chunkStart < items.length) {\n      parameters = items.slice(chunkStart, chunkStart + 10000);\n      parameters.unshift(start, 0);\n      // @ts-expect-error Hush, it’s fine.\n      list.splice(...parameters);\n      chunkStart += 10000;\n      start += 10000;\n    }\n  }\n}\n\n/**\n * Append `items` (an array) at the end of `list` (another array).\n * When `list` was empty, returns `items` instead.\n *\n * This prevents a potentially expensive operation when `list` is empty,\n * and adds items in batches to prevent V8 from hanging.\n *\n * @template {unknown} T\n *   Item type.\n * @param {Array<T>} list\n *   List to operate on.\n * @param {Array<T>} items\n *   Items to add to `list`.\n * @returns {Array<T>}\n *   Either `list` or `items`.\n */\nexport function push(list, items) {\n  if (list.length > 0) {\n    splice(list, list.length, 0, items);\n    return list;\n  }\n  return items;\n}","/**\n * @import {\n *   Extension,\n *   Handles,\n *   HtmlExtension,\n *   NormalizedExtension\n * } from 'micromark-util-types'\n */\n\nimport {splice} from 'micromark-util-chunked'\n\nconst hasOwnProperty = {}.hasOwnProperty\n\n/**\n * Combine multiple syntax extensions into one.\n *\n * @param {ReadonlyArray<Extension>} extensions\n *   List of syntax extensions.\n * @returns {NormalizedExtension}\n *   A single combined extension.\n */\nexport function combineExtensions(extensions) {\n  /** @type {NormalizedExtension} */\n  const all = {}\n  let index = -1\n\n  while (++index < extensions.length) {\n    syntaxExtension(all, extensions[index])\n  }\n\n  return all\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {NormalizedExtension} all\n *   Extension to merge into.\n * @param {Extension} extension\n *   Extension to merge.\n * @returns {undefined}\n *   Nothing.\n */\nfunction syntaxExtension(all, extension) {\n  /** @type {keyof Extension} */\n  let hook\n\n  for (hook in extension) {\n    const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n    /** @type {Record<string, unknown>} */\n    const left = maybe || (all[hook] = {})\n    /** @type {Record<string, unknown> | undefined} */\n    const right = extension[hook]\n    /** @type {string} */\n    let code\n\n    if (right) {\n      for (code in right) {\n        if (!hasOwnProperty.call(left, code)) left[code] = []\n        const value = right[code]\n        constructs(\n          // @ts-expect-error Looks like a list.\n          left[code],\n          Array.isArray(value) ? value : value ? [value] : []\n        )\n      }\n    }\n  }\n}\n\n/**\n * Merge `list` into `existing` (both lists of constructs).\n * Mutates `existing`.\n *\n * @param {Array<unknown>} existing\n *   List of constructs to merge into.\n * @param {Array<unknown>} list\n *   List of constructs to merge.\n * @returns {undefined}\n *   Nothing.\n */\nfunction constructs(existing, list) {\n  let index = -1\n  /** @type {Array<unknown>} */\n  const before = []\n\n  while (++index < list.length) {\n    // @ts-expect-error Looks like an object.\n    ;(list[index].add === 'after' ? existing : before).push(list[index])\n  }\n\n  splice(existing, 0, 0, before)\n}\n\n/**\n * Combine multiple HTML extensions into one.\n *\n * @param {ReadonlyArray<HtmlExtension>} htmlExtensions\n *   List of HTML extensions.\n * @returns {HtmlExtension}\n *   Single combined HTML extension.\n */\nexport function combineHtmlExtensions(htmlExtensions) {\n  /** @type {HtmlExtension} */\n  const handlers = {}\n  let index = -1\n\n  while (++index < htmlExtensions.length) {\n    htmlExtension(handlers, htmlExtensions[index])\n  }\n\n  return handlers\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {HtmlExtension} all\n *   Extension to merge into.\n * @param {HtmlExtension} extension\n *   Extension to merge.\n * @returns {undefined}\n *   Nothing.\n */\nfunction htmlExtension(all, extension) {\n  /** @type {keyof HtmlExtension} */\n  let hook\n\n  for (hook in extension) {\n    const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n    const left = maybe || (all[hook] = {})\n    const right = extension[hook]\n    /** @type {keyof Handles} */\n    let type\n\n    if (right) {\n      for (type in right) {\n        // @ts-expect-error assume document vs regular handler are managed correctly.\n        left[type] = right[type]\n      }\n    }\n  }\n}\n","/**\n * Turn the number (in string form as either hexa- or plain decimal) coming from\n * a numeric character reference into a character.\n *\n * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes\n * non-characters and control characters safe.\n *\n * @param {string} value\n *   Value to decode.\n * @param {number} base\n *   Numeric base.\n * @returns {string}\n *   Character.\n */\nexport function decodeNumericCharacterReference(value, base) {\n  const code = Number.parseInt(value, base);\n  if (\n  // C0 except for HT, LF, FF, CR, space.\n  code < 9 || code === 11 || code > 13 && code < 32 ||\n  // Control character (DEL) of C0, and C1 controls.\n  code > 126 && code < 160 ||\n  // Lone high surrogates and low surrogates.\n  code > 55_295 && code < 57_344 ||\n  // Noncharacters.\n  code > 64_975 && code < 65_008 || /* eslint-disable no-bitwise */\n  (code & 65_535) === 65_535 || (code & 65_535) === 65_534 || /* eslint-enable no-bitwise */\n  // Out of range\n  code > 1_114_111) {\n    return \"\\uFFFD\";\n  }\n  return String.fromCodePoint(code);\n}","/**\n * Normalize an identifier (as found in references, definitions).\n *\n * Collapses markdown whitespace, trim, and then lower- and uppercase.\n *\n * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their\n * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different\n * uppercase character (U+0398 (`Θ`)).\n * So, to get a canonical form, we perform both lower- and uppercase.\n *\n * Using uppercase last makes sure keys will never interact with default\n * prototypal values (such as `constructor`): nothing in the prototype of\n * `Object` is uppercase.\n *\n * @param {string} value\n *   Identifier to normalize.\n * @returns {string}\n *   Normalized identifier.\n */\nexport function normalizeIdentifier(value) {\n  return value\n  // Collapse markdown whitespace.\n  .replace(/[\\t\\n\\r ]+/g, \" \")\n  // Trim.\n  .replace(/^ | $/g, '')\n  // Some characters are considered “uppercase”, but if their lowercase\n  // counterpart is uppercased will result in a different uppercase\n  // character.\n  // Hence, to get that form, we perform both lower- and uppercase.\n  // Upper case makes sure keys will not interact with default prototypal\n  // methods: no method is uppercase.\n  .toLowerCase().toUpperCase();\n}","/**\n * @import {Code} from 'micromark-util-types'\n */\n\n/**\n * Check whether the character code represents an ASCII alpha (`a` through `z`,\n * case insensitive).\n *\n * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha.\n *\n * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`)\n * to U+005A (`Z`).\n *\n * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`)\n * to U+007A (`z`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiAlpha = regexCheck(/[A-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII alphanumeric (`a`\n * through `z`, case insensitive, or `0` through `9`).\n *\n * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha\n * (see `asciiAlpha`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiAlphanumeric = regexCheck(/[\\dA-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII atext.\n *\n * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in\n * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),\n * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F\n * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E\n * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE\n * (`{`) to U+007E TILDE (`~`).\n *\n * See:\n * **\\[RFC5322]**:\n * [Internet Message Format](https://tools.ietf.org/html/rfc5322).\n * P. Resnick.\n * IETF.\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiAtext = regexCheck(/[#-'*+\\--9=?A-Z^-~]/);\n\n/**\n * Check whether a character code is an ASCII control character.\n *\n * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL)\n * to U+001F (US), or U+007F (DEL).\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function asciiControl(code) {\n  return (\n    // Special whitespace codes (which have negative values), C0 and Control\n    // character DEL\n    code !== null && (code < 32 || code === 127)\n  );\n}\n\n/**\n * Check whether the character code represents an ASCII digit (`0` through `9`).\n *\n * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to\n * U+0039 (`9`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiDigit = regexCheck(/\\d/);\n\n/**\n * Check whether the character code represents an ASCII hex digit (`a` through\n * `f`, case insensitive, or `0` through `9`).\n *\n * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex\n * digit, or an ASCII lower hex digit.\n *\n * An **ASCII upper hex digit** is a character in the inclusive range U+0041\n * (`A`) to U+0046 (`F`).\n *\n * An **ASCII lower hex digit** is a character in the inclusive range U+0061\n * (`a`) to U+0066 (`f`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiHexDigit = regexCheck(/[\\dA-Fa-f]/);\n\n/**\n * Check whether the character code represents ASCII punctuation.\n *\n * An **ASCII punctuation** is a character in the inclusive ranges U+0021\n * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT\n * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT\n * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);\n\n/**\n * Check whether a character code is a markdown line ending.\n *\n * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN\n * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR).\n *\n * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE\n * RETURN (CR) are replaced by these virtual characters depending on whether\n * they occurred together.\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function markdownLineEnding(code) {\n  return code !== null && code < -2;\n}\n\n/**\n * Check whether a character code is a markdown line ending (see\n * `markdownLineEnding`) or markdown space (see `markdownSpace`).\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function markdownLineEndingOrSpace(code) {\n  return code !== null && (code < 0 || code === 32);\n}\n\n/**\n * Check whether a character code is a markdown space.\n *\n * A **markdown space** is the concrete character U+0020 SPACE (SP) and the\n * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT).\n *\n * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is\n * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL\n * SPACE (VS) characters, depending on the column at which the tab occurred.\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function markdownSpace(code) {\n  return code === -2 || code === -1 || code === 32;\n}\n\n// Size note: removing ASCII from the regex and using `asciiPunctuation` here\n// In fact adds to the bundle size.\n/**\n * Check whether the character code represents Unicode punctuation.\n *\n * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation,\n * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf`\n * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po`\n * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII\n * punctuation (see `asciiPunctuation`).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n *   Code.\n * @returns\n *   Whether it matches.\n */\nexport const unicodePunctuation = regexCheck(/\\p{P}|\\p{S}/u);\n\n/**\n * Check whether the character code represents Unicode whitespace.\n *\n * Note that this does handle micromark specific markdown whitespace characters.\n * See `markdownLineEndingOrSpace` to check that.\n *\n * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator,\n * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF),\n * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\\[UNICODE]**).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n *   Code.\n * @returns\n *   Whether it matches.\n */\nexport const unicodeWhitespace = regexCheck(/\\s/);\n\n/**\n * Create a code check from a regex.\n *\n * @param {RegExp} regex\n *   Expression.\n * @returns {(code: Code) => boolean}\n *   Check.\n */\nfunction regexCheck(regex) {\n  return check;\n\n  /**\n   * Check whether a code matches the bound regex.\n   *\n   * @param {Code} code\n   *   Character code.\n   * @returns {boolean}\n   *   Whether the character code matches the bound regex.\n   */\n  function check(code) {\n    return code !== null && code > -1 && regex.test(String.fromCharCode(code));\n  }\n}","import { asciiAlphanumeric } from 'micromark-util-character';\nimport { encode } from 'micromark-util-encode';\n/**\n * Make a value safe for injection as a URL.\n *\n * This encodes unsafe characters with percent-encoding and skips already\n * encoded sequences (see `normalizeUri`).\n * Further unsafe characters are encoded as character references (see\n * `micromark-util-encode`).\n *\n * A regex of allowed protocols can be given, in which case the URL is\n * sanitized.\n * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or\n * `/^https?$/i` for `img[src]` (this is what `github.com` allows).\n * If the URL includes an unknown protocol (one not matched by `protocol`, such\n * as a dangerous example, `javascript:`), the value is ignored.\n *\n * @param {string | null | undefined} url\n *   URI to sanitize.\n * @param {RegExp | null | undefined} [protocol]\n *   Allowed protocols.\n * @returns {string}\n *   Sanitized URI.\n */\nexport function sanitizeUri(url, protocol) {\n  const value = encode(normalizeUri(url || ''));\n  if (!protocol) {\n    return value;\n  }\n  const colon = value.indexOf(':');\n  const questionMark = value.indexOf('?');\n  const numberSign = value.indexOf('#');\n  const slash = value.indexOf('/');\n  if (\n  // If there is no protocol, it’s relative.\n  colon < 0 ||\n  // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol.\n  slash > -1 && colon > slash || questionMark > -1 && colon > questionMark || numberSign > -1 && colon > numberSign ||\n  // It is a protocol, it should be allowed.\n  protocol.test(value.slice(0, colon))) {\n    return value;\n  }\n  return '';\n}\n\n/**\n * Normalize a URL.\n *\n * Encode unsafe characters with percent-encoding, skipping already encoded\n * sequences.\n *\n * @param {string} value\n *   URI to normalize.\n * @returns {string}\n *   Normalized URI.\n */\nexport function normalizeUri(value) {\n  /** @type {Array<string>} */\n  const result = [];\n  let index = -1;\n  let start = 0;\n  let skip = 0;\n  while (++index < value.length) {\n    const code = value.charCodeAt(index);\n    /** @type {string} */\n    let replace = '';\n\n    // A correct percent encoded value.\n    if (code === 37 && asciiAlphanumeric(value.charCodeAt(index + 1)) && asciiAlphanumeric(value.charCodeAt(index + 2))) {\n      skip = 2;\n    }\n    // ASCII.\n    else if (code < 128) {\n      if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) {\n        replace = String.fromCharCode(code);\n      }\n    }\n    // Astral.\n    else if (code > 55_295 && code < 57_344) {\n      const next = value.charCodeAt(index + 1);\n\n      // A correct surrogate pair.\n      if (code < 56_320 && next > 56_319 && next < 57_344) {\n        replace = String.fromCharCode(code, next);\n        skip = 1;\n      }\n      // Lone surrogate.\n      else {\n        replace = \"\\uFFFD\";\n      }\n    }\n    // Unicode.\n    else {\n      replace = String.fromCharCode(code);\n    }\n    if (replace) {\n      result.push(value.slice(start, index), encodeURIComponent(replace));\n      start = index + skip + 1;\n      replace = '';\n    }\n    if (skip) {\n      index += skip;\n      skip = 0;\n    }\n  }\n  return result.join('') + value.slice(start);\n}","/**\n * @import {Effects, State, TokenType} from 'micromark-util-types'\n */\n\nimport { markdownSpace } from 'micromark-util-character';\n\n// To do: implement `spaceOrTab`, `spaceOrTabMinMax`, `spaceOrTabWithOptions`.\n\n/**\n * Parse spaces and tabs.\n *\n * There is no `nok` parameter:\n *\n * *   spaces in markdown are often optional, in which case this factory can be\n *     used and `ok` will be switched to whether spaces were found or not\n * *   one line ending or space can be detected with `markdownSpace(code)` right\n *     before using `factorySpace`\n *\n * ###### Examples\n *\n * Where `␉` represents a tab (plus how much it expands) and `␠` represents a\n * single space.\n *\n * ```markdown\n * ␉\n * ␠␠␠␠\n * ␉␠\n * ```\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {TokenType} type\n *   Type (`' \\t'`).\n * @param {number | undefined} [max=Infinity]\n *   Max (exclusive).\n * @returns {State}\n *   Start state.\n */\nexport function factorySpace(effects, ok, type, max) {\n  const limit = max ? max - 1 : Number.POSITIVE_INFINITY;\n  let size = 0;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    if (markdownSpace(code)) {\n      effects.enter(type);\n      return prefix(code);\n    }\n    return ok(code);\n  }\n\n  /** @type {State} */\n  function prefix(code) {\n    if (markdownSpace(code) && size++ < limit) {\n      effects.consume(code);\n      return prefix;\n    }\n    effects.exit(type);\n    return ok(code);\n  }\n}","/**\n * @import {\n *   InitialConstruct,\n *   Initializer,\n *   State,\n *   TokenizeContext,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {InitialConstruct} */\nexport const content = {\n  tokenize: initializeContent\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Initializer}\n *   Content.\n */\nfunction initializeContent(effects) {\n  const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial);\n  /** @type {Token} */\n  let previous;\n  return contentStart;\n\n  /** @type {State} */\n  function afterContentStartConstruct(code) {\n    if (code === null) {\n      effects.consume(code);\n      return;\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return factorySpace(effects, contentStart, \"linePrefix\");\n  }\n\n  /** @type {State} */\n  function paragraphInitial(code) {\n    effects.enter(\"paragraph\");\n    return lineStart(code);\n  }\n\n  /** @type {State} */\n  function lineStart(code) {\n    const token = effects.enter(\"chunkText\", {\n      contentType: \"text\",\n      previous\n    });\n    if (previous) {\n      previous.next = token;\n    }\n    previous = token;\n    return data(code);\n  }\n\n  /** @type {State} */\n  function data(code) {\n    if (code === null) {\n      effects.exit(\"chunkText\");\n      effects.exit(\"paragraph\");\n      effects.consume(code);\n      return;\n    }\n    if (markdownLineEnding(code)) {\n      effects.consume(code);\n      effects.exit(\"chunkText\");\n      return lineStart;\n    }\n\n    // Data.\n    effects.consume(code);\n    return data;\n  }\n}","/**\n * @import {\n *   Construct,\n *   ContainerState,\n *   InitialConstruct,\n *   Initializer,\n *   Point,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\n/**\n * @typedef {[Construct, ContainerState]} StackItem\n *   Construct and its state.\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\nimport { splice } from 'micromark-util-chunked';\n/** @type {InitialConstruct} */\nexport const document = {\n  tokenize: initializeDocument\n};\n\n/** @type {Construct} */\nconst containerConstruct = {\n  tokenize: tokenizeContainer\n};\n\n/**\n * @this {TokenizeContext}\n *   Self.\n * @type {Initializer}\n *   Initializer.\n */\nfunction initializeDocument(effects) {\n  const self = this;\n  /** @type {Array<StackItem>} */\n  const stack = [];\n  let continued = 0;\n  /** @type {TokenizeContext | undefined} */\n  let childFlow;\n  /** @type {Token | undefined} */\n  let childToken;\n  /** @type {number} */\n  let lineStartOffset;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    // First we iterate through the open blocks, starting with the root\n    // document, and descending through last children down to the last open\n    // block.\n    // Each block imposes a condition that the line must satisfy if the block is\n    // to remain open.\n    // For example, a block quote requires a `>` character.\n    // A paragraph requires a non-blank line.\n    // In this phase we may match all or just some of the open blocks.\n    // But we cannot close unmatched blocks yet, because we may have a lazy\n    // continuation line.\n    if (continued < stack.length) {\n      const item = stack[continued];\n      self.containerState = item[1];\n      return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code);\n    }\n\n    // Done.\n    return checkNewContainers(code);\n  }\n\n  /** @type {State} */\n  function documentContinue(code) {\n    continued++;\n\n    // Note: this field is called `_closeFlow` but it also closes containers.\n    // Perhaps a good idea to rename it but it’s already used in the wild by\n    // extensions.\n    if (self.containerState._closeFlow) {\n      self.containerState._closeFlow = undefined;\n      if (childFlow) {\n        closeFlow();\n      }\n\n      // Note: this algorithm for moving events around is similar to the\n      // algorithm when dealing with lazy lines in `writeToChild`.\n      const indexBeforeExits = self.events.length;\n      let indexBeforeFlow = indexBeforeExits;\n      /** @type {Point | undefined} */\n      let point;\n\n      // Find the flow chunk.\n      while (indexBeforeFlow--) {\n        if (self.events[indexBeforeFlow][0] === 'exit' && self.events[indexBeforeFlow][1].type === \"chunkFlow\") {\n          point = self.events[indexBeforeFlow][1].end;\n          break;\n        }\n      }\n      exitContainers(continued);\n\n      // Fix positions.\n      let index = indexBeforeExits;\n      while (index < self.events.length) {\n        self.events[index][1].end = {\n          ...point\n        };\n        index++;\n      }\n\n      // Inject the exits earlier (they’re still also at the end).\n      splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));\n\n      // Discard the duplicate exits.\n      self.events.length = index;\n      return checkNewContainers(code);\n    }\n    return start(code);\n  }\n\n  /** @type {State} */\n  function checkNewContainers(code) {\n    // Next, after consuming the continuation markers for existing blocks, we\n    // look for new block starts (e.g. `>` for a block quote).\n    // If we encounter a new block start, we close any blocks unmatched in\n    // step 1 before creating the new block as a child of the last matched\n    // block.\n    if (continued === stack.length) {\n      // No need to `check` whether there’s a container, of `exitContainers`\n      // would be moot.\n      // We can instead immediately `attempt` to parse one.\n      if (!childFlow) {\n        return documentContinued(code);\n      }\n\n      // If we have concrete content, such as block HTML or fenced code,\n      // we can’t have containers “pierce” into them, so we can immediately\n      // start.\n      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {\n        return flowStart(code);\n      }\n\n      // If we do have flow, it could still be a blank line,\n      // but we’d be interrupting it w/ a new container if there’s a current\n      // construct.\n      // To do: next major: remove `_gfmTableDynamicInterruptHack` (no longer\n      // needed in micromark-extension-gfm-table@1.0.6).\n      self.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);\n    }\n\n    // Check if there is a new container.\n    self.containerState = {};\n    return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code);\n  }\n\n  /** @type {State} */\n  function thereIsANewContainer(code) {\n    if (childFlow) closeFlow();\n    exitContainers(continued);\n    return documentContinued(code);\n  }\n\n  /** @type {State} */\n  function thereIsNoNewContainer(code) {\n    self.parser.lazy[self.now().line] = continued !== stack.length;\n    lineStartOffset = self.now().offset;\n    return flowStart(code);\n  }\n\n  /** @type {State} */\n  function documentContinued(code) {\n    // Try new containers.\n    self.containerState = {};\n    return effects.attempt(containerConstruct, containerContinue, flowStart)(code);\n  }\n\n  /** @type {State} */\n  function containerContinue(code) {\n    continued++;\n    stack.push([self.currentConstruct, self.containerState]);\n    // Try another.\n    return documentContinued(code);\n  }\n\n  /** @type {State} */\n  function flowStart(code) {\n    if (code === null) {\n      if (childFlow) closeFlow();\n      exitContainers(0);\n      effects.consume(code);\n      return;\n    }\n    childFlow = childFlow || self.parser.flow(self.now());\n    effects.enter(\"chunkFlow\", {\n      _tokenizer: childFlow,\n      contentType: \"flow\",\n      previous: childToken\n    });\n    return flowContinue(code);\n  }\n\n  /** @type {State} */\n  function flowContinue(code) {\n    if (code === null) {\n      writeToChild(effects.exit(\"chunkFlow\"), true);\n      exitContainers(0);\n      effects.consume(code);\n      return;\n    }\n    if (markdownLineEnding(code)) {\n      effects.consume(code);\n      writeToChild(effects.exit(\"chunkFlow\"));\n      // Get ready for the next line.\n      continued = 0;\n      self.interrupt = undefined;\n      return start;\n    }\n    effects.consume(code);\n    return flowContinue;\n  }\n\n  /**\n   * @param {Token} token\n   *   Token.\n   * @param {boolean | undefined} [endOfFile]\n   *   Whether the token is at the end of the file (default: `false`).\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function writeToChild(token, endOfFile) {\n    const stream = self.sliceStream(token);\n    if (endOfFile) stream.push(null);\n    token.previous = childToken;\n    if (childToken) childToken.next = token;\n    childToken = token;\n    childFlow.defineSkip(token.start);\n    childFlow.write(stream);\n\n    // Alright, so we just added a lazy line:\n    //\n    // ```markdown\n    // > a\n    // b.\n    //\n    // Or:\n    //\n    // > ~~~c\n    // d\n    //\n    // Or:\n    //\n    // > | e |\n    // f\n    // ```\n    //\n    // The construct in the second example (fenced code) does not accept lazy\n    // lines, so it marked itself as done at the end of its first line, and\n    // then the content construct parses `d`.\n    // Most constructs in markdown match on the first line: if the first line\n    // forms a construct, a non-lazy line can’t “unmake” it.\n    //\n    // The construct in the third example is potentially a GFM table, and\n    // those are *weird*.\n    // It *could* be a table, from the first line, if the following line\n    // matches a condition.\n    // In this case, that second line is lazy, which “unmakes” the first line\n    // and turns the whole into one content block.\n    //\n    // We’ve now parsed the non-lazy and the lazy line, and can figure out\n    // whether the lazy line started a new flow block.\n    // If it did, we exit the current containers between the two flow blocks.\n    if (self.parser.lazy[token.start.line]) {\n      let index = childFlow.events.length;\n      while (index--) {\n        if (\n        // The token starts before the line ending…\n        childFlow.events[index][1].start.offset < lineStartOffset && (\n        // …and either is not ended yet…\n        !childFlow.events[index][1].end ||\n        // …or ends after it.\n        childFlow.events[index][1].end.offset > lineStartOffset)) {\n          // Exit: there’s still something open, which means it’s a lazy line\n          // part of something.\n          return;\n        }\n      }\n\n      // Note: this algorithm for moving events around is similar to the\n      // algorithm when closing flow in `documentContinue`.\n      const indexBeforeExits = self.events.length;\n      let indexBeforeFlow = indexBeforeExits;\n      /** @type {boolean | undefined} */\n      let seen;\n      /** @type {Point | undefined} */\n      let point;\n\n      // Find the previous chunk (the one before the lazy line).\n      while (indexBeforeFlow--) {\n        if (self.events[indexBeforeFlow][0] === 'exit' && self.events[indexBeforeFlow][1].type === \"chunkFlow\") {\n          if (seen) {\n            point = self.events[indexBeforeFlow][1].end;\n            break;\n          }\n          seen = true;\n        }\n      }\n      exitContainers(continued);\n\n      // Fix positions.\n      index = indexBeforeExits;\n      while (index < self.events.length) {\n        self.events[index][1].end = {\n          ...point\n        };\n        index++;\n      }\n\n      // Inject the exits earlier (they’re still also at the end).\n      splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));\n\n      // Discard the duplicate exits.\n      self.events.length = index;\n    }\n  }\n\n  /**\n   * @param {number} size\n   *   Size.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function exitContainers(size) {\n    let index = stack.length;\n\n    // Exit open containers.\n    while (index-- > size) {\n      const entry = stack[index];\n      self.containerState = entry[1];\n      entry[0].exit.call(self, effects);\n    }\n    stack.length = size;\n  }\n  function closeFlow() {\n    childFlow.write([null]);\n    childToken = undefined;\n    childFlow = undefined;\n    self.containerState._closeFlow = undefined;\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n *   Tokenizer.\n */\nfunction tokenizeContainer(effects, ok, nok) {\n  // Always populated by defaults.\n\n  return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok, nok), \"linePrefix\", this.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4);\n}","/**\n * @import {Code} from 'micromark-util-types'\n */\n\nimport { markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\n/**\n * Classify whether a code represents whitespace, punctuation, or something\n * else.\n *\n * Used for attention (emphasis, strong), whose sequences can open or close\n * based on the class of surrounding characters.\n *\n * > 👉 **Note**: eof (`null`) is seen as whitespace.\n *\n * @param {Code} code\n *   Code.\n * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined}\n *   Group.\n */\nexport function classifyCharacter(code) {\n  if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n    return 1;\n  }\n  if (unicodePunctuation(code)) {\n    return 2;\n  }\n}","/**\n * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types'\n */\n\n/**\n * Call all `resolveAll`s.\n *\n * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs\n *   List of constructs, optionally with `resolveAll`s.\n * @param {Array<Event>} events\n *   List of events.\n * @param {TokenizeContext} context\n *   Context used by `tokenize`.\n * @returns {Array<Event>}\n *   Changed events.\n */\nexport function resolveAll(constructs, events, context) {\n  /** @type {Array<Resolver>} */\n  const called = []\n  let index = -1\n\n  while (++index < constructs.length) {\n    const resolve = constructs[index].resolveAll\n\n    if (resolve && !called.includes(resolve)) {\n      events = resolve(events, context)\n      called.push(resolve)\n    }\n  }\n\n  return events\n}\n","/**\n * @import {\n *   Code,\n *   Construct,\n *   Event,\n *   Point,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { push, splice } from 'micromark-util-chunked';\nimport { classifyCharacter } from 'micromark-util-classify-character';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/** @type {Construct} */\nexport const attention = {\n  name: 'attention',\n  resolveAll: resolveAllAttention,\n  tokenize: tokenizeAttention\n};\n\n/**\n * Take all events and resolve attention to emphasis or strong.\n *\n * @type {Resolver}\n */\n// eslint-disable-next-line complexity\nfunction resolveAllAttention(events, context) {\n  let index = -1;\n  /** @type {number} */\n  let open;\n  /** @type {Token} */\n  let group;\n  /** @type {Token} */\n  let text;\n  /** @type {Token} */\n  let openingSequence;\n  /** @type {Token} */\n  let closingSequence;\n  /** @type {number} */\n  let use;\n  /** @type {Array<Event>} */\n  let nextEvents;\n  /** @type {number} */\n  let offset;\n\n  // Walk through all events.\n  //\n  // Note: performance of this is fine on an mb of normal markdown, but it’s\n  // a bottleneck for malicious stuff.\n  while (++index < events.length) {\n    // Find a token that can close.\n    if (events[index][0] === 'enter' && events[index][1].type === 'attentionSequence' && events[index][1]._close) {\n      open = index;\n\n      // Now walk back to find an opener.\n      while (open--) {\n        // Find a token that can open the closer.\n        if (events[open][0] === 'exit' && events[open][1].type === 'attentionSequence' && events[open][1]._open &&\n        // If the markers are the same:\n        context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index][1]).charCodeAt(0)) {\n          // If the opening can close or the closing can open,\n          // and the close size *is not* a multiple of three,\n          // but the sum of the opening and closing size *is* multiple of three,\n          // then don’t match.\n          if ((events[open][1]._close || events[index][1]._open) && (events[index][1].end.offset - events[index][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index][1].end.offset - events[index][1].start.offset) % 3)) {\n            continue;\n          }\n\n          // Number of markers to use from the sequence.\n          use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index][1].end.offset - events[index][1].start.offset > 1 ? 2 : 1;\n          const start = {\n            ...events[open][1].end\n          };\n          const end = {\n            ...events[index][1].start\n          };\n          movePoint(start, -use);\n          movePoint(end, use);\n          openingSequence = {\n            type: use > 1 ? \"strongSequence\" : \"emphasisSequence\",\n            start,\n            end: {\n              ...events[open][1].end\n            }\n          };\n          closingSequence = {\n            type: use > 1 ? \"strongSequence\" : \"emphasisSequence\",\n            start: {\n              ...events[index][1].start\n            },\n            end\n          };\n          text = {\n            type: use > 1 ? \"strongText\" : \"emphasisText\",\n            start: {\n              ...events[open][1].end\n            },\n            end: {\n              ...events[index][1].start\n            }\n          };\n          group = {\n            type: use > 1 ? \"strong\" : \"emphasis\",\n            start: {\n              ...openingSequence.start\n            },\n            end: {\n              ...closingSequence.end\n            }\n          };\n          events[open][1].end = {\n            ...openingSequence.start\n          };\n          events[index][1].start = {\n            ...closingSequence.end\n          };\n          nextEvents = [];\n\n          // If there are more markers in the opening, add them before.\n          if (events[open][1].end.offset - events[open][1].start.offset) {\n            nextEvents = push(nextEvents, [['enter', events[open][1], context], ['exit', events[open][1], context]]);\n          }\n\n          // Opening.\n          nextEvents = push(nextEvents, [['enter', group, context], ['enter', openingSequence, context], ['exit', openingSequence, context], ['enter', text, context]]);\n\n          // Always populated by defaults.\n\n          // Between.\n          nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index), context));\n\n          // Closing.\n          nextEvents = push(nextEvents, [['exit', text, context], ['enter', closingSequence, context], ['exit', closingSequence, context], ['exit', group, context]]);\n\n          // If there are more markers in the closing, add them after.\n          if (events[index][1].end.offset - events[index][1].start.offset) {\n            offset = 2;\n            nextEvents = push(nextEvents, [['enter', events[index][1], context], ['exit', events[index][1], context]]);\n          } else {\n            offset = 0;\n          }\n          splice(events, open - 1, index - open + 3, nextEvents);\n          index = open + nextEvents.length - offset - 2;\n          break;\n        }\n      }\n    }\n  }\n\n  // Remove remaining sequences.\n  index = -1;\n  while (++index < events.length) {\n    if (events[index][1].type === 'attentionSequence') {\n      events[index][1].type = 'data';\n    }\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeAttention(effects, ok) {\n  const attentionMarkers = this.parser.constructs.attentionMarkers.null;\n  const previous = this.previous;\n  const before = classifyCharacter(previous);\n\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Before a sequence.\n   *\n   * ```markdown\n   * > | **\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    marker = code;\n    effects.enter('attentionSequence');\n    return inside(code);\n  }\n\n  /**\n   * In a sequence.\n   *\n   * ```markdown\n   * > | **\n   *     ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === marker) {\n      effects.consume(code);\n      return inside;\n    }\n    const token = effects.exit('attentionSequence');\n\n    // To do: next major: move this to resolver, just like `markdown-rs`.\n    const after = classifyCharacter(code);\n\n    // Always populated by defaults.\n\n    const open = !after || after === 2 && before || attentionMarkers.includes(code);\n    const close = !before || before === 2 && after || attentionMarkers.includes(previous);\n    token._open = Boolean(marker === 42 ? open : open && (before || !close));\n    token._close = Boolean(marker === 42 ? close : close && (after || !open));\n    return ok(code);\n  }\n}\n\n/**\n * Move a point a bit.\n *\n * Note: `move` only works inside lines! It’s not possible to move past other\n * chunks (replacement characters, tabs, or line endings).\n *\n * @param {Point} point\n *   Point.\n * @param {number} offset\n *   Amount to move.\n * @returns {undefined}\n *   Nothing.\n */\nfunction movePoint(point, offset) {\n  point.column += offset;\n  point.offset += offset;\n  point._bufferIndex += offset;\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { asciiAlphanumeric, asciiAlpha, asciiAtext, asciiControl } from 'micromark-util-character';\n/** @type {Construct} */\nexport const autolink = {\n  name: 'autolink',\n  tokenize: tokenizeAutolink\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeAutolink(effects, ok, nok) {\n  let size = 0;\n  return start;\n\n  /**\n   * Start of an autolink.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *      ^\n   * > | a<user@example.com>b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"autolink\");\n    effects.enter(\"autolinkMarker\");\n    effects.consume(code);\n    effects.exit(\"autolinkMarker\");\n    effects.enter(\"autolinkProtocol\");\n    return open;\n  }\n\n  /**\n   * After `<`, at protocol or atext.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *       ^\n   * > | a<user@example.com>b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return schemeOrEmailAtext;\n    }\n    if (code === 64) {\n      return nok(code);\n    }\n    return emailAtext(code);\n  }\n\n  /**\n   * At second byte of protocol or atext.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *        ^\n   * > | a<user@example.com>b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function schemeOrEmailAtext(code) {\n    // ASCII alphanumeric and `+`, `-`, and `.`.\n    if (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) {\n      // Count the previous alphabetical from `open` too.\n      size = 1;\n      return schemeInsideOrEmailAtext(code);\n    }\n    return emailAtext(code);\n  }\n\n  /**\n   * In ambiguous protocol or atext.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *        ^\n   * > | a<user@example.com>b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function schemeInsideOrEmailAtext(code) {\n    if (code === 58) {\n      effects.consume(code);\n      size = 0;\n      return urlInside;\n    }\n\n    // ASCII alphanumeric and `+`, `-`, and `.`.\n    if ((code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) && size++ < 32) {\n      effects.consume(code);\n      return schemeInsideOrEmailAtext;\n    }\n    size = 0;\n    return emailAtext(code);\n  }\n\n  /**\n   * After protocol, in URL.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function urlInside(code) {\n    if (code === 62) {\n      effects.exit(\"autolinkProtocol\");\n      effects.enter(\"autolinkMarker\");\n      effects.consume(code);\n      effects.exit(\"autolinkMarker\");\n      effects.exit(\"autolink\");\n      return ok;\n    }\n\n    // ASCII control, space, or `<`.\n    if (code === null || code === 32 || code === 60 || asciiControl(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return urlInside;\n  }\n\n  /**\n   * In email atext.\n   *\n   * ```markdown\n   * > | a<user.name@example.com>b\n   *              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailAtext(code) {\n    if (code === 64) {\n      effects.consume(code);\n      return emailAtSignOrDot;\n    }\n    if (asciiAtext(code)) {\n      effects.consume(code);\n      return emailAtext;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In label, after at-sign or dot.\n   *\n   * ```markdown\n   * > | a<user.name@example.com>b\n   *                 ^       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailAtSignOrDot(code) {\n    return asciiAlphanumeric(code) ? emailLabel(code) : nok(code);\n  }\n\n  /**\n   * In label, where `.` and `>` are allowed.\n   *\n   * ```markdown\n   * > | a<user.name@example.com>b\n   *                   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailLabel(code) {\n    if (code === 46) {\n      effects.consume(code);\n      size = 0;\n      return emailAtSignOrDot;\n    }\n    if (code === 62) {\n      // Exit, then change the token type.\n      effects.exit(\"autolinkProtocol\").type = \"autolinkEmail\";\n      effects.enter(\"autolinkMarker\");\n      effects.consume(code);\n      effects.exit(\"autolinkMarker\");\n      effects.exit(\"autolink\");\n      return ok;\n    }\n    return emailValue(code);\n  }\n\n  /**\n   * In label, where `.` and `>` are *not* allowed.\n   *\n   * Though, this is also used in `emailLabel` to parse other values.\n   *\n   * ```markdown\n   * > | a<user.name@ex-ample.com>b\n   *                    ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailValue(code) {\n    // ASCII alphanumeric or `-`.\n    if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) {\n      const next = code === 45 ? emailValue : emailLabel;\n      effects.consume(code);\n      return next;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const blankLine = {\n  partial: true,\n  tokenize: tokenizeBlankLine\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlankLine(effects, ok, nok) {\n  return start;\n\n  /**\n   * Start of blank line.\n   *\n   * > 👉 **Note**: `␠` represents a space character.\n   *\n   * ```markdown\n   * > | ␠␠␊\n   *     ^\n   * > | ␊\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    return markdownSpace(code) ? factorySpace(effects, after, \"linePrefix\")(code) : after(code);\n  }\n\n  /**\n   * At eof/eol, after optional whitespace.\n   *\n   * > 👉 **Note**: `␠` represents a space character.\n   *\n   * ```markdown\n   * > | ␠␠␊\n   *       ^\n   * > | ␊\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    return code === null || markdownLineEnding(code) ? ok(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Exiter,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const blockQuote = {\n  continuation: {\n    tokenize: tokenizeBlockQuoteContinuation\n  },\n  exit,\n  name: 'blockQuote',\n  tokenize: tokenizeBlockQuoteStart\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlockQuoteStart(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of block quote.\n   *\n   * ```markdown\n   * > | > a\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === 62) {\n      const state = self.containerState;\n      if (!state.open) {\n        effects.enter(\"blockQuote\", {\n          _container: true\n        });\n        state.open = true;\n      }\n      effects.enter(\"blockQuotePrefix\");\n      effects.enter(\"blockQuoteMarker\");\n      effects.consume(code);\n      effects.exit(\"blockQuoteMarker\");\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `>`, before optional whitespace.\n   *\n   * ```markdown\n   * > | > a\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    if (markdownSpace(code)) {\n      effects.enter(\"blockQuotePrefixWhitespace\");\n      effects.consume(code);\n      effects.exit(\"blockQuotePrefixWhitespace\");\n      effects.exit(\"blockQuotePrefix\");\n      return ok;\n    }\n    effects.exit(\"blockQuotePrefix\");\n    return ok(code);\n  }\n}\n\n/**\n * Start of block quote continuation.\n *\n * ```markdown\n *   | > a\n * > | > b\n *     ^\n * ```\n *\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlockQuoteContinuation(effects, ok, nok) {\n  const self = this;\n  return contStart;\n\n  /**\n   * Start of block quote continuation.\n   *\n   * Also used to parse the first block quote opening.\n   *\n   * ```markdown\n   *   | > a\n   * > | > b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function contStart(code) {\n    if (markdownSpace(code)) {\n      // Always populated by defaults.\n\n      return factorySpace(effects, contBefore, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n    }\n    return contBefore(code);\n  }\n\n  /**\n   * At `>`, after optional whitespace.\n   *\n   * Also used to parse the first block quote opening.\n   *\n   * ```markdown\n   *   | > a\n   * > | > b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function contBefore(code) {\n    return effects.attempt(blockQuote, ok, nok)(code);\n  }\n}\n\n/** @type {Exiter} */\nfunction exit(effects) {\n  effects.exit(\"blockQuote\");\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { asciiPunctuation } from 'micromark-util-character';\n/** @type {Construct} */\nexport const characterEscape = {\n  name: 'characterEscape',\n  tokenize: tokenizeCharacterEscape\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCharacterEscape(effects, ok, nok) {\n  return start;\n\n  /**\n   * Start of character escape.\n   *\n   * ```markdown\n   * > | a\\*b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"characterEscape\");\n    effects.enter(\"escapeMarker\");\n    effects.consume(code);\n    effects.exit(\"escapeMarker\");\n    return inside;\n  }\n\n  /**\n   * After `\\`, at punctuation.\n   *\n   * ```markdown\n   * > | a\\*b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    // ASCII punctuation.\n    if (asciiPunctuation(code)) {\n      effects.enter(\"characterEscapeValue\");\n      effects.consume(code);\n      effects.exit(\"characterEscapeValue\");\n      effects.exit(\"characterEscape\");\n      return ok;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { decodeNamedCharacterReference } from 'decode-named-character-reference';\nimport { asciiAlphanumeric, asciiDigit, asciiHexDigit } from 'micromark-util-character';\n/** @type {Construct} */\nexport const characterReference = {\n  name: 'characterReference',\n  tokenize: tokenizeCharacterReference\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCharacterReference(effects, ok, nok) {\n  const self = this;\n  let size = 0;\n  /** @type {number} */\n  let max;\n  /** @type {(code: Code) => boolean} */\n  let test;\n  return start;\n\n  /**\n   * Start of character reference.\n   *\n   * ```markdown\n   * > | a&amp;b\n   *      ^\n   * > | a&#123;b\n   *      ^\n   * > | a&#x9;b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"characterReference\");\n    effects.enter(\"characterReferenceMarker\");\n    effects.consume(code);\n    effects.exit(\"characterReferenceMarker\");\n    return open;\n  }\n\n  /**\n   * After `&`, at `#` for numeric references or alphanumeric for named\n   * references.\n   *\n   * ```markdown\n   * > | a&amp;b\n   *       ^\n   * > | a&#123;b\n   *       ^\n   * > | a&#x9;b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 35) {\n      effects.enter(\"characterReferenceMarkerNumeric\");\n      effects.consume(code);\n      effects.exit(\"characterReferenceMarkerNumeric\");\n      return numeric;\n    }\n    effects.enter(\"characterReferenceValue\");\n    max = 31;\n    test = asciiAlphanumeric;\n    return value(code);\n  }\n\n  /**\n   * After `#`, at `x` for hexadecimals or digit for decimals.\n   *\n   * ```markdown\n   * > | a&#123;b\n   *        ^\n   * > | a&#x9;b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function numeric(code) {\n    if (code === 88 || code === 120) {\n      effects.enter(\"characterReferenceMarkerHexadecimal\");\n      effects.consume(code);\n      effects.exit(\"characterReferenceMarkerHexadecimal\");\n      effects.enter(\"characterReferenceValue\");\n      max = 6;\n      test = asciiHexDigit;\n      return value;\n    }\n    effects.enter(\"characterReferenceValue\");\n    max = 7;\n    test = asciiDigit;\n    return value(code);\n  }\n\n  /**\n   * After markers (`&#x`, `&#`, or `&`), in value, before `;`.\n   *\n   * The character reference kind defines what and how many characters are\n   * allowed.\n   *\n   * ```markdown\n   * > | a&amp;b\n   *       ^^^\n   * > | a&#123;b\n   *        ^^^\n   * > | a&#x9;b\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function value(code) {\n    if (code === 59 && size) {\n      const token = effects.exit(\"characterReferenceValue\");\n      if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self.sliceSerialize(token))) {\n        return nok(code);\n      }\n\n      // To do: `markdown-rs` uses a different name:\n      // `CharacterReferenceMarkerSemi`.\n      effects.enter(\"characterReferenceMarker\");\n      effects.consume(code);\n      effects.exit(\"characterReferenceMarker\");\n      effects.exit(\"characterReference\");\n      return ok;\n    }\n    if (test(code) && size++ < max) {\n      effects.consume(code);\n      return value;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nconst nonLazyContinuation = {\n  partial: true,\n  tokenize: tokenizeNonLazyContinuation\n};\n\n/** @type {Construct} */\nexport const codeFenced = {\n  concrete: true,\n  name: 'codeFenced',\n  tokenize: tokenizeCodeFenced\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCodeFenced(effects, ok, nok) {\n  const self = this;\n  /** @type {Construct} */\n  const closeStart = {\n    partial: true,\n    tokenize: tokenizeCloseStart\n  };\n  let initialPrefix = 0;\n  let sizeOpen = 0;\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Start of code.\n   *\n   * ```markdown\n   * > | ~~~js\n   *     ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: parse whitespace like `markdown-rs`.\n    return beforeSequenceOpen(code);\n  }\n\n  /**\n   * In opening fence, after prefix, at sequence.\n   *\n   * ```markdown\n   * > | ~~~js\n   *     ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeSequenceOpen(code) {\n    const tail = self.events[self.events.length - 1];\n    initialPrefix = tail && tail[1].type === \"linePrefix\" ? tail[2].sliceSerialize(tail[1], true).length : 0;\n    marker = code;\n    effects.enter(\"codeFenced\");\n    effects.enter(\"codeFencedFence\");\n    effects.enter(\"codeFencedFenceSequence\");\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening fence sequence.\n   *\n   * ```markdown\n   * > | ~~~js\n   *      ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === marker) {\n      sizeOpen++;\n      effects.consume(code);\n      return sequenceOpen;\n    }\n    if (sizeOpen < 3) {\n      return nok(code);\n    }\n    effects.exit(\"codeFencedFenceSequence\");\n    return markdownSpace(code) ? factorySpace(effects, infoBefore, \"whitespace\")(code) : infoBefore(code);\n  }\n\n  /**\n   * In opening fence, after the sequence (and optional whitespace), before info.\n   *\n   * ```markdown\n   * > | ~~~js\n   *        ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function infoBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"codeFencedFence\");\n      return self.interrupt ? ok(code) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);\n    }\n    effects.enter(\"codeFencedFenceInfo\");\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return info(code);\n  }\n\n  /**\n   * In info.\n   *\n   * ```markdown\n   * > | ~~~js\n   *        ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function info(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit(\"codeFencedFenceInfo\");\n      return infoBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit(\"codeFencedFenceInfo\");\n      return factorySpace(effects, metaBefore, \"whitespace\")(code);\n    }\n    if (code === 96 && code === marker) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return info;\n  }\n\n  /**\n   * In opening fence, after info and whitespace, before meta.\n   *\n   * ```markdown\n   * > | ~~~js eval\n   *           ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function metaBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return infoBefore(code);\n    }\n    effects.enter(\"codeFencedFenceMeta\");\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return meta(code);\n  }\n\n  /**\n   * In meta.\n   *\n   * ```markdown\n   * > | ~~~js eval\n   *           ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function meta(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit(\"codeFencedFenceMeta\");\n      return infoBefore(code);\n    }\n    if (code === 96 && code === marker) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return meta;\n  }\n\n  /**\n   * At eol/eof in code, before a non-lazy closing fence or content.\n   *\n   * ```markdown\n   * > | ~~~js\n   *          ^\n   * > | alert(1)\n   *             ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function atNonLazyBreak(code) {\n    return effects.attempt(closeStart, after, contentBefore)(code);\n  }\n\n  /**\n   * Before code content, not a closing fence, at eol.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *             ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function contentBefore(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return contentStart;\n  }\n\n  /**\n   * Before code content, not a closing fence.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *     ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function contentStart(code) {\n    return initialPrefix > 0 && markdownSpace(code) ? factorySpace(effects, beforeContentChunk, \"linePrefix\", initialPrefix + 1)(code) : beforeContentChunk(code);\n  }\n\n  /**\n   * Before code content, after optional prefix.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *     ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeContentChunk(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);\n    }\n    effects.enter(\"codeFlowValue\");\n    return contentChunk(code);\n  }\n\n  /**\n   * In code content.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *     ^^^^^^^^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function contentChunk(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"codeFlowValue\");\n      return beforeContentChunk(code);\n    }\n    effects.consume(code);\n    return contentChunk;\n  }\n\n  /**\n   * After code.\n   *\n   * ```markdown\n   *   | ~~~js\n   *   | alert(1)\n   * > | ~~~\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    effects.exit(\"codeFenced\");\n    return ok(code);\n  }\n\n  /**\n   * @this {TokenizeContext}\n   *   Context.\n   * @type {Tokenizer}\n   */\n  function tokenizeCloseStart(effects, ok, nok) {\n    let size = 0;\n    return startBefore;\n\n    /**\n     *\n     *\n     * @type {State}\n     */\n    function startBefore(code) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return start;\n    }\n\n    /**\n     * Before closing fence, at optional whitespace.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function start(code) {\n      // Always populated by defaults.\n\n      // To do: `enter` here or in next state?\n      effects.enter(\"codeFencedFence\");\n      return markdownSpace(code) ? factorySpace(effects, beforeSequenceClose, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code) : beforeSequenceClose(code);\n    }\n\n    /**\n     * In closing fence, after optional whitespace, at sequence.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function beforeSequenceClose(code) {\n      if (code === marker) {\n        effects.enter(\"codeFencedFenceSequence\");\n        return sequenceClose(code);\n      }\n      return nok(code);\n    }\n\n    /**\n     * In closing fence sequence.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function sequenceClose(code) {\n      if (code === marker) {\n        size++;\n        effects.consume(code);\n        return sequenceClose;\n      }\n      if (size >= sizeOpen) {\n        effects.exit(\"codeFencedFenceSequence\");\n        return markdownSpace(code) ? factorySpace(effects, sequenceCloseAfter, \"whitespace\")(code) : sequenceCloseAfter(code);\n      }\n      return nok(code);\n    }\n\n    /**\n     * After closing fence sequence, after optional whitespace.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *        ^\n     * ```\n     *\n     * @type {State}\n     */\n    function sequenceCloseAfter(code) {\n      if (code === null || markdownLineEnding(code)) {\n        effects.exit(\"codeFencedFence\");\n        return ok(code);\n      }\n      return nok(code);\n    }\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeNonLazyContinuation(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return lineStart;\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function lineStart(code) {\n    return self.parser.lazy[self.now().line] ? nok(code) : ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const codeIndented = {\n  name: 'codeIndented',\n  tokenize: tokenizeCodeIndented\n};\n\n/** @type {Construct} */\nconst furtherStart = {\n  partial: true,\n  tokenize: tokenizeFurtherStart\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCodeIndented(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of code (indented).\n   *\n   * > **Parsing note**: it is not needed to check if this first line is a\n   * > filled line (that it has a non-whitespace character), because blank lines\n   * > are parsed already, so we never run into that.\n   *\n   * ```markdown\n   * > |     aaa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: manually check if interrupting like `markdown-rs`.\n\n    effects.enter(\"codeIndented\");\n    // To do: use an improved `space_or_tab` function like `markdown-rs`,\n    // so that we can drop the next state.\n    return factorySpace(effects, afterPrefix, \"linePrefix\", 4 + 1)(code);\n  }\n\n  /**\n   * At start, after 1 or 4 spaces.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === \"linePrefix\" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? atBreak(code) : nok(code);\n  }\n\n  /**\n   * At a break.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^  ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === null) {\n      return after(code);\n    }\n    if (markdownLineEnding(code)) {\n      return effects.attempt(furtherStart, atBreak, after)(code);\n    }\n    effects.enter(\"codeFlowValue\");\n    return inside(code);\n  }\n\n  /**\n   * In code content.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"codeFlowValue\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    return inside;\n  }\n\n  /** @type {State} */\n  function after(code) {\n    effects.exit(\"codeIndented\");\n    // To do: allow interrupting like `markdown-rs`.\n    // Feel free to interrupt.\n    // tokenizer.interrupt = false\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeFurtherStart(effects, ok, nok) {\n  const self = this;\n  return furtherStart;\n\n  /**\n   * At eol, trying to parse another indent.\n   *\n   * ```markdown\n   * > |     aaa\n   *            ^\n   *   |     bbb\n   * ```\n   *\n   * @type {State}\n   */\n  function furtherStart(code) {\n    // To do: improve `lazy` / `pierce` handling.\n    // If this is a lazy line, it can’t be code.\n    if (self.parser.lazy[self.now().line]) {\n      return nok(code);\n    }\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return furtherStart;\n    }\n\n    // To do: the code here in `micromark-js` is a bit different from\n    // `markdown-rs` because there it can attempt spaces.\n    // We can’t yet.\n    //\n    // To do: use an improved `space_or_tab` function like `markdown-rs`,\n    // so that we can drop the next state.\n    return factorySpace(effects, afterPrefix, \"linePrefix\", 4 + 1)(code);\n  }\n\n  /**\n   * At start, after 1 or 4 spaces.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === \"linePrefix\" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? ok(code) : markdownLineEnding(code) ? furtherStart(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Previous,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const codeText = {\n  name: 'codeText',\n  previous,\n  resolve: resolveCodeText,\n  tokenize: tokenizeCodeText\n};\n\n// To do: next major: don’t resolve, like `markdown-rs`.\n/** @type {Resolver} */\nfunction resolveCodeText(events) {\n  let tailExitIndex = events.length - 4;\n  let headEnterIndex = 3;\n  /** @type {number} */\n  let index;\n  /** @type {number | undefined} */\n  let enter;\n\n  // If we start and end with an EOL or a space.\n  if ((events[headEnterIndex][1].type === \"lineEnding\" || events[headEnterIndex][1].type === 'space') && (events[tailExitIndex][1].type === \"lineEnding\" || events[tailExitIndex][1].type === 'space')) {\n    index = headEnterIndex;\n\n    // And we have data.\n    while (++index < tailExitIndex) {\n      if (events[index][1].type === \"codeTextData\") {\n        // Then we have padding.\n        events[headEnterIndex][1].type = \"codeTextPadding\";\n        events[tailExitIndex][1].type = \"codeTextPadding\";\n        headEnterIndex += 2;\n        tailExitIndex -= 2;\n        break;\n      }\n    }\n  }\n\n  // Merge adjacent spaces and data.\n  index = headEnterIndex - 1;\n  tailExitIndex++;\n  while (++index <= tailExitIndex) {\n    if (enter === undefined) {\n      if (index !== tailExitIndex && events[index][1].type !== \"lineEnding\") {\n        enter = index;\n      }\n    } else if (index === tailExitIndex || events[index][1].type === \"lineEnding\") {\n      events[enter][1].type = \"codeTextData\";\n      if (index !== enter + 2) {\n        events[enter][1].end = events[index - 1][1].end;\n        events.splice(enter + 2, index - enter - 2);\n        tailExitIndex -= index - enter - 2;\n        index = enter + 2;\n      }\n      enter = undefined;\n    }\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Previous}\n */\nfunction previous(code) {\n  // If there is a previous code, there will always be a tail.\n  return code !== 96 || this.events[this.events.length - 1][1].type === \"characterEscape\";\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCodeText(effects, ok, nok) {\n  const self = this;\n  let sizeOpen = 0;\n  /** @type {number} */\n  let size;\n  /** @type {Token} */\n  let token;\n  return start;\n\n  /**\n   * Start of code (text).\n   *\n   * ```markdown\n   * > | `a`\n   *     ^\n   * > | \\`a`\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"codeText\");\n    effects.enter(\"codeTextSequence\");\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening sequence.\n   *\n   * ```markdown\n   * > | `a`\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === 96) {\n      effects.consume(code);\n      sizeOpen++;\n      return sequenceOpen;\n    }\n    effects.exit(\"codeTextSequence\");\n    return between(code);\n  }\n\n  /**\n   * Between something and something else.\n   *\n   * ```markdown\n   * > | `a`\n   *      ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function between(code) {\n    // EOF.\n    if (code === null) {\n      return nok(code);\n    }\n\n    // To do: next major: don’t do spaces in resolve, but when compiling,\n    // like `markdown-rs`.\n    // Tabs don’t work, and virtual spaces don’t make sense.\n    if (code === 32) {\n      effects.enter('space');\n      effects.consume(code);\n      effects.exit('space');\n      return between;\n    }\n\n    // Closing fence? Could also be data.\n    if (code === 96) {\n      token = effects.enter(\"codeTextSequence\");\n      size = 0;\n      return sequenceClose(code);\n    }\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return between;\n    }\n\n    // Data.\n    effects.enter(\"codeTextData\");\n    return data(code);\n  }\n\n  /**\n   * In data.\n   *\n   * ```markdown\n   * > | `a`\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function data(code) {\n    if (code === null || code === 32 || code === 96 || markdownLineEnding(code)) {\n      effects.exit(\"codeTextData\");\n      return between(code);\n    }\n    effects.consume(code);\n    return data;\n  }\n\n  /**\n   * In closing sequence.\n   *\n   * ```markdown\n   * > | `a`\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceClose(code) {\n    // More.\n    if (code === 96) {\n      effects.consume(code);\n      size++;\n      return sequenceClose;\n    }\n\n    // Done!\n    if (size === sizeOpen) {\n      effects.exit(\"codeTextSequence\");\n      effects.exit(\"codeText\");\n      return ok(code);\n    }\n\n    // More or less accents: mark as data.\n    token.type = \"codeTextData\";\n    return data(code);\n  }\n}","/**\n * Some of the internal operations of micromark do lots of editing\n * operations on very large arrays. This runs into problems with two\n * properties of most circa-2020 JavaScript interpreters:\n *\n *  - Array-length modifications at the high end of an array (push/pop) are\n *    expected to be common and are implemented in (amortized) time\n *    proportional to the number of elements added or removed, whereas\n *    other operations (shift/unshift and splice) are much less efficient.\n *  - Function arguments are passed on the stack, so adding tens of thousands\n *    of elements to an array with `arr.push(...newElements)` will frequently\n *    cause stack overflows. (see <https://stackoverflow.com/questions/22123769/rangeerror-maximum-call-stack-size-exceeded-why>)\n *\n * SpliceBuffers are an implementation of gap buffers, which are a\n * generalization of the \"queue made of two stacks\" idea. The splice buffer\n * maintains a cursor, and moving the cursor has cost proportional to the\n * distance the cursor moves, but inserting, deleting, or splicing in\n * new information at the cursor is as efficient as the push/pop operation.\n * This allows for an efficient sequence of splices (or pushes, pops, shifts,\n * or unshifts) as long such edits happen at the same part of the array or\n * generally sweep through the array from the beginning to the end.\n *\n * The interface for splice buffers also supports large numbers of inputs by\n * passing a single array argument rather passing multiple arguments on the\n * function call stack.\n *\n * @template T\n *   Item type.\n */\nexport class SpliceBuffer {\n  /**\n   * @param {ReadonlyArray<T> | null | undefined} [initial]\n   *   Initial items (optional).\n   * @returns\n   *   Splice buffer.\n   */\n  constructor(initial) {\n    /** @type {Array<T>} */\n    this.left = initial ? [...initial] : [];\n    /** @type {Array<T>} */\n    this.right = [];\n  }\n\n  /**\n   * Array access;\n   * does not move the cursor.\n   *\n   * @param {number} index\n   *   Index.\n   * @return {T}\n   *   Item.\n   */\n  get(index) {\n    if (index < 0 || index >= this.left.length + this.right.length) {\n      throw new RangeError('Cannot access index `' + index + '` in a splice buffer of size `' + (this.left.length + this.right.length) + '`');\n    }\n    if (index < this.left.length) return this.left[index];\n    return this.right[this.right.length - index + this.left.length - 1];\n  }\n\n  /**\n   * The length of the splice buffer, one greater than the largest index in the\n   * array.\n   */\n  get length() {\n    return this.left.length + this.right.length;\n  }\n\n  /**\n   * Remove and return `list[0]`;\n   * moves the cursor to `0`.\n   *\n   * @returns {T | undefined}\n   *   Item, optional.\n   */\n  shift() {\n    this.setCursor(0);\n    return this.right.pop();\n  }\n\n  /**\n   * Slice the buffer to get an array;\n   * does not move the cursor.\n   *\n   * @param {number} start\n   *   Start.\n   * @param {number | null | undefined} [end]\n   *   End (optional).\n   * @returns {Array<T>}\n   *   Array of items.\n   */\n  slice(start, end) {\n    /** @type {number} */\n    const stop = end === null || end === undefined ? Number.POSITIVE_INFINITY : end;\n    if (stop < this.left.length) {\n      return this.left.slice(start, stop);\n    }\n    if (start > this.left.length) {\n      return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();\n    }\n    return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());\n  }\n\n  /**\n   * Mimics the behavior of Array.prototype.splice() except for the change of\n   * interface necessary to avoid segfaults when patching in very large arrays.\n   *\n   * This operation moves cursor is moved to `start` and results in the cursor\n   * placed after any inserted items.\n   *\n   * @param {number} start\n   *   Start;\n   *   zero-based index at which to start changing the array;\n   *   negative numbers count backwards from the end of the array and values\n   *   that are out-of bounds are clamped to the appropriate end of the array.\n   * @param {number | null | undefined} [deleteCount=0]\n   *   Delete count (default: `0`);\n   *   maximum number of elements to delete, starting from start.\n   * @param {Array<T> | null | undefined} [items=[]]\n   *   Items to include in place of the deleted items (default: `[]`).\n   * @return {Array<T>}\n   *   Any removed items.\n   */\n  splice(start, deleteCount, items) {\n    /** @type {number} */\n    const count = deleteCount || 0;\n    this.setCursor(Math.trunc(start));\n    const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);\n    if (items) chunkedPush(this.left, items);\n    return removed.reverse();\n  }\n\n  /**\n   * Remove and return the highest-numbered item in the array, so\n   * `list[list.length - 1]`;\n   * Moves the cursor to `length`.\n   *\n   * @returns {T | undefined}\n   *   Item, optional.\n   */\n  pop() {\n    this.setCursor(Number.POSITIVE_INFINITY);\n    return this.left.pop();\n  }\n\n  /**\n   * Inserts a single item to the high-numbered side of the array;\n   * moves the cursor to `length`.\n   *\n   * @param {T} item\n   *   Item.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  push(item) {\n    this.setCursor(Number.POSITIVE_INFINITY);\n    this.left.push(item);\n  }\n\n  /**\n   * Inserts many items to the high-numbered side of the array.\n   * Moves the cursor to `length`.\n   *\n   * @param {Array<T>} items\n   *   Items.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  pushMany(items) {\n    this.setCursor(Number.POSITIVE_INFINITY);\n    chunkedPush(this.left, items);\n  }\n\n  /**\n   * Inserts a single item to the low-numbered side of the array;\n   * Moves the cursor to `0`.\n   *\n   * @param {T} item\n   *   Item.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  unshift(item) {\n    this.setCursor(0);\n    this.right.push(item);\n  }\n\n  /**\n   * Inserts many items to the low-numbered side of the array;\n   * moves the cursor to `0`.\n   *\n   * @param {Array<T>} items\n   *   Items.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  unshiftMany(items) {\n    this.setCursor(0);\n    chunkedPush(this.right, items.reverse());\n  }\n\n  /**\n   * Move the cursor to a specific position in the array. Requires\n   * time proportional to the distance moved.\n   *\n   * If `n < 0`, the cursor will end up at the beginning.\n   * If `n > length`, the cursor will end up at the end.\n   *\n   * @param {number} n\n   *   Position.\n   * @return {undefined}\n   *   Nothing.\n   */\n  setCursor(n) {\n    if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0) return;\n    if (n < this.left.length) {\n      // Move cursor to the this.left\n      const removed = this.left.splice(n, Number.POSITIVE_INFINITY);\n      chunkedPush(this.right, removed.reverse());\n    } else {\n      // Move cursor to the this.right\n      const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY);\n      chunkedPush(this.left, removed.reverse());\n    }\n  }\n}\n\n/**\n * Avoid stack overflow by pushing items onto the stack in segments\n *\n * @template T\n *   Item type.\n * @param {Array<T>} list\n *   List to inject into.\n * @param {ReadonlyArray<T>} right\n *   Items to inject.\n * @return {undefined}\n *   Nothing.\n */\nfunction chunkedPush(list, right) {\n  /** @type {number} */\n  let chunkStart = 0;\n  if (right.length < 10000) {\n    list.push(...right);\n  } else {\n    while (chunkStart < right.length) {\n      list.push(...right.slice(chunkStart, chunkStart + 10000));\n      chunkStart += 10000;\n    }\n  }\n}","/**\n * @import {Chunk, Event, Token} from 'micromark-util-types'\n */\n\nimport { splice } from 'micromark-util-chunked';\nimport { SpliceBuffer } from './lib/splice-buffer.js';\n\n// Hidden API exposed for testing.\nexport { SpliceBuffer } from './lib/splice-buffer.js';\n\n/**\n * Tokenize subcontent.\n *\n * @param {Array<Event>} eventsArray\n *   List of events.\n * @returns {boolean}\n *   Whether subtokens were found.\n */\n// eslint-disable-next-line complexity\nexport function subtokenize(eventsArray) {\n  /** @type {Record<string, number>} */\n  const jumps = {};\n  let index = -1;\n  /** @type {Event} */\n  let event;\n  /** @type {number | undefined} */\n  let lineIndex;\n  /** @type {number} */\n  let otherIndex;\n  /** @type {Event} */\n  let otherEvent;\n  /** @type {Array<Event>} */\n  let parameters;\n  /** @type {Array<Event>} */\n  let subevents;\n  /** @type {boolean | undefined} */\n  let more;\n  const events = new SpliceBuffer(eventsArray);\n  while (++index < events.length) {\n    while (index in jumps) {\n      index = jumps[index];\n    }\n    event = events.get(index);\n\n    // Add a hook for the GFM tasklist extension, which needs to know if text\n    // is in the first content of a list item.\n    if (index && event[1].type === \"chunkFlow\" && events.get(index - 1)[1].type === \"listItemPrefix\") {\n      subevents = event[1]._tokenizer.events;\n      otherIndex = 0;\n      if (otherIndex < subevents.length && subevents[otherIndex][1].type === \"lineEndingBlank\") {\n        otherIndex += 2;\n      }\n      if (otherIndex < subevents.length && subevents[otherIndex][1].type === \"content\") {\n        while (++otherIndex < subevents.length) {\n          if (subevents[otherIndex][1].type === \"content\") {\n            break;\n          }\n          if (subevents[otherIndex][1].type === \"chunkText\") {\n            subevents[otherIndex][1]._isInFirstContentOfListItem = true;\n            otherIndex++;\n          }\n        }\n      }\n    }\n\n    // Enter.\n    if (event[0] === 'enter') {\n      if (event[1].contentType) {\n        Object.assign(jumps, subcontent(events, index));\n        index = jumps[index];\n        more = true;\n      }\n    }\n    // Exit.\n    else if (event[1]._container) {\n      otherIndex = index;\n      lineIndex = undefined;\n      while (otherIndex--) {\n        otherEvent = events.get(otherIndex);\n        if (otherEvent[1].type === \"lineEnding\" || otherEvent[1].type === \"lineEndingBlank\") {\n          if (otherEvent[0] === 'enter') {\n            if (lineIndex) {\n              events.get(lineIndex)[1].type = \"lineEndingBlank\";\n            }\n            otherEvent[1].type = \"lineEnding\";\n            lineIndex = otherIndex;\n          }\n        } else if (otherEvent[1].type === \"linePrefix\" || otherEvent[1].type === \"listItemIndent\") {\n          // Move past.\n        } else {\n          break;\n        }\n      }\n      if (lineIndex) {\n        // Fix position.\n        event[1].end = {\n          ...events.get(lineIndex)[1].start\n        };\n\n        // Switch container exit w/ line endings.\n        parameters = events.slice(lineIndex, index);\n        parameters.unshift(event);\n        events.splice(lineIndex, index - lineIndex + 1, parameters);\n      }\n    }\n  }\n\n  // The changes to the `events` buffer must be copied back into the eventsArray\n  splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0));\n  return !more;\n}\n\n/**\n * Tokenize embedded tokens.\n *\n * @param {SpliceBuffer<Event>} events\n *   Events.\n * @param {number} eventIndex\n *   Index.\n * @returns {Record<string, number>}\n *   Gaps.\n */\nfunction subcontent(events, eventIndex) {\n  const token = events.get(eventIndex)[1];\n  const context = events.get(eventIndex)[2];\n  let startPosition = eventIndex - 1;\n  /** @type {Array<number>} */\n  const startPositions = [];\n  let tokenizer = token._tokenizer;\n  if (!tokenizer) {\n    tokenizer = context.parser[token.contentType](token.start);\n    if (token._contentTypeTextTrailing) {\n      tokenizer._contentTypeTextTrailing = true;\n    }\n  }\n  const childEvents = tokenizer.events;\n  /** @type {Array<[number, number]>} */\n  const jumps = [];\n  /** @type {Record<string, number>} */\n  const gaps = {};\n  /** @type {Array<Chunk>} */\n  let stream;\n  /** @type {Token | undefined} */\n  let previous;\n  let index = -1;\n  /** @type {Token | undefined} */\n  let current = token;\n  let adjust = 0;\n  let start = 0;\n  const breaks = [start];\n\n  // Loop forward through the linked tokens to pass them in order to the\n  // subtokenizer.\n  while (current) {\n    // Find the position of the event for this token.\n    while (events.get(++startPosition)[1] !== current) {\n      // Empty.\n    }\n    startPositions.push(startPosition);\n    if (!current._tokenizer) {\n      stream = context.sliceStream(current);\n      if (!current.next) {\n        stream.push(null);\n      }\n      if (previous) {\n        tokenizer.defineSkip(current.start);\n      }\n      if (current._isInFirstContentOfListItem) {\n        tokenizer._gfmTasklistFirstContentOfListItem = true;\n      }\n      tokenizer.write(stream);\n      if (current._isInFirstContentOfListItem) {\n        tokenizer._gfmTasklistFirstContentOfListItem = undefined;\n      }\n    }\n\n    // Unravel the next token.\n    previous = current;\n    current = current.next;\n  }\n\n  // Now, loop back through all events (and linked tokens), to figure out which\n  // parts belong where.\n  current = token;\n  while (++index < childEvents.length) {\n    if (\n    // Find a void token that includes a break.\n    childEvents[index][0] === 'exit' && childEvents[index - 1][0] === 'enter' && childEvents[index][1].type === childEvents[index - 1][1].type && childEvents[index][1].start.line !== childEvents[index][1].end.line) {\n      start = index + 1;\n      breaks.push(start);\n      // Help GC.\n      current._tokenizer = undefined;\n      current.previous = undefined;\n      current = current.next;\n    }\n  }\n\n  // Help GC.\n  tokenizer.events = [];\n\n  // If there’s one more token (which is the cases for lines that end in an\n  // EOF), that’s perfect: the last point we found starts it.\n  // If there isn’t then make sure any remaining content is added to it.\n  if (current) {\n    // Help GC.\n    current._tokenizer = undefined;\n    current.previous = undefined;\n  } else {\n    breaks.pop();\n  }\n\n  // Now splice the events from the subtokenizer into the current events,\n  // moving back to front so that splice indices aren’t affected.\n  index = breaks.length;\n  while (index--) {\n    const slice = childEvents.slice(breaks[index], breaks[index + 1]);\n    const start = startPositions.pop();\n    jumps.push([start, start + slice.length - 1]);\n    events.splice(start, 2, slice);\n  }\n  jumps.reverse();\n  index = -1;\n  while (++index < jumps.length) {\n    gaps[adjust + jumps[index][0]] = adjust + jumps[index][1];\n    adjust += jumps[index][1] - jumps[index][0] - 1;\n  }\n  return gaps;\n}","/**\n * @import {\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\nimport { subtokenize } from 'micromark-util-subtokenize';\n/**\n * No name because it must not be turned off.\n * @type {Construct}\n */\nexport const content = {\n  resolve: resolveContent,\n  tokenize: tokenizeContent\n};\n\n/** @type {Construct} */\nconst continuationConstruct = {\n  partial: true,\n  tokenize: tokenizeContinuation\n};\n\n/**\n * Content is transparent: it’s parsed right now. That way, definitions are also\n * parsed right now: before text in paragraphs (specifically, media) are parsed.\n *\n * @type {Resolver}\n */\nfunction resolveContent(events) {\n  subtokenize(events);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeContent(effects, ok) {\n  /** @type {Token | undefined} */\n  let previous;\n  return chunkStart;\n\n  /**\n   * Before a content chunk.\n   *\n   * ```markdown\n   * > | abc\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function chunkStart(code) {\n    effects.enter(\"content\");\n    previous = effects.enter(\"chunkContent\", {\n      contentType: \"content\"\n    });\n    return chunkInside(code);\n  }\n\n  /**\n   * In a content chunk.\n   *\n   * ```markdown\n   * > | abc\n   *     ^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function chunkInside(code) {\n    if (code === null) {\n      return contentEnd(code);\n    }\n\n    // To do: in `markdown-rs`, each line is parsed on its own, and everything\n    // is stitched together resolving.\n    if (markdownLineEnding(code)) {\n      return effects.check(continuationConstruct, contentContinue, contentEnd)(code);\n    }\n\n    // Data.\n    effects.consume(code);\n    return chunkInside;\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function contentEnd(code) {\n    effects.exit(\"chunkContent\");\n    effects.exit(\"content\");\n    return ok(code);\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function contentContinue(code) {\n    effects.consume(code);\n    effects.exit(\"chunkContent\");\n    previous.next = effects.enter(\"chunkContent\", {\n      contentType: \"content\",\n      previous\n    });\n    previous = previous.next;\n    return chunkInside;\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeContinuation(effects, ok, nok) {\n  const self = this;\n  return startLookahead;\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function startLookahead(code) {\n    effects.exit(\"chunkContent\");\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return factorySpace(effects, prefixed, \"linePrefix\");\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function prefixed(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return nok(code);\n    }\n\n    // Always populated by defaults.\n\n    const tail = self.events[self.events.length - 1];\n    if (!self.parser.constructs.disable.null.includes('codeIndented') && tail && tail[1].type === \"linePrefix\" && tail[2].sliceSerialize(tail[1], true).length >= 4) {\n      return ok(code);\n    }\n    return effects.interrupt(self.parser.constructs.flow, nok, ok)(code);\n  }\n}","/**\n * @import {Effects, State, TokenType} from 'micromark-util-types'\n */\n\nimport { asciiControl, markdownLineEndingOrSpace, markdownLineEnding } from 'micromark-util-character';\n/**\n * Parse destinations.\n *\n * ###### Examples\n *\n * ```markdown\n * <a>\n * <a\\>b>\n * <a b>\n * <a)>\n * a\n * a\\)b\n * a(b)c\n * a(b)\n * ```\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {State} nok\n *   State switched to when unsuccessful.\n * @param {TokenType} type\n *   Type for whole (`<a>` or `b`).\n * @param {TokenType} literalType\n *   Type when enclosed (`<a>`).\n * @param {TokenType} literalMarkerType\n *   Type for enclosing (`<` and `>`).\n * @param {TokenType} rawType\n *   Type when not enclosed (`b`).\n * @param {TokenType} stringType\n *   Type for the value (`a` or `b`).\n * @param {number | undefined} [max=Infinity]\n *   Depth of nested parens (inclusive).\n * @returns {State}\n *   Start state.\n */\nexport function factoryDestination(effects, ok, nok, type, literalType, literalMarkerType, rawType, stringType, max) {\n  const limit = max || Number.POSITIVE_INFINITY;\n  let balance = 0;\n  return start;\n\n  /**\n   * Start of destination.\n   *\n   * ```markdown\n   * > | <aa>\n   *     ^\n   * > | aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === 60) {\n      effects.enter(type);\n      effects.enter(literalType);\n      effects.enter(literalMarkerType);\n      effects.consume(code);\n      effects.exit(literalMarkerType);\n      return enclosedBefore;\n    }\n\n    // ASCII control, space, closing paren.\n    if (code === null || code === 32 || code === 41 || asciiControl(code)) {\n      return nok(code);\n    }\n    effects.enter(type);\n    effects.enter(rawType);\n    effects.enter(stringType);\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return raw(code);\n  }\n\n  /**\n   * After `<`, at an enclosed destination.\n   *\n   * ```markdown\n   * > | <aa>\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function enclosedBefore(code) {\n    if (code === 62) {\n      effects.enter(literalMarkerType);\n      effects.consume(code);\n      effects.exit(literalMarkerType);\n      effects.exit(literalType);\n      effects.exit(type);\n      return ok;\n    }\n    effects.enter(stringType);\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return enclosed(code);\n  }\n\n  /**\n   * In enclosed destination.\n   *\n   * ```markdown\n   * > | <aa>\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function enclosed(code) {\n    if (code === 62) {\n      effects.exit(\"chunkString\");\n      effects.exit(stringType);\n      return enclosedBefore(code);\n    }\n    if (code === null || code === 60 || markdownLineEnding(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return code === 92 ? enclosedEscape : enclosed;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * ```markdown\n   * > | <a\\*a>\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function enclosedEscape(code) {\n    if (code === 60 || code === 62 || code === 92) {\n      effects.consume(code);\n      return enclosed;\n    }\n    return enclosed(code);\n  }\n\n  /**\n   * In raw destination.\n   *\n   * ```markdown\n   * > | aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function raw(code) {\n    if (!balance && (code === null || code === 41 || markdownLineEndingOrSpace(code))) {\n      effects.exit(\"chunkString\");\n      effects.exit(stringType);\n      effects.exit(rawType);\n      effects.exit(type);\n      return ok(code);\n    }\n    if (balance < limit && code === 40) {\n      effects.consume(code);\n      balance++;\n      return raw;\n    }\n    if (code === 41) {\n      effects.consume(code);\n      balance--;\n      return raw;\n    }\n\n    // ASCII control (but *not* `\\0`) and space and `(`.\n    // Note: in `markdown-rs`, `\\0` exists in codes, in `micromark-js` it\n    // doesn’t.\n    if (code === null || code === 32 || code === 40 || asciiControl(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return code === 92 ? rawEscape : raw;\n  }\n\n  /**\n   * After `\\`, at special character.\n   *\n   * ```markdown\n   * > | a\\*a\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function rawEscape(code) {\n    if (code === 40 || code === 41 || code === 92) {\n      effects.consume(code);\n      return raw;\n    }\n    return raw(code);\n  }\n}","/**\n * @import {\n *   Effects,\n *   State,\n *   TokenizeContext,\n *   TokenType\n * } from 'micromark-util-types'\n */\n\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/**\n * Parse labels.\n *\n * > 👉 **Note**: labels in markdown are capped at 999 characters in the string.\n *\n * ###### Examples\n *\n * ```markdown\n * [a]\n * [a\n * b]\n * [a\\]b]\n * ```\n *\n * @this {TokenizeContext}\n *   Tokenize context.\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {State} nok\n *   State switched to when unsuccessful.\n * @param {TokenType} type\n *   Type of the whole label (`[a]`).\n * @param {TokenType} markerType\n *   Type for the markers (`[` and `]`).\n * @param {TokenType} stringType\n *   Type for the identifier (`a`).\n * @returns {State}\n *   Start state.\n */\nexport function factoryLabel(effects, ok, nok, type, markerType, stringType) {\n  const self = this;\n  let size = 0;\n  /** @type {boolean} */\n  let seen;\n  return start;\n\n  /**\n   * Start of label.\n   *\n   * ```markdown\n   * > | [a]\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(type);\n    effects.enter(markerType);\n    effects.consume(code);\n    effects.exit(markerType);\n    effects.enter(stringType);\n    return atBreak;\n  }\n\n  /**\n   * In label, at something, before something else.\n   *\n   * ```markdown\n   * > | [a]\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (size > 999 || code === null || code === 91 || code === 93 && !seen ||\n    // To do: remove in the future once we’ve switched from\n    // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,\n    // which doesn’t need this.\n    // Hidden footnotes hook.\n    /* c8 ignore next 3 */\n    code === 94 && !size && '_hiddenFootnoteSupport' in self.parser.constructs) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.exit(stringType);\n      effects.enter(markerType);\n      effects.consume(code);\n      effects.exit(markerType);\n      effects.exit(type);\n      return ok;\n    }\n\n    // To do: indent? Link chunks and EOLs together?\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return atBreak;\n    }\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return labelInside(code);\n  }\n\n  /**\n   * In label, in text.\n   *\n   * ```markdown\n   * > | [a]\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelInside(code) {\n    if (code === null || code === 91 || code === 93 || markdownLineEnding(code) || size++ > 999) {\n      effects.exit(\"chunkString\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    if (!seen) seen = !markdownSpace(code);\n    return code === 92 ? labelEscape : labelInside;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * ```markdown\n   * > | [a\\*a]\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEscape(code) {\n    if (code === 91 || code === 92 || code === 93) {\n      effects.consume(code);\n      size++;\n      return labelInside;\n    }\n    return labelInside(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Effects,\n *   State,\n *   TokenType\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/**\n * Parse titles.\n *\n * ###### Examples\n *\n * ```markdown\n * \"a\"\n * 'b'\n * (c)\n * \"a\n * b\"\n * 'a\n *     b'\n * (a\\)b)\n * ```\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {State} nok\n *   State switched to when unsuccessful.\n * @param {TokenType} type\n *   Type of the whole title (`\"a\"`, `'b'`, `(c)`).\n * @param {TokenType} markerType\n *   Type for the markers (`\"`, `'`, `(`, and `)`).\n * @param {TokenType} stringType\n *   Type for the value (`a`).\n * @returns {State}\n *   Start state.\n */\nexport function factoryTitle(effects, ok, nok, type, markerType, stringType) {\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Start of title.\n   *\n   * ```markdown\n   * > | \"a\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === 34 || code === 39 || code === 40) {\n      effects.enter(type);\n      effects.enter(markerType);\n      effects.consume(code);\n      effects.exit(markerType);\n      marker = code === 40 ? 41 : code;\n      return begin;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After opening marker.\n   *\n   * This is also used at the closing marker.\n   *\n   * ```markdown\n   * > | \"a\"\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function begin(code) {\n    if (code === marker) {\n      effects.enter(markerType);\n      effects.consume(code);\n      effects.exit(markerType);\n      effects.exit(type);\n      return ok;\n    }\n    effects.enter(stringType);\n    return atBreak(code);\n  }\n\n  /**\n   * At something, before something else.\n   *\n   * ```markdown\n   * > | \"a\"\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === marker) {\n      effects.exit(stringType);\n      return begin(marker);\n    }\n    if (code === null) {\n      return nok(code);\n    }\n\n    // Note: blank lines can’t exist in content.\n    if (markdownLineEnding(code)) {\n      // To do: use `space_or_tab_eol_with_options`, connect.\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return factorySpace(effects, atBreak, \"linePrefix\");\n    }\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return inside(code);\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === marker || code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    return code === 92 ? escape : inside;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * ```markdown\n   * > | \"a\\*b\"\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function escape(code) {\n    if (code === marker || code === 92) {\n      effects.consume(code);\n      return inside;\n    }\n    return inside(code);\n  }\n}","/**\n * @import {Effects, State} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/**\n * Parse spaces and tabs.\n *\n * There is no `nok` parameter:\n *\n * *   line endings or spaces in markdown are often optional, in which case this\n *     factory can be used and `ok` will be switched to whether spaces were found\n *     or not\n * *   one line ending or space can be detected with\n *     `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace`\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @returns {State}\n *   Start state.\n */\nexport function factoryWhitespace(effects, ok) {\n  /** @type {boolean} */\n  let seen;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      seen = true;\n      return start;\n    }\n    if (markdownSpace(code)) {\n      return factorySpace(effects, start, seen ? \"linePrefix\" : \"lineSuffix\")(code);\n    }\n    return ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factoryDestination } from 'micromark-factory-destination';\nimport { factoryLabel } from 'micromark-factory-label';\nimport { factorySpace } from 'micromark-factory-space';\nimport { factoryTitle } from 'micromark-factory-title';\nimport { factoryWhitespace } from 'micromark-factory-whitespace';\nimport { markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\n/** @type {Construct} */\nexport const definition = {\n  name: 'definition',\n  tokenize: tokenizeDefinition\n};\n\n/** @type {Construct} */\nconst titleBefore = {\n  partial: true,\n  tokenize: tokenizeTitleBefore\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeDefinition(effects, ok, nok) {\n  const self = this;\n  /** @type {string} */\n  let identifier;\n  return start;\n\n  /**\n   * At start of a definition.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // Do not interrupt paragraphs (but do follow definitions).\n    // To do: do `interrupt` the way `markdown-rs` does.\n    // To do: parse whitespace the way `markdown-rs` does.\n    effects.enter(\"definition\");\n    return before(code);\n  }\n\n  /**\n   * After optional whitespace, at `[`.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    // To do: parse whitespace the way `markdown-rs` does.\n\n    return factoryLabel.call(self, effects, labelAfter,\n    // Note: we don’t need to reset the way `markdown-rs` does.\n    nok, \"definitionLabel\", \"definitionLabelMarker\", \"definitionLabelString\")(code);\n  }\n\n  /**\n   * After label.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelAfter(code) {\n    identifier = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));\n    if (code === 58) {\n      effects.enter(\"definitionMarker\");\n      effects.consume(code);\n      effects.exit(\"definitionMarker\");\n      return markerAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After marker.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function markerAfter(code) {\n    // Note: whitespace is optional.\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, destinationBefore)(code) : destinationBefore(code);\n  }\n\n  /**\n   * Before destination.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function destinationBefore(code) {\n    return factoryDestination(effects, destinationAfter,\n    // Note: we don’t need to reset the way `markdown-rs` does.\n    nok, \"definitionDestination\", \"definitionDestinationLiteral\", \"definitionDestinationLiteralMarker\", \"definitionDestinationRaw\", \"definitionDestinationString\")(code);\n  }\n\n  /**\n   * After destination.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function destinationAfter(code) {\n    return effects.attempt(titleBefore, after, after)(code);\n  }\n\n  /**\n   * After definition.\n   *\n   * ```markdown\n   * > | [a]: b\n   *           ^\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    return markdownSpace(code) ? factorySpace(effects, afterWhitespace, \"whitespace\")(code) : afterWhitespace(code);\n  }\n\n  /**\n   * After definition, after optional whitespace.\n   *\n   * ```markdown\n   * > | [a]: b\n   *           ^\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterWhitespace(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"definition\");\n\n      // Note: we don’t care about uniqueness.\n      // It’s likely that that doesn’t happen very frequently.\n      // It is more likely that it wastes precious time.\n      self.parser.defined.push(identifier);\n\n      // To do: `markdown-rs` interrupt.\n      // // You’d be interrupting.\n      // tokenizer.interrupt = true\n      return ok(code);\n    }\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeTitleBefore(effects, ok, nok) {\n  return titleBefore;\n\n  /**\n   * After destination, at whitespace.\n   *\n   * ```markdown\n   * > | [a]: b\n   *           ^\n   * > | [a]: b \"c\"\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function titleBefore(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, beforeMarker)(code) : nok(code);\n  }\n\n  /**\n   * At title.\n   *\n   * ```markdown\n   *   | [a]: b\n   * > | \"c\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeMarker(code) {\n    return factoryTitle(effects, titleAfter, nok, \"definitionTitle\", \"definitionTitleMarker\", \"definitionTitleString\")(code);\n  }\n\n  /**\n   * After title.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function titleAfter(code) {\n    return markdownSpace(code) ? factorySpace(effects, titleAfterOptionalWhitespace, \"whitespace\")(code) : titleAfterOptionalWhitespace(code);\n  }\n\n  /**\n   * After title, after optional whitespace.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function titleAfterOptionalWhitespace(code) {\n    return code === null || markdownLineEnding(code) ? ok(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const hardBreakEscape = {\n  name: 'hardBreakEscape',\n  tokenize: tokenizeHardBreakEscape\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHardBreakEscape(effects, ok, nok) {\n  return start;\n\n  /**\n   * Start of a hard break (escape).\n   *\n   * ```markdown\n   * > | a\\\n   *      ^\n   *   | b\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"hardBreakEscape\");\n    effects.consume(code);\n    return after;\n  }\n\n  /**\n   * After `\\`, at eol.\n   *\n   * ```markdown\n   * > | a\\\n   *       ^\n   *   | b\n   * ```\n   *\n   *  @type {State}\n   */\n  function after(code) {\n    if (markdownLineEnding(code)) {\n      effects.exit(\"hardBreakEscape\");\n      return ok(code);\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\nimport { splice } from 'micromark-util-chunked';\n/** @type {Construct} */\nexport const headingAtx = {\n  name: 'headingAtx',\n  resolve: resolveHeadingAtx,\n  tokenize: tokenizeHeadingAtx\n};\n\n/** @type {Resolver} */\nfunction resolveHeadingAtx(events, context) {\n  let contentEnd = events.length - 2;\n  let contentStart = 3;\n  /** @type {Token} */\n  let content;\n  /** @type {Token} */\n  let text;\n\n  // Prefix whitespace, part of the opening.\n  if (events[contentStart][1].type === \"whitespace\") {\n    contentStart += 2;\n  }\n\n  // Suffix whitespace, part of the closing.\n  if (contentEnd - 2 > contentStart && events[contentEnd][1].type === \"whitespace\") {\n    contentEnd -= 2;\n  }\n  if (events[contentEnd][1].type === \"atxHeadingSequence\" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === \"whitespace\")) {\n    contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;\n  }\n  if (contentEnd > contentStart) {\n    content = {\n      type: \"atxHeadingText\",\n      start: events[contentStart][1].start,\n      end: events[contentEnd][1].end\n    };\n    text = {\n      type: \"chunkText\",\n      start: events[contentStart][1].start,\n      end: events[contentEnd][1].end,\n      contentType: \"text\"\n    };\n    splice(events, contentStart, contentEnd - contentStart + 1, [['enter', content, context], ['enter', text, context], ['exit', text, context], ['exit', content, context]]);\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHeadingAtx(effects, ok, nok) {\n  let size = 0;\n  return start;\n\n  /**\n   * Start of a heading (atx).\n   *\n   * ```markdown\n   * > | ## aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: parse indent like `markdown-rs`.\n    effects.enter(\"atxHeading\");\n    return before(code);\n  }\n\n  /**\n   * After optional whitespace, at `#`.\n   *\n   * ```markdown\n   * > | ## aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    effects.enter(\"atxHeadingSequence\");\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening sequence.\n   *\n   * ```markdown\n   * > | ## aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === 35 && size++ < 6) {\n      effects.consume(code);\n      return sequenceOpen;\n    }\n\n    // Always at least one `#`.\n    if (code === null || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"atxHeadingSequence\");\n      return atBreak(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * After something, before something else.\n   *\n   * ```markdown\n   * > | ## aa\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === 35) {\n      effects.enter(\"atxHeadingSequence\");\n      return sequenceFurther(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"atxHeading\");\n      // To do: interrupt like `markdown-rs`.\n      // // Feel free to interrupt.\n      // tokenizer.interrupt = false\n      return ok(code);\n    }\n    if (markdownSpace(code)) {\n      return factorySpace(effects, atBreak, \"whitespace\")(code);\n    }\n\n    // To do: generate `data` tokens, add the `text` token later.\n    // Needs edit map, see: `markdown.rs`.\n    effects.enter(\"atxHeadingText\");\n    return data(code);\n  }\n\n  /**\n   * In further sequence (after whitespace).\n   *\n   * Could be normal “visible” hashes in the heading or a final sequence.\n   *\n   * ```markdown\n   * > | ## aa ##\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceFurther(code) {\n    if (code === 35) {\n      effects.consume(code);\n      return sequenceFurther;\n    }\n    effects.exit(\"atxHeadingSequence\");\n    return atBreak(code);\n  }\n\n  /**\n   * In text.\n   *\n   * ```markdown\n   * > | ## aa\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function data(code) {\n    if (code === null || code === 35 || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"atxHeadingText\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    return data;\n  }\n}","/**\n * List of lowercase HTML “block” tag names.\n *\n * The list, when parsing HTML (flow), results in more relaxed rules (condition\n * 6).\n * Because they are known blocks, the HTML-like syntax doesn’t have to be\n * strictly parsed.\n * For tag names not in this list, a more strict algorithm (condition 7) is used\n * to detect whether the HTML-like syntax is seen as HTML (flow) or not.\n *\n * This is copied from:\n * <https://spec.commonmark.org/0.30/#html-blocks>.\n *\n * > 👉 **Note**: `search` was added in `CommonMark@0.31`.\n */\nexport const htmlBlockNames = [\n  'address',\n  'article',\n  'aside',\n  'base',\n  'basefont',\n  'blockquote',\n  'body',\n  'caption',\n  'center',\n  'col',\n  'colgroup',\n  'dd',\n  'details',\n  'dialog',\n  'dir',\n  'div',\n  'dl',\n  'dt',\n  'fieldset',\n  'figcaption',\n  'figure',\n  'footer',\n  'form',\n  'frame',\n  'frameset',\n  'h1',\n  'h2',\n  'h3',\n  'h4',\n  'h5',\n  'h6',\n  'head',\n  'header',\n  'hr',\n  'html',\n  'iframe',\n  'legend',\n  'li',\n  'link',\n  'main',\n  'menu',\n  'menuitem',\n  'nav',\n  'noframes',\n  'ol',\n  'optgroup',\n  'option',\n  'p',\n  'param',\n  'search',\n  'section',\n  'summary',\n  'table',\n  'tbody',\n  'td',\n  'tfoot',\n  'th',\n  'thead',\n  'title',\n  'tr',\n  'track',\n  'ul'\n]\n\n/**\n * List of lowercase HTML “raw” tag names.\n *\n * The list, when parsing HTML (flow), results in HTML that can include lines\n * without exiting, until a closing tag also in this list is found (condition\n * 1).\n *\n * This module is copied from:\n * <https://spec.commonmark.org/0.30/#html-blocks>.\n *\n * > 👉 **Note**: `textarea` was added in `CommonMark@0.30`.\n */\nexport const htmlRawNames = ['pre', 'script', 'style', 'textarea']\n","/**\n * @import {\n *   Code,\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { asciiAlphanumeric, asciiAlpha, markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\nimport { htmlBlockNames, htmlRawNames } from 'micromark-util-html-tag-name';\nimport { blankLine } from './blank-line.js';\n\n/** @type {Construct} */\nexport const htmlFlow = {\n  concrete: true,\n  name: 'htmlFlow',\n  resolveTo: resolveToHtmlFlow,\n  tokenize: tokenizeHtmlFlow\n};\n\n/** @type {Construct} */\nconst blankLineBefore = {\n  partial: true,\n  tokenize: tokenizeBlankLineBefore\n};\nconst nonLazyContinuationStart = {\n  partial: true,\n  tokenize: tokenizeNonLazyContinuationStart\n};\n\n/** @type {Resolver} */\nfunction resolveToHtmlFlow(events) {\n  let index = events.length;\n  while (index--) {\n    if (events[index][0] === 'enter' && events[index][1].type === \"htmlFlow\") {\n      break;\n    }\n  }\n  if (index > 1 && events[index - 2][1].type === \"linePrefix\") {\n    // Add the prefix start to the HTML token.\n    events[index][1].start = events[index - 2][1].start;\n    // Add the prefix start to the HTML line token.\n    events[index + 1][1].start = events[index - 2][1].start;\n    // Remove the line prefix.\n    events.splice(index - 2, 2);\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHtmlFlow(effects, ok, nok) {\n  const self = this;\n  /** @type {number} */\n  let marker;\n  /** @type {boolean} */\n  let closingTag;\n  /** @type {string} */\n  let buffer;\n  /** @type {number} */\n  let index;\n  /** @type {Code} */\n  let markerB;\n  return start;\n\n  /**\n   * Start of HTML (flow).\n   *\n   * ```markdown\n   * > | <x />\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: parse indent like `markdown-rs`.\n    return before(code);\n  }\n\n  /**\n   * At `<`, after optional whitespace.\n   *\n   * ```markdown\n   * > | <x />\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    effects.enter(\"htmlFlow\");\n    effects.enter(\"htmlFlowData\");\n    effects.consume(code);\n    return open;\n  }\n\n  /**\n   * After `<`, at tag name or other stuff.\n   *\n   * ```markdown\n   * > | <x />\n   *      ^\n   * > | <!doctype>\n   *      ^\n   * > | <!--xxx-->\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 33) {\n      effects.consume(code);\n      return declarationOpen;\n    }\n    if (code === 47) {\n      effects.consume(code);\n      closingTag = true;\n      return tagCloseStart;\n    }\n    if (code === 63) {\n      effects.consume(code);\n      marker = 3;\n      // To do:\n      // tokenizer.concrete = true\n      // To do: use `markdown-rs` style interrupt.\n      // While we’re in an instruction instead of a declaration, we’re on a `?`\n      // right now, so we do need to search for `>`, similar to declarations.\n      return self.interrupt ? ok : continuationDeclarationInside;\n    }\n\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      // Always the case.\n      effects.consume(code);\n      buffer = String.fromCharCode(code);\n      return tagName;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<!`, at declaration, comment, or CDATA.\n   *\n   * ```markdown\n   * > | <!doctype>\n   *       ^\n   * > | <!--xxx-->\n   *       ^\n   * > | <![CDATA[>&<]]>\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function declarationOpen(code) {\n    if (code === 45) {\n      effects.consume(code);\n      marker = 2;\n      return commentOpenInside;\n    }\n    if (code === 91) {\n      effects.consume(code);\n      marker = 5;\n      index = 0;\n      return cdataOpenInside;\n    }\n\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      marker = 4;\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return self.interrupt ? ok : continuationDeclarationInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<!-`, inside a comment, at another `-`.\n   *\n   * ```markdown\n   * > | <!--xxx-->\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentOpenInside(code) {\n    if (code === 45) {\n      effects.consume(code);\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return self.interrupt ? ok : continuationDeclarationInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<![`, inside CDATA, expecting `CDATA[`.\n   *\n   * ```markdown\n   * > | <![CDATA[>&<]]>\n   *        ^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataOpenInside(code) {\n    const value = \"CDATA[\";\n    if (code === value.charCodeAt(index++)) {\n      effects.consume(code);\n      if (index === value.length) {\n        // // Do not form containers.\n        // tokenizer.concrete = true\n        return self.interrupt ? ok : continuation;\n      }\n      return cdataOpenInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `</`, in closing tag, at tag name.\n   *\n   * ```markdown\n   * > | </x>\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagCloseStart(code) {\n    if (asciiAlpha(code)) {\n      // Always the case.\n      effects.consume(code);\n      buffer = String.fromCharCode(code);\n      return tagName;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In tag name.\n   *\n   * ```markdown\n   * > | <ab>\n   *      ^^\n   * > | </ab>\n   *       ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagName(code) {\n    if (code === null || code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      const slash = code === 47;\n      const name = buffer.toLowerCase();\n      if (!slash && !closingTag && htmlRawNames.includes(name)) {\n        marker = 1;\n        // // Do not form containers.\n        // tokenizer.concrete = true\n        return self.interrupt ? ok(code) : continuation(code);\n      }\n      if (htmlBlockNames.includes(buffer.toLowerCase())) {\n        marker = 6;\n        if (slash) {\n          effects.consume(code);\n          return basicSelfClosing;\n        }\n\n        // // Do not form containers.\n        // tokenizer.concrete = true\n        return self.interrupt ? ok(code) : continuation(code);\n      }\n      marker = 7;\n      // Do not support complete HTML when interrupting.\n      return self.interrupt && !self.parser.lazy[self.now().line] ? nok(code) : closingTag ? completeClosingTagAfter(code) : completeAttributeNameBefore(code);\n    }\n\n    // ASCII alphanumerical and `-`.\n    if (code === 45 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      buffer += String.fromCharCode(code);\n      return tagName;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After closing slash of a basic tag name.\n   *\n   * ```markdown\n   * > | <div/>\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function basicSelfClosing(code) {\n    if (code === 62) {\n      effects.consume(code);\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return self.interrupt ? ok : continuation;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After closing slash of a complete tag name.\n   *\n   * ```markdown\n   * > | <x/>\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeClosingTagAfter(code) {\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeClosingTagAfter;\n    }\n    return completeEnd(code);\n  }\n\n  /**\n   * At an attribute name.\n   *\n   * At first, this state is used after a complete tag name, after whitespace,\n   * where it expects optional attributes or the end of the tag.\n   * It is also reused after attributes, when expecting more optional\n   * attributes.\n   *\n   * ```markdown\n   * > | <a />\n   *        ^\n   * > | <a :b>\n   *        ^\n   * > | <a _b>\n   *        ^\n   * > | <a b>\n   *        ^\n   * > | <a >\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeNameBefore(code) {\n    if (code === 47) {\n      effects.consume(code);\n      return completeEnd;\n    }\n\n    // ASCII alphanumerical and `:` and `_`.\n    if (code === 58 || code === 95 || asciiAlpha(code)) {\n      effects.consume(code);\n      return completeAttributeName;\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAttributeNameBefore;\n    }\n    return completeEnd(code);\n  }\n\n  /**\n   * In attribute name.\n   *\n   * ```markdown\n   * > | <a :b>\n   *         ^\n   * > | <a _b>\n   *         ^\n   * > | <a b>\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeName(code) {\n    // ASCII alphanumerical and `-`, `.`, `:`, and `_`.\n    if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return completeAttributeName;\n    }\n    return completeAttributeNameAfter(code);\n  }\n\n  /**\n   * After attribute name, at an optional initializer, the end of the tag, or\n   * whitespace.\n   *\n   * ```markdown\n   * > | <a b>\n   *         ^\n   * > | <a b=c>\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeNameAfter(code) {\n    if (code === 61) {\n      effects.consume(code);\n      return completeAttributeValueBefore;\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAttributeNameAfter;\n    }\n    return completeAttributeNameBefore(code);\n  }\n\n  /**\n   * Before unquoted, double quoted, or single quoted attribute value, allowing\n   * whitespace.\n   *\n   * ```markdown\n   * > | <a b=c>\n   *          ^\n   * > | <a b=\"c\">\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueBefore(code) {\n    if (code === null || code === 60 || code === 61 || code === 62 || code === 96) {\n      return nok(code);\n    }\n    if (code === 34 || code === 39) {\n      effects.consume(code);\n      markerB = code;\n      return completeAttributeValueQuoted;\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAttributeValueBefore;\n    }\n    return completeAttributeValueUnquoted(code);\n  }\n\n  /**\n   * In double or single quoted attribute value.\n   *\n   * ```markdown\n   * > | <a b=\"c\">\n   *           ^\n   * > | <a b='c'>\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueQuoted(code) {\n    if (code === markerB) {\n      effects.consume(code);\n      markerB = null;\n      return completeAttributeValueQuotedAfter;\n    }\n    if (code === null || markdownLineEnding(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return completeAttributeValueQuoted;\n  }\n\n  /**\n   * In unquoted attribute value.\n   *\n   * ```markdown\n   * > | <a b=c>\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueUnquoted(code) {\n    if (code === null || code === 34 || code === 39 || code === 47 || code === 60 || code === 61 || code === 62 || code === 96 || markdownLineEndingOrSpace(code)) {\n      return completeAttributeNameAfter(code);\n    }\n    effects.consume(code);\n    return completeAttributeValueUnquoted;\n  }\n\n  /**\n   * After double or single quoted attribute value, before whitespace or the\n   * end of the tag.\n   *\n   * ```markdown\n   * > | <a b=\"c\">\n   *            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueQuotedAfter(code) {\n    if (code === 47 || code === 62 || markdownSpace(code)) {\n      return completeAttributeNameBefore(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In certain circumstances of a complete tag where only an `>` is allowed.\n   *\n   * ```markdown\n   * > | <a b=\"c\">\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeEnd(code) {\n    if (code === 62) {\n      effects.consume(code);\n      return completeAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `>` in a complete tag.\n   *\n   * ```markdown\n   * > | <x>\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAfter(code) {\n    if (code === null || markdownLineEnding(code)) {\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return continuation(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In continuation of any HTML kind.\n   *\n   * ```markdown\n   * > | <!--xxx-->\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuation(code) {\n    if (code === 45 && marker === 2) {\n      effects.consume(code);\n      return continuationCommentInside;\n    }\n    if (code === 60 && marker === 1) {\n      effects.consume(code);\n      return continuationRawTagOpen;\n    }\n    if (code === 62 && marker === 4) {\n      effects.consume(code);\n      return continuationClose;\n    }\n    if (code === 63 && marker === 3) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    if (code === 93 && marker === 5) {\n      effects.consume(code);\n      return continuationCdataInside;\n    }\n    if (markdownLineEnding(code) && (marker === 6 || marker === 7)) {\n      effects.exit(\"htmlFlowData\");\n      return effects.check(blankLineBefore, continuationAfter, continuationStart)(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"htmlFlowData\");\n      return continuationStart(code);\n    }\n    effects.consume(code);\n    return continuation;\n  }\n\n  /**\n   * In continuation, at eol.\n   *\n   * ```markdown\n   * > | <x>\n   *        ^\n   *   | asd\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationStart(code) {\n    return effects.check(nonLazyContinuationStart, continuationStartNonLazy, continuationAfter)(code);\n  }\n\n  /**\n   * In continuation, at eol, before non-lazy content.\n   *\n   * ```markdown\n   * > | <x>\n   *        ^\n   *   | asd\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationStartNonLazy(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return continuationBefore;\n  }\n\n  /**\n   * In continuation, before non-lazy content.\n   *\n   * ```markdown\n   *   | <x>\n   * > | asd\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return continuationStart(code);\n    }\n    effects.enter(\"htmlFlowData\");\n    return continuation(code);\n  }\n\n  /**\n   * In comment continuation, after one `-`, expecting another.\n   *\n   * ```markdown\n   * > | <!--xxx-->\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationCommentInside(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In raw continuation, after `<`, at `/`.\n   *\n   * ```markdown\n   * > | <script>console.log(1)</script>\n   *                            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationRawTagOpen(code) {\n    if (code === 47) {\n      effects.consume(code);\n      buffer = '';\n      return continuationRawEndTag;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In raw continuation, after `</`, in a raw tag name.\n   *\n   * ```markdown\n   * > | <script>console.log(1)</script>\n   *                             ^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationRawEndTag(code) {\n    if (code === 62) {\n      const name = buffer.toLowerCase();\n      if (htmlRawNames.includes(name)) {\n        effects.consume(code);\n        return continuationClose;\n      }\n      return continuation(code);\n    }\n    if (asciiAlpha(code) && buffer.length < 8) {\n      // Always the case.\n      effects.consume(code);\n      buffer += String.fromCharCode(code);\n      return continuationRawEndTag;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In cdata continuation, after `]`, expecting `]>`.\n   *\n   * ```markdown\n   * > | <![CDATA[>&<]]>\n   *                  ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationCdataInside(code) {\n    if (code === 93) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In declaration or instruction continuation, at `>`.\n   *\n   * ```markdown\n   * > | <!-->\n   *         ^\n   * > | <?>\n   *       ^\n   * > | <!q>\n   *        ^\n   * > | <!--ab-->\n   *             ^\n   * > | <![CDATA[>&<]]>\n   *                   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationDeclarationInside(code) {\n    if (code === 62) {\n      effects.consume(code);\n      return continuationClose;\n    }\n\n    // More dashes.\n    if (code === 45 && marker === 2) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In closed continuation: everything we get until the eol/eof is part of it.\n   *\n   * ```markdown\n   * > | <!doctype>\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationClose(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"htmlFlowData\");\n      return continuationAfter(code);\n    }\n    effects.consume(code);\n    return continuationClose;\n  }\n\n  /**\n   * Done.\n   *\n   * ```markdown\n   * > | <!doctype>\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationAfter(code) {\n    effects.exit(\"htmlFlow\");\n    // // Feel free to interrupt.\n    // tokenizer.interrupt = false\n    // // No longer concrete.\n    // tokenizer.concrete = false\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeNonLazyContinuationStart(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * At eol, before continuation.\n   *\n   * ```markdown\n   * > | * ```js\n   *            ^\n   *   | b\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * A continuation.\n   *\n   * ```markdown\n   *   | * ```js\n   * > | b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    return self.parser.lazy[self.now().line] ? nok(code) : ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlankLineBefore(effects, ok, nok) {\n  return start;\n\n  /**\n   * Before eol, expecting blank line.\n   *\n   * ```markdown\n   * > | <div>\n   *          ^\n   *   |\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return effects.attempt(blankLine, ok, nok);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { asciiAlphanumeric, asciiAlpha, markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const htmlText = {\n  name: 'htmlText',\n  tokenize: tokenizeHtmlText\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHtmlText(effects, ok, nok) {\n  const self = this;\n  /** @type {NonNullable<Code> | undefined} */\n  let marker;\n  /** @type {number} */\n  let index;\n  /** @type {State} */\n  let returnState;\n  return start;\n\n  /**\n   * Start of HTML (text).\n   *\n   * ```markdown\n   * > | a <b> c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"htmlText\");\n    effects.enter(\"htmlTextData\");\n    effects.consume(code);\n    return open;\n  }\n\n  /**\n   * After `<`, at tag name or other stuff.\n   *\n   * ```markdown\n   * > | a <b> c\n   *        ^\n   * > | a <!doctype> c\n   *        ^\n   * > | a <!--b--> c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 33) {\n      effects.consume(code);\n      return declarationOpen;\n    }\n    if (code === 47) {\n      effects.consume(code);\n      return tagCloseStart;\n    }\n    if (code === 63) {\n      effects.consume(code);\n      return instruction;\n    }\n\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return tagOpen;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<!`, at declaration, comment, or CDATA.\n   *\n   * ```markdown\n   * > | a <!doctype> c\n   *         ^\n   * > | a <!--b--> c\n   *         ^\n   * > | a <![CDATA[>&<]]> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function declarationOpen(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return commentOpenInside;\n    }\n    if (code === 91) {\n      effects.consume(code);\n      index = 0;\n      return cdataOpenInside;\n    }\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return declaration;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In a comment, after `<!-`, at another `-`.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentOpenInside(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return commentEnd;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In comment.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function comment(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    if (code === 45) {\n      effects.consume(code);\n      return commentClose;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = comment;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return comment;\n  }\n\n  /**\n   * In comment, after `-`.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentClose(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return commentEnd;\n    }\n    return comment(code);\n  }\n\n  /**\n   * In comment, after `--`.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentEnd(code) {\n    return code === 62 ? end(code) : code === 45 ? commentClose(code) : comment(code);\n  }\n\n  /**\n   * After `<![`, in CDATA, expecting `CDATA[`.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *          ^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataOpenInside(code) {\n    const value = \"CDATA[\";\n    if (code === value.charCodeAt(index++)) {\n      effects.consume(code);\n      return index === value.length ? cdata : cdataOpenInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In CDATA.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *                ^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdata(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.consume(code);\n      return cdataClose;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = cdata;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return cdata;\n  }\n\n  /**\n   * In CDATA, after `]`, at another `]`.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *                    ^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataClose(code) {\n    if (code === 93) {\n      effects.consume(code);\n      return cdataEnd;\n    }\n    return cdata(code);\n  }\n\n  /**\n   * In CDATA, after `]]`, at `>`.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *                     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataEnd(code) {\n    if (code === 62) {\n      return end(code);\n    }\n    if (code === 93) {\n      effects.consume(code);\n      return cdataEnd;\n    }\n    return cdata(code);\n  }\n\n  /**\n   * In declaration.\n   *\n   * ```markdown\n   * > | a <!b> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function declaration(code) {\n    if (code === null || code === 62) {\n      return end(code);\n    }\n    if (markdownLineEnding(code)) {\n      returnState = declaration;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return declaration;\n  }\n\n  /**\n   * In instruction.\n   *\n   * ```markdown\n   * > | a <?b?> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function instruction(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    if (code === 63) {\n      effects.consume(code);\n      return instructionClose;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = instruction;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return instruction;\n  }\n\n  /**\n   * In instruction, after `?`, at `>`.\n   *\n   * ```markdown\n   * > | a <?b?> c\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function instructionClose(code) {\n    return code === 62 ? end(code) : instruction(code);\n  }\n\n  /**\n   * After `</`, in closing tag, at tag name.\n   *\n   * ```markdown\n   * > | a </b> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagCloseStart(code) {\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return tagClose;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `</x`, in a tag name.\n   *\n   * ```markdown\n   * > | a </b> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagClose(code) {\n    // ASCII alphanumerical and `-`.\n    if (code === 45 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return tagClose;\n    }\n    return tagCloseBetween(code);\n  }\n\n  /**\n   * In closing tag, after tag name.\n   *\n   * ```markdown\n   * > | a </b> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagCloseBetween(code) {\n    if (markdownLineEnding(code)) {\n      returnState = tagCloseBetween;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagCloseBetween;\n    }\n    return end(code);\n  }\n\n  /**\n   * After `<x`, in opening tag name.\n   *\n   * ```markdown\n   * > | a <b> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpen(code) {\n    // ASCII alphanumerical and `-`.\n    if (code === 45 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return tagOpen;\n    }\n    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      return tagOpenBetween(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In opening tag, after tag name.\n   *\n   * ```markdown\n   * > | a <b> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenBetween(code) {\n    if (code === 47) {\n      effects.consume(code);\n      return end;\n    }\n\n    // ASCII alphabetical and `:` and `_`.\n    if (code === 58 || code === 95 || asciiAlpha(code)) {\n      effects.consume(code);\n      return tagOpenAttributeName;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenBetween;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagOpenBetween;\n    }\n    return end(code);\n  }\n\n  /**\n   * In attribute name.\n   *\n   * ```markdown\n   * > | a <b c> d\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeName(code) {\n    // ASCII alphabetical and `-`, `.`, `:`, and `_`.\n    if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return tagOpenAttributeName;\n    }\n    return tagOpenAttributeNameAfter(code);\n  }\n\n  /**\n   * After attribute name, before initializer, the end of the tag, or\n   * whitespace.\n   *\n   * ```markdown\n   * > | a <b c> d\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeNameAfter(code) {\n    if (code === 61) {\n      effects.consume(code);\n      return tagOpenAttributeValueBefore;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenAttributeNameAfter;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagOpenAttributeNameAfter;\n    }\n    return tagOpenBetween(code);\n  }\n\n  /**\n   * Before unquoted, double quoted, or single quoted attribute value, allowing\n   * whitespace.\n   *\n   * ```markdown\n   * > | a <b c=d> e\n   *            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueBefore(code) {\n    if (code === null || code === 60 || code === 61 || code === 62 || code === 96) {\n      return nok(code);\n    }\n    if (code === 34 || code === 39) {\n      effects.consume(code);\n      marker = code;\n      return tagOpenAttributeValueQuoted;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenAttributeValueBefore;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagOpenAttributeValueBefore;\n    }\n    effects.consume(code);\n    return tagOpenAttributeValueUnquoted;\n  }\n\n  /**\n   * In double or single quoted attribute value.\n   *\n   * ```markdown\n   * > | a <b c=\"d\"> e\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueQuoted(code) {\n    if (code === marker) {\n      effects.consume(code);\n      marker = undefined;\n      return tagOpenAttributeValueQuotedAfter;\n    }\n    if (code === null) {\n      return nok(code);\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenAttributeValueQuoted;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return tagOpenAttributeValueQuoted;\n  }\n\n  /**\n   * In unquoted attribute value.\n   *\n   * ```markdown\n   * > | a <b c=d> e\n   *            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueUnquoted(code) {\n    if (code === null || code === 34 || code === 39 || code === 60 || code === 61 || code === 96) {\n      return nok(code);\n    }\n    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      return tagOpenBetween(code);\n    }\n    effects.consume(code);\n    return tagOpenAttributeValueUnquoted;\n  }\n\n  /**\n   * After double or single quoted attribute value, before whitespace or the end\n   * of the tag.\n   *\n   * ```markdown\n   * > | a <b c=\"d\"> e\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueQuotedAfter(code) {\n    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      return tagOpenBetween(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In certain circumstances of a tag where only an `>` is allowed.\n   *\n   * ```markdown\n   * > | a <b c=\"d\"> e\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function end(code) {\n    if (code === 62) {\n      effects.consume(code);\n      effects.exit(\"htmlTextData\");\n      effects.exit(\"htmlText\");\n      return ok;\n    }\n    return nok(code);\n  }\n\n  /**\n   * At eol.\n   *\n   * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about\n   * > empty tokens.\n   *\n   * ```markdown\n   * > | a <!--a\n   *            ^\n   *   | b-->\n   * ```\n   *\n   * @type {State}\n   */\n  function lineEndingBefore(code) {\n    effects.exit(\"htmlTextData\");\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return lineEndingAfter;\n  }\n\n  /**\n   * After eol, at optional whitespace.\n   *\n   * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about\n   * > empty tokens.\n   *\n   * ```markdown\n   *   | a <!--a\n   * > | b-->\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function lineEndingAfter(code) {\n    // Always populated by defaults.\n\n    return markdownSpace(code) ? factorySpace(effects, lineEndingAfterPrefix, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code) : lineEndingAfterPrefix(code);\n  }\n\n  /**\n   * After eol, after optional whitespace.\n   *\n   * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about\n   * > empty tokens.\n   *\n   * ```markdown\n   *   | a <!--a\n   * > | b-->\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function lineEndingAfterPrefix(code) {\n    effects.enter(\"htmlTextData\");\n    return returnState(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Event,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factoryDestination } from 'micromark-factory-destination';\nimport { factoryLabel } from 'micromark-factory-label';\nimport { factoryTitle } from 'micromark-factory-title';\nimport { factoryWhitespace } from 'micromark-factory-whitespace';\nimport { markdownLineEndingOrSpace } from 'micromark-util-character';\nimport { push, splice } from 'micromark-util-chunked';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/** @type {Construct} */\nexport const labelEnd = {\n  name: 'labelEnd',\n  resolveAll: resolveAllLabelEnd,\n  resolveTo: resolveToLabelEnd,\n  tokenize: tokenizeLabelEnd\n};\n\n/** @type {Construct} */\nconst resourceConstruct = {\n  tokenize: tokenizeResource\n};\n/** @type {Construct} */\nconst referenceFullConstruct = {\n  tokenize: tokenizeReferenceFull\n};\n/** @type {Construct} */\nconst referenceCollapsedConstruct = {\n  tokenize: tokenizeReferenceCollapsed\n};\n\n/** @type {Resolver} */\nfunction resolveAllLabelEnd(events) {\n  let index = -1;\n  /** @type {Array<Event>} */\n  const newEvents = [];\n  while (++index < events.length) {\n    const token = events[index][1];\n    newEvents.push(events[index]);\n    if (token.type === \"labelImage\" || token.type === \"labelLink\" || token.type === \"labelEnd\") {\n      // Remove the marker.\n      const offset = token.type === \"labelImage\" ? 4 : 2;\n      token.type = \"data\";\n      index += offset;\n    }\n  }\n\n  // If the events are equal, we don't have to copy newEvents to events\n  if (events.length !== newEvents.length) {\n    splice(events, 0, events.length, newEvents);\n  }\n  return events;\n}\n\n/** @type {Resolver} */\nfunction resolveToLabelEnd(events, context) {\n  let index = events.length;\n  let offset = 0;\n  /** @type {Token} */\n  let token;\n  /** @type {number | undefined} */\n  let open;\n  /** @type {number | undefined} */\n  let close;\n  /** @type {Array<Event>} */\n  let media;\n\n  // Find an opening.\n  while (index--) {\n    token = events[index][1];\n    if (open) {\n      // If we see another link, or inactive link label, we’ve been here before.\n      if (token.type === \"link\" || token.type === \"labelLink\" && token._inactive) {\n        break;\n      }\n\n      // Mark other link openings as inactive, as we can’t have links in\n      // links.\n      if (events[index][0] === 'enter' && token.type === \"labelLink\") {\n        token._inactive = true;\n      }\n    } else if (close) {\n      if (events[index][0] === 'enter' && (token.type === \"labelImage\" || token.type === \"labelLink\") && !token._balanced) {\n        open = index;\n        if (token.type !== \"labelLink\") {\n          offset = 2;\n          break;\n        }\n      }\n    } else if (token.type === \"labelEnd\") {\n      close = index;\n    }\n  }\n  const group = {\n    type: events[open][1].type === \"labelLink\" ? \"link\" : \"image\",\n    start: {\n      ...events[open][1].start\n    },\n    end: {\n      ...events[events.length - 1][1].end\n    }\n  };\n  const label = {\n    type: \"label\",\n    start: {\n      ...events[open][1].start\n    },\n    end: {\n      ...events[close][1].end\n    }\n  };\n  const text = {\n    type: \"labelText\",\n    start: {\n      ...events[open + offset + 2][1].end\n    },\n    end: {\n      ...events[close - 2][1].start\n    }\n  };\n  media = [['enter', group, context], ['enter', label, context]];\n\n  // Opening marker.\n  media = push(media, events.slice(open + 1, open + offset + 3));\n\n  // Text open.\n  media = push(media, [['enter', text, context]]);\n\n  // Always populated by defaults.\n\n  // Between.\n  media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context));\n\n  // Text close, marker close, label close.\n  media = push(media, [['exit', text, context], events[close - 2], events[close - 1], ['exit', label, context]]);\n\n  // Reference, resource, or so.\n  media = push(media, events.slice(close + 1));\n\n  // Media close.\n  media = push(media, [['exit', group, context]]);\n  splice(events, open, events.length, media);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLabelEnd(effects, ok, nok) {\n  const self = this;\n  let index = self.events.length;\n  /** @type {Token} */\n  let labelStart;\n  /** @type {boolean} */\n  let defined;\n\n  // Find an opening.\n  while (index--) {\n    if ((self.events[index][1].type === \"labelImage\" || self.events[index][1].type === \"labelLink\") && !self.events[index][1]._balanced) {\n      labelStart = self.events[index][1];\n      break;\n    }\n  }\n  return start;\n\n  /**\n   * Start of label end.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *       ^\n   * > | [a][b] c\n   *       ^\n   * > | [a][] b\n   *       ^\n   * > | [a] b\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // If there is not an okay opening.\n    if (!labelStart) {\n      return nok(code);\n    }\n\n    // If the corresponding label (link) start is marked as inactive,\n    // it means we’d be wrapping a link, like this:\n    //\n    // ```markdown\n    // > | a [b [c](d) e](f) g.\n    //                  ^\n    // ```\n    //\n    // We can’t have that, so it’s just balanced brackets.\n    if (labelStart._inactive) {\n      return labelEndNok(code);\n    }\n    defined = self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize({\n      start: labelStart.end,\n      end: self.now()\n    })));\n    effects.enter(\"labelEnd\");\n    effects.enter(\"labelMarker\");\n    effects.consume(code);\n    effects.exit(\"labelMarker\");\n    effects.exit(\"labelEnd\");\n    return after;\n  }\n\n  /**\n   * After `]`.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *       ^\n   * > | [a][b] c\n   *       ^\n   * > | [a][] b\n   *       ^\n   * > | [a] b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // Note: `markdown-rs` also parses GFM footnotes here, which for us is in\n    // an extension.\n\n    // Resource (`[asd](fgh)`)?\n    if (code === 40) {\n      return effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code);\n    }\n\n    // Full (`[asd][fgh]`) or collapsed (`[asd][]`) reference?\n    if (code === 91) {\n      return effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code);\n    }\n\n    // Shortcut (`[asd]`) reference?\n    return defined ? labelEndOk(code) : labelEndNok(code);\n  }\n\n  /**\n   * After `]`, at `[`, but not at a full reference.\n   *\n   * > 👉 **Note**: we only get here if the label is defined.\n   *\n   * ```markdown\n   * > | [a][] b\n   *        ^\n   * > | [a] b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceNotFull(code) {\n    return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code);\n  }\n\n  /**\n   * Done, we found something.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *           ^\n   * > | [a][b] c\n   *           ^\n   * > | [a][] b\n   *          ^\n   * > | [a] b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEndOk(code) {\n    // Note: `markdown-rs` does a bunch of stuff here.\n    return ok(code);\n  }\n\n  /**\n   * Done, it’s nothing.\n   *\n   * There was an okay opening, but we didn’t match anything.\n   *\n   * ```markdown\n   * > | [a](b c\n   *        ^\n   * > | [a][b c\n   *        ^\n   * > | [a] b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEndNok(code) {\n    labelStart._balanced = true;\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeResource(effects, ok, nok) {\n  return resourceStart;\n\n  /**\n   * At a resource.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceStart(code) {\n    effects.enter(\"resource\");\n    effects.enter(\"resourceMarker\");\n    effects.consume(code);\n    effects.exit(\"resourceMarker\");\n    return resourceBefore;\n  }\n\n  /**\n   * In resource, after `(`, at optional whitespace.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceBefore(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceOpen)(code) : resourceOpen(code);\n  }\n\n  /**\n   * In resource, after optional whitespace, at `)` or a destination.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceOpen(code) {\n    if (code === 41) {\n      return resourceEnd(code);\n    }\n    return factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, \"resourceDestination\", \"resourceDestinationLiteral\", \"resourceDestinationLiteralMarker\", \"resourceDestinationRaw\", \"resourceDestinationString\", 32)(code);\n  }\n\n  /**\n   * In resource, after destination, at optional whitespace.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceDestinationAfter(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceBetween)(code) : resourceEnd(code);\n  }\n\n  /**\n   * At invalid destination.\n   *\n   * ```markdown\n   * > | [a](<<) b\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceDestinationMissing(code) {\n    return nok(code);\n  }\n\n  /**\n   * In resource, after destination and whitespace, at `(` or title.\n   *\n   * ```markdown\n   * > | [a](b ) c\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceBetween(code) {\n    if (code === 34 || code === 39 || code === 40) {\n      return factoryTitle(effects, resourceTitleAfter, nok, \"resourceTitle\", \"resourceTitleMarker\", \"resourceTitleString\")(code);\n    }\n    return resourceEnd(code);\n  }\n\n  /**\n   * In resource, after title, at optional whitespace.\n   *\n   * ```markdown\n   * > | [a](b \"c\") d\n   *              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceTitleAfter(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceEnd)(code) : resourceEnd(code);\n  }\n\n  /**\n   * In resource, at `)`.\n   *\n   * ```markdown\n   * > | [a](b) d\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceEnd(code) {\n    if (code === 41) {\n      effects.enter(\"resourceMarker\");\n      effects.consume(code);\n      effects.exit(\"resourceMarker\");\n      effects.exit(\"resource\");\n      return ok;\n    }\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeReferenceFull(effects, ok, nok) {\n  const self = this;\n  return referenceFull;\n\n  /**\n   * In a reference (full), at the `[`.\n   *\n   * ```markdown\n   * > | [a][b] d\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceFull(code) {\n    return factoryLabel.call(self, effects, referenceFullAfter, referenceFullMissing, \"reference\", \"referenceMarker\", \"referenceString\")(code);\n  }\n\n  /**\n   * In a reference (full), after `]`.\n   *\n   * ```markdown\n   * > | [a][b] d\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceFullAfter(code) {\n    return self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1))) ? ok(code) : nok(code);\n  }\n\n  /**\n   * In reference (full) that was missing.\n   *\n   * ```markdown\n   * > | [a][b d\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceFullMissing(code) {\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeReferenceCollapsed(effects, ok, nok) {\n  return referenceCollapsedStart;\n\n  /**\n   * In reference (collapsed), at `[`.\n   *\n   * > 👉 **Note**: we only get here if the label is defined.\n   *\n   * ```markdown\n   * > | [a][] d\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceCollapsedStart(code) {\n    // We only attempt a collapsed label if there’s a `[`.\n\n    effects.enter(\"reference\");\n    effects.enter(\"referenceMarker\");\n    effects.consume(code);\n    effects.exit(\"referenceMarker\");\n    return referenceCollapsedOpen;\n  }\n\n  /**\n   * In reference (collapsed), at `]`.\n   *\n   * > 👉 **Note**: we only get here if the label is defined.\n   *\n   * ```markdown\n   * > | [a][] d\n   *         ^\n   * ```\n   *\n   *  @type {State}\n   */\n  function referenceCollapsedOpen(code) {\n    if (code === 93) {\n      effects.enter(\"referenceMarker\");\n      effects.consume(code);\n      effects.exit(\"referenceMarker\");\n      effects.exit(\"reference\");\n      return ok;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { labelEnd } from './label-end.js';\n\n/** @type {Construct} */\nexport const labelStartImage = {\n  name: 'labelStartImage',\n  resolveAll: labelEnd.resolveAll,\n  tokenize: tokenizeLabelStartImage\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLabelStartImage(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of label (image) start.\n   *\n   * ```markdown\n   * > | a ![b] c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"labelImage\");\n    effects.enter(\"labelImageMarker\");\n    effects.consume(code);\n    effects.exit(\"labelImageMarker\");\n    return open;\n  }\n\n  /**\n   * After `!`, at `[`.\n   *\n   * ```markdown\n   * > | a ![b] c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 91) {\n      effects.enter(\"labelMarker\");\n      effects.consume(code);\n      effects.exit(\"labelMarker\");\n      effects.exit(\"labelImage\");\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `![`.\n   *\n   * ```markdown\n   * > | a ![b] c\n   *         ^\n   * ```\n   *\n   * This is needed in because, when GFM footnotes are enabled, images never\n   * form when started with a `^`.\n   * Instead, links form:\n   *\n   * ```markdown\n   * ![^a](b)\n   *\n   * ![^a][b]\n   *\n   * [b]: c\n   * ```\n   *\n   * ```html\n   * <p>!<a href=\\\"b\\\">^a</a></p>\n   * <p>!<a href=\\\"c\\\">^a</a></p>\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // To do: use a new field to do this, this is still needed for\n    // `micromark-extension-gfm-footnote`, but the `label-start-link`\n    // behavior isn’t.\n    // Hidden footnotes hook.\n    /* c8 ignore next 3 */\n    return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs ? nok(code) : ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { labelEnd } from './label-end.js';\n\n/** @type {Construct} */\nexport const labelStartLink = {\n  name: 'labelStartLink',\n  resolveAll: labelEnd.resolveAll,\n  tokenize: tokenizeLabelStartLink\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLabelStartLink(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of label (link) start.\n   *\n   * ```markdown\n   * > | a [b] c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"labelLink\");\n    effects.enter(\"labelMarker\");\n    effects.consume(code);\n    effects.exit(\"labelMarker\");\n    effects.exit(\"labelLink\");\n    return after;\n  }\n\n  /** @type {State} */\n  function after(code) {\n    // To do: this isn’t needed in `micromark-extension-gfm-footnote`,\n    // remove.\n    // Hidden footnotes hook.\n    /* c8 ignore next 3 */\n    return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs ? nok(code) : ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const lineEnding = {\n  name: 'lineEnding',\n  tokenize: tokenizeLineEnding\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLineEnding(effects, ok) {\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return factorySpace(effects, ok, \"linePrefix\");\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const thematicBreak = {\n  name: 'thematicBreak',\n  tokenize: tokenizeThematicBreak\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeThematicBreak(effects, ok, nok) {\n  let size = 0;\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Start of thematic break.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"thematicBreak\");\n    // To do: parse indent like `markdown-rs`.\n    return before(code);\n  }\n\n  /**\n   * After optional whitespace, at marker.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    marker = code;\n    return atBreak(code);\n  }\n\n  /**\n   * After something, before something else.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === marker) {\n      effects.enter(\"thematicBreakSequence\");\n      return sequence(code);\n    }\n    if (size >= 3 && (code === null || markdownLineEnding(code))) {\n      effects.exit(\"thematicBreak\");\n      return ok(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In sequence.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequence(code) {\n    if (code === marker) {\n      effects.consume(code);\n      size++;\n      return sequence;\n    }\n    effects.exit(\"thematicBreakSequence\");\n    return markdownSpace(code) ? factorySpace(effects, atBreak, \"whitespace\")(code) : atBreak(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   Exiter,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { asciiDigit, markdownSpace } from 'micromark-util-character';\nimport { blankLine } from './blank-line.js';\nimport { thematicBreak } from './thematic-break.js';\n\n/** @type {Construct} */\nexport const list = {\n  continuation: {\n    tokenize: tokenizeListContinuation\n  },\n  exit: tokenizeListEnd,\n  name: 'list',\n  tokenize: tokenizeListStart\n};\n\n/** @type {Construct} */\nconst listItemPrefixWhitespaceConstruct = {\n  partial: true,\n  tokenize: tokenizeListItemPrefixWhitespace\n};\n\n/** @type {Construct} */\nconst indentConstruct = {\n  partial: true,\n  tokenize: tokenizeIndent\n};\n\n// To do: `markdown-rs` parses list items on their own and later stitches them\n// together.\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeListStart(effects, ok, nok) {\n  const self = this;\n  const tail = self.events[self.events.length - 1];\n  let initialSize = tail && tail[1].type === \"linePrefix\" ? tail[2].sliceSerialize(tail[1], true).length : 0;\n  let size = 0;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    const kind = self.containerState.type || (code === 42 || code === 43 || code === 45 ? \"listUnordered\" : \"listOrdered\");\n    if (kind === \"listUnordered\" ? !self.containerState.marker || code === self.containerState.marker : asciiDigit(code)) {\n      if (!self.containerState.type) {\n        self.containerState.type = kind;\n        effects.enter(kind, {\n          _container: true\n        });\n      }\n      if (kind === \"listUnordered\") {\n        effects.enter(\"listItemPrefix\");\n        return code === 42 || code === 45 ? effects.check(thematicBreak, nok, atMarker)(code) : atMarker(code);\n      }\n      if (!self.interrupt || code === 49) {\n        effects.enter(\"listItemPrefix\");\n        effects.enter(\"listItemValue\");\n        return inside(code);\n      }\n    }\n    return nok(code);\n  }\n\n  /** @type {State} */\n  function inside(code) {\n    if (asciiDigit(code) && ++size < 10) {\n      effects.consume(code);\n      return inside;\n    }\n    if ((!self.interrupt || size < 2) && (self.containerState.marker ? code === self.containerState.marker : code === 41 || code === 46)) {\n      effects.exit(\"listItemValue\");\n      return atMarker(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * @type {State}\n   **/\n  function atMarker(code) {\n    effects.enter(\"listItemMarker\");\n    effects.consume(code);\n    effects.exit(\"listItemMarker\");\n    self.containerState.marker = self.containerState.marker || code;\n    return effects.check(blankLine,\n    // Can’t be empty when interrupting.\n    self.interrupt ? nok : onBlank, effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix));\n  }\n\n  /** @type {State} */\n  function onBlank(code) {\n    self.containerState.initialBlankLine = true;\n    initialSize++;\n    return endOfPrefix(code);\n  }\n\n  /** @type {State} */\n  function otherPrefix(code) {\n    if (markdownSpace(code)) {\n      effects.enter(\"listItemPrefixWhitespace\");\n      effects.consume(code);\n      effects.exit(\"listItemPrefixWhitespace\");\n      return endOfPrefix;\n    }\n    return nok(code);\n  }\n\n  /** @type {State} */\n  function endOfPrefix(code) {\n    self.containerState.size = initialSize + self.sliceSerialize(effects.exit(\"listItemPrefix\"), true).length;\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeListContinuation(effects, ok, nok) {\n  const self = this;\n  self.containerState._closeFlow = undefined;\n  return effects.check(blankLine, onBlank, notBlank);\n\n  /** @type {State} */\n  function onBlank(code) {\n    self.containerState.furtherBlankLines = self.containerState.furtherBlankLines || self.containerState.initialBlankLine;\n\n    // We have a blank line.\n    // Still, try to consume at most the items size.\n    return factorySpace(effects, ok, \"listItemIndent\", self.containerState.size + 1)(code);\n  }\n\n  /** @type {State} */\n  function notBlank(code) {\n    if (self.containerState.furtherBlankLines || !markdownSpace(code)) {\n      self.containerState.furtherBlankLines = undefined;\n      self.containerState.initialBlankLine = undefined;\n      return notInCurrentItem(code);\n    }\n    self.containerState.furtherBlankLines = undefined;\n    self.containerState.initialBlankLine = undefined;\n    return effects.attempt(indentConstruct, ok, notInCurrentItem)(code);\n  }\n\n  /** @type {State} */\n  function notInCurrentItem(code) {\n    // While we do continue, we signal that the flow should be closed.\n    self.containerState._closeFlow = true;\n    // As we’re closing flow, we’re no longer interrupting.\n    self.interrupt = undefined;\n    // Always populated by defaults.\n\n    return factorySpace(effects, effects.attempt(list, ok, nok), \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeIndent(effects, ok, nok) {\n  const self = this;\n  return factorySpace(effects, afterPrefix, \"listItemIndent\", self.containerState.size + 1);\n\n  /** @type {State} */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === \"listItemIndent\" && tail[2].sliceSerialize(tail[1], true).length === self.containerState.size ? ok(code) : nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Exiter}\n */\nfunction tokenizeListEnd(effects) {\n  effects.exit(this.containerState.type);\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeListItemPrefixWhitespace(effects, ok, nok) {\n  const self = this;\n\n  // Always populated by defaults.\n\n  return factorySpace(effects, afterPrefix, \"listItemPrefixWhitespace\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4 + 1);\n\n  /** @type {State} */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return !markdownSpace(code) && tail && tail[1].type === \"listItemPrefixWhitespace\" ? ok(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const setextUnderline = {\n  name: 'setextUnderline',\n  resolveTo: resolveToSetextUnderline,\n  tokenize: tokenizeSetextUnderline\n};\n\n/** @type {Resolver} */\nfunction resolveToSetextUnderline(events, context) {\n  // To do: resolve like `markdown-rs`.\n  let index = events.length;\n  /** @type {number | undefined} */\n  let content;\n  /** @type {number | undefined} */\n  let text;\n  /** @type {number | undefined} */\n  let definition;\n\n  // Find the opening of the content.\n  // It’ll always exist: we don’t tokenize if it isn’t there.\n  while (index--) {\n    if (events[index][0] === 'enter') {\n      if (events[index][1].type === \"content\") {\n        content = index;\n        break;\n      }\n      if (events[index][1].type === \"paragraph\") {\n        text = index;\n      }\n    }\n    // Exit\n    else {\n      if (events[index][1].type === \"content\") {\n        // Remove the content end (if needed we’ll add it later)\n        events.splice(index, 1);\n      }\n      if (!definition && events[index][1].type === \"definition\") {\n        definition = index;\n      }\n    }\n  }\n  const heading = {\n    type: \"setextHeading\",\n    start: {\n      ...events[content][1].start\n    },\n    end: {\n      ...events[events.length - 1][1].end\n    }\n  };\n\n  // Change the paragraph to setext heading text.\n  events[text][1].type = \"setextHeadingText\";\n\n  // If we have definitions in the content, we’ll keep on having content,\n  // but we need move it.\n  if (definition) {\n    events.splice(text, 0, ['enter', heading, context]);\n    events.splice(definition + 1, 0, ['exit', events[content][1], context]);\n    events[content][1].end = {\n      ...events[definition][1].end\n    };\n  } else {\n    events[content][1] = heading;\n  }\n\n  // Add the heading exit at the end.\n  events.push(['exit', heading, context]);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeSetextUnderline(effects, ok, nok) {\n  const self = this;\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * At start of heading (setext) underline.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    let index = self.events.length;\n    /** @type {boolean | undefined} */\n    let paragraph;\n    // Find an opening.\n    while (index--) {\n      // Skip enter/exit of line ending, line prefix, and content.\n      // We can now either have a definition or a paragraph.\n      if (self.events[index][1].type !== \"lineEnding\" && self.events[index][1].type !== \"linePrefix\" && self.events[index][1].type !== \"content\") {\n        paragraph = self.events[index][1].type === \"paragraph\";\n        break;\n      }\n    }\n\n    // To do: handle lazy/pierce like `markdown-rs`.\n    // To do: parse indent like `markdown-rs`.\n    if (!self.parser.lazy[self.now().line] && (self.interrupt || paragraph)) {\n      effects.enter(\"setextHeadingLine\");\n      marker = code;\n      return before(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * After optional whitespace, at `-` or `=`.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    effects.enter(\"setextHeadingLineSequence\");\n    return inside(code);\n  }\n\n  /**\n   * In sequence.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === marker) {\n      effects.consume(code);\n      return inside;\n    }\n    effects.exit(\"setextHeadingLineSequence\");\n    return markdownSpace(code) ? factorySpace(effects, after, \"lineSuffix\")(code) : after(code);\n  }\n\n  /**\n   * After sequence, after optional whitespace.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"setextHeadingLine\");\n      return ok(code);\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   InitialConstruct,\n *   Initializer,\n *   State,\n *   TokenizeContext\n * } from 'micromark-util-types'\n */\n\nimport { blankLine, content } from 'micromark-core-commonmark';\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {InitialConstruct} */\nexport const flow = {\n  tokenize: initializeFlow\n};\n\n/**\n * @this {TokenizeContext}\n *   Self.\n * @type {Initializer}\n *   Initializer.\n */\nfunction initializeFlow(effects) {\n  const self = this;\n  const initial = effects.attempt(\n  // Try to parse a blank line.\n  blankLine, atBlankEnding,\n  // Try to parse initial flow (essentially, only code).\n  effects.attempt(this.parser.constructs.flowInitial, afterConstruct, factorySpace(effects, effects.attempt(this.parser.constructs.flow, afterConstruct, effects.attempt(content, afterConstruct)), \"linePrefix\")));\n  return initial;\n\n  /** @type {State} */\n  function atBlankEnding(code) {\n    if (code === null) {\n      effects.consume(code);\n      return;\n    }\n    effects.enter(\"lineEndingBlank\");\n    effects.consume(code);\n    effects.exit(\"lineEndingBlank\");\n    self.currentConstruct = undefined;\n    return initial;\n  }\n\n  /** @type {State} */\n  function afterConstruct(code) {\n    if (code === null) {\n      effects.consume(code);\n      return;\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    self.currentConstruct = undefined;\n    return initial;\n  }\n}","/**\n * @import {\n *   Code,\n *   InitialConstruct,\n *   Initializer,\n *   Resolver,\n *   State,\n *   TokenizeContext\n * } from 'micromark-util-types'\n */\n\nexport const resolver = {\n  resolveAll: createResolver()\n};\nexport const string = initializeFactory('string');\nexport const text = initializeFactory('text');\n\n/**\n * @param {'string' | 'text'} field\n *   Field.\n * @returns {InitialConstruct}\n *   Construct.\n */\nfunction initializeFactory(field) {\n  return {\n    resolveAll: createResolver(field === 'text' ? resolveAllLineSuffixes : undefined),\n    tokenize: initializeText\n  };\n\n  /**\n   * @this {TokenizeContext}\n   *   Context.\n   * @type {Initializer}\n   */\n  function initializeText(effects) {\n    const self = this;\n    const constructs = this.parser.constructs[field];\n    const text = effects.attempt(constructs, start, notText);\n    return start;\n\n    /** @type {State} */\n    function start(code) {\n      return atBreak(code) ? text(code) : notText(code);\n    }\n\n    /** @type {State} */\n    function notText(code) {\n      if (code === null) {\n        effects.consume(code);\n        return;\n      }\n      effects.enter(\"data\");\n      effects.consume(code);\n      return data;\n    }\n\n    /** @type {State} */\n    function data(code) {\n      if (atBreak(code)) {\n        effects.exit(\"data\");\n        return text(code);\n      }\n\n      // Data.\n      effects.consume(code);\n      return data;\n    }\n\n    /**\n     * @param {Code} code\n     *   Code.\n     * @returns {boolean}\n     *   Whether the code is a break.\n     */\n    function atBreak(code) {\n      if (code === null) {\n        return true;\n      }\n      const list = constructs[code];\n      let index = -1;\n      if (list) {\n        // Always populated by defaults.\n\n        while (++index < list.length) {\n          const item = list[index];\n          if (!item.previous || item.previous.call(self, self.previous)) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n  }\n}\n\n/**\n * @param {Resolver | undefined} [extraResolver]\n *   Resolver.\n * @returns {Resolver}\n *   Resolver.\n */\nfunction createResolver(extraResolver) {\n  return resolveAllText;\n\n  /** @type {Resolver} */\n  function resolveAllText(events, context) {\n    let index = -1;\n    /** @type {number | undefined} */\n    let enter;\n\n    // A rather boring computation (to merge adjacent `data` events) which\n    // improves mm performance by 29%.\n    while (++index <= events.length) {\n      if (enter === undefined) {\n        if (events[index] && events[index][1].type === \"data\") {\n          enter = index;\n          index++;\n        }\n      } else if (!events[index] || events[index][1].type !== \"data\") {\n        // Don’t do anything if there is one data token.\n        if (index !== enter + 2) {\n          events[enter][1].end = events[index - 1][1].end;\n          events.splice(enter + 2, index - enter - 2);\n          index = enter + 2;\n        }\n        enter = undefined;\n      }\n    }\n    return extraResolver ? extraResolver(events, context) : events;\n  }\n}\n\n/**\n * A rather ugly set of instructions which again looks at chunks in the input\n * stream.\n * The reason to do this here is that it is *much* faster to parse in reverse.\n * And that we can’t hook into `null` to split the line suffix before an EOF.\n * To do: figure out if we can make this into a clean utility, or even in core.\n * As it will be useful for GFMs literal autolink extension (and maybe even\n * tables?)\n *\n * @type {Resolver}\n */\nfunction resolveAllLineSuffixes(events, context) {\n  let eventIndex = 0; // Skip first.\n\n  while (++eventIndex <= events.length) {\n    if ((eventIndex === events.length || events[eventIndex][1].type === \"lineEnding\") && events[eventIndex - 1][1].type === \"data\") {\n      const data = events[eventIndex - 1][1];\n      const chunks = context.sliceStream(data);\n      let index = chunks.length;\n      let bufferIndex = -1;\n      let size = 0;\n      /** @type {boolean | undefined} */\n      let tabs;\n      while (index--) {\n        const chunk = chunks[index];\n        if (typeof chunk === 'string') {\n          bufferIndex = chunk.length;\n          while (chunk.charCodeAt(bufferIndex - 1) === 32) {\n            size++;\n            bufferIndex--;\n          }\n          if (bufferIndex) break;\n          bufferIndex = -1;\n        }\n        // Number\n        else if (chunk === -2) {\n          tabs = true;\n          size++;\n        } else if (chunk === -1) {\n          // Empty\n        } else {\n          // Replacement character, exit.\n          index++;\n          break;\n        }\n      }\n\n      // Allow final trailing whitespace.\n      if (context._contentTypeTextTrailing && eventIndex === events.length) {\n        size = 0;\n      }\n      if (size) {\n        const token = {\n          type: eventIndex === events.length || tabs || size < 2 ? \"lineSuffix\" : \"hardBreakTrailing\",\n          start: {\n            _bufferIndex: index ? bufferIndex : data.start._bufferIndex + bufferIndex,\n            _index: data.start._index + index,\n            line: data.end.line,\n            column: data.end.column - size,\n            offset: data.end.offset - size\n          },\n          end: {\n            ...data.end\n          }\n        };\n        data.end = {\n          ...token.start\n        };\n        if (data.start.offset === data.end.offset) {\n          Object.assign(data, token);\n        } else {\n          events.splice(eventIndex, 0, ['enter', token, context], ['exit', token, context]);\n          eventIndex += 2;\n        }\n      }\n      eventIndex++;\n    }\n  }\n  return events;\n}","/**\n * @import {Extension} from 'micromark-util-types'\n */\n\nimport { attention, autolink, blockQuote, characterEscape, characterReference, codeFenced, codeIndented, codeText, definition, hardBreakEscape, headingAtx, htmlFlow, htmlText, labelEnd, labelStartImage, labelStartLink, lineEnding, list, setextUnderline, thematicBreak } from 'micromark-core-commonmark';\nimport { resolver as resolveText } from './initialize/text.js';\n\n/** @satisfies {Extension['document']} */\nexport const document = {\n  [42]: list,\n  [43]: list,\n  [45]: list,\n  [48]: list,\n  [49]: list,\n  [50]: list,\n  [51]: list,\n  [52]: list,\n  [53]: list,\n  [54]: list,\n  [55]: list,\n  [56]: list,\n  [57]: list,\n  [62]: blockQuote\n};\n\n/** @satisfies {Extension['contentInitial']} */\nexport const contentInitial = {\n  [91]: definition\n};\n\n/** @satisfies {Extension['flowInitial']} */\nexport const flowInitial = {\n  [-2]: codeIndented,\n  [-1]: codeIndented,\n  [32]: codeIndented\n};\n\n/** @satisfies {Extension['flow']} */\nexport const flow = {\n  [35]: headingAtx,\n  [42]: thematicBreak,\n  [45]: [setextUnderline, thematicBreak],\n  [60]: htmlFlow,\n  [61]: setextUnderline,\n  [95]: thematicBreak,\n  [96]: codeFenced,\n  [126]: codeFenced\n};\n\n/** @satisfies {Extension['string']} */\nexport const string = {\n  [38]: characterReference,\n  [92]: characterEscape\n};\n\n/** @satisfies {Extension['text']} */\nexport const text = {\n  [-5]: lineEnding,\n  [-4]: lineEnding,\n  [-3]: lineEnding,\n  [33]: labelStartImage,\n  [38]: characterReference,\n  [42]: attention,\n  [60]: [autolink, htmlText],\n  [91]: labelStartLink,\n  [92]: [hardBreakEscape, characterEscape],\n  [93]: labelEnd,\n  [95]: attention,\n  [96]: codeText\n};\n\n/** @satisfies {Extension['insideSpan']} */\nexport const insideSpan = {\n  null: [attention, resolveText]\n};\n\n/** @satisfies {Extension['attentionMarkers']} */\nexport const attentionMarkers = {\n  null: [42, 95]\n};\n\n/** @satisfies {Extension['disable']} */\nexport const disable = {\n  null: []\n};","/**\n * @import {\n *   Chunk,\n *   Code,\n *   ConstructRecord,\n *   Construct,\n *   Effects,\n *   InitialConstruct,\n *   ParseContext,\n *   Point,\n *   State,\n *   TokenizeContext,\n *   Token\n * } from 'micromark-util-types'\n */\n\n/**\n * @callback Restore\n *   Restore the state.\n * @returns {undefined}\n *   Nothing.\n *\n * @typedef Info\n *   Info.\n * @property {Restore} restore\n *   Restore.\n * @property {number} from\n *   From.\n *\n * @callback ReturnHandle\n *   Handle a successful run.\n * @param {Construct} construct\n *   Construct.\n * @param {Info} info\n *   Info.\n * @returns {undefined}\n *   Nothing.\n */\n\nimport { markdownLineEnding } from 'micromark-util-character';\nimport { push, splice } from 'micromark-util-chunked';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/**\n * Create a tokenizer.\n * Tokenizers deal with one type of data (e.g., containers, flow, text).\n * The parser is the object dealing with it all.\n * `initialize` works like other constructs, except that only its `tokenize`\n * function is used, in which case it doesn’t receive an `ok` or `nok`.\n * `from` can be given to set the point before the first character, although\n * when further lines are indented, they must be set with `defineSkip`.\n *\n * @param {ParseContext} parser\n *   Parser.\n * @param {InitialConstruct} initialize\n *   Construct.\n * @param {Omit<Point, '_bufferIndex' | '_index'> | undefined} [from]\n *   Point (optional).\n * @returns {TokenizeContext}\n *   Context.\n */\nexport function createTokenizer(parser, initialize, from) {\n  /** @type {Point} */\n  let point = {\n    _bufferIndex: -1,\n    _index: 0,\n    line: from && from.line || 1,\n    column: from && from.column || 1,\n    offset: from && from.offset || 0\n  };\n  /** @type {Record<string, number>} */\n  const columnStart = {};\n  /** @type {Array<Construct>} */\n  const resolveAllConstructs = [];\n  /** @type {Array<Chunk>} */\n  let chunks = [];\n  /** @type {Array<Token>} */\n  let stack = [];\n  /** @type {boolean | undefined} */\n  let consumed = true;\n\n  /**\n   * Tools used for tokenizing.\n   *\n   * @type {Effects}\n   */\n  const effects = {\n    attempt: constructFactory(onsuccessfulconstruct),\n    check: constructFactory(onsuccessfulcheck),\n    consume,\n    enter,\n    exit,\n    interrupt: constructFactory(onsuccessfulcheck, {\n      interrupt: true\n    })\n  };\n\n  /**\n   * State and tools for resolving and serializing.\n   *\n   * @type {TokenizeContext}\n   */\n  const context = {\n    code: null,\n    containerState: {},\n    defineSkip,\n    events: [],\n    now,\n    parser,\n    previous: null,\n    sliceSerialize,\n    sliceStream,\n    write\n  };\n\n  /**\n   * The state function.\n   *\n   * @type {State | undefined}\n   */\n  let state = initialize.tokenize.call(context, effects);\n\n  /**\n   * Track which character we expect to be consumed, to catch bugs.\n   *\n   * @type {Code}\n   */\n  let expectedCode;\n  if (initialize.resolveAll) {\n    resolveAllConstructs.push(initialize);\n  }\n  return context;\n\n  /** @type {TokenizeContext['write']} */\n  function write(slice) {\n    chunks = push(chunks, slice);\n    main();\n\n    // Exit if we’re not done, resolve might change stuff.\n    if (chunks[chunks.length - 1] !== null) {\n      return [];\n    }\n    addResult(initialize, 0);\n\n    // Otherwise, resolve, and exit.\n    context.events = resolveAll(resolveAllConstructs, context.events, context);\n    return context.events;\n  }\n\n  //\n  // Tools.\n  //\n\n  /** @type {TokenizeContext['sliceSerialize']} */\n  function sliceSerialize(token, expandTabs) {\n    return serializeChunks(sliceStream(token), expandTabs);\n  }\n\n  /** @type {TokenizeContext['sliceStream']} */\n  function sliceStream(token) {\n    return sliceChunks(chunks, token);\n  }\n\n  /** @type {TokenizeContext['now']} */\n  function now() {\n    // This is a hot path, so we clone manually instead of `Object.assign({}, point)`\n    const {\n      _bufferIndex,\n      _index,\n      line,\n      column,\n      offset\n    } = point;\n    return {\n      _bufferIndex,\n      _index,\n      line,\n      column,\n      offset\n    };\n  }\n\n  /** @type {TokenizeContext['defineSkip']} */\n  function defineSkip(value) {\n    columnStart[value.line] = value.column;\n    accountForPotentialSkip();\n  }\n\n  //\n  // State management.\n  //\n\n  /**\n   * Main loop (note that `_index` and `_bufferIndex` in `point` are modified by\n   * `consume`).\n   * Here is where we walk through the chunks, which either include strings of\n   * several characters, or numerical character codes.\n   * The reason to do this in a loop instead of a call is so the stack can\n   * drain.\n   *\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function main() {\n    /** @type {number} */\n    let chunkIndex;\n    while (point._index < chunks.length) {\n      const chunk = chunks[point._index];\n\n      // If we’re in a buffer chunk, loop through it.\n      if (typeof chunk === 'string') {\n        chunkIndex = point._index;\n        if (point._bufferIndex < 0) {\n          point._bufferIndex = 0;\n        }\n        while (point._index === chunkIndex && point._bufferIndex < chunk.length) {\n          go(chunk.charCodeAt(point._bufferIndex));\n        }\n      } else {\n        go(chunk);\n      }\n    }\n  }\n\n  /**\n   * Deal with one code.\n   *\n   * @param {Code} code\n   *   Code.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function go(code) {\n    consumed = undefined;\n    expectedCode = code;\n    state = state(code);\n  }\n\n  /** @type {Effects['consume']} */\n  function consume(code) {\n    if (markdownLineEnding(code)) {\n      point.line++;\n      point.column = 1;\n      point.offset += code === -3 ? 2 : 1;\n      accountForPotentialSkip();\n    } else if (code !== -1) {\n      point.column++;\n      point.offset++;\n    }\n\n    // Not in a string chunk.\n    if (point._bufferIndex < 0) {\n      point._index++;\n    } else {\n      point._bufferIndex++;\n\n      // At end of string chunk.\n      if (point._bufferIndex ===\n      // Points w/ non-negative `_bufferIndex` reference\n      // strings.\n      /** @type {string} */\n      chunks[point._index].length) {\n        point._bufferIndex = -1;\n        point._index++;\n      }\n    }\n\n    // Expose the previous character.\n    context.previous = code;\n\n    // Mark as consumed.\n    consumed = true;\n  }\n\n  /** @type {Effects['enter']} */\n  function enter(type, fields) {\n    /** @type {Token} */\n    // @ts-expect-error Patch instead of assign required fields to help GC.\n    const token = fields || {};\n    token.type = type;\n    token.start = now();\n    context.events.push(['enter', token, context]);\n    stack.push(token);\n    return token;\n  }\n\n  /** @type {Effects['exit']} */\n  function exit(type) {\n    const token = stack.pop();\n    token.end = now();\n    context.events.push(['exit', token, context]);\n    return token;\n  }\n\n  /**\n   * Use results.\n   *\n   * @type {ReturnHandle}\n   */\n  function onsuccessfulconstruct(construct, info) {\n    addResult(construct, info.from);\n  }\n\n  /**\n   * Discard results.\n   *\n   * @type {ReturnHandle}\n   */\n  function onsuccessfulcheck(_, info) {\n    info.restore();\n  }\n\n  /**\n   * Factory to attempt/check/interrupt.\n   *\n   * @param {ReturnHandle} onreturn\n   *   Callback.\n   * @param {{interrupt?: boolean | undefined} | undefined} [fields]\n   *   Fields.\n   */\n  function constructFactory(onreturn, fields) {\n    return hook;\n\n    /**\n     * Handle either an object mapping codes to constructs, a list of\n     * constructs, or a single construct.\n     *\n     * @param {Array<Construct> | ConstructRecord | Construct} constructs\n     *   Constructs.\n     * @param {State} returnState\n     *   State.\n     * @param {State | undefined} [bogusState]\n     *   State.\n     * @returns {State}\n     *   State.\n     */\n    function hook(constructs, returnState, bogusState) {\n      /** @type {ReadonlyArray<Construct>} */\n      let listOfConstructs;\n      /** @type {number} */\n      let constructIndex;\n      /** @type {Construct} */\n      let currentConstruct;\n      /** @type {Info} */\n      let info;\n      return Array.isArray(constructs) ? /* c8 ignore next 1 */\n      handleListOfConstructs(constructs) : 'tokenize' in constructs ?\n      // Looks like a construct.\n      handleListOfConstructs([(/** @type {Construct} */constructs)]) : handleMapOfConstructs(constructs);\n\n      /**\n       * Handle a list of construct.\n       *\n       * @param {ConstructRecord} map\n       *   Constructs.\n       * @returns {State}\n       *   State.\n       */\n      function handleMapOfConstructs(map) {\n        return start;\n\n        /** @type {State} */\n        function start(code) {\n          const left = code !== null && map[code];\n          const all = code !== null && map.null;\n          const list = [\n          // To do: add more extension tests.\n          /* c8 ignore next 2 */\n          ...(Array.isArray(left) ? left : left ? [left] : []), ...(Array.isArray(all) ? all : all ? [all] : [])];\n          return handleListOfConstructs(list)(code);\n        }\n      }\n\n      /**\n       * Handle a list of construct.\n       *\n       * @param {ReadonlyArray<Construct>} list\n       *   Constructs.\n       * @returns {State}\n       *   State.\n       */\n      function handleListOfConstructs(list) {\n        listOfConstructs = list;\n        constructIndex = 0;\n        if (list.length === 0) {\n          return bogusState;\n        }\n        return handleConstruct(list[constructIndex]);\n      }\n\n      /**\n       * Handle a single construct.\n       *\n       * @param {Construct} construct\n       *   Construct.\n       * @returns {State}\n       *   State.\n       */\n      function handleConstruct(construct) {\n        return start;\n\n        /** @type {State} */\n        function start(code) {\n          // To do: not needed to store if there is no bogus state, probably?\n          // Currently doesn’t work because `inspect` in document does a check\n          // w/o a bogus, which doesn’t make sense. But it does seem to help perf\n          // by not storing.\n          info = store();\n          currentConstruct = construct;\n          if (!construct.partial) {\n            context.currentConstruct = construct;\n          }\n\n          // Always populated by defaults.\n\n          if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) {\n            return nok(code);\n          }\n          return construct.tokenize.call(\n          // If we do have fields, create an object w/ `context` as its\n          // prototype.\n          // This allows a “live binding”, which is needed for `interrupt`.\n          fields ? Object.assign(Object.create(context), fields) : context, effects, ok, nok)(code);\n        }\n      }\n\n      /** @type {State} */\n      function ok(code) {\n        consumed = true;\n        onreturn(currentConstruct, info);\n        return returnState;\n      }\n\n      /** @type {State} */\n      function nok(code) {\n        consumed = true;\n        info.restore();\n        if (++constructIndex < listOfConstructs.length) {\n          return handleConstruct(listOfConstructs[constructIndex]);\n        }\n        return bogusState;\n      }\n    }\n  }\n\n  /**\n   * @param {Construct} construct\n   *   Construct.\n   * @param {number} from\n   *   From.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function addResult(construct, from) {\n    if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {\n      resolveAllConstructs.push(construct);\n    }\n    if (construct.resolve) {\n      splice(context.events, from, context.events.length - from, construct.resolve(context.events.slice(from), context));\n    }\n    if (construct.resolveTo) {\n      context.events = construct.resolveTo(context.events, context);\n    }\n  }\n\n  /**\n   * Store state.\n   *\n   * @returns {Info}\n   *   Info.\n   */\n  function store() {\n    const startPoint = now();\n    const startPrevious = context.previous;\n    const startCurrentConstruct = context.currentConstruct;\n    const startEventsIndex = context.events.length;\n    const startStack = Array.from(stack);\n    return {\n      from: startEventsIndex,\n      restore\n    };\n\n    /**\n     * Restore state.\n     *\n     * @returns {undefined}\n     *   Nothing.\n     */\n    function restore() {\n      point = startPoint;\n      context.previous = startPrevious;\n      context.currentConstruct = startCurrentConstruct;\n      context.events.length = startEventsIndex;\n      stack = startStack;\n      accountForPotentialSkip();\n    }\n  }\n\n  /**\n   * Move the current point a bit forward in the line when it’s on a column\n   * skip.\n   *\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function accountForPotentialSkip() {\n    if (point.line in columnStart && point.column < 2) {\n      point.column = columnStart[point.line];\n      point.offset += columnStart[point.line] - 1;\n    }\n  }\n}\n\n/**\n * Get the chunks from a slice of chunks in the range of a token.\n *\n * @param {ReadonlyArray<Chunk>} chunks\n *   Chunks.\n * @param {Pick<Token, 'end' | 'start'>} token\n *   Token.\n * @returns {Array<Chunk>}\n *   Chunks.\n */\nfunction sliceChunks(chunks, token) {\n  const startIndex = token.start._index;\n  const startBufferIndex = token.start._bufferIndex;\n  const endIndex = token.end._index;\n  const endBufferIndex = token.end._bufferIndex;\n  /** @type {Array<Chunk>} */\n  let view;\n  if (startIndex === endIndex) {\n    // @ts-expect-error `_bufferIndex` is used on string chunks.\n    view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];\n  } else {\n    view = chunks.slice(startIndex, endIndex);\n    if (startBufferIndex > -1) {\n      const head = view[0];\n      if (typeof head === 'string') {\n        view[0] = head.slice(startBufferIndex);\n        /* c8 ignore next 4 -- used to be used, no longer */\n      } else {\n        view.shift();\n      }\n    }\n    if (endBufferIndex > 0) {\n      // @ts-expect-error `_bufferIndex` is used on string chunks.\n      view.push(chunks[endIndex].slice(0, endBufferIndex));\n    }\n  }\n  return view;\n}\n\n/**\n * Get the string value of a slice of chunks.\n *\n * @param {ReadonlyArray<Chunk>} chunks\n *   Chunks.\n * @param {boolean | undefined} [expandTabs=false]\n *   Whether to expand tabs (default: `false`).\n * @returns {string}\n *   Result.\n */\nfunction serializeChunks(chunks, expandTabs) {\n  let index = -1;\n  /** @type {Array<string>} */\n  const result = [];\n  /** @type {boolean | undefined} */\n  let atTab;\n  while (++index < chunks.length) {\n    const chunk = chunks[index];\n    /** @type {string} */\n    let value;\n    if (typeof chunk === 'string') {\n      value = chunk;\n    } else switch (chunk) {\n      case -5:\n        {\n          value = \"\\r\";\n          break;\n        }\n      case -4:\n        {\n          value = \"\\n\";\n          break;\n        }\n      case -3:\n        {\n          value = \"\\r\" + \"\\n\";\n          break;\n        }\n      case -2:\n        {\n          value = expandTabs ? \" \" : \"\\t\";\n          break;\n        }\n      case -1:\n        {\n          if (!expandTabs && atTab) continue;\n          value = \" \";\n          break;\n        }\n      default:\n        {\n          // Currently only replacement character.\n          value = String.fromCharCode(chunk);\n        }\n    }\n    atTab = chunk === -2;\n    result.push(value);\n  }\n  return result.join('');\n}","/**\n * @import {\n *   Create,\n *   FullNormalizedExtension,\n *   InitialConstruct,\n *   ParseContext,\n *   ParseOptions\n * } from 'micromark-util-types'\n */\n\nimport { combineExtensions } from 'micromark-util-combine-extensions';\nimport { content } from './initialize/content.js';\nimport { document } from './initialize/document.js';\nimport { flow } from './initialize/flow.js';\nimport { string, text } from './initialize/text.js';\nimport * as defaultConstructs from './constructs.js';\nimport { createTokenizer } from './create-tokenizer.js';\n\n/**\n * @param {ParseOptions | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ParseContext}\n *   Parser.\n */\nexport function parse(options) {\n  const settings = options || {};\n  const constructs = /** @type {FullNormalizedExtension} */\n  combineExtensions([defaultConstructs, ...(settings.extensions || [])]);\n\n  /** @type {ParseContext} */\n  const parser = {\n    constructs,\n    content: create(content),\n    defined: [],\n    document: create(document),\n    flow: create(flow),\n    lazy: {},\n    string: create(string),\n    text: create(text)\n  };\n  return parser;\n\n  /**\n   * @param {InitialConstruct} initial\n   *   Construct to start with.\n   * @returns {Create}\n   *   Create a tokenizer.\n   */\n  function create(initial) {\n    return creator;\n    /** @type {Create} */\n    function creator(from) {\n      return createTokenizer(parser, initial, from);\n    }\n  }\n}","/**\n * @import {Event} from 'micromark-util-types'\n */\n\nimport { subtokenize } from 'micromark-util-subtokenize';\n\n/**\n * @param {Array<Event>} events\n *   Events.\n * @returns {Array<Event>}\n *   Events.\n */\nexport function postprocess(events) {\n  while (!subtokenize(events)) {\n    // Empty\n  }\n  return events;\n}","/**\n * @import {Chunk, Code, Encoding, Value} from 'micromark-util-types'\n */\n\n/**\n * @callback Preprocessor\n *   Preprocess a value.\n * @param {Value} value\n *   Value.\n * @param {Encoding | null | undefined} [encoding]\n *   Encoding when `value` is a typed array (optional).\n * @param {boolean | null | undefined} [end=false]\n *   Whether this is the last chunk (default: `false`).\n * @returns {Array<Chunk>}\n *   Chunks.\n */\n\nconst search = /[\\0\\t\\n\\r]/g;\n\n/**\n * @returns {Preprocessor}\n *   Preprocess a value.\n */\nexport function preprocess() {\n  let column = 1;\n  let buffer = '';\n  /** @type {boolean | undefined} */\n  let start = true;\n  /** @type {boolean | undefined} */\n  let atCarriageReturn;\n  return preprocessor;\n\n  /** @type {Preprocessor} */\n  // eslint-disable-next-line complexity\n  function preprocessor(value, encoding, end) {\n    /** @type {Array<Chunk>} */\n    const chunks = [];\n    /** @type {RegExpMatchArray | null} */\n    let match;\n    /** @type {number} */\n    let next;\n    /** @type {number} */\n    let startPosition;\n    /** @type {number} */\n    let endPosition;\n    /** @type {Code} */\n    let code;\n    value = buffer + (typeof value === 'string' ? value.toString() : new TextDecoder(encoding || undefined).decode(value));\n    startPosition = 0;\n    buffer = '';\n    if (start) {\n      // To do: `markdown-rs` actually parses BOMs (byte order mark).\n      if (value.charCodeAt(0) === 65279) {\n        startPosition++;\n      }\n      start = undefined;\n    }\n    while (startPosition < value.length) {\n      search.lastIndex = startPosition;\n      match = search.exec(value);\n      endPosition = match && match.index !== undefined ? match.index : value.length;\n      code = value.charCodeAt(endPosition);\n      if (!match) {\n        buffer = value.slice(startPosition);\n        break;\n      }\n      if (code === 10 && startPosition === endPosition && atCarriageReturn) {\n        chunks.push(-3);\n        atCarriageReturn = undefined;\n      } else {\n        if (atCarriageReturn) {\n          chunks.push(-5);\n          atCarriageReturn = undefined;\n        }\n        if (startPosition < endPosition) {\n          chunks.push(value.slice(startPosition, endPosition));\n          column += endPosition - startPosition;\n        }\n        switch (code) {\n          case 0:\n            {\n              chunks.push(65533);\n              column++;\n              break;\n            }\n          case 9:\n            {\n              next = Math.ceil(column / 4) * 4;\n              chunks.push(-2);\n              while (column++ < next) chunks.push(-1);\n              break;\n            }\n          case 10:\n            {\n              chunks.push(-4);\n              column = 1;\n              break;\n            }\n          default:\n            {\n              atCarriageReturn = true;\n              column = 1;\n            }\n        }\n      }\n      startPosition = endPosition + 1;\n    }\n    if (end) {\n      if (atCarriageReturn) chunks.push(-5);\n      if (buffer) chunks.push(buffer);\n      chunks.push(null);\n    }\n    return chunks;\n  }\n}","import { decodeNamedCharacterReference } from 'decode-named-character-reference';\nimport { decodeNumericCharacterReference } from 'micromark-util-decode-numeric-character-reference';\nconst characterEscapeOrReference = /\\\\([!-/:-@[-`{-~])|&(#(?:\\d{1,7}|x[\\da-f]{1,6})|[\\da-z]{1,31});/gi;\n\n/**\n * Decode markdown strings (which occur in places such as fenced code info\n * strings, destinations, labels, and titles).\n *\n * The “string” content type allows character escapes and -references.\n * This decodes those.\n *\n * @param {string} value\n *   Value to decode.\n * @returns {string}\n *   Decoded value.\n */\nexport function decodeString(value) {\n  return value.replace(characterEscapeOrReference, decode);\n}\n\n/**\n * @param {string} $0\n *   Match.\n * @param {string} $1\n *   Character escape.\n * @param {string} $2\n *   Character reference.\n * @returns {string}\n *   Decoded value\n */\nfunction decode($0, $1, $2) {\n  if ($1) {\n    // Escape.\n    return $1;\n  }\n\n  // Reference.\n  const head = $2.charCodeAt(0);\n  if (head === 35) {\n    const head = $2.charCodeAt(1);\n    const hex = head === 120 || head === 88;\n    return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10);\n  }\n  return decodeNamedCharacterReference($2) || $0;\n}","/**\n * @import {\n *   Break,\n *   Blockquote,\n *   Code,\n *   Definition,\n *   Emphasis,\n *   Heading,\n *   Html,\n *   Image,\n *   InlineCode,\n *   Link,\n *   ListItem,\n *   List,\n *   Nodes,\n *   Paragraph,\n *   PhrasingContent,\n *   ReferenceType,\n *   Root,\n *   Strong,\n *   Text,\n *   ThematicBreak\n * } from 'mdast'\n * @import {\n *   Encoding,\n *   Event,\n *   Token,\n *   Value\n * } from 'micromark-util-types'\n * @import {Point} from 'unist'\n * @import {\n *   CompileContext,\n *   CompileData,\n *   Config,\n *   Extension,\n *   Handle,\n *   OnEnterError,\n *   Options\n * } from './types.js'\n */\n\nimport { toString } from 'mdast-util-to-string';\nimport { parse, postprocess, preprocess } from 'micromark';\nimport { decodeNumericCharacterReference } from 'micromark-util-decode-numeric-character-reference';\nimport { decodeString } from 'micromark-util-decode-string';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nimport { decodeNamedCharacterReference } from 'decode-named-character-reference';\nimport { stringifyPosition } from 'unist-util-stringify-position';\nconst own = {}.hasOwnProperty;\n\n/**\n * Turn markdown into a syntax tree.\n *\n * @overload\n * @param {Value} value\n * @param {Encoding | null | undefined} [encoding]\n * @param {Options | null | undefined} [options]\n * @returns {Root}\n *\n * @overload\n * @param {Value} value\n * @param {Options | null | undefined} [options]\n * @returns {Root}\n *\n * @param {Value} value\n *   Markdown to parse.\n * @param {Encoding | Options | null | undefined} [encoding]\n *   Character encoding for when `value` is `Buffer`.\n * @param {Options | null | undefined} [options]\n *   Configuration.\n * @returns {Root}\n *   mdast tree.\n */\nexport function fromMarkdown(value, encoding, options) {\n  if (encoding && typeof encoding === 'object') {\n    options = encoding;\n    encoding = undefined;\n  }\n  return compiler(options)(postprocess(parse(options).document().write(preprocess()(value, encoding, true))));\n}\n\n/**\n * Note this compiler only understand complete buffering, not streaming.\n *\n * @param {Options | null | undefined} [options]\n */\nfunction compiler(options) {\n  /** @type {Config} */\n  const config = {\n    transforms: [],\n    canContainEols: ['emphasis', 'fragment', 'heading', 'paragraph', 'strong'],\n    enter: {\n      autolink: opener(link),\n      autolinkProtocol: onenterdata,\n      autolinkEmail: onenterdata,\n      atxHeading: opener(heading),\n      blockQuote: opener(blockQuote),\n      characterEscape: onenterdata,\n      characterReference: onenterdata,\n      codeFenced: opener(codeFlow),\n      codeFencedFenceInfo: buffer,\n      codeFencedFenceMeta: buffer,\n      codeIndented: opener(codeFlow, buffer),\n      codeText: opener(codeText, buffer),\n      codeTextData: onenterdata,\n      data: onenterdata,\n      codeFlowValue: onenterdata,\n      definition: opener(definition),\n      definitionDestinationString: buffer,\n      definitionLabelString: buffer,\n      definitionTitleString: buffer,\n      emphasis: opener(emphasis),\n      hardBreakEscape: opener(hardBreak),\n      hardBreakTrailing: opener(hardBreak),\n      htmlFlow: opener(html, buffer),\n      htmlFlowData: onenterdata,\n      htmlText: opener(html, buffer),\n      htmlTextData: onenterdata,\n      image: opener(image),\n      label: buffer,\n      link: opener(link),\n      listItem: opener(listItem),\n      listItemValue: onenterlistitemvalue,\n      listOrdered: opener(list, onenterlistordered),\n      listUnordered: opener(list),\n      paragraph: opener(paragraph),\n      reference: onenterreference,\n      referenceString: buffer,\n      resourceDestinationString: buffer,\n      resourceTitleString: buffer,\n      setextHeading: opener(heading),\n      strong: opener(strong),\n      thematicBreak: opener(thematicBreak)\n    },\n    exit: {\n      atxHeading: closer(),\n      atxHeadingSequence: onexitatxheadingsequence,\n      autolink: closer(),\n      autolinkEmail: onexitautolinkemail,\n      autolinkProtocol: onexitautolinkprotocol,\n      blockQuote: closer(),\n      characterEscapeValue: onexitdata,\n      characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,\n      characterReferenceMarkerNumeric: onexitcharacterreferencemarker,\n      characterReferenceValue: onexitcharacterreferencevalue,\n      characterReference: onexitcharacterreference,\n      codeFenced: closer(onexitcodefenced),\n      codeFencedFence: onexitcodefencedfence,\n      codeFencedFenceInfo: onexitcodefencedfenceinfo,\n      codeFencedFenceMeta: onexitcodefencedfencemeta,\n      codeFlowValue: onexitdata,\n      codeIndented: closer(onexitcodeindented),\n      codeText: closer(onexitcodetext),\n      codeTextData: onexitdata,\n      data: onexitdata,\n      definition: closer(),\n      definitionDestinationString: onexitdefinitiondestinationstring,\n      definitionLabelString: onexitdefinitionlabelstring,\n      definitionTitleString: onexitdefinitiontitlestring,\n      emphasis: closer(),\n      hardBreakEscape: closer(onexithardbreak),\n      hardBreakTrailing: closer(onexithardbreak),\n      htmlFlow: closer(onexithtmlflow),\n      htmlFlowData: onexitdata,\n      htmlText: closer(onexithtmltext),\n      htmlTextData: onexitdata,\n      image: closer(onexitimage),\n      label: onexitlabel,\n      labelText: onexitlabeltext,\n      lineEnding: onexitlineending,\n      link: closer(onexitlink),\n      listItem: closer(),\n      listOrdered: closer(),\n      listUnordered: closer(),\n      paragraph: closer(),\n      referenceString: onexitreferencestring,\n      resourceDestinationString: onexitresourcedestinationstring,\n      resourceTitleString: onexitresourcetitlestring,\n      resource: onexitresource,\n      setextHeading: closer(onexitsetextheading),\n      setextHeadingLineSequence: onexitsetextheadinglinesequence,\n      setextHeadingText: onexitsetextheadingtext,\n      strong: closer(),\n      thematicBreak: closer()\n    }\n  };\n  configure(config, (options || {}).mdastExtensions || []);\n\n  /** @type {CompileData} */\n  const data = {};\n  return compile;\n\n  /**\n   * Turn micromark events into an mdast tree.\n   *\n   * @param {Array<Event>} events\n   *   Events.\n   * @returns {Root}\n   *   mdast tree.\n   */\n  function compile(events) {\n    /** @type {Root} */\n    let tree = {\n      type: 'root',\n      children: []\n    };\n    /** @type {Omit<CompileContext, 'sliceSerialize'>} */\n    const context = {\n      stack: [tree],\n      tokenStack: [],\n      config,\n      enter,\n      exit,\n      buffer,\n      resume,\n      data\n    };\n    /** @type {Array<number>} */\n    const listStack = [];\n    let index = -1;\n    while (++index < events.length) {\n      // We preprocess lists to add `listItem` tokens, and to infer whether\n      // items the list itself are spread out.\n      if (events[index][1].type === \"listOrdered\" || events[index][1].type === \"listUnordered\") {\n        if (events[index][0] === 'enter') {\n          listStack.push(index);\n        } else {\n          const tail = listStack.pop();\n          index = prepareList(events, tail, index);\n        }\n      }\n    }\n    index = -1;\n    while (++index < events.length) {\n      const handler = config[events[index][0]];\n      if (own.call(handler, events[index][1].type)) {\n        handler[events[index][1].type].call(Object.assign({\n          sliceSerialize: events[index][2].sliceSerialize\n        }, context), events[index][1]);\n      }\n    }\n\n    // Handle tokens still being open.\n    if (context.tokenStack.length > 0) {\n      const tail = context.tokenStack[context.tokenStack.length - 1];\n      const handler = tail[1] || defaultOnError;\n      handler.call(context, undefined, tail[0]);\n    }\n\n    // Figure out `root` position.\n    tree.position = {\n      start: point(events.length > 0 ? events[0][1].start : {\n        line: 1,\n        column: 1,\n        offset: 0\n      }),\n      end: point(events.length > 0 ? events[events.length - 2][1].end : {\n        line: 1,\n        column: 1,\n        offset: 0\n      })\n    };\n\n    // Call transforms.\n    index = -1;\n    while (++index < config.transforms.length) {\n      tree = config.transforms[index](tree) || tree;\n    }\n    return tree;\n  }\n\n  /**\n   * @param {Array<Event>} events\n   * @param {number} start\n   * @param {number} length\n   * @returns {number}\n   */\n  function prepareList(events, start, length) {\n    let index = start - 1;\n    let containerBalance = -1;\n    let listSpread = false;\n    /** @type {Token | undefined} */\n    let listItem;\n    /** @type {number | undefined} */\n    let lineIndex;\n    /** @type {number | undefined} */\n    let firstBlankLineIndex;\n    /** @type {boolean | undefined} */\n    let atMarker;\n    while (++index <= length) {\n      const event = events[index];\n      switch (event[1].type) {\n        case \"listUnordered\":\n        case \"listOrdered\":\n        case \"blockQuote\":\n          {\n            if (event[0] === 'enter') {\n              containerBalance++;\n            } else {\n              containerBalance--;\n            }\n            atMarker = undefined;\n            break;\n          }\n        case \"lineEndingBlank\":\n          {\n            if (event[0] === 'enter') {\n              if (listItem && !atMarker && !containerBalance && !firstBlankLineIndex) {\n                firstBlankLineIndex = index;\n              }\n              atMarker = undefined;\n            }\n            break;\n          }\n        case \"linePrefix\":\n        case \"listItemValue\":\n        case \"listItemMarker\":\n        case \"listItemPrefix\":\n        case \"listItemPrefixWhitespace\":\n          {\n            // Empty.\n\n            break;\n          }\n        default:\n          {\n            atMarker = undefined;\n          }\n      }\n      if (!containerBalance && event[0] === 'enter' && event[1].type === \"listItemPrefix\" || containerBalance === -1 && event[0] === 'exit' && (event[1].type === \"listUnordered\" || event[1].type === \"listOrdered\")) {\n        if (listItem) {\n          let tailIndex = index;\n          lineIndex = undefined;\n          while (tailIndex--) {\n            const tailEvent = events[tailIndex];\n            if (tailEvent[1].type === \"lineEnding\" || tailEvent[1].type === \"lineEndingBlank\") {\n              if (tailEvent[0] === 'exit') continue;\n              if (lineIndex) {\n                events[lineIndex][1].type = \"lineEndingBlank\";\n                listSpread = true;\n              }\n              tailEvent[1].type = \"lineEnding\";\n              lineIndex = tailIndex;\n            } else if (tailEvent[1].type === \"linePrefix\" || tailEvent[1].type === \"blockQuotePrefix\" || tailEvent[1].type === \"blockQuotePrefixWhitespace\" || tailEvent[1].type === \"blockQuoteMarker\" || tailEvent[1].type === \"listItemIndent\") {\n              // Empty\n            } else {\n              break;\n            }\n          }\n          if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {\n            listItem._spread = true;\n          }\n\n          // Fix position.\n          listItem.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end);\n          events.splice(lineIndex || index, 0, ['exit', listItem, event[2]]);\n          index++;\n          length++;\n        }\n\n        // Create a new list item.\n        if (event[1].type === \"listItemPrefix\") {\n          /** @type {Token} */\n          const item = {\n            type: 'listItem',\n            _spread: false,\n            start: Object.assign({}, event[1].start),\n            // @ts-expect-error: we’ll add `end` in a second.\n            end: undefined\n          };\n          listItem = item;\n          events.splice(index, 0, ['enter', item, event[2]]);\n          index++;\n          length++;\n          firstBlankLineIndex = undefined;\n          atMarker = true;\n        }\n      }\n    }\n    events[start][1]._spread = listSpread;\n    return length;\n  }\n\n  /**\n   * Create an opener handle.\n   *\n   * @param {(token: Token) => Nodes} create\n   *   Create a node.\n   * @param {Handle | undefined} [and]\n   *   Optional function to also run.\n   * @returns {Handle}\n   *   Handle.\n   */\n  function opener(create, and) {\n    return open;\n\n    /**\n     * @this {CompileContext}\n     * @param {Token} token\n     * @returns {undefined}\n     */\n    function open(token) {\n      enter.call(this, create(token), token);\n      if (and) and.call(this, token);\n    }\n  }\n\n  /**\n   * @type {CompileContext['buffer']}\n   */\n  function buffer() {\n    this.stack.push({\n      type: 'fragment',\n      children: []\n    });\n  }\n\n  /**\n   * @type {CompileContext['enter']}\n   */\n  function enter(node, token, errorHandler) {\n    const parent = this.stack[this.stack.length - 1];\n    /** @type {Array<Nodes>} */\n    const siblings = parent.children;\n    siblings.push(node);\n    this.stack.push(node);\n    this.tokenStack.push([token, errorHandler || undefined]);\n    node.position = {\n      start: point(token.start),\n      // @ts-expect-error: `end` will be patched later.\n      end: undefined\n    };\n  }\n\n  /**\n   * Create a closer handle.\n   *\n   * @param {Handle | undefined} [and]\n   *   Optional function to also run.\n   * @returns {Handle}\n   *   Handle.\n   */\n  function closer(and) {\n    return close;\n\n    /**\n     * @this {CompileContext}\n     * @param {Token} token\n     * @returns {undefined}\n     */\n    function close(token) {\n      if (and) and.call(this, token);\n      exit.call(this, token);\n    }\n  }\n\n  /**\n   * @type {CompileContext['exit']}\n   */\n  function exit(token, onExitError) {\n    const node = this.stack.pop();\n    const open = this.tokenStack.pop();\n    if (!open) {\n      throw new Error('Cannot close `' + token.type + '` (' + stringifyPosition({\n        start: token.start,\n        end: token.end\n      }) + '): it’s not open');\n    } else if (open[0].type !== token.type) {\n      if (onExitError) {\n        onExitError.call(this, token, open[0]);\n      } else {\n        const handler = open[1] || defaultOnError;\n        handler.call(this, token, open[0]);\n      }\n    }\n    node.position.end = point(token.end);\n  }\n\n  /**\n   * @type {CompileContext['resume']}\n   */\n  function resume() {\n    return toString(this.stack.pop());\n  }\n\n  //\n  // Handlers.\n  //\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onenterlistordered() {\n    this.data.expectingFirstListItemValue = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onenterlistitemvalue(token) {\n    if (this.data.expectingFirstListItemValue) {\n      const ancestor = this.stack[this.stack.length - 2];\n      ancestor.start = Number.parseInt(this.sliceSerialize(token), 10);\n      this.data.expectingFirstListItemValue = undefined;\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefencedfenceinfo() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.lang = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefencedfencemeta() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.meta = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefencedfence() {\n    // Exit if this is the closing fence.\n    if (this.data.flowCodeInside) return;\n    this.buffer();\n    this.data.flowCodeInside = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefenced() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data.replace(/^(\\r?\\n|\\r)|(\\r?\\n|\\r)$/g, '');\n    this.data.flowCodeInside = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodeindented() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data.replace(/(\\r?\\n|\\r)$/g, '');\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitdefinitionlabelstring(token) {\n    const label = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.label = label;\n    node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitdefinitiontitlestring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.title = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitdefinitiondestinationstring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.url = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitatxheadingsequence(token) {\n    const node = this.stack[this.stack.length - 1];\n    if (!node.depth) {\n      const depth = this.sliceSerialize(token).length;\n      node.depth = depth;\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitsetextheadingtext() {\n    this.data.setextHeadingSlurpLineEnding = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitsetextheadinglinesequence(token) {\n    const node = this.stack[this.stack.length - 1];\n    node.depth = this.sliceSerialize(token).codePointAt(0) === 61 ? 1 : 2;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitsetextheading() {\n    this.data.setextHeadingSlurpLineEnding = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onenterdata(token) {\n    const node = this.stack[this.stack.length - 1];\n    /** @type {Array<Nodes>} */\n    const siblings = node.children;\n    let tail = siblings[siblings.length - 1];\n    if (!tail || tail.type !== 'text') {\n      // Add a new text node.\n      tail = text();\n      tail.position = {\n        start: point(token.start),\n        // @ts-expect-error: we’ll add `end` later.\n        end: undefined\n      };\n      siblings.push(tail);\n    }\n    this.stack.push(tail);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitdata(token) {\n    const tail = this.stack.pop();\n    tail.value += this.sliceSerialize(token);\n    tail.position.end = point(token.end);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlineending(token) {\n    const context = this.stack[this.stack.length - 1];\n    // If we’re at a hard break, include the line ending in there.\n    if (this.data.atHardBreak) {\n      const tail = context.children[context.children.length - 1];\n      tail.position.end = point(token.end);\n      this.data.atHardBreak = undefined;\n      return;\n    }\n    if (!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type)) {\n      onenterdata.call(this, token);\n      onexitdata.call(this, token);\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexithardbreak() {\n    this.data.atHardBreak = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexithtmlflow() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexithtmltext() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitcodetext() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlink() {\n    const node = this.stack[this.stack.length - 1];\n    // Note: there are also `identifier` and `label` fields on this link node!\n    // These are used / cleaned here.\n\n    // To do: clean.\n    if (this.data.inReference) {\n      /** @type {ReferenceType} */\n      const referenceType = this.data.referenceType || 'shortcut';\n      node.type += 'Reference';\n      // @ts-expect-error: mutate.\n      node.referenceType = referenceType;\n      // @ts-expect-error: mutate.\n      delete node.url;\n      delete node.title;\n    } else {\n      // @ts-expect-error: mutate.\n      delete node.identifier;\n      // @ts-expect-error: mutate.\n      delete node.label;\n    }\n    this.data.referenceType = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitimage() {\n    const node = this.stack[this.stack.length - 1];\n    // Note: there are also `identifier` and `label` fields on this link node!\n    // These are used / cleaned here.\n\n    // To do: clean.\n    if (this.data.inReference) {\n      /** @type {ReferenceType} */\n      const referenceType = this.data.referenceType || 'shortcut';\n      node.type += 'Reference';\n      // @ts-expect-error: mutate.\n      node.referenceType = referenceType;\n      // @ts-expect-error: mutate.\n      delete node.url;\n      delete node.title;\n    } else {\n      // @ts-expect-error: mutate.\n      delete node.identifier;\n      // @ts-expect-error: mutate.\n      delete node.label;\n    }\n    this.data.referenceType = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlabeltext(token) {\n    const string = this.sliceSerialize(token);\n    const ancestor = this.stack[this.stack.length - 2];\n    // @ts-expect-error: stash this on the node, as it might become a reference\n    // later.\n    ancestor.label = decodeString(string);\n    // @ts-expect-error: same as above.\n    ancestor.identifier = normalizeIdentifier(string).toLowerCase();\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlabel() {\n    const fragment = this.stack[this.stack.length - 1];\n    const value = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    // Assume a reference.\n    this.data.inReference = true;\n    if (node.type === 'link') {\n      /** @type {Array<PhrasingContent>} */\n      const children = fragment.children;\n      node.children = children;\n    } else {\n      node.alt = value;\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitresourcedestinationstring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.url = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitresourcetitlestring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.title = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitresource() {\n    this.data.inReference = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onenterreference() {\n    this.data.referenceType = 'collapsed';\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitreferencestring(token) {\n    const label = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    // @ts-expect-error: stash this on the node, as it might become a reference\n    // later.\n    node.label = label;\n    // @ts-expect-error: same as above.\n    node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();\n    this.data.referenceType = 'full';\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitcharacterreferencemarker(token) {\n    this.data.characterReferenceType = token.type;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcharacterreferencevalue(token) {\n    const data = this.sliceSerialize(token);\n    const type = this.data.characterReferenceType;\n    /** @type {string} */\n    let value;\n    if (type) {\n      value = decodeNumericCharacterReference(data, type === \"characterReferenceMarkerNumeric\" ? 10 : 16);\n      this.data.characterReferenceType = undefined;\n    } else {\n      const result = decodeNamedCharacterReference(data);\n      value = result;\n    }\n    const tail = this.stack[this.stack.length - 1];\n    tail.value += value;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcharacterreference(token) {\n    const tail = this.stack.pop();\n    tail.position.end = point(token.end);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitautolinkprotocol(token) {\n    onexitdata.call(this, token);\n    const node = this.stack[this.stack.length - 1];\n    node.url = this.sliceSerialize(token);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitautolinkemail(token) {\n    onexitdata.call(this, token);\n    const node = this.stack[this.stack.length - 1];\n    node.url = 'mailto:' + this.sliceSerialize(token);\n  }\n\n  //\n  // Creaters.\n  //\n\n  /** @returns {Blockquote} */\n  function blockQuote() {\n    return {\n      type: 'blockquote',\n      children: []\n    };\n  }\n\n  /** @returns {Code} */\n  function codeFlow() {\n    return {\n      type: 'code',\n      lang: null,\n      meta: null,\n      value: ''\n    };\n  }\n\n  /** @returns {InlineCode} */\n  function codeText() {\n    return {\n      type: 'inlineCode',\n      value: ''\n    };\n  }\n\n  /** @returns {Definition} */\n  function definition() {\n    return {\n      type: 'definition',\n      identifier: '',\n      label: null,\n      title: null,\n      url: ''\n    };\n  }\n\n  /** @returns {Emphasis} */\n  function emphasis() {\n    return {\n      type: 'emphasis',\n      children: []\n    };\n  }\n\n  /** @returns {Heading} */\n  function heading() {\n    return {\n      type: 'heading',\n      // @ts-expect-error `depth` will be set later.\n      depth: 0,\n      children: []\n    };\n  }\n\n  /** @returns {Break} */\n  function hardBreak() {\n    return {\n      type: 'break'\n    };\n  }\n\n  /** @returns {Html} */\n  function html() {\n    return {\n      type: 'html',\n      value: ''\n    };\n  }\n\n  /** @returns {Image} */\n  function image() {\n    return {\n      type: 'image',\n      title: null,\n      url: '',\n      alt: null\n    };\n  }\n\n  /** @returns {Link} */\n  function link() {\n    return {\n      type: 'link',\n      title: null,\n      url: '',\n      children: []\n    };\n  }\n\n  /**\n   * @param {Token} token\n   * @returns {List}\n   */\n  function list(token) {\n    return {\n      type: 'list',\n      ordered: token.type === 'listOrdered',\n      start: null,\n      spread: token._spread,\n      children: []\n    };\n  }\n\n  /**\n   * @param {Token} token\n   * @returns {ListItem}\n   */\n  function listItem(token) {\n    return {\n      type: 'listItem',\n      spread: token._spread,\n      checked: null,\n      children: []\n    };\n  }\n\n  /** @returns {Paragraph} */\n  function paragraph() {\n    return {\n      type: 'paragraph',\n      children: []\n    };\n  }\n\n  /** @returns {Strong} */\n  function strong() {\n    return {\n      type: 'strong',\n      children: []\n    };\n  }\n\n  /** @returns {Text} */\n  function text() {\n    return {\n      type: 'text',\n      value: ''\n    };\n  }\n\n  /** @returns {ThematicBreak} */\n  function thematicBreak() {\n    return {\n      type: 'thematicBreak'\n    };\n  }\n}\n\n/**\n * Copy a point-like value.\n *\n * @param {Point} d\n *   Point-like value.\n * @returns {Point}\n *   unist point.\n */\nfunction point(d) {\n  return {\n    line: d.line,\n    column: d.column,\n    offset: d.offset\n  };\n}\n\n/**\n * @param {Config} combined\n * @param {Array<Array<Extension> | Extension>} extensions\n * @returns {undefined}\n */\nfunction configure(combined, extensions) {\n  let index = -1;\n  while (++index < extensions.length) {\n    const value = extensions[index];\n    if (Array.isArray(value)) {\n      configure(combined, value);\n    } else {\n      extension(combined, value);\n    }\n  }\n}\n\n/**\n * @param {Config} combined\n * @param {Extension} extension\n * @returns {undefined}\n */\nfunction extension(combined, extension) {\n  /** @type {keyof Extension} */\n  let key;\n  for (key in extension) {\n    if (own.call(extension, key)) {\n      switch (key) {\n        case 'canContainEols':\n          {\n            const right = extension[key];\n            if (right) {\n              combined[key].push(...right);\n            }\n            break;\n          }\n        case 'transforms':\n          {\n            const right = extension[key];\n            if (right) {\n              combined[key].push(...right);\n            }\n            break;\n          }\n        case 'enter':\n        case 'exit':\n          {\n            const right = extension[key];\n            if (right) {\n              Object.assign(combined[key], right);\n            }\n            break;\n          }\n        // No default\n      }\n    }\n  }\n}\n\n/** @type {OnEnterError} */\nfunction defaultOnError(left, right) {\n  if (left) {\n    throw new Error('Cannot close `' + left.type + '` (' + stringifyPosition({\n      start: left.start,\n      end: left.end\n    }) + '): a different token (`' + right.type + '`, ' + stringifyPosition({\n      start: right.start,\n      end: right.end\n    }) + ') is open');\n  } else {\n    throw new Error('Cannot close document, a token (`' + right.type + '`, ' + stringifyPosition({\n      start: right.start,\n      end: right.end\n    }) + ') is still open');\n  }\n}","/**\n * @typedef {import('mdast').Root} Root\n * @typedef {import('mdast-util-from-markdown').Options} FromMarkdownOptions\n * @typedef {import('unified').Parser<Root>} Parser\n * @typedef {import('unified').Processor<Root>} Processor\n */\n\n/**\n * @typedef {Omit<FromMarkdownOptions, 'extensions' | 'mdastExtensions'>} Options\n */\n\nimport {fromMarkdown} from 'mdast-util-from-markdown'\n\n/**\n * Aadd support for parsing from markdown.\n *\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function remarkParse(options) {\n  /** @type {Processor} */\n  // @ts-expect-error: TS in JSDoc generates wrong types if `this` is typed regularly.\n  const self = this\n\n  self.parser = parser\n\n  /**\n   * @type {Parser}\n   */\n  function parser(doc) {\n    return fromMarkdown(doc, {\n      ...self.data('settings'),\n      ...options,\n      // Note: these options are not in the readme.\n      // The goal is for them to be set by plugins on `data` instead of being\n      // passed by users.\n      extensions: self.data('micromarkExtensions') || [],\n      mdastExtensions: self.data('fromMarkdownExtensions') || []\n    })\n  }\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Blockquote} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `blockquote` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Blockquote} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function blockquote(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'blockquote',\n    properties: {},\n    children: state.wrap(state.all(node), true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Text} from 'hast'\n * @import {Break} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `break` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Break} node\n *   mdast node.\n * @returns {Array<Element | Text>}\n *   hast element content.\n */\nexport function hardBreak(state, node) {\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'br', properties: {}, children: []}\n  state.patch(node, result)\n  return [state.applyData(node, result), {type: 'text', value: '\\n'}]\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {Code} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `code` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Code} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function code(state, node) {\n  const value = node.value ? node.value + '\\n' : ''\n  /** @type {Properties} */\n  const properties = {}\n  // Someone can write `js&#x20;python&#x9;ruby`.\n  const language = node.lang ? node.lang.split(/\\s+/) : []\n\n  // GH/CM still drop the non-first languages.\n  if (language.length > 0) {\n    properties.className = ['language-' + language[0]]\n  }\n\n  // Create `<code>`.\n  /** @type {Element} */\n  let result = {\n    type: 'element',\n    tagName: 'code',\n    properties,\n    children: [{type: 'text', value}]\n  }\n\n  if (node.meta) {\n    result.data = {meta: node.meta}\n  }\n\n  state.patch(node, result)\n  result = state.applyData(node, result)\n\n  // Create `<pre>`.\n  result = {type: 'element', tagName: 'pre', properties: {}, children: [result]}\n  state.patch(node, result)\n  return result\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Delete} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `delete` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Delete} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function strikethrough(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'del',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Emphasis} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `emphasis` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Emphasis} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function emphasis(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'em',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {FootnoteReference} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Turn an mdast `footnoteReference` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {FootnoteReference} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function footnoteReference(state, node) {\n  const clobberPrefix =\n    typeof state.options.clobberPrefix === 'string'\n      ? state.options.clobberPrefix\n      : 'user-content-'\n  const id = String(node.identifier).toUpperCase()\n  const safeId = normalizeUri(id.toLowerCase())\n  const index = state.footnoteOrder.indexOf(id)\n  /** @type {number} */\n  let counter\n\n  let reuseCounter = state.footnoteCounts.get(id)\n\n  if (reuseCounter === undefined) {\n    reuseCounter = 0\n    state.footnoteOrder.push(id)\n    counter = state.footnoteOrder.length\n  } else {\n    counter = index + 1\n  }\n\n  reuseCounter += 1\n  state.footnoteCounts.set(id, reuseCounter)\n\n  /** @type {Element} */\n  const link = {\n    type: 'element',\n    tagName: 'a',\n    properties: {\n      href: '#' + clobberPrefix + 'fn-' + safeId,\n      id:\n        clobberPrefix +\n        'fnref-' +\n        safeId +\n        (reuseCounter > 1 ? '-' + reuseCounter : ''),\n      dataFootnoteRef: true,\n      ariaDescribedBy: ['footnote-label']\n    },\n    children: [{type: 'text', value: String(counter)}]\n  }\n  state.patch(node, link)\n\n  /** @type {Element} */\n  const sup = {\n    type: 'element',\n    tagName: 'sup',\n    properties: {},\n    children: [link]\n  }\n  state.patch(node, sup)\n  return state.applyData(node, sup)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Heading} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `heading` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Heading} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function heading(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'h' + node.depth,\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Html} from 'mdast'\n * @import {State} from '../state.js'\n * @import {Raw} from '../../index.js'\n */\n\n/**\n * Turn an mdast `html` node into hast (`raw` node in dangerous mode, otherwise\n * nothing).\n *\n * @param {State} state\n *   Info passed around.\n * @param {Html} node\n *   mdast node.\n * @returns {Element | Raw | undefined}\n *   hast node.\n */\nexport function html(state, node) {\n  if (state.options.allowDangerousHtml) {\n    /** @type {Raw} */\n    const result = {type: 'raw', value: node.value}\n    state.patch(node, result)\n    return state.applyData(node, result)\n  }\n\n  return undefined\n}\n","/**\n * @import {ElementContent} from 'hast'\n * @import {Reference, Nodes} from 'mdast'\n * @import {State} from './state.js'\n */\n\n/**\n * Return the content of a reference without definition as plain text.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Extract<Nodes, Reference>} node\n *   Reference node (image, link).\n * @returns {Array<ElementContent>}\n *   hast content.\n */\nexport function revert(state, node) {\n  const subtype = node.referenceType\n  let suffix = ']'\n\n  if (subtype === 'collapsed') {\n    suffix += '[]'\n  } else if (subtype === 'full') {\n    suffix += '[' + (node.label || node.identifier) + ']'\n  }\n\n  if (node.type === 'imageReference') {\n    return [{type: 'text', value: '![' + node.alt + suffix}]\n  }\n\n  const contents = state.all(node)\n  const head = contents[0]\n\n  if (head && head.type === 'text') {\n    head.value = '[' + head.value\n  } else {\n    contents.unshift({type: 'text', value: '['})\n  }\n\n  const tail = contents[contents.length - 1]\n\n  if (tail && tail.type === 'text') {\n    tail.value += suffix\n  } else {\n    contents.push({type: 'text', value: suffix})\n  }\n\n  return contents\n}\n","/**\n * @import {ElementContent, Element, Properties} from 'hast'\n * @import {ImageReference} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\nimport {revert} from '../revert.js'\n\n/**\n * Turn an mdast `imageReference` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {ImageReference} node\n *   mdast node.\n * @returns {Array<ElementContent> | ElementContent}\n *   hast node.\n */\nexport function imageReference(state, node) {\n  const id = String(node.identifier).toUpperCase()\n  const definition = state.definitionById.get(id)\n\n  if (!definition) {\n    return revert(state, node)\n  }\n\n  /** @type {Properties} */\n  const properties = {src: normalizeUri(definition.url || ''), alt: node.alt}\n\n  if (definition.title !== null && definition.title !== undefined) {\n    properties.title = definition.title\n  }\n\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'img', properties, children: []}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {Image} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Turn an mdast `image` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Image} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function image(state, node) {\n  /** @type {Properties} */\n  const properties = {src: normalizeUri(node.url)}\n\n  if (node.alt !== null && node.alt !== undefined) {\n    properties.alt = node.alt\n  }\n\n  if (node.title !== null && node.title !== undefined) {\n    properties.title = node.title\n  }\n\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'img', properties, children: []}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Text} from 'hast'\n * @import {InlineCode} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `inlineCode` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {InlineCode} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function inlineCode(state, node) {\n  /** @type {Text} */\n  const text = {type: 'text', value: node.value.replace(/\\r?\\n|\\r/g, ' ')}\n  state.patch(node, text)\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'code',\n    properties: {},\n    children: [text]\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {ElementContent, Element, Properties} from 'hast'\n * @import {LinkReference} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\nimport {revert} from '../revert.js'\n\n/**\n * Turn an mdast `linkReference` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {LinkReference} node\n *   mdast node.\n * @returns {Array<ElementContent> | ElementContent}\n *   hast node.\n */\nexport function linkReference(state, node) {\n  const id = String(node.identifier).toUpperCase()\n  const definition = state.definitionById.get(id)\n\n  if (!definition) {\n    return revert(state, node)\n  }\n\n  /** @type {Properties} */\n  const properties = {href: normalizeUri(definition.url || '')}\n\n  if (definition.title !== null && definition.title !== undefined) {\n    properties.title = definition.title\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'a',\n    properties,\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {Link} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Turn an mdast `link` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Link} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function link(state, node) {\n  /** @type {Properties} */\n  const properties = {href: normalizeUri(node.url)}\n\n  if (node.title !== null && node.title !== undefined) {\n    properties.title = node.title\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'a',\n    properties,\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {ElementContent, Element, Properties} from 'hast'\n * @import {ListItem, Parents} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `listItem` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {ListItem} node\n *   mdast node.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @returns {Element}\n *   hast node.\n */\nexport function listItem(state, node, parent) {\n  const results = state.all(node)\n  const loose = parent ? listLoose(parent) : listItemLoose(node)\n  /** @type {Properties} */\n  const properties = {}\n  /** @type {Array<ElementContent>} */\n  const children = []\n\n  if (typeof node.checked === 'boolean') {\n    const head = results[0]\n    /** @type {Element} */\n    let paragraph\n\n    if (head && head.type === 'element' && head.tagName === 'p') {\n      paragraph = head\n    } else {\n      paragraph = {type: 'element', tagName: 'p', properties: {}, children: []}\n      results.unshift(paragraph)\n    }\n\n    if (paragraph.children.length > 0) {\n      paragraph.children.unshift({type: 'text', value: ' '})\n    }\n\n    paragraph.children.unshift({\n      type: 'element',\n      tagName: 'input',\n      properties: {type: 'checkbox', checked: node.checked, disabled: true},\n      children: []\n    })\n\n    // According to github-markdown-css, this class hides bullet.\n    // See: <https://github.com/sindresorhus/github-markdown-css>.\n    properties.className = ['task-list-item']\n  }\n\n  let index = -1\n\n  while (++index < results.length) {\n    const child = results[index]\n\n    // Add eols before nodes, except if this is a loose, first paragraph.\n    if (\n      loose ||\n      index !== 0 ||\n      child.type !== 'element' ||\n      child.tagName !== 'p'\n    ) {\n      children.push({type: 'text', value: '\\n'})\n    }\n\n    if (child.type === 'element' && child.tagName === 'p' && !loose) {\n      children.push(...child.children)\n    } else {\n      children.push(child)\n    }\n  }\n\n  const tail = results[results.length - 1]\n\n  // Add a final eol.\n  if (tail && (loose || tail.type !== 'element' || tail.tagName !== 'p')) {\n    children.push({type: 'text', value: '\\n'})\n  }\n\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'li', properties, children}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n\n/**\n * @param {Parents} node\n * @return {Boolean}\n */\nfunction listLoose(node) {\n  let loose = false\n  if (node.type === 'list') {\n    loose = node.spread || false\n    const children = node.children\n    let index = -1\n\n    while (!loose && ++index < children.length) {\n      loose = listItemLoose(children[index])\n    }\n  }\n\n  return loose\n}\n\n/**\n * @param {ListItem} node\n * @return {Boolean}\n */\nfunction listItemLoose(node) {\n  const spread = node.spread\n\n  return spread === null || spread === undefined\n    ? node.children.length > 1\n    : spread\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {List} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `list` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {List} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function list(state, node) {\n  /** @type {Properties} */\n  const properties = {}\n  const results = state.all(node)\n  let index = -1\n\n  if (typeof node.start === 'number' && node.start !== 1) {\n    properties.start = node.start\n  }\n\n  // Like GitHub, add a class for custom styling.\n  while (++index < results.length) {\n    const child = results[index]\n\n    if (\n      child.type === 'element' &&\n      child.tagName === 'li' &&\n      child.properties &&\n      Array.isArray(child.properties.className) &&\n      child.properties.className.includes('task-list-item')\n    ) {\n      properties.className = ['contains-task-list']\n      break\n    }\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: node.ordered ? 'ol' : 'ul',\n    properties,\n    children: state.wrap(results, true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Paragraph} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `paragraph` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Paragraph} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function paragraph(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'p',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Parents as HastParents, Root as HastRoot} from 'hast'\n * @import {Root as MdastRoot} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `root` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdastRoot} node\n *   mdast node.\n * @returns {HastParents}\n *   hast node.\n */\nexport function root(state, node) {\n  /** @type {HastRoot} */\n  const result = {type: 'root', children: state.wrap(state.all(node))}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Strong} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `strong` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Strong} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function strong(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'strong',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Table} from 'mdast'\n * @import {Element} from 'hast'\n * @import {State} from '../state.js'\n */\n\nimport {pointEnd, pointStart} from 'unist-util-position'\n\n/**\n * Turn an mdast `table` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Table} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function table(state, node) {\n  const rows = state.all(node)\n  const firstRow = rows.shift()\n  /** @type {Array<Element>} */\n  const tableContent = []\n\n  if (firstRow) {\n    /** @type {Element} */\n    const head = {\n      type: 'element',\n      tagName: 'thead',\n      properties: {},\n      children: state.wrap([firstRow], true)\n    }\n    state.patch(node.children[0], head)\n    tableContent.push(head)\n  }\n\n  if (rows.length > 0) {\n    /** @type {Element} */\n    const body = {\n      type: 'element',\n      tagName: 'tbody',\n      properties: {},\n      children: state.wrap(rows, true)\n    }\n\n    const start = pointStart(node.children[1])\n    const end = pointEnd(node.children[node.children.length - 1])\n    if (start && end) body.position = {start, end}\n    tableContent.push(body)\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'table',\n    properties: {},\n    children: state.wrap(tableContent, true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, ElementContent, Properties} from 'hast'\n * @import {Parents, TableRow} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `tableRow` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {TableRow} node\n *   mdast node.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @returns {Element}\n *   hast node.\n */\nexport function tableRow(state, node, parent) {\n  const siblings = parent ? parent.children : undefined\n  // Generate a body row when without parent.\n  const rowIndex = siblings ? siblings.indexOf(node) : 1\n  const tagName = rowIndex === 0 ? 'th' : 'td'\n  // To do: option to use `style`?\n  const align = parent && parent.type === 'table' ? parent.align : undefined\n  const length = align ? align.length : node.children.length\n  let cellIndex = -1\n  /** @type {Array<ElementContent>} */\n  const cells = []\n\n  while (++cellIndex < length) {\n    // Note: can also be undefined.\n    const cell = node.children[cellIndex]\n    /** @type {Properties} */\n    const properties = {}\n    const alignValue = align ? align[cellIndex] : undefined\n\n    if (alignValue) {\n      properties.align = alignValue\n    }\n\n    /** @type {Element} */\n    let result = {type: 'element', tagName, properties, children: []}\n\n    if (cell) {\n      result.children = state.all(cell)\n      state.patch(cell, result)\n      result = state.applyData(cell, result)\n    }\n\n    cells.push(result)\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'tr',\n    properties: {},\n    children: state.wrap(cells, true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {TableCell} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `tableCell` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {TableCell} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function tableCell(state, node) {\n  // Note: this function is normally not called: see `table-row` for how rows\n  // and their cells are compiled.\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'td', // Assume body cell.\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","const tab = 9 /* `\\t` */\nconst space = 32 /* ` ` */\n\n/**\n * Remove initial and final spaces and tabs at the line breaks in `value`.\n * Does not trim initial and final spaces and tabs of the value itself.\n *\n * @param {string} value\n *   Value to trim.\n * @returns {string}\n *   Trimmed value.\n */\nexport function trimLines(value) {\n  const source = String(value)\n  const search = /\\r?\\n|\\r/g\n  let match = search.exec(source)\n  let last = 0\n  /** @type {Array<string>} */\n  const lines = []\n\n  while (match) {\n    lines.push(\n      trimLine(source.slice(last, match.index), last > 0, true),\n      match[0]\n    )\n\n    last = match.index + match[0].length\n    match = search.exec(source)\n  }\n\n  lines.push(trimLine(source.slice(last), last > 0, false))\n\n  return lines.join('')\n}\n\n/**\n * @param {string} value\n *   Line to trim.\n * @param {boolean} start\n *   Whether to trim the start of the line.\n * @param {boolean} end\n *   Whether to trim the end of the line.\n * @returns {string}\n *   Trimmed line.\n */\nfunction trimLine(value, start, end) {\n  let startIndex = 0\n  let endIndex = value.length\n\n  if (start) {\n    let code = value.codePointAt(startIndex)\n\n    while (code === tab || code === space) {\n      startIndex++\n      code = value.codePointAt(startIndex)\n    }\n  }\n\n  if (end) {\n    let code = value.codePointAt(endIndex - 1)\n\n    while (code === tab || code === space) {\n      endIndex--\n      code = value.codePointAt(endIndex - 1)\n    }\n  }\n\n  return endIndex > startIndex ? value.slice(startIndex, endIndex) : ''\n}\n","/**\n * @import {Element as HastElement, Text as HastText} from 'hast'\n * @import {Text as MdastText} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {trimLines} from 'trim-lines'\n\n/**\n * Turn an mdast `text` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdastText} node\n *   mdast node.\n * @returns {HastElement | HastText}\n *   hast node.\n */\nexport function text(state, node) {\n  /** @type {HastText} */\n  const result = {type: 'text', value: trimLines(String(node.value))}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {ThematicBreak} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `thematicBreak` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {ThematicBreak} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function thematicBreak(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'hr',\n    properties: {},\n    children: []\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Handlers} from '../state.js'\n */\n\nimport {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {strikethrough} from './delete.js'\nimport {emphasis} from './emphasis.js'\nimport {footnoteReference} from './footnote-reference.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {imageReference} from './image-reference.js'\nimport {image} from './image.js'\nimport {inlineCode} from './inline-code.js'\nimport {linkReference} from './link-reference.js'\nimport {link} from './link.js'\nimport {listItem} from './list-item.js'\nimport {list} from './list.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {table} from './table.js'\nimport {tableRow} from './table-row.js'\nimport {tableCell} from './table-cell.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\n/**\n * Default handlers for nodes.\n *\n * @satisfies {Handlers}\n */\nexport const handlers = {\n  blockquote,\n  break: hardBreak,\n  code,\n  delete: strikethrough,\n  emphasis,\n  footnoteReference,\n  heading,\n  html,\n  imageReference,\n  image,\n  inlineCode,\n  linkReference,\n  link,\n  listItem,\n  list,\n  paragraph,\n  // @ts-expect-error: root is different, but hard to type.\n  root,\n  strong,\n  table,\n  tableCell,\n  tableRow,\n  text,\n  thematicBreak,\n  toml: ignore,\n  yaml: ignore,\n  definition: ignore,\n  footnoteDefinition: ignore\n}\n\n// Return nothing for nodes that are ignored.\nfunction ignore() {\n  return undefined\n}\n","export const VOID       = -1;\nexport const PRIMITIVE  = 0;\nexport const ARRAY      = 1;\nexport const OBJECT     = 2;\nexport const DATE       = 3;\nexport const REGEXP     = 4;\nexport const MAP        = 5;\nexport const SET        = 6;\nexport const ERROR      = 7;\nexport const BIGINT     = 8;\n// export const SYMBOL = 9;\n","import {\n  VOID, PRIMITIVE,\n  ARRAY, OBJECT,\n  DATE, REGEXP, MAP, SET,\n  ERROR, BIGINT\n} from './types.js';\n\nconst env = typeof self === 'object' ? self : globalThis;\n\nconst deserializer = ($, _) => {\n  const as = (out, index) => {\n    $.set(index, out);\n    return out;\n  };\n\n  const unpair = index => {\n    if ($.has(index))\n      return $.get(index);\n\n    const [type, value] = _[index];\n    switch (type) {\n      case PRIMITIVE:\n      case VOID:\n        return as(value, index);\n      case ARRAY: {\n        const arr = as([], index);\n        for (const index of value)\n          arr.push(unpair(index));\n        return arr;\n      }\n      case OBJECT: {\n        const object = as({}, index);\n        for (const [key, index] of value)\n          object[unpair(key)] = unpair(index);\n        return object;\n      }\n      case DATE:\n        return as(new Date(value), index);\n      case REGEXP: {\n        const {source, flags} = value;\n        return as(new RegExp(source, flags), index);\n      }\n      case MAP: {\n        const map = as(new Map, index);\n        for (const [key, index] of value)\n          map.set(unpair(key), unpair(index));\n        return map;\n      }\n      case SET: {\n        const set = as(new Set, index);\n        for (const index of value)\n          set.add(unpair(index));\n        return set;\n      }\n      case ERROR: {\n        const {name, message} = value;\n        return as(new env[name](message), index);\n      }\n      case BIGINT:\n        return as(BigInt(value), index);\n      case 'BigInt':\n        return as(Object(BigInt(value)), index);\n      case 'ArrayBuffer':\n        return as(new Uint8Array(value).buffer, value);\n      case 'DataView': {\n        const { buffer } = new Uint8Array(value);\n        return as(new DataView(buffer), value);\n      }\n    }\n    return as(new env[type](value), index);\n  };\n\n  return unpair;\n};\n\n/**\n * @typedef {Array<string,any>} Record a type representation\n */\n\n/**\n * Returns a deserialized value from a serialized array of Records.\n * @param {Record[]} serialized a previously serialized value.\n * @returns {any}\n */\nexport const deserialize = serialized => deserializer(new Map, serialized)(0);\n","import {\n  VOID, PRIMITIVE,\n  ARRAY, OBJECT,\n  DATE, REGEXP, MAP, SET,\n  ERROR, BIGINT\n} from './types.js';\n\nconst EMPTY = '';\n\nconst {toString} = {};\nconst {keys} = Object;\n\nconst typeOf = value => {\n  const type = typeof value;\n  if (type !== 'object' || !value)\n    return [PRIMITIVE, type];\n\n  const asString = toString.call(value).slice(8, -1);\n  switch (asString) {\n    case 'Array':\n      return [ARRAY, EMPTY];\n    case 'Object':\n      return [OBJECT, EMPTY];\n    case 'Date':\n      return [DATE, EMPTY];\n    case 'RegExp':\n      return [REGEXP, EMPTY];\n    case 'Map':\n      return [MAP, EMPTY];\n    case 'Set':\n      return [SET, EMPTY];\n    case 'DataView':\n      return [ARRAY, asString];\n  }\n\n  if (asString.includes('Array'))\n    return [ARRAY, asString];\n\n  if (asString.includes('Error'))\n    return [ERROR, asString];\n\n  return [OBJECT, asString];\n};\n\nconst shouldSkip = ([TYPE, type]) => (\n  TYPE === PRIMITIVE &&\n  (type === 'function' || type === 'symbol')\n);\n\nconst serializer = (strict, json, $, _) => {\n\n  const as = (out, value) => {\n    const index = _.push(out) - 1;\n    $.set(value, index);\n    return index;\n  };\n\n  const pair = value => {\n    if ($.has(value))\n      return $.get(value);\n\n    let [TYPE, type] = typeOf(value);\n    switch (TYPE) {\n      case PRIMITIVE: {\n        let entry = value;\n        switch (type) {\n          case 'bigint':\n            TYPE = BIGINT;\n            entry = value.toString();\n            break;\n          case 'function':\n          case 'symbol':\n            if (strict)\n              throw new TypeError('unable to serialize ' + type);\n            entry = null;\n            break;\n          case 'undefined':\n            return as([VOID], value);\n        }\n        return as([TYPE, entry], value);\n      }\n      case ARRAY: {\n        if (type) {\n          let spread = value;\n          if (type === 'DataView') {\n            spread = new Uint8Array(value.buffer);\n          }\n          else if (type === 'ArrayBuffer') {\n            spread = new Uint8Array(value);\n          }\n          return as([type, [...spread]], value);\n        }\n\n        const arr = [];\n        const index = as([TYPE, arr], value);\n        for (const entry of value)\n          arr.push(pair(entry));\n        return index;\n      }\n      case OBJECT: {\n        if (type) {\n          switch (type) {\n            case 'BigInt':\n              return as([type, value.toString()], value);\n            case 'Boolean':\n            case 'Number':\n            case 'String':\n              return as([type, value.valueOf()], value);\n          }\n        }\n\n        if (json && ('toJSON' in value))\n          return pair(value.toJSON());\n\n        const entries = [];\n        const index = as([TYPE, entries], value);\n        for (const key of keys(value)) {\n          if (strict || !shouldSkip(typeOf(value[key])))\n            entries.push([pair(key), pair(value[key])]);\n        }\n        return index;\n      }\n      case DATE:\n        return as([TYPE, value.toISOString()], value);\n      case REGEXP: {\n        const {source, flags} = value;\n        return as([TYPE, {source, flags}], value);\n      }\n      case MAP: {\n        const entries = [];\n        const index = as([TYPE, entries], value);\n        for (const [key, entry] of value) {\n          if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))\n            entries.push([pair(key), pair(entry)]);\n        }\n        return index;\n      }\n      case SET: {\n        const entries = [];\n        const index = as([TYPE, entries], value);\n        for (const entry of value) {\n          if (strict || !shouldSkip(typeOf(entry)))\n            entries.push(pair(entry));\n        }\n        return index;\n      }\n    }\n\n    const {message} = value;\n    return as([TYPE, {name: type, message}], value);\n  };\n\n  return pair;\n};\n\n/**\n * @typedef {Array<string,any>} Record a type representation\n */\n\n/**\n * Returns an array of serialized Records.\n * @param {any} value a serializable value.\n * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,\n *  if `true`, will not throw errors on incompatible types, and behave more\n *  like JSON stringify would behave. Symbol and Function will be discarded.\n * @returns {Record[]}\n */\n export const serialize = (value, {json, lossy} = {}) => {\n  const _ = [];\n  return serializer(!(json || lossy), !!json, new Map, _)(value), _;\n};\n","import {deserialize} from './deserialize.js';\nimport {serialize} from './serialize.js';\n\n/**\n * @typedef {Array<string,any>} Record a type representation\n */\n\n/**\n * Returns an array of serialized Records.\n * @param {any} any a serializable value.\n * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with\n * a transfer option (ignored when polyfilled) and/or non standard fields that\n * fallback to the polyfill if present.\n * @returns {Record[]}\n */\nexport default typeof structuredClone === \"function\" ?\n  /* c8 ignore start */\n  (any, options) => (\n    options && ('json' in options || 'lossy' in options) ?\n      deserialize(serialize(any, options)) : structuredClone(any)\n  ) :\n  (any, options) => deserialize(serialize(any, options));\n  /* c8 ignore stop */\n\nexport {deserialize, serialize};\n","/**\n * @import {ElementContent, Element} from 'hast'\n * @import {State} from './state.js'\n */\n\n/**\n * @callback FootnoteBackContentTemplate\n *   Generate content for the backreference dynamically.\n *\n *   For the following markdown:\n *\n *   ```markdown\n *   Alpha[^micromark], bravo[^micromark], and charlie[^remark].\n *\n *   [^remark]: things about remark\n *   [^micromark]: things about micromark\n *   ```\n *\n *   This function will be called with:\n *\n *   *  `0` and `0` for the backreference from `things about micromark` to\n *      `alpha`, as it is the first used definition, and the first call to it\n *   *  `0` and `1` for the backreference from `things about micromark` to\n *      `bravo`, as it is the first used definition, and the second call to it\n *   *  `1` and `0` for the backreference from `things about remark` to\n *      `charlie`, as it is the second used definition\n * @param {number} referenceIndex\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {Array<ElementContent> | ElementContent | string}\n *   Content for the backreference when linking back from definitions to their\n *   reference.\n *\n * @callback FootnoteBackLabelTemplate\n *   Generate a back label dynamically.\n *\n *   For the following markdown:\n *\n *   ```markdown\n *   Alpha[^micromark], bravo[^micromark], and charlie[^remark].\n *\n *   [^remark]: things about remark\n *   [^micromark]: things about micromark\n *   ```\n *\n *   This function will be called with:\n *\n *   *  `0` and `0` for the backreference from `things about micromark` to\n *      `alpha`, as it is the first used definition, and the first call to it\n *   *  `0` and `1` for the backreference from `things about micromark` to\n *      `bravo`, as it is the first used definition, and the second call to it\n *   *  `1` and `0` for the backreference from `things about remark` to\n *      `charlie`, as it is the second used definition\n * @param {number} referenceIndex\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {string}\n *   Back label to use when linking back from definitions to their reference.\n */\n\nimport structuredClone from '@ungap/structured-clone'\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Generate the default content that GitHub uses on backreferences.\n *\n * @param {number} _\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {Array<ElementContent>}\n *   Content.\n */\nexport function defaultFootnoteBackContent(_, rereferenceIndex) {\n  /** @type {Array<ElementContent>} */\n  const result = [{type: 'text', value: '↩'}]\n\n  if (rereferenceIndex > 1) {\n    result.push({\n      type: 'element',\n      tagName: 'sup',\n      properties: {},\n      children: [{type: 'text', value: String(rereferenceIndex)}]\n    })\n  }\n\n  return result\n}\n\n/**\n * Generate the default label that GitHub uses on backreferences.\n *\n * @param {number} referenceIndex\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {string}\n *   Label.\n */\nexport function defaultFootnoteBackLabel(referenceIndex, rereferenceIndex) {\n  return (\n    'Back to reference ' +\n    (referenceIndex + 1) +\n    (rereferenceIndex > 1 ? '-' + rereferenceIndex : '')\n  )\n}\n\n/**\n * Generate a hast footer for called footnote definitions.\n *\n * @param {State} state\n *   Info passed around.\n * @returns {Element | undefined}\n *   `section` element or `undefined`.\n */\n// eslint-disable-next-line complexity\nexport function footer(state) {\n  const clobberPrefix =\n    typeof state.options.clobberPrefix === 'string'\n      ? state.options.clobberPrefix\n      : 'user-content-'\n  const footnoteBackContent =\n    state.options.footnoteBackContent || defaultFootnoteBackContent\n  const footnoteBackLabel =\n    state.options.footnoteBackLabel || defaultFootnoteBackLabel\n  const footnoteLabel = state.options.footnoteLabel || 'Footnotes'\n  const footnoteLabelTagName = state.options.footnoteLabelTagName || 'h2'\n  const footnoteLabelProperties = state.options.footnoteLabelProperties || {\n    className: ['sr-only']\n  }\n  /** @type {Array<ElementContent>} */\n  const listItems = []\n  let referenceIndex = -1\n\n  while (++referenceIndex < state.footnoteOrder.length) {\n    const definition = state.footnoteById.get(\n      state.footnoteOrder[referenceIndex]\n    )\n\n    if (!definition) {\n      continue\n    }\n\n    const content = state.all(definition)\n    const id = String(definition.identifier).toUpperCase()\n    const safeId = normalizeUri(id.toLowerCase())\n    let rereferenceIndex = 0\n    /** @type {Array<ElementContent>} */\n    const backReferences = []\n    const counts = state.footnoteCounts.get(id)\n\n    // eslint-disable-next-line no-unmodified-loop-condition\n    while (counts !== undefined && ++rereferenceIndex <= counts) {\n      if (backReferences.length > 0) {\n        backReferences.push({type: 'text', value: ' '})\n      }\n\n      let children =\n        typeof footnoteBackContent === 'string'\n          ? footnoteBackContent\n          : footnoteBackContent(referenceIndex, rereferenceIndex)\n\n      if (typeof children === 'string') {\n        children = {type: 'text', value: children}\n      }\n\n      backReferences.push({\n        type: 'element',\n        tagName: 'a',\n        properties: {\n          href:\n            '#' +\n            clobberPrefix +\n            'fnref-' +\n            safeId +\n            (rereferenceIndex > 1 ? '-' + rereferenceIndex : ''),\n          dataFootnoteBackref: '',\n          ariaLabel:\n            typeof footnoteBackLabel === 'string'\n              ? footnoteBackLabel\n              : footnoteBackLabel(referenceIndex, rereferenceIndex),\n          className: ['data-footnote-backref']\n        },\n        children: Array.isArray(children) ? children : [children]\n      })\n    }\n\n    const tail = content[content.length - 1]\n\n    if (tail && tail.type === 'element' && tail.tagName === 'p') {\n      const tailTail = tail.children[tail.children.length - 1]\n      if (tailTail && tailTail.type === 'text') {\n        tailTail.value += ' '\n      } else {\n        tail.children.push({type: 'text', value: ' '})\n      }\n\n      tail.children.push(...backReferences)\n    } else {\n      content.push(...backReferences)\n    }\n\n    /** @type {Element} */\n    const listItem = {\n      type: 'element',\n      tagName: 'li',\n      properties: {id: clobberPrefix + 'fn-' + safeId},\n      children: state.wrap(content, true)\n    }\n\n    state.patch(definition, listItem)\n\n    listItems.push(listItem)\n  }\n\n  if (listItems.length === 0) {\n    return\n  }\n\n  return {\n    type: 'element',\n    tagName: 'section',\n    properties: {dataFootnotes: true, className: ['footnotes']},\n    children: [\n      {\n        type: 'element',\n        tagName: footnoteLabelTagName,\n        properties: {\n          ...structuredClone(footnoteLabelProperties),\n          id: 'footnote-label'\n        },\n        children: [{type: 'text', value: footnoteLabel}]\n      },\n      {type: 'text', value: '\\n'},\n      {\n        type: 'element',\n        tagName: 'ol',\n        properties: {},\n        children: state.wrap(listItems, true)\n      },\n      {type: 'text', value: '\\n'}\n    ]\n  }\n}\n","/**\n * @import {Node, Parent} from 'unist'\n */\n\n/**\n * @template Fn\n * @template Fallback\n * @typedef {Fn extends (value: any) => value is infer Thing ? Thing : Fallback} Predicate\n */\n\n/**\n * @callback Check\n *   Check that an arbitrary value is a node.\n * @param {unknown} this\n *   The given context.\n * @param {unknown} [node]\n *   Anything (typically a node).\n * @param {number | null | undefined} [index]\n *   The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n *   The node’s parent.\n * @returns {boolean}\n *   Whether this is a node and passes a test.\n *\n * @typedef {Record<string, unknown> | Node} Props\n *   Object to check for equivalence.\n *\n *   Note: `Node` is included as it is common but is not indexable.\n *\n * @typedef {Array<Props | TestFunction | string> | ReadonlyArray<Props | TestFunction | string> | Props | TestFunction | string | null | undefined} Test\n *   Check for an arbitrary node.\n *\n * @callback TestFunction\n *   Check if a node passes a test.\n * @param {unknown} this\n *   The given context.\n * @param {Node} node\n *   A node.\n * @param {number | undefined} [index]\n *   The node’s position in its parent.\n * @param {Parent | undefined} [parent]\n *   The node’s parent.\n * @returns {boolean | undefined | void}\n *   Whether this node passes the test.\n *\n *   Note: `void` is included until TS sees no return as `undefined`.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param {unknown} node\n *   Thing to check, typically `Node`.\n * @param {Test} test\n *   A check for a specific node.\n * @param {number | null | undefined} index\n *   The node’s position in its parent.\n * @param {Parent | null | undefined} parent\n *   The node’s parent.\n * @param {unknown} context\n *   Context object (`this`) to pass to `test` functions.\n * @returns {boolean}\n *   Whether `node` is a node and passes a test.\n */\nexport const is =\n  // Note: overloads in JSDoc can’t yet use different `@template`s.\n  /**\n   * @type {(\n   *   (<Condition extends ReadonlyArray<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n   *   (<Condition extends Array<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n   *   (<Condition extends string>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n   *   (<Condition extends Props>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n   *   (<Condition extends TestFunction>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n   *   ((node?: null | undefined) => false) &\n   *   ((node: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n   *   ((node: unknown, test?: Test, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => boolean)\n   * )}\n   */\n  (\n    /**\n     * @param {unknown} [node]\n     * @param {Test} [test]\n     * @param {number | null | undefined} [index]\n     * @param {Parent | null | undefined} [parent]\n     * @param {unknown} [context]\n     * @returns {boolean}\n     */\n    // eslint-disable-next-line max-params\n    function (node, test, index, parent, context) {\n      const check = convert(test)\n\n      if (\n        index !== undefined &&\n        index !== null &&\n        (typeof index !== 'number' ||\n          index < 0 ||\n          index === Number.POSITIVE_INFINITY)\n      ) {\n        throw new Error('Expected positive finite index')\n      }\n\n      if (\n        parent !== undefined &&\n        parent !== null &&\n        (!is(parent) || !parent.children)\n      ) {\n        throw new Error('Expected parent node')\n      }\n\n      if (\n        (parent === undefined || parent === null) !==\n        (index === undefined || index === null)\n      ) {\n        throw new Error('Expected both parent and index')\n      }\n\n      return looksLikeANode(node)\n        ? check.call(context, node, index, parent)\n        : false\n    }\n  )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param {Test} test\n *   *   when nullish, checks if `node` is a `Node`.\n *   *   when `string`, works like passing `(node) => node.type === test`.\n *   *   when `function` checks if function passed the node is true.\n *   *   when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n *   *   when `array`, checks if any one of the subtests pass.\n * @returns {Check}\n *   An assertion.\n */\nexport const convert =\n  // Note: overloads in JSDoc can’t yet use different `@template`s.\n  /**\n   * @type {(\n   *   (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n   *   (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n   *   (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n   *   ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n   *   ((test?: Test) => Check)\n   * )}\n   */\n  (\n    /**\n     * @param {Test} [test]\n     * @returns {Check}\n     */\n    function (test) {\n      if (test === null || test === undefined) {\n        return ok\n      }\n\n      if (typeof test === 'function') {\n        return castFactory(test)\n      }\n\n      if (typeof test === 'object') {\n        return Array.isArray(test)\n          ? anyFactory(test)\n          : // Cast because `ReadonlyArray` goes into the above but `isArray`\n            // narrows to `Array`.\n            propertiesFactory(/** @type {Props} */ (test))\n      }\n\n      if (typeof test === 'string') {\n        return typeFactory(test)\n      }\n\n      throw new Error('Expected function, string, or object as test')\n    }\n  )\n\n/**\n * @param {Array<Props | TestFunction | string>} tests\n * @returns {Check}\n */\nfunction anyFactory(tests) {\n  /** @type {Array<Check>} */\n  const checks = []\n  let index = -1\n\n  while (++index < tests.length) {\n    checks[index] = convert(tests[index])\n  }\n\n  return castFactory(any)\n\n  /**\n   * @this {unknown}\n   * @type {TestFunction}\n   */\n  function any(...parameters) {\n    let index = -1\n\n    while (++index < checks.length) {\n      if (checks[index].apply(this, parameters)) return true\n    }\n\n    return false\n  }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {Check}\n */\nfunction propertiesFactory(check) {\n  const checkAsRecord = /** @type {Record<string, unknown>} */ (check)\n\n  return castFactory(all)\n\n  /**\n   * @param {Node} node\n   * @returns {boolean}\n   */\n  function all(node) {\n    const nodeAsRecord = /** @type {Record<string, unknown>} */ (\n      /** @type {unknown} */ (node)\n    )\n\n    /** @type {string} */\n    let key\n\n    for (key in check) {\n      if (nodeAsRecord[key] !== checkAsRecord[key]) return false\n    }\n\n    return true\n  }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {Check}\n */\nfunction typeFactory(check) {\n  return castFactory(type)\n\n  /**\n   * @param {Node} node\n   */\n  function type(node) {\n    return node && node.type === check\n  }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunction} testFunction\n * @returns {Check}\n */\nfunction castFactory(testFunction) {\n  return check\n\n  /**\n   * @this {unknown}\n   * @type {Check}\n   */\n  function check(value, index, parent) {\n    return Boolean(\n      looksLikeANode(value) &&\n        testFunction.call(\n          this,\n          value,\n          typeof index === 'number' ? index : undefined,\n          parent || undefined\n        )\n    )\n  }\n}\n\nfunction ok() {\n  return true\n}\n\n/**\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction looksLikeANode(value) {\n  return value !== null && typeof value === 'object' && 'type' in value\n}\n","/**\n * @import {Node as UnistNode, Parent as UnistParent} from 'unist'\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n *   Test from `unist-util-is`.\n *\n *   Note: we have remove and add `undefined`, because otherwise when generating\n *   automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n *   which doesn’t work when publishing on npm.\n */\n\n/**\n * @typedef {(\n *   Fn extends (value: any) => value is infer Thing\n *   ? Thing\n *   : Fallback\n * )} Predicate\n *   Get the value of a type guard `Fn`.\n * @template Fn\n *   Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n *   Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n *   Check extends null | undefined // No test.\n *   ? Value\n *   : Value extends {type: Check} // String (type) test.\n *   ? Value\n *   : Value extends Check // Partial test.\n *   ? Value\n *   : Check extends Function // Function test.\n *   ? Predicate<Check, Value> extends Value\n *     ? Predicate<Check, Value>\n *     : never\n *   : never // Some other test?\n * )} MatchesOne\n *   Check whether a node matches a primitive check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n *   Check extends ReadonlyArray<infer T>\n *   ? MatchesOne<Value, T>\n *   : Check extends Array<infer T>\n *   ? MatchesOne<Value, T>\n *   : MatchesOne<Value, Check>\n * )} Matches\n *   Check whether a node matches a check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n *   Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n *   Increment a number in the type system.\n * @template {Uint} [I=0]\n *   Index.\n */\n\n/**\n * @typedef {(\n *   Node extends UnistParent\n *   ? Node extends {children: Array<infer Children>}\n *     ? Child extends Children ? Node : never\n *     : never\n *   : never\n * )} InternalParent\n *   Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n *   Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {(\n *   Depth extends Max\n *   ? never\n *   :\n *     | InternalParent<Node, Child>\n *     | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n *   Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor\n *   Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Tree\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {(\n *   Tree extends UnistParent\n *     ? Depth extends Max\n *       ? Tree\n *       : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n *     : Tree\n * )} InclusiveDescendant\n *   Collect all (inclusive) descendants of `Tree`.\n *\n *   > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n *   > recurse without actually running into an infinite loop, which the\n *   > previous version did.\n *   >\n *   > Practically, a max of `2` is typically enough assuming a `Root` is\n *   > passed, but it doesn’t improve performance.\n *   > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n *   > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n *   Tree type.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @typedef {'skip' | boolean} Action\n *   Union of the action types.\n *\n * @typedef {number} Index\n *   Move to the sibling at `index` next (after node itself is completely\n *   traversed).\n *\n *   Useful if mutating the tree, such as removing the node the visitor is\n *   currently on, or any of its previous siblings.\n *   Results less than 0 or greater than or equal to `children.length` stop\n *   traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n *   List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n *   Any value that can be returned from a visitor.\n */\n\n/**\n * @callback Visitor\n *   Handle a node (matching `test`, if given).\n *\n *   Visitors are free to transform `node`.\n *   They can also transform the parent of node (the last of `ancestors`).\n *\n *   Replacing `node` itself, if `SKIP` is not returned, still causes its\n *   descendants to be walked (which is a bug).\n *\n *   When adding or removing previous siblings of `node` (or next siblings, in\n *   case of reverse), the `Visitor` should return a new `Index` to specify the\n *   sibling to traverse after `node` is traversed.\n *   Adding or removing next siblings of `node` (or previous siblings, in case\n *   of reverse) is handled as expected without needing to return a new `Index`.\n *\n *   Removing the children property of an ancestor still results in them being\n *   traversed.\n * @param {Visited} node\n *   Found node.\n * @param {Array<VisitedParents>} ancestors\n *   Ancestors of `node`.\n * @returns {VisitorResult}\n *   What to do next.\n *\n *   An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n *   An `Action` is treated as a tuple of `[Action]`.\n *\n *   Passing a tuple back only makes sense if the `Action` is `SKIP`.\n *   When the `Action` is `EXIT`, that action can be returned.\n *   When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n *   Visited node type.\n * @template {UnistParent} [VisitedParents=UnistParent]\n *   Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor\n *   Build a typed `Visitor` function from a tree and a test.\n *\n *   It will infer which values are passed as `node` and which as `parents`.\n * @template {UnistNode} [Tree=UnistNode]\n *   Tree type.\n * @template {Test} [Check=Test]\n *   Test type.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from 'unist-util-visit-parents/do-not-use-color'\n\n/** @type {Readonly<ActionTuple>} */\nconst empty = []\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n *   Tree to traverse.\n * @param {Visitor | Test} test\n *   `unist-util-is`-compatible test\n * @param {Visitor | boolean | null | undefined} [visitor]\n *   Handle each node.\n * @param {boolean | null | undefined} [reverse]\n *   Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n *   Nothing.\n *\n * @template {UnistNode} Tree\n *   Node type.\n * @template {Test} Check\n *   `unist-util-is`-compatible test.\n */\nexport function visitParents(tree, test, visitor, reverse) {\n  /** @type {Test} */\n  let check\n\n  if (typeof test === 'function' && typeof visitor !== 'function') {\n    reverse = visitor\n    // @ts-expect-error no visitor given, so `visitor` is test.\n    visitor = test\n  } else {\n    // @ts-expect-error visitor given, so `test` isn’t a visitor.\n    check = test\n  }\n\n  const is = convert(check)\n  const step = reverse ? -1 : 1\n\n  factory(tree, undefined, [])()\n\n  /**\n   * @param {UnistNode} node\n   * @param {number | undefined} index\n   * @param {Array<UnistParent>} parents\n   */\n  function factory(node, index, parents) {\n    const value = /** @type {Record<string, unknown>} */ (\n      node && typeof node === 'object' ? node : {}\n    )\n\n    if (typeof value.type === 'string') {\n      const name =\n        // `hast`\n        typeof value.tagName === 'string'\n          ? value.tagName\n          : // `xast`\n            typeof value.name === 'string'\n            ? value.name\n            : undefined\n\n      Object.defineProperty(visit, 'name', {\n        value:\n          'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n      })\n    }\n\n    return visit\n\n    function visit() {\n      /** @type {Readonly<ActionTuple>} */\n      let result = empty\n      /** @type {Readonly<ActionTuple>} */\n      let subresult\n      /** @type {number} */\n      let offset\n      /** @type {Array<UnistParent>} */\n      let grandparents\n\n      if (!test || is(node, index, parents[parents.length - 1] || undefined)) {\n        // @ts-expect-error: `visitor` is now a visitor.\n        result = toResult(visitor(node, parents))\n\n        if (result[0] === EXIT) {\n          return result\n        }\n      }\n\n      if ('children' in node && node.children) {\n        const nodeAsParent = /** @type {UnistParent} */ (node)\n\n        if (nodeAsParent.children && result[0] !== SKIP) {\n          offset = (reverse ? nodeAsParent.children.length : -1) + step\n          grandparents = parents.concat(nodeAsParent)\n\n          while (offset > -1 && offset < nodeAsParent.children.length) {\n            const child = nodeAsParent.children[offset]\n\n            subresult = factory(child, offset, grandparents)()\n\n            if (subresult[0] === EXIT) {\n              return subresult\n            }\n\n            offset =\n              typeof subresult[1] === 'number' ? subresult[1] : offset + step\n          }\n        }\n      }\n\n      return result\n    }\n  }\n}\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n *   Valid return values from visitors.\n * @returns {Readonly<ActionTuple>}\n *   Clean result.\n */\nfunction toResult(value) {\n  if (Array.isArray(value)) {\n    return value\n  }\n\n  if (typeof value === 'number') {\n    return [CONTINUE, value]\n  }\n\n  return value === null || value === undefined ? empty : [value]\n}\n","/**\n * @import {Node as UnistNode, Parent as UnistParent} from 'unist'\n * @import {VisitorResult} from 'unist-util-visit-parents'\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n *   Test from `unist-util-is`.\n *\n *   Note: we have remove and add `undefined`, because otherwise when generating\n *   automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n *   which doesn’t work when publishing on npm.\n */\n\n// To do: use types from `unist-util-visit-parents` when it’s released.\n\n/**\n * @typedef {(\n *   Fn extends (value: any) => value is infer Thing\n *   ? Thing\n *   : Fallback\n * )} Predicate\n *   Get the value of a type guard `Fn`.\n * @template Fn\n *   Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n *   Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n *   Check extends null | undefined // No test.\n *   ? Value\n *   : Value extends {type: Check} // String (type) test.\n *   ? Value\n *   : Value extends Check // Partial test.\n *   ? Value\n *   : Check extends Function // Function test.\n *   ? Predicate<Check, Value> extends Value\n *     ? Predicate<Check, Value>\n *     : never\n *   : never // Some other test?\n * )} MatchesOne\n *   Check whether a node matches a primitive check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n *   Check extends ReadonlyArray<any>\n *   ? MatchesOne<Value, Check[number]>\n *   : MatchesOne<Value, Check>\n * )} Matches\n *   Check whether a node matches a check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n *   Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n *   Increment a number in the type system.\n * @template {Uint} [I=0]\n *   Index.\n */\n\n/**\n * @typedef {(\n *   Node extends UnistParent\n *   ? Node extends {children: Array<infer Children>}\n *     ? Child extends Children ? Node : never\n *     : never\n *   : never\n * )} InternalParent\n *   Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n *   Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {(\n *   Depth extends Max\n *   ? never\n *   :\n *     | InternalParent<Node, Child>\n *     | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n *   Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @typedef {(\n *   Tree extends UnistParent\n *     ? Depth extends Max\n *       ? Tree\n *       : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n *     : Tree\n * )} InclusiveDescendant\n *   Collect all (inclusive) descendants of `Tree`.\n *\n *   > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n *   > recurse without actually running into an infinite loop, which the\n *   > previous version did.\n *   >\n *   > Practically, a max of `2` is typically enough assuming a `Root` is\n *   > passed, but it doesn’t improve performance.\n *   > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n *   > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n *   Tree type.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @callback Visitor\n *   Handle a node (matching `test`, if given).\n *\n *   Visitors are free to transform `node`.\n *   They can also transform `parent`.\n *\n *   Replacing `node` itself, if `SKIP` is not returned, still causes its\n *   descendants to be walked (which is a bug).\n *\n *   When adding or removing previous siblings of `node` (or next siblings, in\n *   case of reverse), the `Visitor` should return a new `Index` to specify the\n *   sibling to traverse after `node` is traversed.\n *   Adding or removing next siblings of `node` (or previous siblings, in case\n *   of reverse) is handled as expected without needing to return a new `Index`.\n *\n *   Removing the children property of `parent` still results in them being\n *   traversed.\n * @param {Visited} node\n *   Found node.\n * @param {Visited extends UnistNode ? number | undefined : never} index\n *   Index of `node` in `parent`.\n * @param {Ancestor extends UnistParent ? Ancestor | undefined : never} parent\n *   Parent of `node`.\n * @returns {VisitorResult}\n *   What to do next.\n *\n *   An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n *   An `Action` is treated as a tuple of `[Action]`.\n *\n *   Passing a tuple back only makes sense if the `Action` is `SKIP`.\n *   When the `Action` is `EXIT`, that action can be returned.\n *   When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n *   Visited node type.\n * @template {UnistParent} [Ancestor=UnistParent]\n *   Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Visited, Parent<Ancestor, Visited>>} BuildVisitorFromMatch\n *   Build a typed `Visitor` function from a node and all possible parents.\n *\n *   It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Visited\n *   Node type.\n * @template {UnistParent} Ancestor\n *   Parent type.\n */\n\n/**\n * @typedef {(\n *   BuildVisitorFromMatch<\n *     Matches<Descendant, Check>,\n *     Extract<Descendant, UnistParent>\n *   >\n * )} BuildVisitorFromDescendants\n *   Build a typed `Visitor` function from a list of descendants and a test.\n *\n *   It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Descendant\n *   Node type.\n * @template {Test} Check\n *   Test type.\n */\n\n/**\n * @typedef {(\n *   BuildVisitorFromDescendants<\n *     InclusiveDescendant<Tree>,\n *     Check\n *   >\n * )} BuildVisitor\n *   Build a typed `Visitor` function from a tree and a test.\n *\n *   It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} [Tree=UnistNode]\n *   Node type.\n * @template {Test} [Check=Test]\n *   Test type.\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n\n/**\n * Visit nodes.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n *   Tree to traverse.\n * @param {Visitor | Test} testOrVisitor\n *   `unist-util-is`-compatible test (optional, omit to pass a visitor).\n * @param {Visitor | boolean | null | undefined} [visitorOrReverse]\n *   Handle each node (when test is omitted, pass `reverse`).\n * @param {boolean | null | undefined} [maybeReverse=false]\n *   Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n *   Nothing.\n *\n * @template {UnistNode} Tree\n *   Node type.\n * @template {Test} Check\n *   `unist-util-is`-compatible test.\n */\nexport function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {\n  /** @type {boolean | null | undefined} */\n  let reverse\n  /** @type {Test} */\n  let test\n  /** @type {Visitor} */\n  let visitor\n\n  if (\n    typeof testOrVisitor === 'function' &&\n    typeof visitorOrReverse !== 'function'\n  ) {\n    test = undefined\n    visitor = testOrVisitor\n    reverse = visitorOrReverse\n  } else {\n    // @ts-expect-error: assume the overload with test was given.\n    test = testOrVisitor\n    // @ts-expect-error: assume the overload with test was given.\n    visitor = visitorOrReverse\n    reverse = maybeReverse\n  }\n\n  visitParents(tree, test, overload, reverse)\n\n  /**\n   * @param {UnistNode} node\n   * @param {Array<UnistParent>} parents\n   */\n  function overload(node, parents) {\n    const parent = parents[parents.length - 1]\n    const index = parent ? parent.children.indexOf(node) : undefined\n    return visitor(node, index, parent)\n  }\n}\n","/**\n * @import {\n *   ElementContent as HastElementContent,\n *   Element as HastElement,\n *   Nodes as HastNodes,\n *   Properties as HastProperties,\n *   RootContent as HastRootContent,\n *   Text as HastText\n * } from 'hast'\n * @import {\n *   Definition as MdastDefinition,\n *   FootnoteDefinition as MdastFootnoteDefinition,\n *   Nodes as MdastNodes,\n *   Parents as MdastParents\n * } from 'mdast'\n * @import {VFile} from 'vfile'\n * @import {\n *   FootnoteBackContentTemplate,\n *   FootnoteBackLabelTemplate\n * } from './footer.js'\n */\n\n/**\n * @callback Handler\n *   Handle a node.\n * @param {State} state\n *   Info passed around.\n * @param {any} node\n *   mdast node to handle.\n * @param {MdastParents | undefined} parent\n *   Parent of `node`.\n * @returns {Array<HastElementContent> | HastElementContent | undefined}\n *   hast node.\n *\n * @typedef {Partial<Record<MdastNodes['type'], Handler>>} Handlers\n *   Handle nodes.\n *\n * @typedef Options\n *   Configuration (optional).\n * @property {boolean | null | undefined} [allowDangerousHtml=false]\n *   Whether to persist raw HTML in markdown in the hast tree (default:\n *   `false`).\n * @property {string | null | undefined} [clobberPrefix='user-content-']\n *   Prefix to use before the `id` property on footnotes to prevent them from\n *   *clobbering* (default: `'user-content-'`).\n *\n *   Pass `''` for trusted markdown and when you are careful with\n *   polyfilling.\n *   You could pass a different prefix.\n *\n *   DOM clobbering is this:\n *\n *   ```html\n *   <p id=\"x\"></p>\n *   <script>alert(x) // `x` now refers to the `p#x` DOM element</script>\n *   ```\n *\n *   The above example shows that elements are made available by browsers, by\n *   their ID, on the `window` object.\n *   This is a security risk because you might be expecting some other variable\n *   at that place.\n *   It can also break polyfills.\n *   Using a prefix solves these problems.\n * @property {VFile | null | undefined} [file]\n *   Corresponding virtual file representing the input document (optional).\n * @property {FootnoteBackContentTemplate | string | null | undefined} [footnoteBackContent]\n *   Content of the backreference back to references (default: `defaultFootnoteBackContent`).\n *\n *   The default value is:\n *\n *   ```js\n *   function defaultFootnoteBackContent(_, rereferenceIndex) {\n *     const result = [{type: 'text', value: '↩'}]\n *\n *     if (rereferenceIndex > 1) {\n *       result.push({\n *         type: 'element',\n *         tagName: 'sup',\n *         properties: {},\n *         children: [{type: 'text', value: String(rereferenceIndex)}]\n *       })\n *     }\n *\n *     return result\n *   }\n *   ```\n *\n *   This content is used in the `a` element of each backreference (the `↩`\n *   links).\n * @property {FootnoteBackLabelTemplate | string | null | undefined} [footnoteBackLabel]\n *   Label to describe the backreference back to references (default:\n *   `defaultFootnoteBackLabel`).\n *\n *   The default value is:\n *\n *   ```js\n *   function defaultFootnoteBackLabel(referenceIndex, rereferenceIndex) {\n *    return (\n *      'Back to reference ' +\n *      (referenceIndex + 1) +\n *      (rereferenceIndex > 1 ? '-' + rereferenceIndex : '')\n *    )\n *   }\n *   ```\n *\n *   Change it when the markdown is not in English.\n *\n *   This label is used in the `ariaLabel` property on each backreference\n *   (the `↩` links).\n *   It affects users of assistive technology.\n * @property {string | null | undefined} [footnoteLabel='Footnotes']\n *   Textual label to use for the footnotes section (default: `'Footnotes'`).\n *\n *   Change it when the markdown is not in English.\n *\n *   This label is typically hidden visually (assuming a `sr-only` CSS class\n *   is defined that does that) and so affects screen readers only.\n *   If you do have such a class, but want to show this section to everyone,\n *   pass different properties with the `footnoteLabelProperties` option.\n * @property {HastProperties | null | undefined} [footnoteLabelProperties={className: ['sr-only']}]\n *   Properties to use on the footnote label (default: `{className:\n *   ['sr-only']}`).\n *\n *   Change it to show the label and add other properties.\n *\n *   This label is typically hidden visually (assuming an `sr-only` CSS class\n *   is defined that does that) and so affects screen readers only.\n *   If you do have such a class, but want to show this section to everyone,\n *   pass an empty string.\n *   You can also add different properties.\n *\n *   > **Note**: `id: 'footnote-label'` is always added, because footnote\n *   > calls use it with `aria-describedby` to provide an accessible label.\n * @property {string | null | undefined} [footnoteLabelTagName='h2']\n *   HTML tag name to use for the footnote label element (default: `'h2'`).\n *\n *   Change it to match your document structure.\n *\n *   This label is typically hidden visually (assuming a `sr-only` CSS class\n *   is defined that does that) and so affects screen readers only.\n *   If you do have such a class, but want to show this section to everyone,\n *   pass different properties with the `footnoteLabelProperties` option.\n * @property {Handlers | null | undefined} [handlers]\n *   Extra handlers for nodes (optional).\n * @property {Array<MdastNodes['type']> | null | undefined} [passThrough]\n *   List of custom mdast node types to pass through (keep) in hast (note that\n *   the node itself is passed, but eventual children are transformed)\n *   (optional).\n * @property {Handler | null | undefined} [unknownHandler]\n *   Handler for all unknown nodes (optional).\n *\n * @typedef State\n *   Info passed around.\n * @property {(node: MdastNodes) => Array<HastElementContent>} all\n *   Transform the children of an mdast parent to hast.\n * @property {<Type extends HastNodes>(from: MdastNodes, to: Type) => HastElement | Type} applyData\n *   Honor the `data` of `from`, and generate an element instead of `node`.\n * @property {Map<string, MdastDefinition>} definitionById\n *   Definitions by their identifier.\n * @property {Map<string, MdastFootnoteDefinition>} footnoteById\n *   Footnote definitions by their identifier.\n * @property {Map<string, number>} footnoteCounts\n *   Counts for how often the same footnote was called.\n * @property {Array<string>} footnoteOrder\n *   Identifiers of order when footnote calls first appear in tree order.\n * @property {Handlers} handlers\n *   Applied handlers.\n * @property {(node: MdastNodes, parent: MdastParents | undefined) => Array<HastElementContent> | HastElementContent | undefined} one\n *   Transform an mdast node to hast.\n * @property {Options} options\n *   Configuration.\n * @property {(from: MdastNodes, node: HastNodes) => undefined} patch\n *   Copy a node’s positional info.\n * @property {<Type extends HastRootContent>(nodes: Array<Type>, loose?: boolean | undefined) => Array<HastText | Type>} wrap\n *   Wrap `nodes` with line endings between each node, adds initial/final line endings when `loose`.\n */\n\nimport structuredClone from '@ungap/structured-clone'\nimport {visit} from 'unist-util-visit'\nimport {position} from 'unist-util-position'\nimport {handlers as defaultHandlers} from './handlers/index.js'\n\nconst own = {}.hasOwnProperty\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Create `state` from an mdast tree.\n *\n * @param {MdastNodes} tree\n *   mdast node to transform.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {State}\n *   `state` function.\n */\nexport function createState(tree, options) {\n  const settings = options || emptyOptions\n  /** @type {Map<string, MdastDefinition>} */\n  const definitionById = new Map()\n  /** @type {Map<string, MdastFootnoteDefinition>} */\n  const footnoteById = new Map()\n  /** @type {Map<string, number>} */\n  const footnoteCounts = new Map()\n  /** @type {Handlers} */\n  // @ts-expect-error: the root handler returns a root.\n  // Hard to type.\n  const handlers = {...defaultHandlers, ...settings.handlers}\n\n  /** @type {State} */\n  const state = {\n    all,\n    applyData,\n    definitionById,\n    footnoteById,\n    footnoteCounts,\n    footnoteOrder: [],\n    handlers,\n    one,\n    options: settings,\n    patch,\n    wrap\n  }\n\n  visit(tree, function (node) {\n    if (node.type === 'definition' || node.type === 'footnoteDefinition') {\n      const map = node.type === 'definition' ? definitionById : footnoteById\n      const id = String(node.identifier).toUpperCase()\n\n      // Mimick CM behavior of link definitions.\n      // See: <https://github.com/syntax-tree/mdast-util-definitions/blob/9032189/lib/index.js#L20-L21>.\n      if (!map.has(id)) {\n        // @ts-expect-error: node type matches map.\n        map.set(id, node)\n      }\n    }\n  })\n\n  return state\n\n  /**\n   * Transform an mdast node into a hast node.\n   *\n   * @param {MdastNodes} node\n   *   mdast node.\n   * @param {MdastParents | undefined} [parent]\n   *   Parent of `node`.\n   * @returns {Array<HastElementContent> | HastElementContent | undefined}\n   *   Resulting hast node.\n   */\n  function one(node, parent) {\n    const type = node.type\n    const handle = state.handlers[type]\n\n    if (own.call(state.handlers, type) && handle) {\n      return handle(state, node, parent)\n    }\n\n    if (state.options.passThrough && state.options.passThrough.includes(type)) {\n      if ('children' in node) {\n        const {children, ...shallow} = node\n        const result = structuredClone(shallow)\n        // @ts-expect-error: TS doesn’t understand…\n        result.children = state.all(node)\n        // @ts-expect-error: TS doesn’t understand…\n        return result\n      }\n\n      // @ts-expect-error: it’s custom.\n      return structuredClone(node)\n    }\n\n    const unknown = state.options.unknownHandler || defaultUnknownHandler\n\n    return unknown(state, node, parent)\n  }\n\n  /**\n   * Transform the children of an mdast node into hast nodes.\n   *\n   * @param {MdastNodes} parent\n   *   mdast node to compile\n   * @returns {Array<HastElementContent>}\n   *   Resulting hast nodes.\n   */\n  function all(parent) {\n    /** @type {Array<HastElementContent>} */\n    const values = []\n\n    if ('children' in parent) {\n      const nodes = parent.children\n      let index = -1\n      while (++index < nodes.length) {\n        const result = state.one(nodes[index], parent)\n\n        // To do: see if we van clean this? Can we merge texts?\n        if (result) {\n          if (index && nodes[index - 1].type === 'break') {\n            if (!Array.isArray(result) && result.type === 'text') {\n              result.value = trimMarkdownSpaceStart(result.value)\n            }\n\n            if (!Array.isArray(result) && result.type === 'element') {\n              const head = result.children[0]\n\n              if (head && head.type === 'text') {\n                head.value = trimMarkdownSpaceStart(head.value)\n              }\n            }\n          }\n\n          if (Array.isArray(result)) {\n            values.push(...result)\n          } else {\n            values.push(result)\n          }\n        }\n      }\n    }\n\n    return values\n  }\n}\n\n/**\n * Copy a node’s positional info.\n *\n * @param {MdastNodes} from\n *   mdast node to copy from.\n * @param {HastNodes} to\n *   hast node to copy into.\n * @returns {undefined}\n *   Nothing.\n */\nfunction patch(from, to) {\n  if (from.position) to.position = position(from)\n}\n\n/**\n * Honor the `data` of `from` and maybe generate an element instead of `to`.\n *\n * @template {HastNodes} Type\n *   Node type.\n * @param {MdastNodes} from\n *   mdast node to use data from.\n * @param {Type} to\n *   hast node to change.\n * @returns {HastElement | Type}\n *   Nothing.\n */\nfunction applyData(from, to) {\n  /** @type {HastElement | Type} */\n  let result = to\n\n  // Handle `data.hName`, `data.hProperties, `data.hChildren`.\n  if (from && from.data) {\n    const hName = from.data.hName\n    const hChildren = from.data.hChildren\n    const hProperties = from.data.hProperties\n\n    if (typeof hName === 'string') {\n      // Transforming the node resulted in an element with a different name\n      // than wanted:\n      if (result.type === 'element') {\n        result.tagName = hName\n      }\n      // Transforming the node resulted in a non-element, which happens for\n      // raw, text, and root nodes (unless custom handlers are passed).\n      // The intent of `hName` is to create an element, but likely also to keep\n      // the content around (otherwise: pass `hChildren`).\n      else {\n        /** @type {Array<HastElementContent>} */\n        // @ts-expect-error: assume no doctypes in `root`.\n        const children = 'children' in result ? result.children : [result]\n        result = {type: 'element', tagName: hName, properties: {}, children}\n      }\n    }\n\n    if (result.type === 'element' && hProperties) {\n      Object.assign(result.properties, structuredClone(hProperties))\n    }\n\n    if (\n      'children' in result &&\n      result.children &&\n      hChildren !== null &&\n      hChildren !== undefined\n    ) {\n      result.children = hChildren\n    }\n  }\n\n  return result\n}\n\n/**\n * Transform an unknown node.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdastNodes} node\n *   Unknown mdast node.\n * @returns {HastElement | HastText}\n *   Resulting hast node.\n */\nfunction defaultUnknownHandler(state, node) {\n  const data = node.data || {}\n  /** @type {HastElement | HastText} */\n  const result =\n    'value' in node &&\n    !(own.call(data, 'hProperties') || own.call(data, 'hChildren'))\n      ? {type: 'text', value: node.value}\n      : {\n          type: 'element',\n          tagName: 'div',\n          properties: {},\n          children: state.all(node)\n        }\n\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n\n/**\n * Wrap `nodes` with line endings between each node.\n *\n * @template {HastRootContent} Type\n *   Node type.\n * @param {Array<Type>} nodes\n *   List of nodes to wrap.\n * @param {boolean | undefined} [loose=false]\n *   Whether to add line endings at start and end (default: `false`).\n * @returns {Array<HastText | Type>}\n *   Wrapped nodes.\n */\nexport function wrap(nodes, loose) {\n  /** @type {Array<HastText | Type>} */\n  const result = []\n  let index = -1\n\n  if (loose) {\n    result.push({type: 'text', value: '\\n'})\n  }\n\n  while (++index < nodes.length) {\n    if (index) result.push({type: 'text', value: '\\n'})\n    result.push(nodes[index])\n  }\n\n  if (loose && nodes.length > 0) {\n    result.push({type: 'text', value: '\\n'})\n  }\n\n  return result\n}\n\n/**\n * Trim spaces and tabs at the start of `value`.\n *\n * @param {string} value\n *   Value to trim.\n * @returns {string}\n *   Result.\n */\nfunction trimMarkdownSpaceStart(value) {\n  let index = 0\n  let code = value.charCodeAt(index)\n\n  while (code === 9 || code === 32) {\n    index++\n    code = value.charCodeAt(index)\n  }\n\n  return value.slice(index)\n}\n","/**\n * @import {Nodes as HastNodes} from 'hast'\n * @import {Nodes as MdastNodes} from 'mdast'\n * @import {Options} from './state.js'\n */\n\nimport {ok as assert} from 'devlop'\nimport {footer} from './footer.js'\nimport {createState} from './state.js'\n\n/**\n * Transform mdast to hast.\n *\n * ##### Notes\n *\n * ###### HTML\n *\n * Raw HTML is available in mdast as `html` nodes and can be embedded in hast\n * as semistandard `raw` nodes.\n * Most utilities ignore `raw` nodes but two notable ones don’t:\n *\n * *   `hast-util-to-html` also has an option `allowDangerousHtml` which will\n *     output the raw HTML.\n *     This is typically discouraged as noted by the option name but is useful\n *     if you completely trust authors\n * *   `hast-util-raw` can handle the raw embedded HTML strings by parsing them\n *     into standard hast nodes (`element`, `text`, etc).\n *     This is a heavy task as it needs a full HTML parser, but it is the only\n *     way to support untrusted content\n *\n * ###### Footnotes\n *\n * Many options supported here relate to footnotes.\n * Footnotes are not specified by CommonMark, which we follow by default.\n * They are supported by GitHub, so footnotes can be enabled in markdown with\n * `mdast-util-gfm`.\n *\n * The options `footnoteBackLabel` and `footnoteLabel` define natural language\n * that explains footnotes, which is hidden for sighted users but shown to\n * assistive technology.\n * When your page is not in English, you must define translated values.\n *\n * Back references use ARIA attributes, but the section label itself uses a\n * heading that is hidden with an `sr-only` class.\n * To show it to sighted users, define different attributes in\n * `footnoteLabelProperties`.\n *\n * ###### Clobbering\n *\n * Footnotes introduces a problem, as it links footnote calls to footnote\n * definitions on the page through `id` attributes generated from user content,\n * which results in DOM clobbering.\n *\n * DOM clobbering is this:\n *\n * ```html\n * <p id=x></p>\n * <script>alert(x) // `x` now refers to the DOM `p#x` element</script>\n * ```\n *\n * Elements by their ID are made available by browsers on the `window` object,\n * which is a security risk.\n * Using a prefix solves this problem.\n *\n * More information on how to handle clobbering and the prefix is explained in\n * Example: headings (DOM clobbering) in `rehype-sanitize`.\n *\n * ###### Unknown nodes\n *\n * Unknown nodes are nodes with a type that isn’t in `handlers` or `passThrough`.\n * The default behavior for unknown nodes is:\n *\n * *   when the node has a `value` (and doesn’t have `data.hName`,\n *     `data.hProperties`, or `data.hChildren`, see later), create a hast `text`\n *     node\n * *   otherwise, create a `<div>` element (which could be changed with\n *     `data.hName`), with its children mapped from mdast to hast as well\n *\n * This behavior can be changed by passing an `unknownHandler`.\n *\n * @param {MdastNodes} tree\n *   mdast tree.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {HastNodes}\n *   hast tree.\n */\nexport function toHast(tree, options) {\n  const state = createState(tree, options)\n  const node = state.one(tree, undefined)\n  const foot = footer(state)\n  /** @type {HastNodes} */\n  const result = Array.isArray(node)\n    ? {type: 'root', children: node}\n    : node || {type: 'root', children: []}\n\n  if (foot) {\n    // If there’s a footer, there were definitions, meaning block\n    // content.\n    // So `result` is a parent node.\n    assert('children' in result)\n    result.children.push({type: 'text', value: '\\n'}, foot)\n  }\n\n  return result\n}\n","/**\n * @import {Root as HastRoot} from 'hast'\n * @import {Root as MdastRoot} from 'mdast'\n * @import {Options as ToHastOptions} from 'mdast-util-to-hast'\n * @import {Processor} from 'unified'\n * @import {VFile} from 'vfile'\n */\n\n/**\n * @typedef {Omit<ToHastOptions, 'file'>} Options\n *\n * @callback TransformBridge\n *   Bridge-mode.\n *\n *   Runs the destination with the new hast tree.\n *   Discards result.\n * @param {MdastRoot} tree\n *   Tree.\n * @param {VFile} file\n *   File.\n * @returns {Promise<undefined>}\n *   Nothing.\n *\n * @callback TransformMutate\n *  Mutate-mode.\n *\n *  Further transformers run on the hast tree.\n * @param {MdastRoot} tree\n *   Tree.\n * @param {VFile} file\n *   File.\n * @returns {HastRoot}\n *   Tree (hast).\n */\n\nimport {toHast} from 'mdast-util-to-hast'\n\n/**\n * Turn markdown into HTML.\n *\n * ##### Notes\n *\n * ###### Signature\n *\n * * if a processor is given,\n *   runs the (rehype) plugins used on it with a hast tree,\n *   then discards the result (*bridge mode*)\n * * otherwise,\n *   returns a hast tree,\n *   the plugins used after `remarkRehype` are rehype plugins (*mutate mode*)\n *\n * > 👉 **Note**:\n * > It’s highly unlikely that you want to pass a `processor`.\n *\n * ###### HTML\n *\n * Raw HTML is available in mdast as `html` nodes and can be embedded in hast\n * as semistandard `raw` nodes.\n * Most plugins ignore `raw` nodes but two notable ones don’t:\n *\n * * `rehype-stringify` also has an option `allowDangerousHtml` which will\n *   output the raw HTML.\n *   This is typically discouraged as noted by the option name but is useful if\n *   you completely trust authors\n * * `rehype-raw` can handle the raw embedded HTML strings by parsing them\n *   into standard hast nodes (`element`, `text`, etc);\n *   this is a heavy task as it needs a full HTML parser,\n *   but it is the only way to support untrusted content\n *\n * ###### Footnotes\n *\n * Many options supported here relate to footnotes.\n * Footnotes are not specified by CommonMark,\n * which we follow by default.\n * They are supported by GitHub,\n * so footnotes can be enabled in markdown with `remark-gfm`.\n *\n * The options `footnoteBackLabel` and `footnoteLabel` define natural language\n * that explains footnotes,\n * which is hidden for sighted users but shown to assistive technology.\n * When your page is not in English,\n * you must define translated values.\n *\n * Back references use ARIA attributes,\n * but the section label itself uses a heading that is hidden with an\n * `sr-only` class.\n * To show it to sighted users,\n * define different attributes in `footnoteLabelProperties`.\n *\n * ###### Clobbering\n *\n * Footnotes introduces a problem,\n * as it links footnote calls to footnote definitions on the page through `id`\n * attributes generated from user content,\n * which results in DOM clobbering.\n *\n * DOM clobbering is this:\n *\n * ```html\n * <p id=x></p>\n * <script>alert(x) // `x` now refers to the DOM `p#x` element</script>\n * ```\n *\n * Elements by their ID are made available by browsers on the `window` object,\n * which is a security risk.\n * Using a prefix solves this problem.\n *\n * More information on how to handle clobbering and the prefix is explained in\n * *Example: headings (DOM clobbering)* in `rehype-sanitize`.\n *\n * ###### Unknown nodes\n *\n * Unknown nodes are nodes with a type that isn’t in `handlers` or `passThrough`.\n * The default behavior for unknown nodes is:\n *\n * * when the node has a `value`\n *   (and doesn’t have `data.hName`, `data.hProperties`, or `data.hChildren`,\n *   see later),\n *   create a hast `text` node\n * * otherwise,\n *   create a `<div>` element (which could be changed with `data.hName`),\n *   with its children mapped from mdast to hast as well\n *\n * This behavior can be changed by passing an `unknownHandler`.\n *\n * @overload\n * @param {Processor} processor\n * @param {Readonly<Options> | null | undefined} [options]\n * @returns {TransformBridge}\n *\n * @overload\n * @param {Readonly<Options> | null | undefined} [options]\n * @returns {TransformMutate}\n *\n * @overload\n * @param {Readonly<Options> | Processor | null | undefined} [destination]\n * @param {Readonly<Options> | null | undefined} [options]\n * @returns {TransformBridge | TransformMutate}\n *\n * @param {Readonly<Options> | Processor | null | undefined} [destination]\n *   Processor or configuration (optional).\n * @param {Readonly<Options> | null | undefined} [options]\n *   When a processor was given,\n *   configuration (optional).\n * @returns {TransformBridge | TransformMutate}\n *   Transform.\n */\nexport default function remarkRehype(destination, options) {\n  if (destination && 'run' in destination) {\n    /**\n     * @type {TransformBridge}\n     */\n    return async function (tree, file) {\n      // Cast because root in -> root out.\n      const hastTree = /** @type {HastRoot} */ (\n        toHast(tree, {file, ...options})\n      )\n      await destination.run(hastTree, file)\n    }\n  }\n\n  /**\n   * @type {TransformMutate}\n   */\n  return function (tree, file) {\n    // Cast because root in -> root out.\n    // To do: in the future, disallow ` || options` fallback.\n    // With `unified-engine`, `destination` can be `undefined` but\n    // `options` will be the file set.\n    // We should not pass that as `options`.\n    return /** @type {HastRoot} */ (\n      toHast(tree, {file, ...(destination || options)})\n    )\n  }\n}\n","/**\n * Throw a given error.\n *\n * @param {Error|null|undefined} [error]\n *   Maybe error.\n * @returns {asserts error is null|undefined}\n */\nexport function bail(error) {\n  if (error) {\n    throw error\n  }\n}\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n","// To do: remove `void`s\n// To do: remove `null` from output of our APIs, allow it as user APIs.\n\n/**\n * @typedef {(error?: Error | null | undefined, ...output: Array<any>) => void} Callback\n *   Callback.\n *\n * @typedef {(...input: Array<any>) => any} Middleware\n *   Ware.\n *\n * @typedef Pipeline\n *   Pipeline.\n * @property {Run} run\n *   Run the pipeline.\n * @property {Use} use\n *   Add middleware.\n *\n * @typedef {(...input: Array<any>) => void} Run\n *   Call all middleware.\n *\n *   Calls `done` on completion with either an error or the output of the\n *   last middleware.\n *\n *   > 👉 **Note**: as the length of input defines whether async functions get a\n *   > `next` function,\n *   > it’s recommended to keep `input` at one value normally.\n\n *\n * @typedef {(fn: Middleware) => Pipeline} Use\n *   Add middleware.\n */\n\n/**\n * Create new middleware.\n *\n * @returns {Pipeline}\n *   Pipeline.\n */\nexport function trough() {\n  /** @type {Array<Middleware>} */\n  const fns = []\n  /** @type {Pipeline} */\n  const pipeline = {run, use}\n\n  return pipeline\n\n  /** @type {Run} */\n  function run(...values) {\n    let middlewareIndex = -1\n    /** @type {Callback} */\n    const callback = values.pop()\n\n    if (typeof callback !== 'function') {\n      throw new TypeError('Expected function as last argument, not ' + callback)\n    }\n\n    next(null, ...values)\n\n    /**\n     * Run the next `fn`, or we’re done.\n     *\n     * @param {Error | null | undefined} error\n     * @param {Array<any>} output\n     */\n    function next(error, ...output) {\n      const fn = fns[++middlewareIndex]\n      let index = -1\n\n      if (error) {\n        callback(error)\n        return\n      }\n\n      // Copy non-nullish input into values.\n      while (++index < values.length) {\n        if (output[index] === null || output[index] === undefined) {\n          output[index] = values[index]\n        }\n      }\n\n      // Save the newly created `output` for the next call.\n      values = output\n\n      // Next or done.\n      if (fn) {\n        wrap(fn, next)(...output)\n      } else {\n        callback(null, ...output)\n      }\n    }\n  }\n\n  /** @type {Use} */\n  function use(middelware) {\n    if (typeof middelware !== 'function') {\n      throw new TypeError(\n        'Expected `middelware` to be a function, not ' + middelware\n      )\n    }\n\n    fns.push(middelware)\n    return pipeline\n  }\n}\n\n/**\n * Wrap `middleware` into a uniform interface.\n *\n * You can pass all input to the resulting function.\n * `callback` is then called with the output of `middleware`.\n *\n * If `middleware` accepts more arguments than the later given in input,\n * an extra `done` function is passed to it after that input,\n * which must be called by `middleware`.\n *\n * The first value in `input` is the main input value.\n * All other input values are the rest input values.\n * The values given to `callback` are the input values,\n * merged with every non-nullish output value.\n *\n * * if `middleware` throws an error,\n *   returns a promise that is rejected,\n *   or calls the given `done` function with an error,\n *   `callback` is called with that error\n * * if `middleware` returns a value or returns a promise that is resolved,\n *   that value is the main output value\n * * if `middleware` calls `done`,\n *   all non-nullish values except for the first one (the error) overwrite the\n *   output values\n *\n * @param {Middleware} middleware\n *   Function to wrap.\n * @param {Callback} callback\n *   Callback called with the output of `middleware`.\n * @returns {Run}\n *   Wrapped middleware.\n */\nexport function wrap(middleware, callback) {\n  /** @type {boolean} */\n  let called\n\n  return wrapped\n\n  /**\n   * Call `middleware`.\n   * @this {any}\n   * @param {Array<any>} parameters\n   * @returns {void}\n   */\n  function wrapped(...parameters) {\n    const fnExpectsCallback = middleware.length > parameters.length\n    /** @type {any} */\n    let result\n\n    if (fnExpectsCallback) {\n      parameters.push(done)\n    }\n\n    try {\n      result = middleware.apply(this, parameters)\n    } catch (error) {\n      const exception = /** @type {Error} */ (error)\n\n      // Well, this is quite the pickle.\n      // `middleware` received a callback and called it synchronously, but that\n      // threw an error.\n      // The only thing left to do is to throw the thing instead.\n      if (fnExpectsCallback && called) {\n        throw exception\n      }\n\n      return done(exception)\n    }\n\n    if (!fnExpectsCallback) {\n      if (result && result.then && typeof result.then === 'function') {\n        result.then(then, done)\n      } else if (result instanceof Error) {\n        done(result)\n      } else {\n        then(result)\n      }\n    }\n  }\n\n  /**\n   * Call `callback`, only once.\n   *\n   * @type {Callback}\n   */\n  function done(error, ...output) {\n    if (!called) {\n      called = true\n      callback(error, ...output)\n    }\n  }\n\n  /**\n   * Call `done` with one value.\n   *\n   * @param {any} [value]\n   */\n  function then(value) {\n    done(null, value)\n  }\n}\n","// A derivative work based on:\n// <https://github.com/browserify/path-browserify>.\n// Which is licensed:\n//\n// MIT License\n//\n// Copyright (c) 2013 James Halliday\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A derivative work based on:\n//\n// Parts of that are extracted from Node’s internal `path` module:\n// <https://github.com/nodejs/node/blob/master/lib/path.js>.\n// Which is licensed:\n//\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nexport const minpath = {basename, dirname, extname, join, sep: '/'}\n\n/* eslint-disable max-depth, complexity */\n\n/**\n * Get the basename from a path.\n *\n * @param {string} path\n *   File path.\n * @param {string | null | undefined} [extname]\n *   Extension to strip.\n * @returns {string}\n *   Stem or basename.\n */\nfunction basename(path, extname) {\n  if (extname !== undefined && typeof extname !== 'string') {\n    throw new TypeError('\"ext\" argument must be a string')\n  }\n\n  assertPath(path)\n  let start = 0\n  let end = -1\n  let index = path.length\n  /** @type {boolean | undefined} */\n  let seenNonSlash\n\n  if (\n    extname === undefined ||\n    extname.length === 0 ||\n    extname.length > path.length\n  ) {\n    while (index--) {\n      if (path.codePointAt(index) === 47 /* `/` */) {\n        // If we reached a path separator that was not part of a set of path\n        // separators at the end of the string, stop now.\n        if (seenNonSlash) {\n          start = index + 1\n          break\n        }\n      } else if (end < 0) {\n        // We saw the first non-path separator, mark this as the end of our\n        // path component.\n        seenNonSlash = true\n        end = index + 1\n      }\n    }\n\n    return end < 0 ? '' : path.slice(start, end)\n  }\n\n  if (extname === path) {\n    return ''\n  }\n\n  let firstNonSlashEnd = -1\n  let extnameIndex = extname.length - 1\n\n  while (index--) {\n    if (path.codePointAt(index) === 47 /* `/` */) {\n      // If we reached a path separator that was not part of a set of path\n      // separators at the end of the string, stop now.\n      if (seenNonSlash) {\n        start = index + 1\n        break\n      }\n    } else {\n      if (firstNonSlashEnd < 0) {\n        // We saw the first non-path separator, remember this index in case\n        // we need it if the extension ends up not matching.\n        seenNonSlash = true\n        firstNonSlashEnd = index + 1\n      }\n\n      if (extnameIndex > -1) {\n        // Try to match the explicit extension.\n        if (path.codePointAt(index) === extname.codePointAt(extnameIndex--)) {\n          if (extnameIndex < 0) {\n            // We matched the extension, so mark this as the end of our path\n            // component\n            end = index\n          }\n        } else {\n          // Extension does not match, so our result is the entire path\n          // component\n          extnameIndex = -1\n          end = firstNonSlashEnd\n        }\n      }\n    }\n  }\n\n  if (start === end) {\n    end = firstNonSlashEnd\n  } else if (end < 0) {\n    end = path.length\n  }\n\n  return path.slice(start, end)\n}\n\n/**\n * Get the dirname from a path.\n *\n * @param {string} path\n *   File path.\n * @returns {string}\n *   File path.\n */\nfunction dirname(path) {\n  assertPath(path)\n\n  if (path.length === 0) {\n    return '.'\n  }\n\n  let end = -1\n  let index = path.length\n  /** @type {boolean | undefined} */\n  let unmatchedSlash\n\n  // Prefix `--` is important to not run on `0`.\n  while (--index) {\n    if (path.codePointAt(index) === 47 /* `/` */) {\n      if (unmatchedSlash) {\n        end = index\n        break\n      }\n    } else if (!unmatchedSlash) {\n      // We saw the first non-path separator\n      unmatchedSlash = true\n    }\n  }\n\n  return end < 0\n    ? path.codePointAt(0) === 47 /* `/` */\n      ? '/'\n      : '.'\n    : end === 1 && path.codePointAt(0) === 47 /* `/` */\n      ? '//'\n      : path.slice(0, end)\n}\n\n/**\n * Get an extname from a path.\n *\n * @param {string} path\n *   File path.\n * @returns {string}\n *   Extname.\n */\nfunction extname(path) {\n  assertPath(path)\n\n  let index = path.length\n\n  let end = -1\n  let startPart = 0\n  let startDot = -1\n  // Track the state of characters (if any) we see before our first dot and\n  // after any path separator we find.\n  let preDotState = 0\n  /** @type {boolean | undefined} */\n  let unmatchedSlash\n\n  while (index--) {\n    const code = path.codePointAt(index)\n\n    if (code === 47 /* `/` */) {\n      // If we reached a path separator that was not part of a set of path\n      // separators at the end of the string, stop now.\n      if (unmatchedSlash) {\n        startPart = index + 1\n        break\n      }\n\n      continue\n    }\n\n    if (end < 0) {\n      // We saw the first non-path separator, mark this as the end of our\n      // extension.\n      unmatchedSlash = true\n      end = index + 1\n    }\n\n    if (code === 46 /* `.` */) {\n      // If this is our first dot, mark it as the start of our extension.\n      if (startDot < 0) {\n        startDot = index\n      } else if (preDotState !== 1) {\n        preDotState = 1\n      }\n    } else if (startDot > -1) {\n      // We saw a non-dot and non-path separator before our dot, so we should\n      // have a good chance at having a non-empty extension.\n      preDotState = -1\n    }\n  }\n\n  if (\n    startDot < 0 ||\n    end < 0 ||\n    // We saw a non-dot character immediately before the dot.\n    preDotState === 0 ||\n    // The (right-most) trimmed path component is exactly `..`.\n    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)\n  ) {\n    return ''\n  }\n\n  return path.slice(startDot, end)\n}\n\n/**\n * Join segments from a path.\n *\n * @param {Array<string>} segments\n *   Path segments.\n * @returns {string}\n *   File path.\n */\nfunction join(...segments) {\n  let index = -1\n  /** @type {string | undefined} */\n  let joined\n\n  while (++index < segments.length) {\n    assertPath(segments[index])\n\n    if (segments[index]) {\n      joined =\n        joined === undefined ? segments[index] : joined + '/' + segments[index]\n    }\n  }\n\n  return joined === undefined ? '.' : normalize(joined)\n}\n\n/**\n * Normalize a basic file path.\n *\n * @param {string} path\n *   File path.\n * @returns {string}\n *   File path.\n */\n// Note: `normalize` is not exposed as `path.normalize`, so some code is\n// manually removed from it.\nfunction normalize(path) {\n  assertPath(path)\n\n  const absolute = path.codePointAt(0) === 47 /* `/` */\n\n  // Normalize the path according to POSIX rules.\n  let value = normalizeString(path, !absolute)\n\n  if (value.length === 0 && !absolute) {\n    value = '.'\n  }\n\n  if (value.length > 0 && path.codePointAt(path.length - 1) === 47 /* / */) {\n    value += '/'\n  }\n\n  return absolute ? '/' + value : value\n}\n\n/**\n * Resolve `.` and `..` elements in a path with directory names.\n *\n * @param {string} path\n *   File path.\n * @param {boolean} allowAboveRoot\n *   Whether `..` can move above root.\n * @returns {string}\n *   File path.\n */\nfunction normalizeString(path, allowAboveRoot) {\n  let result = ''\n  let lastSegmentLength = 0\n  let lastSlash = -1\n  let dots = 0\n  let index = -1\n  /** @type {number | undefined} */\n  let code\n  /** @type {number} */\n  let lastSlashIndex\n\n  while (++index <= path.length) {\n    if (index < path.length) {\n      code = path.codePointAt(index)\n    } else if (code === 47 /* `/` */) {\n      break\n    } else {\n      code = 47 /* `/` */\n    }\n\n    if (code === 47 /* `/` */) {\n      if (lastSlash === index - 1 || dots === 1) {\n        // Empty.\n      } else if (lastSlash !== index - 1 && dots === 2) {\n        if (\n          result.length < 2 ||\n          lastSegmentLength !== 2 ||\n          result.codePointAt(result.length - 1) !== 46 /* `.` */ ||\n          result.codePointAt(result.length - 2) !== 46 /* `.` */\n        ) {\n          if (result.length > 2) {\n            lastSlashIndex = result.lastIndexOf('/')\n\n            if (lastSlashIndex !== result.length - 1) {\n              if (lastSlashIndex < 0) {\n                result = ''\n                lastSegmentLength = 0\n              } else {\n                result = result.slice(0, lastSlashIndex)\n                lastSegmentLength = result.length - 1 - result.lastIndexOf('/')\n              }\n\n              lastSlash = index\n              dots = 0\n              continue\n            }\n          } else if (result.length > 0) {\n            result = ''\n            lastSegmentLength = 0\n            lastSlash = index\n            dots = 0\n            continue\n          }\n        }\n\n        if (allowAboveRoot) {\n          result = result.length > 0 ? result + '/..' : '..'\n          lastSegmentLength = 2\n        }\n      } else {\n        if (result.length > 0) {\n          result += '/' + path.slice(lastSlash + 1, index)\n        } else {\n          result = path.slice(lastSlash + 1, index)\n        }\n\n        lastSegmentLength = index - lastSlash - 1\n      }\n\n      lastSlash = index\n      dots = 0\n    } else if (code === 46 /* `.` */ && dots > -1) {\n      dots++\n    } else {\n      dots = -1\n    }\n  }\n\n  return result\n}\n\n/**\n * Make sure `path` is a string.\n *\n * @param {string} path\n *   File path.\n * @returns {asserts path is string}\n *   Nothing.\n */\nfunction assertPath(path) {\n  if (typeof path !== 'string') {\n    throw new TypeError(\n      'Path must be a string. Received ' + JSON.stringify(path)\n    )\n  }\n}\n\n/* eslint-enable max-depth, complexity */\n","// Somewhat based on:\n// <https://github.com/defunctzombie/node-process/blob/master/browser.js>.\n// But I don’t think one tiny line of code can be copyrighted. 😅\nexport const minproc = {cwd}\n\nfunction cwd() {\n  return '/'\n}\n","/**\n * Checks if a value has the shape of a WHATWG URL object.\n *\n * Using a symbol or instanceof would not be able to recognize URL objects\n * coming from other implementations (e.g. in Electron), so instead we are\n * checking some well known properties for a lack of a better test.\n *\n * We use `href` and `protocol` as they are the only properties that are\n * easy to retrieve and calculate due to the lazy nature of the getters.\n *\n * We check for auth attribute to distinguish legacy url instance with\n * WHATWG URL instance.\n *\n * @param {unknown} fileUrlOrPath\n *   File path or URL.\n * @returns {fileUrlOrPath is URL}\n *   Whether it’s a URL.\n */\n// From: <https://github.com/nodejs/node/blob/6a3403c/lib/internal/url.js#L720>\nexport function isUrl(fileUrlOrPath) {\n  return Boolean(\n    fileUrlOrPath !== null &&\n      typeof fileUrlOrPath === 'object' &&\n      'href' in fileUrlOrPath &&\n      fileUrlOrPath.href &&\n      'protocol' in fileUrlOrPath &&\n      fileUrlOrPath.protocol &&\n      // @ts-expect-error: indexing is fine.\n      fileUrlOrPath.auth === undefined\n  )\n}\n","import {isUrl} from './minurl.shared.js'\n\nexport {isUrl} from './minurl.shared.js'\n\n// See: <https://github.com/nodejs/node/blob/6a3403c/lib/internal/url.js>\n\n/**\n * @param {URL | string} path\n *   File URL.\n * @returns {string}\n *   File URL.\n */\nexport function urlToPath(path) {\n  if (typeof path === 'string') {\n    path = new URL(path)\n  } else if (!isUrl(path)) {\n    /** @type {NodeJS.ErrnoException} */\n    const error = new TypeError(\n      'The \"path\" argument must be of type string or an instance of URL. Received `' +\n        path +\n        '`'\n    )\n    error.code = 'ERR_INVALID_ARG_TYPE'\n    throw error\n  }\n\n  if (path.protocol !== 'file:') {\n    /** @type {NodeJS.ErrnoException} */\n    const error = new TypeError('The URL must be of scheme file')\n    error.code = 'ERR_INVALID_URL_SCHEME'\n    throw error\n  }\n\n  return getPathFromURLPosix(path)\n}\n\n/**\n * Get a path from a POSIX URL.\n *\n * @param {URL} url\n *   URL.\n * @returns {string}\n *   File path.\n */\nfunction getPathFromURLPosix(url) {\n  if (url.hostname !== '') {\n    /** @type {NodeJS.ErrnoException} */\n    const error = new TypeError(\n      'File URL host must be \"localhost\" or empty on darwin'\n    )\n    error.code = 'ERR_INVALID_FILE_URL_HOST'\n    throw error\n  }\n\n  const pathname = url.pathname\n  let index = -1\n\n  while (++index < pathname.length) {\n    if (\n      pathname.codePointAt(index) === 37 /* `%` */ &&\n      pathname.codePointAt(index + 1) === 50 /* `2` */\n    ) {\n      const third = pathname.codePointAt(index + 2)\n      if (third === 70 /* `F` */ || third === 102 /* `f` */) {\n        /** @type {NodeJS.ErrnoException} */\n        const error = new TypeError(\n          'File URL path must not include encoded / characters'\n        )\n        error.code = 'ERR_INVALID_FILE_URL_PATH'\n        throw error\n      }\n    }\n  }\n\n  return decodeURIComponent(pathname)\n}\n","/**\n * @import {Node, Point, Position} from 'unist'\n * @import {Options as MessageOptions} from 'vfile-message'\n * @import {Compatible, Data, Map, Options, Value} from 'vfile'\n */\n\n/**\n * @typedef {object & {type: string, position?: Position | undefined}} NodeLike\n */\n\nimport {VFileMessage} from 'vfile-message'\nimport {minpath} from '#minpath'\nimport {minproc} from '#minproc'\nimport {urlToPath, isUrl} from '#minurl'\n\n/**\n * Order of setting (least specific to most), we need this because otherwise\n * `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a\n * stem can be set.\n */\nconst order = /** @type {const} */ ([\n  'history',\n  'path',\n  'basename',\n  'stem',\n  'extname',\n  'dirname'\n])\n\nexport class VFile {\n  /**\n   * Create a new virtual file.\n   *\n   * `options` is treated as:\n   *\n   * *   `string` or `Uint8Array` — `{value: options}`\n   * *   `URL` — `{path: options}`\n   * *   `VFile` — shallow copies its data over to the new file\n   * *   `object` — all fields are shallow copied over to the new file\n   *\n   * Path related fields are set in the following order (least specific to\n   * most specific): `history`, `path`, `basename`, `stem`, `extname`,\n   * `dirname`.\n   *\n   * You cannot set `dirname` or `extname` without setting either `history`,\n   * `path`, `basename`, or `stem` too.\n   *\n   * @param {Compatible | null | undefined} [value]\n   *   File value.\n   * @returns\n   *   New instance.\n   */\n  constructor(value) {\n    /** @type {Options | VFile} */\n    let options\n\n    if (!value) {\n      options = {}\n    } else if (isUrl(value)) {\n      options = {path: value}\n    } else if (typeof value === 'string' || isUint8Array(value)) {\n      options = {value}\n    } else {\n      options = value\n    }\n\n    /* eslint-disable no-unused-expressions */\n\n    /**\n     * Base of `path` (default: `process.cwd()` or `'/'` in browsers).\n     *\n     * @type {string}\n     */\n    // Prevent calling `cwd` (which could be expensive) if it’s not needed;\n    // the empty string will be overridden in the next block.\n    this.cwd = 'cwd' in options ? '' : minproc.cwd()\n\n    /**\n     * Place to store custom info (default: `{}`).\n     *\n     * It’s OK to store custom data directly on the file but moving it to\n     * `data` is recommended.\n     *\n     * @type {Data}\n     */\n    this.data = {}\n\n    /**\n     * List of file paths the file moved between.\n     *\n     * The first is the original path and the last is the current path.\n     *\n     * @type {Array<string>}\n     */\n    this.history = []\n\n    /**\n     * List of messages associated with the file.\n     *\n     * @type {Array<VFileMessage>}\n     */\n    this.messages = []\n\n    /**\n     * Raw value.\n     *\n     * @type {Value}\n     */\n    this.value\n\n    // The below are non-standard, they are “well-known”.\n    // As in, used in several tools.\n    /**\n     * Source map.\n     *\n     * This type is equivalent to the `RawSourceMap` type from the `source-map`\n     * module.\n     *\n     * @type {Map | null | undefined}\n     */\n    this.map\n\n    /**\n     * Custom, non-string, compiled, representation.\n     *\n     * This is used by unified to store non-string results.\n     * One example is when turning markdown into React nodes.\n     *\n     * @type {unknown}\n     */\n    this.result\n\n    /**\n     * Whether a file was saved to disk.\n     *\n     * This is used by vfile reporters.\n     *\n     * @type {boolean}\n     */\n    this.stored\n    /* eslint-enable no-unused-expressions */\n\n    // Set path related properties in the correct order.\n    let index = -1\n\n    while (++index < order.length) {\n      const field = order[index]\n\n      // Note: we specifically use `in` instead of `hasOwnProperty` to accept\n      // `vfile`s too.\n      if (\n        field in options &&\n        options[field] !== undefined &&\n        options[field] !== null\n      ) {\n        // @ts-expect-error: TS doesn’t understand basic reality.\n        this[field] = field === 'history' ? [...options[field]] : options[field]\n      }\n    }\n\n    /** @type {string} */\n    let field\n\n    // Set non-path related properties.\n    for (field in options) {\n      // @ts-expect-error: fine to set other things.\n      if (!order.includes(field)) {\n        // @ts-expect-error: fine to set other things.\n        this[field] = options[field]\n      }\n    }\n  }\n\n  /**\n   * Get the basename (including extname) (example: `'index.min.js'`).\n   *\n   * @returns {string | undefined}\n   *   Basename.\n   */\n  get basename() {\n    return typeof this.path === 'string'\n      ? minpath.basename(this.path)\n      : undefined\n  }\n\n  /**\n   * Set basename (including extname) (`'index.min.js'`).\n   *\n   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n   * on windows).\n   * Cannot be nullified (use `file.path = file.dirname` instead).\n   *\n   * @param {string} basename\n   *   Basename.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set basename(basename) {\n    assertNonEmpty(basename, 'basename')\n    assertPart(basename, 'basename')\n    this.path = minpath.join(this.dirname || '', basename)\n  }\n\n  /**\n   * Get the parent path (example: `'~'`).\n   *\n   * @returns {string | undefined}\n   *   Dirname.\n   */\n  get dirname() {\n    return typeof this.path === 'string'\n      ? minpath.dirname(this.path)\n      : undefined\n  }\n\n  /**\n   * Set the parent path (example: `'~'`).\n   *\n   * Cannot be set if there’s no `path` yet.\n   *\n   * @param {string | undefined} dirname\n   *   Dirname.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set dirname(dirname) {\n    assertPath(this.basename, 'dirname')\n    this.path = minpath.join(dirname || '', this.basename)\n  }\n\n  /**\n   * Get the extname (including dot) (example: `'.js'`).\n   *\n   * @returns {string | undefined}\n   *   Extname.\n   */\n  get extname() {\n    return typeof this.path === 'string'\n      ? minpath.extname(this.path)\n      : undefined\n  }\n\n  /**\n   * Set the extname (including dot) (example: `'.js'`).\n   *\n   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n   * on windows).\n   * Cannot be set if there’s no `path` yet.\n   *\n   * @param {string | undefined} extname\n   *   Extname.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set extname(extname) {\n    assertPart(extname, 'extname')\n    assertPath(this.dirname, 'extname')\n\n    if (extname) {\n      if (extname.codePointAt(0) !== 46 /* `.` */) {\n        throw new Error('`extname` must start with `.`')\n      }\n\n      if (extname.includes('.', 1)) {\n        throw new Error('`extname` cannot contain multiple dots')\n      }\n    }\n\n    this.path = minpath.join(this.dirname, this.stem + (extname || ''))\n  }\n\n  /**\n   * Get the full path (example: `'~/index.min.js'`).\n   *\n   * @returns {string}\n   *   Path.\n   */\n  get path() {\n    return this.history[this.history.length - 1]\n  }\n\n  /**\n   * Set the full path (example: `'~/index.min.js'`).\n   *\n   * Cannot be nullified.\n   * You can set a file URL (a `URL` object with a `file:` protocol) which will\n   * be turned into a path with `url.fileURLToPath`.\n   *\n   * @param {URL | string} path\n   *   Path.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set path(path) {\n    if (isUrl(path)) {\n      path = urlToPath(path)\n    }\n\n    assertNonEmpty(path, 'path')\n\n    if (this.path !== path) {\n      this.history.push(path)\n    }\n  }\n\n  /**\n   * Get the stem (basename w/o extname) (example: `'index.min'`).\n   *\n   * @returns {string | undefined}\n   *   Stem.\n   */\n  get stem() {\n    return typeof this.path === 'string'\n      ? minpath.basename(this.path, this.extname)\n      : undefined\n  }\n\n  /**\n   * Set the stem (basename w/o extname) (example: `'index.min'`).\n   *\n   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n   * on windows).\n   * Cannot be nullified (use `file.path = file.dirname` instead).\n   *\n   * @param {string} stem\n   *   Stem.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set stem(stem) {\n    assertNonEmpty(stem, 'stem')\n    assertPart(stem, 'stem')\n    this.path = minpath.join(this.dirname || '', stem + (this.extname || ''))\n  }\n\n  // Normal prototypal methods.\n  /**\n   * Create a fatal message for `reason` associated with the file.\n   *\n   * The `fatal` field of the message is set to `true` (error; file not usable)\n   * and the `file` field is set to the current file path.\n   * The message is added to the `messages` field on `file`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {MessageOptions | null | undefined} [options]\n   * @returns {never}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns {never}\n   *   Never.\n   * @throws {VFileMessage}\n   *   Message.\n   */\n  fail(causeOrReason, optionsOrParentOrPlace, origin) {\n    // @ts-expect-error: the overloads are fine.\n    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)\n\n    message.fatal = true\n\n    throw message\n  }\n\n  /**\n   * Create an info message for `reason` associated with the file.\n   *\n   * The `fatal` field of the message is set to `undefined` (info; change\n   * likely not needed) and the `file` field is set to the current file path.\n   * The message is added to the `messages` field on `file`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {MessageOptions | null | undefined} [options]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns {VFileMessage}\n   *   Message.\n   */\n  info(causeOrReason, optionsOrParentOrPlace, origin) {\n    // @ts-expect-error: the overloads are fine.\n    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)\n\n    message.fatal = undefined\n\n    return message\n  }\n\n  /**\n   * Create a message for `reason` associated with the file.\n   *\n   * The `fatal` field of the message is set to `false` (warning; change may be\n   * needed) and the `file` field is set to the current file path.\n   * The message is added to the `messages` field on `file`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {MessageOptions | null | undefined} [options]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns {VFileMessage}\n   *   Message.\n   */\n  message(causeOrReason, optionsOrParentOrPlace, origin) {\n    const message = new VFileMessage(\n      // @ts-expect-error: the overloads are fine.\n      causeOrReason,\n      optionsOrParentOrPlace,\n      origin\n    )\n\n    if (this.path) {\n      message.name = this.path + ':' + message.name\n      message.file = this.path\n    }\n\n    message.fatal = false\n\n    this.messages.push(message)\n\n    return message\n  }\n\n  /**\n   * Serialize the file.\n   *\n   * > **Note**: which encodings are supported depends on the engine.\n   * > For info on Node.js, see:\n   * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.\n   *\n   * @param {string | null | undefined} [encoding='utf8']\n   *   Character encoding to understand `value` as when it’s a `Uint8Array`\n   *   (default: `'utf-8'`).\n   * @returns {string}\n   *   Serialized file.\n   */\n  toString(encoding) {\n    if (this.value === undefined) {\n      return ''\n    }\n\n    if (typeof this.value === 'string') {\n      return this.value\n    }\n\n    const decoder = new TextDecoder(encoding || undefined)\n    return decoder.decode(this.value)\n  }\n}\n\n/**\n * Assert that `part` is not a path (as in, does not contain `path.sep`).\n *\n * @param {string | null | undefined} part\n *   File path part.\n * @param {string} name\n *   Part name.\n * @returns {undefined}\n *   Nothing.\n */\nfunction assertPart(part, name) {\n  if (part && part.includes(minpath.sep)) {\n    throw new Error(\n      '`' + name + '` cannot be a path: did not expect `' + minpath.sep + '`'\n    )\n  }\n}\n\n/**\n * Assert that `part` is not empty.\n *\n * @param {string | undefined} part\n *   Thing.\n * @param {string} name\n *   Part name.\n * @returns {asserts part is string}\n *   Nothing.\n */\nfunction assertNonEmpty(part, name) {\n  if (!part) {\n    throw new Error('`' + name + '` cannot be empty')\n  }\n}\n\n/**\n * Assert `path` exists.\n *\n * @param {string | undefined} path\n *   Path.\n * @param {string} name\n *   Dependency name.\n * @returns {asserts path is string}\n *   Nothing.\n */\nfunction assertPath(path, name) {\n  if (!path) {\n    throw new Error('Setting `' + name + '` requires `path` to be set too')\n  }\n}\n\n/**\n * Assert `value` is an `Uint8Array`.\n *\n * @param {unknown} value\n *   thing.\n * @returns {value is Uint8Array}\n *   Whether `value` is an `Uint8Array`.\n */\nfunction isUint8Array(value) {\n  return Boolean(\n    value &&\n      typeof value === 'object' &&\n      'byteLength' in value &&\n      'byteOffset' in value\n  )\n}\n","export const CallableInstance =\n  /**\n   * @type {new <Parameters extends Array<unknown>, Result>(property: string | symbol) => (...parameters: Parameters) => Result}\n   */\n  (\n    /** @type {unknown} */\n    (\n      /**\n       * @this {Function}\n       * @param {string | symbol} property\n       * @returns {(...parameters: Array<unknown>) => unknown}\n       */\n      function (property) {\n        const self = this\n        const constr = self.constructor\n        const proto = /** @type {Record<string | symbol, Function>} */ (\n          // Prototypes do exist.\n          // type-coverage:ignore-next-line\n          constr.prototype\n        )\n        const value = proto[property]\n        /** @type {(...parameters: Array<unknown>) => unknown} */\n        const apply = function () {\n          return value.apply(apply, arguments)\n        }\n\n        Object.setPrototypeOf(apply, proto)\n\n        // Not needed for us in `unified`: we only call this on the `copy`\n        // function,\n        // and we don't need to add its fields (`length`, `name`)\n        // over.\n        // See also: GH-246.\n        // const names = Object.getOwnPropertyNames(value)\n        //\n        // for (const p of names) {\n        //   const descriptor = Object.getOwnPropertyDescriptor(value, p)\n        //   if (descriptor) Object.defineProperty(apply, p, descriptor)\n        // }\n\n        return apply\n      }\n    )\n  )\n","/**\n * @typedef {import('trough').Pipeline} Pipeline\n *\n * @typedef {import('unist').Node} Node\n *\n * @typedef {import('vfile').Compatible} Compatible\n * @typedef {import('vfile').Value} Value\n *\n * @typedef {import('../index.js').CompileResultMap} CompileResultMap\n * @typedef {import('../index.js').Data} Data\n * @typedef {import('../index.js').Settings} Settings\n */\n\n/**\n * @typedef {CompileResultMap[keyof CompileResultMap]} CompileResults\n *   Acceptable results from compilers.\n *\n *   To register custom results, add them to\n *   {@linkcode CompileResultMap}.\n */\n\n/**\n * @template {Node} [Tree=Node]\n *   The node that the compiler receives (default: `Node`).\n * @template {CompileResults} [Result=CompileResults]\n *   The thing that the compiler yields (default: `CompileResults`).\n * @callback Compiler\n *   A **compiler** handles the compiling of a syntax tree to something else\n *   (in most cases, text) (TypeScript type).\n *\n *   It is used in the stringify phase and called with a {@linkcode Node}\n *   and {@linkcode VFile} representation of the document to compile.\n *   It should return the textual representation of the given tree (typically\n *   `string`).\n *\n *   > **Note**: unified typically compiles by serializing: most compilers\n *   > return `string` (or `Uint8Array`).\n *   > Some compilers, such as the one configured with\n *   > [`rehype-react`][rehype-react], return other values (in this case, a\n *   > React tree).\n *   > If you’re using a compiler that doesn’t serialize, expect different\n *   > result values.\n *   >\n *   > To register custom results in TypeScript, add them to\n *   > {@linkcode CompileResultMap}.\n *\n *   [rehype-react]: https://github.com/rehypejs/rehype-react\n * @param {Tree} tree\n *   Tree to compile.\n * @param {VFile} file\n *   File associated with `tree`.\n * @returns {Result}\n *   New content: compiled text (`string` or `Uint8Array`, for `file.value`) or\n *   something else (for `file.result`).\n */\n\n/**\n * @template {Node} [Tree=Node]\n *   The node that the parser yields (default: `Node`)\n * @callback Parser\n *   A **parser** handles the parsing of text to a syntax tree.\n *\n *   It is used in the parse phase and is called with a `string` and\n *   {@linkcode VFile} of the document to parse.\n *   It must return the syntax tree representation of the given file\n *   ({@linkcode Node}).\n * @param {string} document\n *   Document to parse.\n * @param {VFile} file\n *   File associated with `document`.\n * @returns {Tree}\n *   Node representing the given file.\n */\n\n/**\n * @typedef {(\n *   Plugin<Array<any>, any, any> |\n *   PluginTuple<Array<any>, any, any> |\n *   Preset\n * )} Pluggable\n *   Union of the different ways to add plugins and settings.\n */\n\n/**\n * @typedef {Array<Pluggable>} PluggableList\n *   List of plugins and presets.\n */\n\n// Note: we can’t use `callback` yet as it messes up `this`:\n//  <https://github.com/microsoft/TypeScript/issues/55197>.\n/**\n * @template {Array<unknown>} [PluginParameters=[]]\n *   Arguments passed to the plugin (default: `[]`, the empty tuple).\n * @template {Node | string | undefined} [Input=Node]\n *   Value that is expected as input (default: `Node`).\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node it expects.\n *   *   If the plugin sets a {@linkcode Parser}, this should be\n *       `string`.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be the\n *       node it expects.\n * @template [Output=Input]\n *   Value that is yielded as output (default: `Input`).\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node that that yields.\n *   *   If the plugin sets a {@linkcode Parser}, this should be the\n *       node that it yields.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be\n *       result it yields.\n * @typedef {(\n *   (this: Processor, ...parameters: PluginParameters) =>\n *     Input extends string ? // Parser.\n *        Output extends Node | undefined ? undefined | void : never :\n *     Output extends CompileResults ? // Compiler.\n *        Input extends Node | undefined ? undefined | void : never :\n *     Transformer<\n *       Input extends Node ? Input : Node,\n *       Output extends Node ? Output : Node\n *     > | undefined | void\n * )} Plugin\n *   Single plugin.\n *\n *   Plugins configure the processors they are applied on in the following\n *   ways:\n *\n *   *   they change the processor, such as the parser, the compiler, or by\n *       configuring data\n *   *   they specify how to handle trees and files\n *\n *   In practice, they are functions that can receive options and configure the\n *   processor (`this`).\n *\n *   > **Note**: plugins are called when the processor is *frozen*, not when\n *   > they are applied.\n */\n\n/**\n * Tuple of a plugin and its configuration.\n *\n * The first item is a plugin, the rest are its parameters.\n *\n * @template {Array<unknown>} [TupleParameters=[]]\n *   Arguments passed to the plugin (default: `[]`, the empty tuple).\n * @template {Node | string | undefined} [Input=undefined]\n *   Value that is expected as input (optional).\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node it expects.\n *   *   If the plugin sets a {@linkcode Parser}, this should be\n *       `string`.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be the\n *       node it expects.\n * @template [Output=undefined] (optional).\n *   Value that is yielded as output.\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node that that yields.\n *   *   If the plugin sets a {@linkcode Parser}, this should be the\n *       node that it yields.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be\n *       result it yields.\n * @typedef {(\n *   [\n *     plugin: Plugin<TupleParameters, Input, Output>,\n *     ...parameters: TupleParameters\n *   ]\n * )} PluginTuple\n */\n\n/**\n * @typedef Preset\n *   Sharable configuration.\n *\n *   They can contain plugins and settings.\n * @property {PluggableList | undefined} [plugins]\n *   List of plugins and presets (optional).\n * @property {Settings | undefined} [settings]\n *   Shared settings for parsers and compilers (optional).\n */\n\n/**\n * @template {VFile} [File=VFile]\n *   The file that the callback receives (default: `VFile`).\n * @callback ProcessCallback\n *   Callback called when the process is done.\n *\n *   Called with either an error or a result.\n * @param {Error | undefined} [error]\n *   Fatal error (optional).\n * @param {File | undefined} [file]\n *   Processed file (optional).\n * @returns {undefined}\n *   Nothing.\n */\n\n/**\n * @template {Node} [Tree=Node]\n *   The tree that the callback receives (default: `Node`).\n * @callback RunCallback\n *   Callback called when transformers are done.\n *\n *   Called with either an error or results.\n * @param {Error | undefined} [error]\n *   Fatal error (optional).\n * @param {Tree | undefined} [tree]\n *   Transformed tree (optional).\n * @param {VFile | undefined} [file]\n *   File (optional).\n * @returns {undefined}\n *   Nothing.\n */\n\n/**\n * @template {Node} [Output=Node]\n *   Node type that the transformer yields (default: `Node`).\n * @callback TransformCallback\n *   Callback passed to transforms.\n *\n *   If the signature of a `transformer` accepts a third argument, the\n *   transformer may perform asynchronous operations, and must call it.\n * @param {Error | undefined} [error]\n *   Fatal error to stop the process (optional).\n * @param {Output | undefined} [tree]\n *   New, changed, tree (optional).\n * @param {VFile | undefined} [file]\n *   New, changed, file (optional).\n * @returns {undefined}\n *   Nothing.\n */\n\n/**\n * @template {Node} [Input=Node]\n *   Node type that the transformer expects (default: `Node`).\n * @template {Node} [Output=Input]\n *   Node type that the transformer yields (default: `Input`).\n * @callback Transformer\n *   Transformers handle syntax trees and files.\n *\n *   They are functions that are called each time a syntax tree and file are\n *   passed through the run phase.\n *   When an error occurs in them (either because it’s thrown, returned,\n *   rejected, or passed to `next`), the process stops.\n *\n *   The run phase is handled by [`trough`][trough], see its documentation for\n *   the exact semantics of these functions.\n *\n *   > **Note**: you should likely ignore `next`: don’t accept it.\n *   > it supports callback-style async work.\n *   > But promises are likely easier to reason about.\n *\n *   [trough]: https://github.com/wooorm/trough#function-fninput-next\n * @param {Input} tree\n *   Tree to handle.\n * @param {VFile} file\n *   File to handle.\n * @param {TransformCallback<Output>} next\n *   Callback.\n * @returns {(\n *   Promise<Output | undefined | void> |\n *   Promise<never> | // For some reason this is needed separately.\n *   Output |\n *   Error |\n *   undefined |\n *   void\n * )}\n *   If you accept `next`, nothing.\n *   Otherwise:\n *\n *   *   `Error` — fatal error to stop the process\n *   *   `Promise<undefined>` or `undefined` — the next transformer keeps using\n *       same tree\n *   *   `Promise<Node>` or `Node` — new, changed, tree\n */\n\n/**\n * @template {Node | undefined} ParseTree\n *   Output of `parse`.\n * @template {Node | undefined} HeadTree\n *   Input for `run`.\n * @template {Node | undefined} TailTree\n *   Output for `run`.\n * @template {Node | undefined} CompileTree\n *   Input of `stringify`.\n * @template {CompileResults | undefined} CompileResult\n *   Output of `stringify`.\n * @template {Node | string | undefined} Input\n *   Input of plugin.\n * @template Output\n *   Output of plugin (optional).\n * @typedef {(\n *   Input extends string\n *     ? Output extends Node | undefined\n *       ? // Parser.\n *         Processor<\n *           Output extends undefined ? ParseTree : Output,\n *           HeadTree,\n *           TailTree,\n *           CompileTree,\n *           CompileResult\n *         >\n *       : // Unknown.\n *         Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n *     : Output extends CompileResults\n *     ? Input extends Node | undefined\n *       ? // Compiler.\n *         Processor<\n *           ParseTree,\n *           HeadTree,\n *           TailTree,\n *           Input extends undefined ? CompileTree : Input,\n *           Output extends undefined ? CompileResult : Output\n *         >\n *       : // Unknown.\n *         Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n *     : Input extends Node | undefined\n *     ? Output extends Node | undefined\n *       ? // Transform.\n *         Processor<\n *           ParseTree,\n *           HeadTree extends undefined ? Input : HeadTree,\n *           Output extends undefined ? TailTree : Output,\n *           CompileTree,\n *           CompileResult\n *         >\n *       : // Unknown.\n *         Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n *     : // Unknown.\n *       Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n * )} UsePlugin\n *   Create a processor based on the input/output of a {@link Plugin plugin}.\n */\n\n/**\n * @template {CompileResults | undefined} Result\n *   Node type that the transformer yields.\n * @typedef {(\n *   Result extends Value | undefined ?\n *     VFile :\n *     VFile & {result: Result}\n *   )} VFileWithOutput\n *   Type to generate a {@linkcode VFile} corresponding to a compiler result.\n *\n *   If a result that is not acceptable on a `VFile` is used, that will\n *   be stored on the `result` field of {@linkcode VFile}.\n */\n\nimport {bail} from 'bail'\nimport extend from 'extend'\nimport {ok as assert} from 'devlop'\nimport isPlainObj from 'is-plain-obj'\nimport {trough} from 'trough'\nimport {VFile} from 'vfile'\nimport {CallableInstance} from './callable-instance.js'\n\n// To do: next major: drop `Compiler`, `Parser`: prefer lowercase.\n\n// To do: we could start yielding `never` in TS when a parser is missing and\n// `parse` is called.\n// Currently, we allow directly setting `processor.parser`, which is untyped.\n\nconst own = {}.hasOwnProperty\n\n/**\n * @template {Node | undefined} [ParseTree=undefined]\n *   Output of `parse` (optional).\n * @template {Node | undefined} [HeadTree=undefined]\n *   Input for `run` (optional).\n * @template {Node | undefined} [TailTree=undefined]\n *   Output for `run` (optional).\n * @template {Node | undefined} [CompileTree=undefined]\n *   Input of `stringify` (optional).\n * @template {CompileResults | undefined} [CompileResult=undefined]\n *   Output of `stringify` (optional).\n * @extends {CallableInstance<[], Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>>}\n */\nexport class Processor extends CallableInstance {\n  /**\n   * Create a processor.\n   */\n  constructor() {\n    // If `Processor()` is called (w/o new), `copy` is called instead.\n    super('copy')\n\n    /**\n     * Compiler to use (deprecated).\n     *\n     * @deprecated\n     *   Use `compiler` instead.\n     * @type {(\n     *   Compiler<\n     *     CompileTree extends undefined ? Node : CompileTree,\n     *     CompileResult extends undefined ? CompileResults : CompileResult\n     *   > |\n     *   undefined\n     * )}\n     */\n    this.Compiler = undefined\n\n    /**\n     * Parser to use (deprecated).\n     *\n     * @deprecated\n     *   Use `parser` instead.\n     * @type {(\n     *   Parser<ParseTree extends undefined ? Node : ParseTree> |\n     *   undefined\n     * )}\n     */\n    this.Parser = undefined\n\n    // Note: the following fields are considered private.\n    // However, they are needed for tests, and TSC generates an untyped\n    // `private freezeIndex` field for, which trips `type-coverage` up.\n    // Instead, we use `@deprecated` to visualize that they shouldn’t be used.\n    /**\n     * Internal list of configured plugins.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {Array<PluginTuple<Array<unknown>>>}\n     */\n    this.attachers = []\n\n    /**\n     * Compiler to use.\n     *\n     * @type {(\n     *   Compiler<\n     *     CompileTree extends undefined ? Node : CompileTree,\n     *     CompileResult extends undefined ? CompileResults : CompileResult\n     *   > |\n     *   undefined\n     * )}\n     */\n    this.compiler = undefined\n\n    /**\n     * Internal state to track where we are while freezing.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {number}\n     */\n    this.freezeIndex = -1\n\n    /**\n     * Internal state to track whether we’re frozen.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {boolean | undefined}\n     */\n    this.frozen = undefined\n\n    /**\n     * Internal state.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {Data}\n     */\n    this.namespace = {}\n\n    /**\n     * Parser to use.\n     *\n     * @type {(\n     *   Parser<ParseTree extends undefined ? Node : ParseTree> |\n     *   undefined\n     * )}\n     */\n    this.parser = undefined\n\n    /**\n     * Internal list of configured transformers.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {Pipeline}\n     */\n    this.transformers = trough()\n  }\n\n  /**\n   * Copy a processor.\n   *\n   * @deprecated\n   *   This is a private internal method and should not be used.\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *   New *unfrozen* processor ({@linkcode Processor}) that is\n   *   configured to work the same as its ancestor.\n   *   When the descendant processor is configured in the future it does not\n   *   affect the ancestral processor.\n   */\n  copy() {\n    // Cast as the type parameters will be the same after attaching.\n    const destination =\n      /** @type {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} */ (\n        new Processor()\n      )\n    let index = -1\n\n    while (++index < this.attachers.length) {\n      const attacher = this.attachers[index]\n      destination.use(...attacher)\n    }\n\n    destination.data(extend(true, {}, this.namespace))\n\n    return destination\n  }\n\n  /**\n   * Configure the processor with info available to all plugins.\n   * Information is stored in an object.\n   *\n   * Typically, options can be given to a specific plugin, but sometimes it\n   * makes sense to have information shared with several plugins.\n   * For example, a list of HTML elements that are self-closing, which is\n   * needed during all phases.\n   *\n   * > **Note**: setting information cannot occur on *frozen* processors.\n   * > Call the processor first to create a new unfrozen processor.\n   *\n   * > **Note**: to register custom data in TypeScript, augment the\n   * > {@linkcode Data} interface.\n   *\n   * @example\n   *   This example show how to get and set info:\n   *\n   *   ```js\n   *   import {unified} from 'unified'\n   *\n   *   const processor = unified().data('alpha', 'bravo')\n   *\n   *   processor.data('alpha') // => 'bravo'\n   *\n   *   processor.data() // => {alpha: 'bravo'}\n   *\n   *   processor.data({charlie: 'delta'})\n   *\n   *   processor.data() // => {charlie: 'delta'}\n   *   ```\n   *\n   * @template {keyof Data} Key\n   *\n   * @overload\n   * @returns {Data}\n   *\n   * @overload\n   * @param {Data} dataset\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @overload\n   * @param {Key} key\n   * @returns {Data[Key]}\n   *\n   * @overload\n   * @param {Key} key\n   * @param {Data[Key]} value\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @param {Data | Key} [key]\n   *   Key to get or set, or entire dataset to set, or nothing to get the\n   *   entire dataset (optional).\n   * @param {Data[Key]} [value]\n   *   Value to set (optional).\n   * @returns {unknown}\n   *   The current processor when setting, the value at `key` when getting, or\n   *   the entire dataset when getting without key.\n   */\n  data(key, value) {\n    if (typeof key === 'string') {\n      // Set `key`.\n      if (arguments.length === 2) {\n        assertUnfrozen('data', this.frozen)\n        this.namespace[key] = value\n        return this\n      }\n\n      // Get `key`.\n      return (own.call(this.namespace, key) && this.namespace[key]) || undefined\n    }\n\n    // Set space.\n    if (key) {\n      assertUnfrozen('data', this.frozen)\n      this.namespace = key\n      return this\n    }\n\n    // Get space.\n    return this.namespace\n  }\n\n  /**\n   * Freeze a processor.\n   *\n   * Frozen processors are meant to be extended and not to be configured\n   * directly.\n   *\n   * When a processor is frozen it cannot be unfrozen.\n   * New processors working the same way can be created by calling the\n   * processor.\n   *\n   * It’s possible to freeze processors explicitly by calling `.freeze()`.\n   * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,\n   * `.stringify()`, `.process()`, or `.processSync()` are called.\n   *\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *   The current processor.\n   */\n  freeze() {\n    if (this.frozen) {\n      return this\n    }\n\n    // Cast so that we can type plugins easier.\n    // Plugins are supposed to be usable on different processors, not just on\n    // this exact processor.\n    const self = /** @type {Processor} */ (/** @type {unknown} */ (this))\n\n    while (++this.freezeIndex < this.attachers.length) {\n      const [attacher, ...options] = this.attachers[this.freezeIndex]\n\n      if (options[0] === false) {\n        continue\n      }\n\n      if (options[0] === true) {\n        options[0] = undefined\n      }\n\n      const transformer = attacher.call(self, ...options)\n\n      if (typeof transformer === 'function') {\n        this.transformers.use(transformer)\n      }\n    }\n\n    this.frozen = true\n    this.freezeIndex = Number.POSITIVE_INFINITY\n\n    return this\n  }\n\n  /**\n   * Parse text to a syntax tree.\n   *\n   * > **Note**: `parse` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `parse` performs the parse phase, not the run phase or other\n   * > phases.\n   *\n   * @param {Compatible | undefined} [file]\n   *   file to parse (optional); typically `string` or `VFile`; any value\n   *   accepted as `x` in `new VFile(x)`.\n   * @returns {ParseTree extends undefined ? Node : ParseTree}\n   *   Syntax tree representing `file`.\n   */\n  parse(file) {\n    this.freeze()\n    const realFile = vfile(file)\n    const parser = this.parser || this.Parser\n    assertParser('parse', parser)\n    return parser(String(realFile), realFile)\n  }\n\n  /**\n   * Process the given file as configured on the processor.\n   *\n   * > **Note**: `process` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `process` performs the parse, run, and stringify phases.\n   *\n   * @overload\n   * @param {Compatible | undefined} file\n   * @param {ProcessCallback<VFileWithOutput<CompileResult>>} done\n   * @returns {undefined}\n   *\n   * @overload\n   * @param {Compatible | undefined} [file]\n   * @returns {Promise<VFileWithOutput<CompileResult>>}\n   *\n   * @param {Compatible | undefined} [file]\n   *   File (optional); typically `string` or `VFile`]; any value accepted as\n   *   `x` in `new VFile(x)`.\n   * @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]\n   *   Callback (optional).\n   * @returns {Promise<VFile> | undefined}\n   *   Nothing if `done` is given.\n   *   Otherwise a promise, rejected with a fatal error or resolved with the\n   *   processed file.\n   *\n   *   The parsed, transformed, and compiled value is available at\n   *   `file.value` (see note).\n   *\n   *   > **Note**: unified typically compiles by serializing: most\n   *   > compilers return `string` (or `Uint8Array`).\n   *   > Some compilers, such as the one configured with\n   *   > [`rehype-react`][rehype-react], return other values (in this case, a\n   *   > React tree).\n   *   > If you’re using a compiler that doesn’t serialize, expect different\n   *   > result values.\n   *   >\n   *   > To register custom results in TypeScript, add them to\n   *   > {@linkcode CompileResultMap}.\n   *\n   *   [rehype-react]: https://github.com/rehypejs/rehype-react\n   */\n  process(file, done) {\n    const self = this\n\n    this.freeze()\n    assertParser('process', this.parser || this.Parser)\n    assertCompiler('process', this.compiler || this.Compiler)\n\n    return done ? executor(undefined, done) : new Promise(executor)\n\n    // Note: `void`s needed for TS.\n    /**\n     * @param {((file: VFileWithOutput<CompileResult>) => undefined | void) | undefined} resolve\n     * @param {(error: Error | undefined) => undefined | void} reject\n     * @returns {undefined}\n     */\n    function executor(resolve, reject) {\n      const realFile = vfile(file)\n      // Assume `ParseTree` (the result of the parser) matches `HeadTree` (the\n      // input of the first transform).\n      const parseTree =\n        /** @type {HeadTree extends undefined ? Node : HeadTree} */ (\n          /** @type {unknown} */ (self.parse(realFile))\n        )\n\n      self.run(parseTree, realFile, function (error, tree, file) {\n        if (error || !tree || !file) {\n          return realDone(error)\n        }\n\n        // Assume `TailTree` (the output of the last transform) matches\n        // `CompileTree` (the input of the compiler).\n        const compileTree =\n          /** @type {CompileTree extends undefined ? Node : CompileTree} */ (\n            /** @type {unknown} */ (tree)\n          )\n\n        const compileResult = self.stringify(compileTree, file)\n\n        if (looksLikeAValue(compileResult)) {\n          file.value = compileResult\n        } else {\n          file.result = compileResult\n        }\n\n        realDone(error, /** @type {VFileWithOutput<CompileResult>} */ (file))\n      })\n\n      /**\n       * @param {Error | undefined} error\n       * @param {VFileWithOutput<CompileResult> | undefined} [file]\n       * @returns {undefined}\n       */\n      function realDone(error, file) {\n        if (error || !file) {\n          reject(error)\n        } else if (resolve) {\n          resolve(file)\n        } else {\n          assert(done, '`done` is defined if `resolve` is not')\n          done(undefined, file)\n        }\n      }\n    }\n  }\n\n  /**\n   * Process the given file as configured on the processor.\n   *\n   * An error is thrown if asynchronous transforms are configured.\n   *\n   * > **Note**: `processSync` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `processSync` performs the parse, run, and stringify phases.\n   *\n   * @param {Compatible | undefined} [file]\n   *   File (optional); typically `string` or `VFile`; any value accepted as\n   *   `x` in `new VFile(x)`.\n   * @returns {VFileWithOutput<CompileResult>}\n   *   The processed file.\n   *\n   *   The parsed, transformed, and compiled value is available at\n   *   `file.value` (see note).\n   *\n   *   > **Note**: unified typically compiles by serializing: most\n   *   > compilers return `string` (or `Uint8Array`).\n   *   > Some compilers, such as the one configured with\n   *   > [`rehype-react`][rehype-react], return other values (in this case, a\n   *   > React tree).\n   *   > If you’re using a compiler that doesn’t serialize, expect different\n   *   > result values.\n   *   >\n   *   > To register custom results in TypeScript, add them to\n   *   > {@linkcode CompileResultMap}.\n   *\n   *   [rehype-react]: https://github.com/rehypejs/rehype-react\n   */\n  processSync(file) {\n    /** @type {boolean} */\n    let complete = false\n    /** @type {VFileWithOutput<CompileResult> | undefined} */\n    let result\n\n    this.freeze()\n    assertParser('processSync', this.parser || this.Parser)\n    assertCompiler('processSync', this.compiler || this.Compiler)\n\n    this.process(file, realDone)\n    assertDone('processSync', 'process', complete)\n    assert(result, 'we either bailed on an error or have a tree')\n\n    return result\n\n    /**\n     * @type {ProcessCallback<VFileWithOutput<CompileResult>>}\n     */\n    function realDone(error, file) {\n      complete = true\n      bail(error)\n      result = file\n    }\n  }\n\n  /**\n   * Run *transformers* on a syntax tree.\n   *\n   * > **Note**: `run` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `run` performs the run phase, not other phases.\n   *\n   * @overload\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done\n   * @returns {undefined}\n   *\n   * @overload\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   * @param {Compatible | undefined} file\n   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done\n   * @returns {undefined}\n   *\n   * @overload\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   * @param {Compatible | undefined} [file]\n   * @returns {Promise<TailTree extends undefined ? Node : TailTree>}\n   *\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   *   Tree to transform and inspect.\n   * @param {(\n   *   RunCallback<TailTree extends undefined ? Node : TailTree> |\n   *   Compatible\n   * )} [file]\n   *   File associated with `node` (optional); any value accepted as `x` in\n   *   `new VFile(x)`.\n   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]\n   *   Callback (optional).\n   * @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}\n   *   Nothing if `done` is given.\n   *   Otherwise, a promise rejected with a fatal error or resolved with the\n   *   transformed tree.\n   */\n  run(tree, file, done) {\n    assertNode(tree)\n    this.freeze()\n\n    const transformers = this.transformers\n\n    if (!done && typeof file === 'function') {\n      done = file\n      file = undefined\n    }\n\n    return done ? executor(undefined, done) : new Promise(executor)\n\n    // Note: `void`s needed for TS.\n    /**\n     * @param {(\n     *   ((tree: TailTree extends undefined ? Node : TailTree) => undefined | void) |\n     *   undefined\n     * )} resolve\n     * @param {(error: Error) => undefined | void} reject\n     * @returns {undefined}\n     */\n    function executor(resolve, reject) {\n      assert(\n        typeof file !== 'function',\n        '`file` can’t be a `done` anymore, we checked'\n      )\n      const realFile = vfile(file)\n      transformers.run(tree, realFile, realDone)\n\n      /**\n       * @param {Error | undefined} error\n       * @param {Node} outputTree\n       * @param {VFile} file\n       * @returns {undefined}\n       */\n      function realDone(error, outputTree, file) {\n        const resultingTree =\n          /** @type {TailTree extends undefined ? Node : TailTree} */ (\n            outputTree || tree\n          )\n\n        if (error) {\n          reject(error)\n        } else if (resolve) {\n          resolve(resultingTree)\n        } else {\n          assert(done, '`done` is defined if `resolve` is not')\n          done(undefined, resultingTree, file)\n        }\n      }\n    }\n  }\n\n  /**\n   * Run *transformers* on a syntax tree.\n   *\n   * An error is thrown if asynchronous transforms are configured.\n   *\n   * > **Note**: `runSync` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `runSync` performs the run phase, not other phases.\n   *\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   *   Tree to transform and inspect.\n   * @param {Compatible | undefined} [file]\n   *   File associated with `node` (optional); any value accepted as `x` in\n   *   `new VFile(x)`.\n   * @returns {TailTree extends undefined ? Node : TailTree}\n   *   Transformed tree.\n   */\n  runSync(tree, file) {\n    /** @type {boolean} */\n    let complete = false\n    /** @type {(TailTree extends undefined ? Node : TailTree) | undefined} */\n    let result\n\n    this.run(tree, file, realDone)\n\n    assertDone('runSync', 'run', complete)\n    assert(result, 'we either bailed on an error or have a tree')\n    return result\n\n    /**\n     * @type {RunCallback<TailTree extends undefined ? Node : TailTree>}\n     */\n    function realDone(error, tree) {\n      bail(error)\n      result = tree\n      complete = true\n    }\n  }\n\n  /**\n   * Compile a syntax tree.\n   *\n   * > **Note**: `stringify` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `stringify` performs the stringify phase, not the run phase\n   * > or other phases.\n   *\n   * @param {CompileTree extends undefined ? Node : CompileTree} tree\n   *   Tree to compile.\n   * @param {Compatible | undefined} [file]\n   *   File associated with `node` (optional); any value accepted as `x` in\n   *   `new VFile(x)`.\n   * @returns {CompileResult extends undefined ? Value : CompileResult}\n   *   Textual representation of the tree (see note).\n   *\n   *   > **Note**: unified typically compiles by serializing: most compilers\n   *   > return `string` (or `Uint8Array`).\n   *   > Some compilers, such as the one configured with\n   *   > [`rehype-react`][rehype-react], return other values (in this case, a\n   *   > React tree).\n   *   > If you’re using a compiler that doesn’t serialize, expect different\n   *   > result values.\n   *   >\n   *   > To register custom results in TypeScript, add them to\n   *   > {@linkcode CompileResultMap}.\n   *\n   *   [rehype-react]: https://github.com/rehypejs/rehype-react\n   */\n  stringify(tree, file) {\n    this.freeze()\n    const realFile = vfile(file)\n    const compiler = this.compiler || this.Compiler\n    assertCompiler('stringify', compiler)\n    assertNode(tree)\n\n    return compiler(tree, realFile)\n  }\n\n  /**\n   * Configure the processor to use a plugin, a list of usable values, or a\n   * preset.\n   *\n   * If the processor is already using a plugin, the previous plugin\n   * configuration is changed based on the options that are passed in.\n   * In other words, the plugin is not added a second time.\n   *\n   * > **Note**: `use` cannot be called on *frozen* processors.\n   * > Call the processor first to create a new unfrozen processor.\n   *\n   * @example\n   *   There are many ways to pass plugins to `.use()`.\n   *   This example gives an overview:\n   *\n   *   ```js\n   *   import {unified} from 'unified'\n   *\n   *   unified()\n   *     // Plugin with options:\n   *     .use(pluginA, {x: true, y: true})\n   *     // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):\n   *     .use(pluginA, {y: false, z: true})\n   *     // Plugins:\n   *     .use([pluginB, pluginC])\n   *     // Two plugins, the second with options:\n   *     .use([pluginD, [pluginE, {}]])\n   *     // Preset with plugins and settings:\n   *     .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})\n   *     // Settings only:\n   *     .use({settings: {position: false}})\n   *   ```\n   *\n   * @template {Array<unknown>} [Parameters=[]]\n   * @template {Node | string | undefined} [Input=undefined]\n   * @template [Output=Input]\n   *\n   * @overload\n   * @param {Preset | null | undefined} [preset]\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @overload\n   * @param {PluggableList} list\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @overload\n   * @param {Plugin<Parameters, Input, Output>} plugin\n   * @param {...(Parameters | [boolean])} parameters\n   * @returns {UsePlugin<ParseTree, HeadTree, TailTree, CompileTree, CompileResult, Input, Output>}\n   *\n   * @param {PluggableList | Plugin | Preset | null | undefined} value\n   *   Usable value.\n   * @param {...unknown} parameters\n   *   Parameters, when a plugin is given as a usable value.\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *   Current processor.\n   */\n  use(value, ...parameters) {\n    const attachers = this.attachers\n    const namespace = this.namespace\n\n    assertUnfrozen('use', this.frozen)\n\n    if (value === null || value === undefined) {\n      // Empty.\n    } else if (typeof value === 'function') {\n      addPlugin(value, parameters)\n    } else if (typeof value === 'object') {\n      if (Array.isArray(value)) {\n        addList(value)\n      } else {\n        addPreset(value)\n      }\n    } else {\n      throw new TypeError('Expected usable value, not `' + value + '`')\n    }\n\n    return this\n\n    /**\n     * @param {Pluggable} value\n     * @returns {undefined}\n     */\n    function add(value) {\n      if (typeof value === 'function') {\n        addPlugin(value, [])\n      } else if (typeof value === 'object') {\n        if (Array.isArray(value)) {\n          const [plugin, ...parameters] =\n            /** @type {PluginTuple<Array<unknown>>} */ (value)\n          addPlugin(plugin, parameters)\n        } else {\n          addPreset(value)\n        }\n      } else {\n        throw new TypeError('Expected usable value, not `' + value + '`')\n      }\n    }\n\n    /**\n     * @param {Preset} result\n     * @returns {undefined}\n     */\n    function addPreset(result) {\n      if (!('plugins' in result) && !('settings' in result)) {\n        throw new Error(\n          'Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither'\n        )\n      }\n\n      addList(result.plugins)\n\n      if (result.settings) {\n        namespace.settings = extend(true, namespace.settings, result.settings)\n      }\n    }\n\n    /**\n     * @param {PluggableList | null | undefined} plugins\n     * @returns {undefined}\n     */\n    function addList(plugins) {\n      let index = -1\n\n      if (plugins === null || plugins === undefined) {\n        // Empty.\n      } else if (Array.isArray(plugins)) {\n        while (++index < plugins.length) {\n          const thing = plugins[index]\n          add(thing)\n        }\n      } else {\n        throw new TypeError('Expected a list of plugins, not `' + plugins + '`')\n      }\n    }\n\n    /**\n     * @param {Plugin} plugin\n     * @param {Array<unknown>} parameters\n     * @returns {undefined}\n     */\n    function addPlugin(plugin, parameters) {\n      let index = -1\n      let entryIndex = -1\n\n      while (++index < attachers.length) {\n        if (attachers[index][0] === plugin) {\n          entryIndex = index\n          break\n        }\n      }\n\n      if (entryIndex === -1) {\n        attachers.push([plugin, ...parameters])\n      }\n      // Only set if there was at least a `primary` value, otherwise we’d change\n      // `arguments.length`.\n      else if (parameters.length > 0) {\n        let [primary, ...rest] = parameters\n        const currentPrimary = attachers[entryIndex][1]\n        if (isPlainObj(currentPrimary) && isPlainObj(primary)) {\n          primary = extend(true, currentPrimary, primary)\n        }\n\n        attachers[entryIndex] = [plugin, primary, ...rest]\n      }\n    }\n  }\n}\n\n// Note: this returns a *callable* instance.\n// That’s why it’s documented as a function.\n/**\n * Create a new processor.\n *\n * @example\n *   This example shows how a new processor can be created (from `remark`) and linked\n *   to **stdin**(4) and **stdout**(4).\n *\n *   ```js\n *   import process from 'node:process'\n *   import concatStream from 'concat-stream'\n *   import {remark} from 'remark'\n *\n *   process.stdin.pipe(\n *     concatStream(function (buf) {\n *       process.stdout.write(String(remark().processSync(buf)))\n *     })\n *   )\n *   ```\n *\n * @returns\n *   New *unfrozen* processor (`processor`).\n *\n *   This processor is configured to work the same as its ancestor.\n *   When the descendant processor is configured in the future it does not\n *   affect the ancestral processor.\n */\nexport const unified = new Processor().freeze()\n\n/**\n * Assert a parser is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Parser}\n */\nfunction assertParser(name, value) {\n  if (typeof value !== 'function') {\n    throw new TypeError('Cannot `' + name + '` without `parser`')\n  }\n}\n\n/**\n * Assert a compiler is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Compiler}\n */\nfunction assertCompiler(name, value) {\n  if (typeof value !== 'function') {\n    throw new TypeError('Cannot `' + name + '` without `compiler`')\n  }\n}\n\n/**\n * Assert the processor is not frozen.\n *\n * @param {string} name\n * @param {unknown} frozen\n * @returns {asserts frozen is false}\n */\nfunction assertUnfrozen(name, frozen) {\n  if (frozen) {\n    throw new Error(\n      'Cannot call `' +\n        name +\n        '` on a frozen processor.\\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.'\n    )\n  }\n}\n\n/**\n * Assert `node` is a unist node.\n *\n * @param {unknown} node\n * @returns {asserts node is Node}\n */\nfunction assertNode(node) {\n  // `isPlainObj` unfortunately uses `any` instead of `unknown`.\n  // type-coverage:ignore-next-line\n  if (!isPlainObj(node) || typeof node.type !== 'string') {\n    throw new TypeError('Expected node, got `' + node + '`')\n    // Fine.\n  }\n}\n\n/**\n * Assert that `complete` is `true`.\n *\n * @param {string} name\n * @param {string} asyncName\n * @param {unknown} complete\n * @returns {asserts complete is true}\n */\nfunction assertDone(name, asyncName, complete) {\n  if (!complete) {\n    throw new Error(\n      '`' + name + '` finished async. Use `' + asyncName + '` instead'\n    )\n  }\n}\n\n/**\n * @param {Compatible | undefined} [value]\n * @returns {VFile}\n */\nfunction vfile(value) {\n  return looksLikeAVFile(value) ? value : new VFile(value)\n}\n\n/**\n * @param {Compatible | undefined} [value]\n * @returns {value is VFile}\n */\nfunction looksLikeAVFile(value) {\n  return Boolean(\n    value &&\n      typeof value === 'object' &&\n      'message' in value &&\n      'messages' in value\n  )\n}\n\n/**\n * @param {unknown} [value]\n * @returns {value is Value}\n */\nfunction looksLikeAValue(value) {\n  return typeof value === 'string' || isUint8Array(value)\n}\n\n/**\n * Assert `value` is an `Uint8Array`.\n *\n * @param {unknown} value\n *   thing.\n * @returns {value is Uint8Array}\n *   Whether `value` is an `Uint8Array`.\n */\nfunction isUint8Array(value) {\n  return Boolean(\n    value &&\n      typeof value === 'object' &&\n      'byteLength' in value &&\n      'byteOffset' in value\n  )\n}\n","/**\n * @import {Element, Nodes, Parents, Root} from 'hast'\n * @import {Root as MdastRoot} from 'mdast'\n * @import {ComponentType, JSX, ReactElement, ReactNode} from 'react'\n * @import {Options as RemarkRehypeOptions} from 'remark-rehype'\n * @import {BuildVisitor} from 'unist-util-visit'\n * @import {PluggableList, Processor} from 'unified'\n */\n\n/**\n * @callback AllowElement\n *   Filter elements.\n * @param {Readonly<Element>} element\n *   Element to check.\n * @param {number} index\n *   Index of `element` in `parent`.\n * @param {Readonly<Parents> | undefined} parent\n *   Parent of `element`.\n * @returns {boolean | null | undefined}\n *   Whether to allow `element` (default: `false`).\n */\n\n/**\n * @typedef ExtraProps\n *   Extra fields we pass.\n * @property {Element | undefined} [node]\n *   passed when `passNode` is on.\n */\n\n/**\n * @typedef {{\n *   [Key in keyof JSX.IntrinsicElements]?: ComponentType<JSX.IntrinsicElements[Key] & ExtraProps> | keyof JSX.IntrinsicElements\n * }} Components\n *   Map tag names to components.\n */\n\n/**\n * @typedef Deprecation\n *   Deprecation.\n * @property {string} from\n *   Old field.\n * @property {string} id\n *   ID in readme.\n * @property {keyof Options} [to]\n *   New field.\n */\n\n/**\n * @typedef Options\n *   Configuration.\n * @property {AllowElement | null | undefined} [allowElement]\n *   Filter elements (optional);\n *   `allowedElements` / `disallowedElements` is used first.\n * @property {ReadonlyArray<string> | null | undefined} [allowedElements]\n *   Tag names to allow (default: all tag names);\n *   cannot combine w/ `disallowedElements`.\n * @property {string | null | undefined} [children]\n *   Markdown.\n * @property {Components | null | undefined} [components]\n *   Map tag names to components.\n * @property {ReadonlyArray<string> | null | undefined} [disallowedElements]\n *   Tag names to disallow (default: `[]`);\n *   cannot combine w/ `allowedElements`.\n * @property {PluggableList | null | undefined} [rehypePlugins]\n *   List of rehype plugins to use.\n * @property {PluggableList | null | undefined} [remarkPlugins]\n *   List of remark plugins to use.\n * @property {Readonly<RemarkRehypeOptions> | null | undefined} [remarkRehypeOptions]\n *   Options to pass through to `remark-rehype`.\n * @property {boolean | null | undefined} [skipHtml=false]\n *   Ignore HTML in markdown completely (default: `false`).\n * @property {boolean | null | undefined} [unwrapDisallowed=false]\n *   Extract (unwrap) what’s in disallowed elements (default: `false`);\n *   normally when say `strong` is not allowed, it and it’s children are dropped,\n *   with `unwrapDisallowed` the element itself is replaced by its children.\n * @property {UrlTransform | null | undefined} [urlTransform]\n *   Change URLs (default: `defaultUrlTransform`)\n */\n\n/**\n * @typedef HooksOptionsOnly\n *   Configuration specifically for {@linkcode MarkdownHooks}.\n * @property {ReactNode | null | undefined} [fallback]\n *   Content to render while the processor processing the markdown (optional).\n */\n\n/**\n * @typedef {Options & HooksOptionsOnly} HooksOptions\n *   Configuration for {@linkcode MarkdownHooks};\n *   extends the regular {@linkcode Options} with a `fallback` prop.\n */\n\n/**\n * @callback UrlTransform\n *   Transform all URLs.\n * @param {string} url\n *   URL.\n * @param {string} key\n *   Property name (example: `'href'`).\n * @param {Readonly<Element>} node\n *   Node.\n * @returns {string | null | undefined}\n *   Transformed URL (optional).\n */\n\nimport {unreachable} from 'devlop'\nimport {toJsxRuntime} from 'hast-util-to-jsx-runtime'\nimport {urlAttributes} from 'html-url-attributes'\nimport {Fragment, jsx, jsxs} from 'react/jsx-runtime'\nimport {useEffect, useState} from 'react'\nimport remarkParse from 'remark-parse'\nimport remarkRehype from 'remark-rehype'\nimport {unified} from 'unified'\nimport {visit} from 'unist-util-visit'\nimport {VFile} from 'vfile'\n\nconst changelog =\n  'https://github.com/remarkjs/react-markdown/blob/main/changelog.md'\n\n/** @type {PluggableList} */\nconst emptyPlugins = []\n/** @type {Readonly<RemarkRehypeOptions>} */\nconst emptyRemarkRehypeOptions = {allowDangerousHtml: true}\nconst safeProtocol = /^(https?|ircs?|mailto|xmpp)$/i\n\n// Mutable because we `delete` any time it’s used and a message is sent.\n/** @type {ReadonlyArray<Readonly<Deprecation>>} */\nconst deprecations = [\n  {from: 'astPlugins', id: 'remove-buggy-html-in-markdown-parser'},\n  {from: 'allowDangerousHtml', id: 'remove-buggy-html-in-markdown-parser'},\n  {\n    from: 'allowNode',\n    id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n    to: 'allowElement'\n  },\n  {\n    from: 'allowedTypes',\n    id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n    to: 'allowedElements'\n  },\n  {from: 'className', id: 'remove-classname'},\n  {\n    from: 'disallowedTypes',\n    id: 'replace-allownode-allowedtypes-and-disallowedtypes',\n    to: 'disallowedElements'\n  },\n  {from: 'escapeHtml', id: 'remove-buggy-html-in-markdown-parser'},\n  {from: 'includeElementIndex', id: '#remove-includeelementindex'},\n  {\n    from: 'includeNodeIndex',\n    id: 'change-includenodeindex-to-includeelementindex'\n  },\n  {from: 'linkTarget', id: 'remove-linktarget'},\n  {from: 'plugins', id: 'change-plugins-to-remarkplugins', to: 'remarkPlugins'},\n  {from: 'rawSourcePos', id: '#remove-rawsourcepos'},\n  {from: 'renderers', id: 'change-renderers-to-components', to: 'components'},\n  {from: 'source', id: 'change-source-to-children', to: 'children'},\n  {from: 'sourcePos', id: '#remove-sourcepos'},\n  {from: 'transformImageUri', id: '#add-urltransform', to: 'urlTransform'},\n  {from: 'transformLinkUri', id: '#add-urltransform', to: 'urlTransform'}\n]\n\n/**\n * Component to render markdown.\n *\n * This is a synchronous component.\n * When using async plugins,\n * see {@linkcode MarkdownAsync} or {@linkcode MarkdownHooks}.\n *\n * @param {Readonly<Options>} options\n *   Props.\n * @returns {ReactElement}\n *   React element.\n */\nexport function Markdown(options) {\n  const processor = createProcessor(options)\n  const file = createFile(options)\n  return post(processor.runSync(processor.parse(file), file), options)\n}\n\n/**\n * Component to render markdown with support for async plugins\n * through async/await.\n *\n * Components returning promises are supported on the server.\n * For async support on the client,\n * see {@linkcode MarkdownHooks}.\n *\n * @param {Readonly<Options>} options\n *   Props.\n * @returns {Promise<ReactElement>}\n *   Promise to a React element.\n */\nexport async function MarkdownAsync(options) {\n  const processor = createProcessor(options)\n  const file = createFile(options)\n  const tree = await processor.run(processor.parse(file), file)\n  return post(tree, options)\n}\n\n/**\n * Component to render markdown with support for async plugins through hooks.\n *\n * This uses `useEffect` and `useState` hooks.\n * Hooks run on the client and do not immediately render something.\n * For async support on the server,\n * see {@linkcode MarkdownAsync}.\n *\n * @param {Readonly<HooksOptions>} options\n *   Props.\n * @returns {ReactNode}\n *   React node.\n */\nexport function MarkdownHooks(options) {\n  const processor = createProcessor(options)\n  const [error, setError] = useState(\n    /** @type {Error | undefined} */ (undefined)\n  )\n  const [tree, setTree] = useState(/** @type {Root | undefined} */ (undefined))\n\n  useEffect(\n    function () {\n      let cancelled = false\n      const file = createFile(options)\n\n      processor.run(processor.parse(file), file, function (error, tree) {\n        if (!cancelled) {\n          setError(error)\n          setTree(tree)\n        }\n      })\n\n      /**\n       * @returns {undefined}\n       *   Nothing.\n       */\n      return function () {\n        cancelled = true\n      }\n    },\n    [\n      options.children,\n      options.rehypePlugins,\n      options.remarkPlugins,\n      options.remarkRehypeOptions\n    ]\n  )\n\n  if (error) throw error\n\n  return tree ? post(tree, options) : options.fallback\n}\n\n/**\n * Set up the `unified` processor.\n *\n * @param {Readonly<Options>} options\n *   Props.\n * @returns {Processor<MdastRoot, MdastRoot, Root, undefined, undefined>}\n *   Result.\n */\nfunction createProcessor(options) {\n  const rehypePlugins = options.rehypePlugins || emptyPlugins\n  const remarkPlugins = options.remarkPlugins || emptyPlugins\n  const remarkRehypeOptions = options.remarkRehypeOptions\n    ? {...options.remarkRehypeOptions, ...emptyRemarkRehypeOptions}\n    : emptyRemarkRehypeOptions\n\n  const processor = unified()\n    .use(remarkParse)\n    .use(remarkPlugins)\n    .use(remarkRehype, remarkRehypeOptions)\n    .use(rehypePlugins)\n\n  return processor\n}\n\n/**\n * Set up the virtual file.\n *\n * @param {Readonly<Options>} options\n *   Props.\n * @returns {VFile}\n *   Result.\n */\nfunction createFile(options) {\n  const children = options.children || ''\n  const file = new VFile()\n\n  if (typeof children === 'string') {\n    file.value = children\n  } else {\n    unreachable(\n      'Unexpected value `' +\n        children +\n        '` for `children` prop, expected `string`'\n    )\n  }\n\n  return file\n}\n\n/**\n * Process the result from unified some more.\n *\n * @param {Nodes} tree\n *   Tree.\n * @param {Readonly<Options>} options\n *   Props.\n * @returns {ReactElement}\n *   React element.\n */\nfunction post(tree, options) {\n  const allowedElements = options.allowedElements\n  const allowElement = options.allowElement\n  const components = options.components\n  const disallowedElements = options.disallowedElements\n  const skipHtml = options.skipHtml\n  const unwrapDisallowed = options.unwrapDisallowed\n  const urlTransform = options.urlTransform || defaultUrlTransform\n\n  for (const deprecation of deprecations) {\n    if (Object.hasOwn(options, deprecation.from)) {\n      unreachable(\n        'Unexpected `' +\n          deprecation.from +\n          '` prop, ' +\n          (deprecation.to\n            ? 'use `' + deprecation.to + '` instead'\n            : 'remove it') +\n          ' (see <' +\n          changelog +\n          '#' +\n          deprecation.id +\n          '> for more info)'\n      )\n    }\n  }\n\n  if (allowedElements && disallowedElements) {\n    unreachable(\n      'Unexpected combined `allowedElements` and `disallowedElements`, expected one or the other'\n    )\n  }\n\n  visit(tree, transform)\n\n  return toJsxRuntime(tree, {\n    Fragment,\n    components,\n    ignoreInvalidStyle: true,\n    jsx,\n    jsxs,\n    passKeys: true,\n    passNode: true\n  })\n\n  /** @type {BuildVisitor<Root>} */\n  function transform(node, index, parent) {\n    if (node.type === 'raw' && parent && typeof index === 'number') {\n      if (skipHtml) {\n        parent.children.splice(index, 1)\n      } else {\n        parent.children[index] = {type: 'text', value: node.value}\n      }\n\n      return index\n    }\n\n    if (node.type === 'element') {\n      /** @type {string} */\n      let key\n\n      for (key in urlAttributes) {\n        if (\n          Object.hasOwn(urlAttributes, key) &&\n          Object.hasOwn(node.properties, key)\n        ) {\n          const value = node.properties[key]\n          const test = urlAttributes[key]\n          if (test === null || test.includes(node.tagName)) {\n            node.properties[key] = urlTransform(String(value || ''), key, node)\n          }\n        }\n      }\n    }\n\n    if (node.type === 'element') {\n      let remove = allowedElements\n        ? !allowedElements.includes(node.tagName)\n        : disallowedElements\n          ? disallowedElements.includes(node.tagName)\n          : false\n\n      if (!remove && allowElement && typeof index === 'number') {\n        remove = !allowElement(node, index, parent)\n      }\n\n      if (remove && parent && typeof index === 'number') {\n        if (unwrapDisallowed && node.children) {\n          parent.children.splice(index, 1, ...node.children)\n        } else {\n          parent.children.splice(index, 1)\n        }\n\n        return index\n      }\n    }\n  }\n}\n\n/**\n * Make a URL safe.\n *\n * @satisfies {UrlTransform}\n * @param {string} value\n *   URL.\n * @returns {string}\n *   Safe URL.\n */\nexport function defaultUrlTransform(value) {\n  // Same as:\n  // <https://github.com/micromark/micromark/blob/929275e/packages/micromark-util-sanitize-uri/dev/index.js#L34>\n  // But without the `encode` part.\n  const colon = value.indexOf(':')\n  const questionMark = value.indexOf('?')\n  const numberSign = value.indexOf('#')\n  const slash = value.indexOf('/')\n\n  if (\n    // If there is no protocol, it’s relative.\n    colon === -1 ||\n    // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol.\n    (slash !== -1 && colon > slash) ||\n    (questionMark !== -1 && colon > questionMark) ||\n    (numberSign !== -1 && colon > numberSign) ||\n    // It is a protocol, it should be allowed.\n    safeProtocol.test(value.slice(0, colon))\n  ) {\n    return value\n  }\n\n  return ''\n}\n","/**\n * Count how often a character (or substring) is used in a string.\n *\n * @param {string} value\n *   Value to search in.\n * @param {string} character\n *   Character (or substring) to look for.\n * @return {number}\n *   Number of times `character` occurred in `value`.\n */\nexport function ccount(value, character) {\n  const source = String(value)\n\n  if (typeof character !== 'string') {\n    throw new TypeError('Expected character')\n  }\n\n  let count = 0\n  let index = source.indexOf(character)\n\n  while (index !== -1) {\n    count++\n    index = source.indexOf(character, index + character.length)\n  }\n\n  return count\n}\n","export default function escapeStringRegexp(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a `\\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n}\n","/**\n * @import {Nodes, Parents, PhrasingContent, Root, Text} from 'mdast'\n * @import {BuildVisitor, Test, VisitorResult} from 'unist-util-visit-parents'\n */\n\n/**\n * @typedef RegExpMatchObject\n *   Info on the match.\n * @property {number} index\n *   The index of the search at which the result was found.\n * @property {string} input\n *   A copy of the search string in the text node.\n * @property {[...Array<Parents>, Text]} stack\n *   All ancestors of the text node, where the last node is the text itself.\n *\n * @typedef {RegExp | string} Find\n *   Pattern to find.\n *\n *   Strings are escaped and then turned into global expressions.\n *\n * @typedef {Array<FindAndReplaceTuple>} FindAndReplaceList\n *   Several find and replaces, in array form.\n *\n * @typedef {[Find, Replace?]} FindAndReplaceTuple\n *   Find and replace in tuple form.\n *\n * @typedef {ReplaceFunction | string | null | undefined} Replace\n *   Thing to replace with.\n *\n * @callback ReplaceFunction\n *   Callback called when a search matches.\n * @param {...any} parameters\n *   The parameters are the result of corresponding search expression:\n *\n *   * `value` (`string`) — whole match\n *   * `...capture` (`Array<string>`) — matches from regex capture groups\n *   * `match` (`RegExpMatchObject`) — info on the match\n * @returns {Array<PhrasingContent> | PhrasingContent | string | false | null | undefined}\n *   Thing to replace with.\n *\n *   * when `null`, `undefined`, `''`, remove the match\n *   * …or when `false`, do not replace at all\n *   * …or when `string`, replace with a text node of that value\n *   * …or when `Node` or `Array<Node>`, replace with those nodes\n *\n * @typedef {[RegExp, ReplaceFunction]} Pair\n *   Normalized find and replace.\n *\n * @typedef {Array<Pair>} Pairs\n *   All find and replaced.\n *\n * @typedef Options\n *   Configuration.\n * @property {Test | null | undefined} [ignore]\n *   Test for which nodes to ignore (optional).\n */\n\nimport escape from 'escape-string-regexp'\nimport {visitParents} from 'unist-util-visit-parents'\nimport {convert} from 'unist-util-is'\n\n/**\n * Find patterns in a tree and replace them.\n *\n * The algorithm searches the tree in *preorder* for complete values in `Text`\n * nodes.\n * Partial matches are not supported.\n *\n * @param {Nodes} tree\n *   Tree to change.\n * @param {FindAndReplaceList | FindAndReplaceTuple} list\n *   Patterns to find.\n * @param {Options | null | undefined} [options]\n *   Configuration (when `find` is not `Find`).\n * @returns {undefined}\n *   Nothing.\n */\nexport function findAndReplace(tree, list, options) {\n  const settings = options || {}\n  const ignored = convert(settings.ignore || [])\n  const pairs = toPairs(list)\n  let pairIndex = -1\n\n  while (++pairIndex < pairs.length) {\n    visitParents(tree, 'text', visitor)\n  }\n\n  /** @type {BuildVisitor<Root, 'text'>} */\n  function visitor(node, parents) {\n    let index = -1\n    /** @type {Parents | undefined} */\n    let grandparent\n\n    while (++index < parents.length) {\n      const parent = parents[index]\n      /** @type {Array<Nodes> | undefined} */\n      const siblings = grandparent ? grandparent.children : undefined\n\n      if (\n        ignored(\n          parent,\n          siblings ? siblings.indexOf(parent) : undefined,\n          grandparent\n        )\n      ) {\n        return\n      }\n\n      grandparent = parent\n    }\n\n    if (grandparent) {\n      return handler(node, parents)\n    }\n  }\n\n  /**\n   * Handle a text node which is not in an ignored parent.\n   *\n   * @param {Text} node\n   *   Text node.\n   * @param {Array<Parents>} parents\n   *   Parents.\n   * @returns {VisitorResult}\n   *   Result.\n   */\n  function handler(node, parents) {\n    const parent = parents[parents.length - 1]\n    const find = pairs[pairIndex][0]\n    const replace = pairs[pairIndex][1]\n    let start = 0\n    /** @type {Array<Nodes>} */\n    const siblings = parent.children\n    const index = siblings.indexOf(node)\n    let change = false\n    /** @type {Array<PhrasingContent>} */\n    let nodes = []\n\n    find.lastIndex = 0\n\n    let match = find.exec(node.value)\n\n    while (match) {\n      const position = match.index\n      /** @type {RegExpMatchObject} */\n      const matchObject = {\n        index: match.index,\n        input: match.input,\n        stack: [...parents, node]\n      }\n      let value = replace(...match, matchObject)\n\n      if (typeof value === 'string') {\n        value = value.length > 0 ? {type: 'text', value} : undefined\n      }\n\n      // It wasn’t a match after all.\n      if (value === false) {\n        // False acts as if there was no match.\n        // So we need to reset `lastIndex`, which currently being at the end of\n        // the current match, to the beginning.\n        find.lastIndex = position + 1\n      } else {\n        if (start !== position) {\n          nodes.push({\n            type: 'text',\n            value: node.value.slice(start, position)\n          })\n        }\n\n        if (Array.isArray(value)) {\n          nodes.push(...value)\n        } else if (value) {\n          nodes.push(value)\n        }\n\n        start = position + match[0].length\n        change = true\n      }\n\n      if (!find.global) {\n        break\n      }\n\n      match = find.exec(node.value)\n    }\n\n    if (change) {\n      if (start < node.value.length) {\n        nodes.push({type: 'text', value: node.value.slice(start)})\n      }\n\n      parent.children.splice(index, 1, ...nodes)\n    } else {\n      nodes = [node]\n    }\n\n    return index + nodes.length\n  }\n}\n\n/**\n * Turn a tuple or a list of tuples into pairs.\n *\n * @param {FindAndReplaceList | FindAndReplaceTuple} tupleOrList\n *   Schema.\n * @returns {Pairs}\n *   Clean pairs.\n */\nfunction toPairs(tupleOrList) {\n  /** @type {Pairs} */\n  const result = []\n\n  if (!Array.isArray(tupleOrList)) {\n    throw new TypeError('Expected find and replace tuple or list of tuples')\n  }\n\n  /** @type {FindAndReplaceList} */\n  // @ts-expect-error: correct.\n  const list =\n    !tupleOrList[0] || Array.isArray(tupleOrList[0])\n      ? tupleOrList\n      : [tupleOrList]\n\n  let index = -1\n\n  while (++index < list.length) {\n    const tuple = list[index]\n    result.push([toExpression(tuple[0]), toFunction(tuple[1])])\n  }\n\n  return result\n}\n\n/**\n * Turn a find into an expression.\n *\n * @param {Find} find\n *   Find.\n * @returns {RegExp}\n *   Expression.\n */\nfunction toExpression(find) {\n  return typeof find === 'string' ? new RegExp(escape(find), 'g') : find\n}\n\n/**\n * Turn a replace into a function.\n *\n * @param {Replace} replace\n *   Replace.\n * @returns {ReplaceFunction}\n *   Function.\n */\nfunction toFunction(replace) {\n  return typeof replace === 'function'\n    ? replace\n    : function () {\n        return replace\n      }\n}\n","/**\n * @import {RegExpMatchObject, ReplaceFunction} from 'mdast-util-find-and-replace'\n * @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, Transform as FromMarkdownTransform} from 'mdast-util-from-markdown'\n * @import {ConstructName, Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n * @import {Link, PhrasingContent} from 'mdast'\n */\n\nimport {ccount} from 'ccount'\nimport {ok as assert} from 'devlop'\nimport {unicodePunctuation, unicodeWhitespace} from 'micromark-util-character'\nimport {findAndReplace} from 'mdast-util-find-and-replace'\n\n/** @type {ConstructName} */\nconst inConstruct = 'phrasing'\n/** @type {Array<ConstructName>} */\nconst notInConstruct = ['autolink', 'link', 'image', 'label']\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralFromMarkdown() {\n  return {\n    transforms: [transformGfmAutolinkLiterals],\n    enter: {\n      literalAutolink: enterLiteralAutolink,\n      literalAutolinkEmail: enterLiteralAutolinkValue,\n      literalAutolinkHttp: enterLiteralAutolinkValue,\n      literalAutolinkWww: enterLiteralAutolinkValue\n    },\n    exit: {\n      literalAutolink: exitLiteralAutolink,\n      literalAutolinkEmail: exitLiteralAutolinkEmail,\n      literalAutolinkHttp: exitLiteralAutolinkHttp,\n      literalAutolinkWww: exitLiteralAutolinkWww\n    }\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralToMarkdown() {\n  return {\n    unsafe: [\n      {\n        character: '@',\n        before: '[+\\\\-.\\\\w]',\n        after: '[\\\\-.\\\\w]',\n        inConstruct,\n        notInConstruct\n      },\n      {\n        character: '.',\n        before: '[Ww]',\n        after: '[\\\\-.\\\\w]',\n        inConstruct,\n        notInConstruct\n      },\n      {\n        character: ':',\n        before: '[ps]',\n        after: '\\\\/',\n        inConstruct,\n        notInConstruct\n      }\n    ]\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolink(token) {\n  this.enter({type: 'link', title: null, url: '', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolinkValue(token) {\n  this.config.enter.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkHttp(token) {\n  this.config.exit.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkWww(token) {\n  this.config.exit.data.call(this, token)\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'link')\n  node.url = 'http://' + this.sliceSerialize(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkEmail(token) {\n  this.config.exit.autolinkEmail.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolink(token) {\n  this.exit(token)\n}\n\n/** @type {FromMarkdownTransform} */\nfunction transformGfmAutolinkLiterals(tree) {\n  findAndReplace(\n    tree,\n    [\n      [/(https?:\\/\\/|www(?=\\.))([-.\\w]+)([^ \\t\\r\\n]*)/gi, findUrl],\n      [/(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)/gu, findEmail]\n    ],\n    {ignore: ['link', 'linkReference']}\n  )\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} protocol\n * @param {string} domain\n * @param {string} path\n * @param {RegExpMatchObject} match\n * @returns {Array<PhrasingContent> | Link | false}\n */\n// eslint-disable-next-line max-params\nfunction findUrl(_, protocol, domain, path, match) {\n  let prefix = ''\n\n  // Not an expected previous character.\n  if (!previous(match)) {\n    return false\n  }\n\n  // Treat `www` as part of the domain.\n  if (/^w/i.test(protocol)) {\n    domain = protocol + domain\n    protocol = ''\n    prefix = 'http://'\n  }\n\n  if (!isCorrectDomain(domain)) {\n    return false\n  }\n\n  const parts = splitUrl(domain + path)\n\n  if (!parts[0]) return false\n\n  /** @type {Link} */\n  const result = {\n    type: 'link',\n    title: null,\n    url: prefix + protocol + parts[0],\n    children: [{type: 'text', value: protocol + parts[0]}]\n  }\n\n  if (parts[1]) {\n    return [result, {type: 'text', value: parts[1]}]\n  }\n\n  return result\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} atext\n * @param {string} label\n * @param {RegExpMatchObject} match\n * @returns {Link | false}\n */\nfunction findEmail(_, atext, label, match) {\n  if (\n    // Not an expected previous character.\n    !previous(match, true) ||\n    // Label ends in not allowed character.\n    /[-\\d_]$/.test(label)\n  ) {\n    return false\n  }\n\n  return {\n    type: 'link',\n    title: null,\n    url: 'mailto:' + atext + '@' + label,\n    children: [{type: 'text', value: atext + '@' + label}]\n  }\n}\n\n/**\n * @param {string} domain\n * @returns {boolean}\n */\nfunction isCorrectDomain(domain) {\n  const parts = domain.split('.')\n\n  if (\n    parts.length < 2 ||\n    (parts[parts.length - 1] &&\n      (/_/.test(parts[parts.length - 1]) ||\n        !/[a-zA-Z\\d]/.test(parts[parts.length - 1]))) ||\n    (parts[parts.length - 2] &&\n      (/_/.test(parts[parts.length - 2]) ||\n        !/[a-zA-Z\\d]/.test(parts[parts.length - 2])))\n  ) {\n    return false\n  }\n\n  return true\n}\n\n/**\n * @param {string} url\n * @returns {[string, string | undefined]}\n */\nfunction splitUrl(url) {\n  const trailExec = /[!\"&'),.:;<>?\\]}]+$/.exec(url)\n\n  if (!trailExec) {\n    return [url, undefined]\n  }\n\n  url = url.slice(0, trailExec.index)\n\n  let trail = trailExec[0]\n  let closingParenIndex = trail.indexOf(')')\n  const openingParens = ccount(url, '(')\n  let closingParens = ccount(url, ')')\n\n  while (closingParenIndex !== -1 && openingParens > closingParens) {\n    url += trail.slice(0, closingParenIndex + 1)\n    trail = trail.slice(closingParenIndex + 1)\n    closingParenIndex = trail.indexOf(')')\n    closingParens++\n  }\n\n  return [url, trail]\n}\n\n/**\n * @param {RegExpMatchObject} match\n * @param {boolean | null | undefined} [email=false]\n * @returns {boolean}\n */\nfunction previous(match, email) {\n  const code = match.input.charCodeAt(match.index - 1)\n\n  return (\n    (match.index === 0 ||\n      unicodeWhitespace(code) ||\n      unicodePunctuation(code)) &&\n    // If it’s an email, the previous character should not be a slash.\n    (!email || code !== 47)\n  )\n}\n","/**\n * @import {\n *   CompileContext,\n *   Extension as FromMarkdownExtension,\n *   Handle as FromMarkdownHandle\n * } from 'mdast-util-from-markdown'\n * @import {ToMarkdownOptions} from 'mdast-util-gfm-footnote'\n * @import {\n *   Handle as ToMarkdownHandle,\n *   Map,\n *   Options as ToMarkdownExtension\n * } from 'mdast-util-to-markdown'\n * @import {FootnoteDefinition, FootnoteReference} from 'mdast'\n */\n\nimport {ok as assert} from 'devlop'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\n\nfootnoteReference.peek = footnoteReferencePeek\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCallString() {\n  this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCall(token) {\n  this.enter({type: 'footnoteReference', identifier: '', label: ''}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinitionLabelString() {\n  this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinition(token) {\n  this.enter(\n    {type: 'footnoteDefinition', identifier: '', label: '', children: []},\n    token\n  )\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCallString(token) {\n  const label = this.resume()\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'footnoteReference')\n  node.identifier = normalizeIdentifier(\n    this.sliceSerialize(token)\n  ).toLowerCase()\n  node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCall(token) {\n  this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinitionLabelString(token) {\n  const label = this.resume()\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'footnoteDefinition')\n  node.identifier = normalizeIdentifier(\n    this.sliceSerialize(token)\n  ).toLowerCase()\n  node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinition(token) {\n  this.exit(token)\n}\n\n/** @type {ToMarkdownHandle} */\nfunction footnoteReferencePeek() {\n  return '['\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {FootnoteReference} node\n */\nfunction footnoteReference(node, _, state, info) {\n  const tracker = state.createTracker(info)\n  let value = tracker.move('[^')\n  const exit = state.enter('footnoteReference')\n  const subexit = state.enter('reference')\n  value += tracker.move(\n    state.safe(state.associationId(node), {after: ']', before: value})\n  )\n  subexit()\n  exit()\n  value += tracker.move(']')\n  return value\n}\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown`.\n */\nexport function gfmFootnoteFromMarkdown() {\n  return {\n    enter: {\n      gfmFootnoteCallString: enterFootnoteCallString,\n      gfmFootnoteCall: enterFootnoteCall,\n      gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,\n      gfmFootnoteDefinition: enterFootnoteDefinition\n    },\n    exit: {\n      gfmFootnoteCallString: exitFootnoteCallString,\n      gfmFootnoteCall: exitFootnoteCall,\n      gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,\n      gfmFootnoteDefinition: exitFootnoteDefinition\n    }\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @param {ToMarkdownOptions | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown`.\n */\nexport function gfmFootnoteToMarkdown(options) {\n  // To do: next major: change default.\n  let firstLineBlank = false\n\n  if (options && options.firstLineBlank) {\n    firstLineBlank = true\n  }\n\n  return {\n    handlers: {footnoteDefinition, footnoteReference},\n    // This is on by default already.\n    unsafe: [{character: '[', inConstruct: ['label', 'phrasing', 'reference']}]\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {FootnoteDefinition} node\n   */\n  function footnoteDefinition(node, _, state, info) {\n    const tracker = state.createTracker(info)\n    let value = tracker.move('[^')\n    const exit = state.enter('footnoteDefinition')\n    const subexit = state.enter('label')\n    value += tracker.move(\n      state.safe(state.associationId(node), {before: value, after: ']'})\n    )\n    subexit()\n\n    value += tracker.move(']:')\n\n    if (node.children && node.children.length > 0) {\n      tracker.shift(4)\n\n      value += tracker.move(\n        (firstLineBlank ? '\\n' : ' ') +\n          state.indentLines(\n            state.containerFlow(node, tracker.current()),\n            firstLineBlank ? mapAll : mapExceptFirst\n          )\n      )\n    }\n\n    exit()\n\n    return value\n  }\n}\n\n/** @type {Map} */\nfunction mapExceptFirst(line, index, blank) {\n  return index === 0 ? line : mapAll(line, index, blank)\n}\n\n/** @type {Map} */\nfunction mapAll(line, index, blank) {\n  return (blank ? '' : '    ') + line\n}\n","/**\n * @typedef {import('mdast').Delete} Delete\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').ConstructName} ConstructName\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n */\n\n/**\n * List of constructs that occur in phrasing (paragraphs, headings), but cannot\n * contain strikethrough.\n * So they sort of cancel each other out.\n * Note: could use a better name.\n *\n * Note: keep in sync with: <https://github.com/syntax-tree/mdast-util-to-markdown/blob/8ce8dbf/lib/unsafe.js#L14>\n *\n * @type {Array<ConstructName>}\n */\nconst constructsWithoutStrikethrough = [\n  'autolink',\n  'destinationLiteral',\n  'destinationRaw',\n  'reference',\n  'titleQuote',\n  'titleApostrophe'\n]\n\nhandleDelete.peek = peekDelete\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughFromMarkdown() {\n  return {\n    canContainEols: ['delete'],\n    enter: {strikethrough: enterStrikethrough},\n    exit: {strikethrough: exitStrikethrough}\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughToMarkdown() {\n  return {\n    unsafe: [\n      {\n        character: '~',\n        inConstruct: 'phrasing',\n        notInConstruct: constructsWithoutStrikethrough\n      }\n    ],\n    handlers: {delete: handleDelete}\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterStrikethrough(token) {\n  this.enter({type: 'delete', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitStrikethrough(token) {\n  this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {Delete} node\n */\nfunction handleDelete(node, _, state, info) {\n  const tracker = state.createTracker(info)\n  const exit = state.enter('strikethrough')\n  let value = tracker.move('~~')\n  value += state.containerPhrasing(node, {\n    ...tracker.current(),\n    before: value,\n    after: '~'\n  })\n  value += tracker.move('~~')\n  exit()\n  return value\n}\n\n/** @type {ToMarkdownHandle} */\nfunction peekDelete() {\n  return '~'\n}\n","// To do: next major: remove.\n/**\n * @typedef {Options} MarkdownTableOptions\n *   Configuration.\n */\n\n/**\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [alignDelimiters=true]\n *   Whether to align the delimiters (default: `true`);\n *   they are aligned by default:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   Pass `false` to make them staggered:\n *\n *   ```markdown\n *   | Alpha | B |\n *   | - | - |\n *   | C | Delta |\n *   ```\n * @property {ReadonlyArray<string | null | undefined> | string | null | undefined} [align]\n *   How to align columns (default: `''`);\n *   one style for all columns or styles for their respective columns;\n *   each style is either `'l'` (left), `'r'` (right), or `'c'` (center);\n *   other values are treated as `''`, which doesn’t place the colon in the\n *   alignment row but does align left;\n *   *only the lowercased first character is used, so `Right` is fine.*\n * @property {boolean | null | undefined} [delimiterEnd=true]\n *   Whether to end each row with the delimiter (default: `true`).\n *\n *   > 👉 **Note**: please don’t use this: it could create fragile structures\n *   > that aren’t understandable to some markdown parsers.\n *\n *   When `true`, there are ending delimiters:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   When `false`, there are no ending delimiters:\n *\n *   ```markdown\n *   | Alpha | B\n *   | ----- | -----\n *   | C     | Delta\n *   ```\n * @property {boolean | null | undefined} [delimiterStart=true]\n *   Whether to begin each row with the delimiter (default: `true`).\n *\n *   > 👉 **Note**: please don’t use this: it could create fragile structures\n *   > that aren’t understandable to some markdown parsers.\n *\n *   When `true`, there are starting delimiters:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   When `false`, there are no starting delimiters:\n *\n *   ```markdown\n *   Alpha | B     |\n *   ----- | ----- |\n *   C     | Delta |\n *   ```\n * @property {boolean | null | undefined} [padding=true]\n *   Whether to add a space of padding between delimiters and cells\n *   (default: `true`).\n *\n *   When `true`, there is padding:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   When `false`, there is no padding:\n *\n *   ```markdown\n *   |Alpha|B    |\n *   |-----|-----|\n *   |C    |Delta|\n *   ```\n * @property {((value: string) => number) | null | undefined} [stringLength]\n *   Function to detect the length of table cell content (optional);\n *   this is used when aligning the delimiters (`|`) between table cells;\n *   full-width characters and emoji mess up delimiter alignment when viewing\n *   the markdown source;\n *   to fix this, you can pass this function,\n *   which receives the cell content and returns its “visible” size;\n *   note that what is and isn’t visible depends on where the text is displayed.\n *\n *   Without such a function, the following:\n *\n *   ```js\n *   markdownTable([\n *     ['Alpha', 'Bravo'],\n *     ['中文', 'Charlie'],\n *     ['👩‍❤️‍👩', 'Delta']\n *   ])\n *   ```\n *\n *   Yields:\n *\n *   ```markdown\n *   | Alpha | Bravo |\n *   | - | - |\n *   | 中文 | Charlie |\n *   | 👩‍❤️‍👩 | Delta |\n *   ```\n *\n *   With [`string-width`](https://github.com/sindresorhus/string-width):\n *\n *   ```js\n *   import stringWidth from 'string-width'\n *\n *   markdownTable(\n *     [\n *       ['Alpha', 'Bravo'],\n *       ['中文', 'Charlie'],\n *       ['👩‍❤️‍👩', 'Delta']\n *     ],\n *     {stringLength: stringWidth}\n *   )\n *   ```\n *\n *   Yields:\n *\n *   ```markdown\n *   | Alpha | Bravo   |\n *   | ----- | ------- |\n *   | 中文  | Charlie |\n *   | 👩‍❤️‍👩    | Delta   |\n *   ```\n */\n\n/**\n * @param {string} value\n *   Cell value.\n * @returns {number}\n *   Cell size.\n */\nfunction defaultStringLength(value) {\n  return value.length\n}\n\n/**\n * Generate a markdown\n * ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables))\n * table.\n *\n * @param {ReadonlyArray<ReadonlyArray<string | null | undefined>>} table\n *   Table data (matrix of strings).\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Result.\n */\nexport function markdownTable(table, options) {\n  const settings = options || {}\n  // To do: next major: change to spread.\n  const align = (settings.align || []).concat()\n  const stringLength = settings.stringLength || defaultStringLength\n  /** @type {Array<number>} Character codes as symbols for alignment per column. */\n  const alignments = []\n  /** @type {Array<Array<string>>} Cells per row. */\n  const cellMatrix = []\n  /** @type {Array<Array<number>>} Sizes of each cell per row. */\n  const sizeMatrix = []\n  /** @type {Array<number>} */\n  const longestCellByColumn = []\n  let mostCellsPerRow = 0\n  let rowIndex = -1\n\n  // This is a superfluous loop if we don’t align delimiters, but otherwise we’d\n  // do superfluous work when aligning, so optimize for aligning.\n  while (++rowIndex < table.length) {\n    /** @type {Array<string>} */\n    const row = []\n    /** @type {Array<number>} */\n    const sizes = []\n    let columnIndex = -1\n\n    if (table[rowIndex].length > mostCellsPerRow) {\n      mostCellsPerRow = table[rowIndex].length\n    }\n\n    while (++columnIndex < table[rowIndex].length) {\n      const cell = serialize(table[rowIndex][columnIndex])\n\n      if (settings.alignDelimiters !== false) {\n        const size = stringLength(cell)\n        sizes[columnIndex] = size\n\n        if (\n          longestCellByColumn[columnIndex] === undefined ||\n          size > longestCellByColumn[columnIndex]\n        ) {\n          longestCellByColumn[columnIndex] = size\n        }\n      }\n\n      row.push(cell)\n    }\n\n    cellMatrix[rowIndex] = row\n    sizeMatrix[rowIndex] = sizes\n  }\n\n  // Figure out which alignments to use.\n  let columnIndex = -1\n\n  if (typeof align === 'object' && 'length' in align) {\n    while (++columnIndex < mostCellsPerRow) {\n      alignments[columnIndex] = toAlignment(align[columnIndex])\n    }\n  } else {\n    const code = toAlignment(align)\n\n    while (++columnIndex < mostCellsPerRow) {\n      alignments[columnIndex] = code\n    }\n  }\n\n  // Inject the alignment row.\n  columnIndex = -1\n  /** @type {Array<string>} */\n  const row = []\n  /** @type {Array<number>} */\n  const sizes = []\n\n  while (++columnIndex < mostCellsPerRow) {\n    const code = alignments[columnIndex]\n    let before = ''\n    let after = ''\n\n    if (code === 99 /* `c` */) {\n      before = ':'\n      after = ':'\n    } else if (code === 108 /* `l` */) {\n      before = ':'\n    } else if (code === 114 /* `r` */) {\n      after = ':'\n    }\n\n    // There *must* be at least one hyphen-minus in each alignment cell.\n    let size =\n      settings.alignDelimiters === false\n        ? 1\n        : Math.max(\n            1,\n            longestCellByColumn[columnIndex] - before.length - after.length\n          )\n\n    const cell = before + '-'.repeat(size) + after\n\n    if (settings.alignDelimiters !== false) {\n      size = before.length + size + after.length\n\n      if (size > longestCellByColumn[columnIndex]) {\n        longestCellByColumn[columnIndex] = size\n      }\n\n      sizes[columnIndex] = size\n    }\n\n    row[columnIndex] = cell\n  }\n\n  // Inject the alignment row.\n  cellMatrix.splice(1, 0, row)\n  sizeMatrix.splice(1, 0, sizes)\n\n  rowIndex = -1\n  /** @type {Array<string>} */\n  const lines = []\n\n  while (++rowIndex < cellMatrix.length) {\n    const row = cellMatrix[rowIndex]\n    const sizes = sizeMatrix[rowIndex]\n    columnIndex = -1\n    /** @type {Array<string>} */\n    const line = []\n\n    while (++columnIndex < mostCellsPerRow) {\n      const cell = row[columnIndex] || ''\n      let before = ''\n      let after = ''\n\n      if (settings.alignDelimiters !== false) {\n        const size =\n          longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)\n        const code = alignments[columnIndex]\n\n        if (code === 114 /* `r` */) {\n          before = ' '.repeat(size)\n        } else if (code === 99 /* `c` */) {\n          if (size % 2) {\n            before = ' '.repeat(size / 2 + 0.5)\n            after = ' '.repeat(size / 2 - 0.5)\n          } else {\n            before = ' '.repeat(size / 2)\n            after = before\n          }\n        } else {\n          after = ' '.repeat(size)\n        }\n      }\n\n      if (settings.delimiterStart !== false && !columnIndex) {\n        line.push('|')\n      }\n\n      if (\n        settings.padding !== false &&\n        // Don’t add the opening space if we’re not aligning and the cell is\n        // empty: there will be a closing space.\n        !(settings.alignDelimiters === false && cell === '') &&\n        (settings.delimiterStart !== false || columnIndex)\n      ) {\n        line.push(' ')\n      }\n\n      if (settings.alignDelimiters !== false) {\n        line.push(before)\n      }\n\n      line.push(cell)\n\n      if (settings.alignDelimiters !== false) {\n        line.push(after)\n      }\n\n      if (settings.padding !== false) {\n        line.push(' ')\n      }\n\n      if (\n        settings.delimiterEnd !== false ||\n        columnIndex !== mostCellsPerRow - 1\n      ) {\n        line.push('|')\n      }\n    }\n\n    lines.push(\n      settings.delimiterEnd === false\n        ? line.join('').replace(/ +$/, '')\n        : line.join('')\n    )\n  }\n\n  return lines.join('\\n')\n}\n\n/**\n * @param {string | null | undefined} [value]\n *   Value to serialize.\n * @returns {string}\n *   Result.\n */\nfunction serialize(value) {\n  return value === null || value === undefined ? '' : String(value)\n}\n\n/**\n * @param {string | null | undefined} value\n *   Value.\n * @returns {number}\n *   Alignment.\n */\nfunction toAlignment(value) {\n  const code = typeof value === 'string' ? value.codePointAt(0) : 0\n\n  return code === 67 /* `C` */ || code === 99 /* `c` */\n    ? 99 /* `c` */\n    : code === 76 /* `L` */ || code === 108 /* `l` */\n      ? 108 /* `l` */\n      : code === 82 /* `R` */ || code === 114 /* `r` */\n        ? 114 /* `r` */\n        : 0\n}\n","/**\n * @import {Blockquote, Parents} from 'mdast'\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Blockquote} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function blockquote(node, _, state, info) {\n  const exit = state.enter('blockquote')\n  const tracker = state.createTracker(info)\n  tracker.move('> ')\n  tracker.shift(2)\n  const value = state.indentLines(\n    state.containerFlow(node, tracker.current()),\n    map\n  )\n  exit()\n  return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n  return '>' + (blank ? '' : ' ') + line\n}\n","/**\n * @import {ConstructName, Unsafe} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe} pattern\n * @returns {boolean}\n */\nexport function patternInScope(stack, pattern) {\n  return (\n    listInScope(stack, pattern.inConstruct, true) &&\n    !listInScope(stack, pattern.notInConstruct, false)\n  )\n}\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe['inConstruct']} list\n * @param {boolean} none\n * @returns {boolean}\n */\nfunction listInScope(stack, list, none) {\n  if (typeof list === 'string') {\n    list = [list]\n  }\n\n  if (!list || list.length === 0) {\n    return none\n  }\n\n  let index = -1\n\n  while (++index < list.length) {\n    if (stack.includes(list[index])) {\n      return true\n    }\n  }\n\n  return false\n}\n","/**\n * @import {Break, Parents} from 'mdast'\n * @import {Info, State} from 'mdast-util-to-markdown'\n */\n\nimport {patternInScope} from '../util/pattern-in-scope.js'\n\n/**\n * @param {Break} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function hardBreak(_, _1, state, info) {\n  let index = -1\n\n  while (++index < state.unsafe.length) {\n    // If we can’t put eols in this construct (setext headings, tables), use a\n    // space instead.\n    if (\n      state.unsafe[index].character === '\\n' &&\n      patternInScope(state.stack, state.unsafe[index])\n    ) {\n      return /[ \\t]/.test(info.before) ? '' : ' '\n    }\n  }\n\n  return '\\\\\\n'\n}\n","/**\n * Get the count of the longest repeating streak of `substring` in `value`.\n *\n * @param {string} value\n *   Content to search in.\n * @param {string} substring\n *   Substring to look for, typically one character.\n * @returns {number}\n *   Count of most frequent adjacent `substring`s in `value`.\n */\nexport function longestStreak(value, substring) {\n  const source = String(value)\n  let index = source.indexOf(substring)\n  let expected = index\n  let count = 0\n  let max = 0\n\n  if (typeof substring !== 'string') {\n    throw new TypeError('Expected substring')\n  }\n\n  while (index !== -1) {\n    if (index === expected) {\n      if (++count > max) {\n        max = count\n      }\n    } else {\n      count = 1\n    }\n\n    expected = index + substring.length\n    index = source.indexOf(substring, expected)\n  }\n\n  return max\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Code} from 'mdast'\n */\n\n/**\n * @param {Code} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatCodeAsIndented(node, state) {\n  return Boolean(\n    state.options.fences === false &&\n      node.value &&\n      // If there’s no info…\n      !node.lang &&\n      // And there’s a non-whitespace character…\n      /[^ \\r\\n]/.test(node.value) &&\n      // And the value doesn’t start or end in a blank…\n      !/^[\\t ]*(?:[\\r\\n]|$)|(?:^|[\\r\\n])[\\t ]*$/.test(node.value)\n  )\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['fence'], null | undefined>}\n */\nexport function checkFence(state) {\n  const marker = state.options.fence || '`'\n\n  if (marker !== '`' && marker !== '~') {\n    throw new Error(\n      'Cannot serialize code with `' +\n        marker +\n        '` for `options.fence`, expected `` ` `` or `~`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {Code, Parents} from 'mdast'\n */\n\nimport {longestStreak} from 'longest-streak'\nimport {formatCodeAsIndented} from '../util/format-code-as-indented.js'\nimport {checkFence} from '../util/check-fence.js'\n\n/**\n * @param {Code} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function code(node, _, state, info) {\n  const marker = checkFence(state)\n  const raw = node.value || ''\n  const suffix = marker === '`' ? 'GraveAccent' : 'Tilde'\n\n  if (formatCodeAsIndented(node, state)) {\n    const exit = state.enter('codeIndented')\n    const value = state.indentLines(raw, map)\n    exit()\n    return value\n  }\n\n  const tracker = state.createTracker(info)\n  const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3))\n  const exit = state.enter('codeFenced')\n  let value = tracker.move(sequence)\n\n  if (node.lang) {\n    const subexit = state.enter(`codeFencedLang${suffix}`)\n    value += tracker.move(\n      state.safe(node.lang, {\n        before: value,\n        after: ' ',\n        encode: ['`'],\n        ...tracker.current()\n      })\n    )\n    subexit()\n  }\n\n  if (node.lang && node.meta) {\n    const subexit = state.enter(`codeFencedMeta${suffix}`)\n    value += tracker.move(' ')\n    value += tracker.move(\n      state.safe(node.meta, {\n        before: value,\n        after: '\\n',\n        encode: ['`'],\n        ...tracker.current()\n      })\n    )\n    subexit()\n  }\n\n  value += tracker.move('\\n')\n\n  if (raw) {\n    value += tracker.move(raw + '\\n')\n  }\n\n  value += tracker.move(sequence)\n  exit()\n  return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n  return (blank ? '' : '    ') + line\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['quote'], null | undefined>}\n */\nexport function checkQuote(state) {\n  const marker = state.options.quote || '\"'\n\n  if (marker !== '\"' && marker !== \"'\") {\n    throw new Error(\n      'Cannot serialize title with `' +\n        marker +\n        '` for `options.quote`, expected `\"`, or `\\'`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Definition, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\n/**\n * @param {Definition} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function definition(node, _, state, info) {\n  const quote = checkQuote(state)\n  const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n  const exit = state.enter('definition')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('[')\n  value += tracker.move(\n    state.safe(state.associationId(node), {\n      before: value,\n      after: ']',\n      ...tracker.current()\n    })\n  )\n  value += tracker.move(']: ')\n\n  subexit()\n\n  if (\n    // If there’s no url, or…\n    !node.url ||\n    // If there are control characters or whitespace.\n    /[\\0- \\u007F]/.test(node.url)\n  ) {\n    subexit = state.enter('destinationLiteral')\n    value += tracker.move('<')\n    value += tracker.move(\n      state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n    )\n    value += tracker.move('>')\n  } else {\n    // No whitespace, raw is prettier.\n    subexit = state.enter('destinationRaw')\n    value += tracker.move(\n      state.safe(node.url, {\n        before: value,\n        after: node.title ? ' ' : '\\n',\n        ...tracker.current()\n      })\n    )\n  }\n\n  subexit()\n\n  if (node.title) {\n    subexit = state.enter(`title${suffix}`)\n    value += tracker.move(' ' + quote)\n    value += tracker.move(\n      state.safe(node.title, {\n        before: value,\n        after: quote,\n        ...tracker.current()\n      })\n    )\n    value += tracker.move(quote)\n    subexit()\n  }\n\n  exit()\n\n  return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['emphasis'], null | undefined>}\n */\nexport function checkEmphasis(state) {\n  const marker = state.options.emphasis || '*'\n\n  if (marker !== '*' && marker !== '_') {\n    throw new Error(\n      'Cannot serialize emphasis with `' +\n        marker +\n        '` for `options.emphasis`, expected `*`, or `_`'\n    )\n  }\n\n  return marker\n}\n","/**\n * Encode a code point as a character reference.\n *\n * @param {number} code\n *   Code point to encode.\n * @returns {string}\n *   Encoded character reference.\n */\nexport function encodeCharacterReference(code) {\n  return '&#x' + code.toString(16).toUpperCase() + ';'\n}\n","/**\n * @import {EncodeSides} from '../types.js'\n */\n\nimport {classifyCharacter} from 'micromark-util-classify-character'\n\n/**\n * Check whether to encode (as a character reference) the characters\n * surrounding an attention run.\n *\n * Which characters are around an attention run influence whether it works or\n * not.\n *\n * See <https://github.com/orgs/syntax-tree/discussions/60> for more info.\n * See this markdown in a particular renderer to see what works:\n *\n * ```markdown\n * |                         | A (letter inside) | B (punctuation inside) | C (whitespace inside) | D (nothing inside) |\n * | ----------------------- | ----------------- | ---------------------- | --------------------- | ------------------ |\n * | 1 (letter outside)      | x*y*z             | x*.*z                  | x* *z                 | x**z               |\n * | 2 (punctuation outside) | .*y*.             | .*.*.                  | .* *.                 | .**.               |\n * | 3 (whitespace outside)  | x *y* z           | x *.* z                | x * * z               | x ** z             |\n * | 4 (nothing outside)     | *x*               | *.*                    | * *                   | **                 |\n * ```\n *\n * @param {number} outside\n *   Code point on the outer side of the run.\n * @param {number} inside\n *   Code point on the inner side of the run.\n * @param {'*' | '_'} marker\n *   Marker of the run.\n *   Underscores are handled more strictly (they form less often) than\n *   asterisks.\n * @returns {EncodeSides}\n *   Whether to encode characters.\n */\n// Important: punctuation must never be encoded.\n// Punctuation is solely used by markdown constructs.\n// And by encoding itself.\n// Encoding them will break constructs or double encode things.\nexport function encodeInfo(outside, inside, marker) {\n  const outsideKind = classifyCharacter(outside)\n  const insideKind = classifyCharacter(inside)\n\n  // Letter outside:\n  if (outsideKind === undefined) {\n    return insideKind === undefined\n      ? // Letter inside:\n        // we have to encode *both* letters for `_` as it is looser.\n        // it already forms for `*` (and GFMs `~`).\n        marker === '_'\n        ? {inside: true, outside: true}\n        : {inside: false, outside: false}\n      : insideKind === 1\n        ? // Whitespace inside: encode both (letter, whitespace).\n          {inside: true, outside: true}\n        : // Punctuation inside: encode outer (letter)\n          {inside: false, outside: true}\n  }\n\n  // Whitespace outside:\n  if (outsideKind === 1) {\n    return insideKind === undefined\n      ? // Letter inside: already forms.\n        {inside: false, outside: false}\n      : insideKind === 1\n        ? // Whitespace inside: encode both (whitespace).\n          {inside: true, outside: true}\n        : // Punctuation inside: already forms.\n          {inside: false, outside: false}\n  }\n\n  // Punctuation outside:\n  return insideKind === undefined\n    ? // Letter inside: already forms.\n      {inside: false, outside: false}\n    : insideKind === 1\n      ? // Whitespace inside: encode inner (whitespace).\n        {inside: true, outside: false}\n      : // Punctuation inside: already forms.\n        {inside: false, outside: false}\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Emphasis, Parents} from 'mdast'\n */\n\nimport {checkEmphasis} from '../util/check-emphasis.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nemphasis.peek = emphasisPeek\n\n/**\n * @param {Emphasis} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function emphasis(node, _, state, info) {\n  const marker = checkEmphasis(state)\n  const exit = state.enter('emphasis')\n  const tracker = state.createTracker(info)\n  const before = tracker.move(marker)\n\n  let between = tracker.move(\n    state.containerPhrasing(node, {\n      after: marker,\n      before,\n      ...tracker.current()\n    })\n  )\n  const betweenHead = between.charCodeAt(0)\n  const open = encodeInfo(\n    info.before.charCodeAt(info.before.length - 1),\n    betweenHead,\n    marker\n  )\n\n  if (open.inside) {\n    between = encodeCharacterReference(betweenHead) + between.slice(1)\n  }\n\n  const betweenTail = between.charCodeAt(between.length - 1)\n  const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n  if (close.inside) {\n    between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n  }\n\n  const after = tracker.move(marker)\n\n  exit()\n\n  state.attentionEncodeSurroundingInfo = {\n    after: close.outside,\n    before: open.outside\n  }\n  return before + between + after\n}\n\n/**\n * @param {Emphasis} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction emphasisPeek(_, _1, state) {\n  return state.options.emphasis || '*'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Heading} from 'mdast'\n */\n\nimport {EXIT, visit} from 'unist-util-visit'\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Heading} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatHeadingAsSetext(node, state) {\n  let literalWithBreak = false\n\n  // Look for literals with a line break.\n  // Note that this also\n  visit(node, function (node) {\n    if (\n      ('value' in node && /\\r?\\n|\\r/.test(node.value)) ||\n      node.type === 'break'\n    ) {\n      literalWithBreak = true\n      return EXIT\n    }\n  })\n\n  return Boolean(\n    (!node.depth || node.depth < 3) &&\n      toString(node) &&\n      (state.options.setext || literalWithBreak)\n  )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Heading, Parents} from 'mdast'\n */\n\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {formatHeadingAsSetext} from '../util/format-heading-as-setext.js'\n\n/**\n * @param {Heading} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function heading(node, _, state, info) {\n  const rank = Math.max(Math.min(6, node.depth || 1), 1)\n  const tracker = state.createTracker(info)\n\n  if (formatHeadingAsSetext(node, state)) {\n    const exit = state.enter('headingSetext')\n    const subexit = state.enter('phrasing')\n    const value = state.containerPhrasing(node, {\n      ...tracker.current(),\n      before: '\\n',\n      after: '\\n'\n    })\n    subexit()\n    exit()\n\n    return (\n      value +\n      '\\n' +\n      (rank === 1 ? '=' : '-').repeat(\n        // The whole size…\n        value.length -\n          // Minus the position of the character after the last EOL (or\n          // 0 if there is none)…\n          (Math.max(value.lastIndexOf('\\r'), value.lastIndexOf('\\n')) + 1)\n      )\n    )\n  }\n\n  const sequence = '#'.repeat(rank)\n  const exit = state.enter('headingAtx')\n  const subexit = state.enter('phrasing')\n\n  // Note: for proper tracking, we should reset the output positions when there\n  // is no content returned, because then the space is not output.\n  // Practically, in that case, there is no content, so it doesn’t matter that\n  // we’ve tracked one too many characters.\n  tracker.move(sequence + ' ')\n\n  let value = state.containerPhrasing(node, {\n    before: '# ',\n    after: '\\n',\n    ...tracker.current()\n  })\n\n  if (/^[\\t ]/.test(value)) {\n    // To do: what effect has the character reference on tracking?\n    value = encodeCharacterReference(value.charCodeAt(0)) + value.slice(1)\n  }\n\n  value = value ? sequence + ' ' + value : sequence\n\n  if (state.options.closeAtx) {\n    value += ' ' + sequence\n  }\n\n  subexit()\n  exit()\n\n  return value\n}\n","/**\n * @import {Html} from 'mdast'\n */\n\nhtml.peek = htmlPeek\n\n/**\n * @param {Html} node\n * @returns {string}\n */\nexport function html(node) {\n  return node.value || ''\n}\n\n/**\n * @returns {string}\n */\nfunction htmlPeek() {\n  return '<'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Image, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\nimage.peek = imagePeek\n\n/**\n * @param {Image} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function image(node, _, state, info) {\n  const quote = checkQuote(state)\n  const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n  const exit = state.enter('image')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('![')\n  value += tracker.move(\n    state.safe(node.alt, {before: value, after: ']', ...tracker.current()})\n  )\n  value += tracker.move('](')\n\n  subexit()\n\n  if (\n    // If there’s no url but there is a title…\n    (!node.url && node.title) ||\n    // If there are control characters or whitespace.\n    /[\\0- \\u007F]/.test(node.url)\n  ) {\n    subexit = state.enter('destinationLiteral')\n    value += tracker.move('<')\n    value += tracker.move(\n      state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n    )\n    value += tracker.move('>')\n  } else {\n    // No whitespace, raw is prettier.\n    subexit = state.enter('destinationRaw')\n    value += tracker.move(\n      state.safe(node.url, {\n        before: value,\n        after: node.title ? ' ' : ')',\n        ...tracker.current()\n      })\n    )\n  }\n\n  subexit()\n\n  if (node.title) {\n    subexit = state.enter(`title${suffix}`)\n    value += tracker.move(' ' + quote)\n    value += tracker.move(\n      state.safe(node.title, {\n        before: value,\n        after: quote,\n        ...tracker.current()\n      })\n    )\n    value += tracker.move(quote)\n    subexit()\n  }\n\n  value += tracker.move(')')\n  exit()\n\n  return value\n}\n\n/**\n * @returns {string}\n */\nfunction imagePeek() {\n  return '!'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {ImageReference, Parents} from 'mdast'\n */\n\nimageReference.peek = imageReferencePeek\n\n/**\n * @param {ImageReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function imageReference(node, _, state, info) {\n  const type = node.referenceType\n  const exit = state.enter('imageReference')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('![')\n  const alt = state.safe(node.alt, {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  value += tracker.move(alt + '][')\n\n  subexit()\n  // Hide the fact that we’re in phrasing, because escapes don’t work.\n  const stack = state.stack\n  state.stack = []\n  subexit = state.enter('reference')\n  // Note: for proper tracking, we should reset the output positions when we end\n  // up making a `shortcut` reference, because then there is no brace output.\n  // Practically, in that case, there is no content, so it doesn’t matter that\n  // we’ve tracked one too many characters.\n  const reference = state.safe(state.associationId(node), {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  subexit()\n  state.stack = stack\n  exit()\n\n  if (type === 'full' || !alt || alt !== reference) {\n    value += tracker.move(reference + ']')\n  } else if (type === 'shortcut') {\n    // Remove the unwanted `[`.\n    value = value.slice(0, -1)\n  } else {\n    value += tracker.move(']')\n  }\n\n  return value\n}\n\n/**\n * @returns {string}\n */\nfunction imageReferencePeek() {\n  return '!'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {InlineCode, Parents} from 'mdast'\n */\n\ninlineCode.peek = inlineCodePeek\n\n/**\n * @param {InlineCode} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nexport function inlineCode(node, _, state) {\n  let value = node.value || ''\n  let sequence = '`'\n  let index = -1\n\n  // If there is a single grave accent on its own in the code, use a fence of\n  // two.\n  // If there are two in a row, use one.\n  while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) {\n    sequence += '`'\n  }\n\n  // If this is not just spaces or eols (tabs don’t count), and either the\n  // first or last character are a space, eol, or tick, then pad with spaces.\n  if (\n    /[^ \\r\\n]/.test(value) &&\n    ((/^[ \\r\\n]/.test(value) && /[ \\r\\n]$/.test(value)) || /^`|`$/.test(value))\n  ) {\n    value = ' ' + value + ' '\n  }\n\n  // We have a potential problem: certain characters after eols could result in\n  // blocks being seen.\n  // For example, if someone injected the string `'\\n# b'`, then that would\n  // result in an ATX heading.\n  // We can’t escape characters in `inlineCode`, but because eols are\n  // transformed to spaces when going from markdown to HTML anyway, we can swap\n  // them out.\n  while (++index < state.unsafe.length) {\n    const pattern = state.unsafe[index]\n    const expression = state.compilePattern(pattern)\n    /** @type {RegExpExecArray | null} */\n    let match\n\n    // Only look for `atBreak`s.\n    // Btw: note that `atBreak` patterns will always start the regex at LF or\n    // CR.\n    if (!pattern.atBreak) continue\n\n    while ((match = expression.exec(value))) {\n      let position = match.index\n\n      // Support CRLF (patterns only look for one of the characters).\n      if (\n        value.charCodeAt(position) === 10 /* `\\n` */ &&\n        value.charCodeAt(position - 1) === 13 /* `\\r` */\n      ) {\n        position--\n      }\n\n      value = value.slice(0, position) + ' ' + value.slice(match.index + 1)\n    }\n  }\n\n  return sequence + value + sequence\n}\n\n/**\n * @returns {string}\n */\nfunction inlineCodePeek() {\n  return '`'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Link} from 'mdast'\n */\n\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Link} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatLinkAsAutolink(node, state) {\n  const raw = toString(node)\n\n  return Boolean(\n    !state.options.resourceLink &&\n      // If there’s a url…\n      node.url &&\n      // And there’s a no title…\n      !node.title &&\n      // And the content of `node` is a single text node…\n      node.children &&\n      node.children.length === 1 &&\n      node.children[0].type === 'text' &&\n      // And if the url is the same as the content…\n      (raw === node.url || 'mailto:' + raw === node.url) &&\n      // And that starts w/ a protocol…\n      /^[a-z][a-z+.-]+:/i.test(node.url) &&\n      // And that doesn’t contain ASCII control codes (character escapes and\n      // references don’t work), space, or angle brackets…\n      !/[\\0- <>\\u007F]/.test(node.url)\n  )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Link, Parents} from 'mdast'\n * @import {Exit} from '../types.js'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\nimport {formatLinkAsAutolink} from '../util/format-link-as-autolink.js'\n\nlink.peek = linkPeek\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function link(node, _, state, info) {\n  const quote = checkQuote(state)\n  const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n  const tracker = state.createTracker(info)\n  /** @type {Exit} */\n  let exit\n  /** @type {Exit} */\n  let subexit\n\n  if (formatLinkAsAutolink(node, state)) {\n    // Hide the fact that we’re in phrasing, because escapes don’t work.\n    const stack = state.stack\n    state.stack = []\n    exit = state.enter('autolink')\n    let value = tracker.move('<')\n    value += tracker.move(\n      state.containerPhrasing(node, {\n        before: value,\n        after: '>',\n        ...tracker.current()\n      })\n    )\n    value += tracker.move('>')\n    exit()\n    state.stack = stack\n    return value\n  }\n\n  exit = state.enter('link')\n  subexit = state.enter('label')\n  let value = tracker.move('[')\n  value += tracker.move(\n    state.containerPhrasing(node, {\n      before: value,\n      after: '](',\n      ...tracker.current()\n    })\n  )\n  value += tracker.move('](')\n  subexit()\n\n  if (\n    // If there’s no url but there is a title…\n    (!node.url && node.title) ||\n    // If there are control characters or whitespace.\n    /[\\0- \\u007F]/.test(node.url)\n  ) {\n    subexit = state.enter('destinationLiteral')\n    value += tracker.move('<')\n    value += tracker.move(\n      state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n    )\n    value += tracker.move('>')\n  } else {\n    // No whitespace, raw is prettier.\n    subexit = state.enter('destinationRaw')\n    value += tracker.move(\n      state.safe(node.url, {\n        before: value,\n        after: node.title ? ' ' : ')',\n        ...tracker.current()\n      })\n    )\n  }\n\n  subexit()\n\n  if (node.title) {\n    subexit = state.enter(`title${suffix}`)\n    value += tracker.move(' ' + quote)\n    value += tracker.move(\n      state.safe(node.title, {\n        before: value,\n        after: quote,\n        ...tracker.current()\n      })\n    )\n    value += tracker.move(quote)\n    subexit()\n  }\n\n  value += tracker.move(')')\n\n  exit()\n  return value\n}\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nfunction linkPeek(node, _, state) {\n  return formatLinkAsAutolink(node, state) ? '<' : '['\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {LinkReference, Parents} from 'mdast'\n */\n\nlinkReference.peek = linkReferencePeek\n\n/**\n * @param {LinkReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function linkReference(node, _, state, info) {\n  const type = node.referenceType\n  const exit = state.enter('linkReference')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('[')\n  const text = state.containerPhrasing(node, {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  value += tracker.move(text + '][')\n\n  subexit()\n  // Hide the fact that we’re in phrasing, because escapes don’t work.\n  const stack = state.stack\n  state.stack = []\n  subexit = state.enter('reference')\n  // Note: for proper tracking, we should reset the output positions when we end\n  // up making a `shortcut` reference, because then there is no brace output.\n  // Practically, in that case, there is no content, so it doesn’t matter that\n  // we’ve tracked one too many characters.\n  const reference = state.safe(state.associationId(node), {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  subexit()\n  state.stack = stack\n  exit()\n\n  if (type === 'full' || !text || text !== reference) {\n    value += tracker.move(reference + ']')\n  } else if (type === 'shortcut') {\n    // Remove the unwanted `[`.\n    value = value.slice(0, -1)\n  } else {\n    value += tracker.move(']')\n  }\n\n  return value\n}\n\n/**\n * @returns {string}\n */\nfunction linkReferencePeek() {\n  return '['\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBullet(state) {\n  const marker = state.options.bullet || '*'\n\n  if (marker !== '*' && marker !== '+' && marker !== '-') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        marker +\n        '` for `options.bullet`, expected `*`, `+`, or `-`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\nimport {checkBullet} from './check-bullet.js'\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBulletOther(state) {\n  const bullet = checkBullet(state)\n  const bulletOther = state.options.bulletOther\n\n  if (!bulletOther) {\n    return bullet === '*' ? '-' : '*'\n  }\n\n  if (bulletOther !== '*' && bulletOther !== '+' && bulletOther !== '-') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        bulletOther +\n        '` for `options.bulletOther`, expected `*`, `+`, or `-`'\n    )\n  }\n\n  if (bulletOther === bullet) {\n    throw new Error(\n      'Expected `bullet` (`' +\n        bullet +\n        '`) and `bulletOther` (`' +\n        bulletOther +\n        '`) to be different'\n    )\n  }\n\n  return bulletOther\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bulletOrdered'], null | undefined>}\n */\nexport function checkBulletOrdered(state) {\n  const marker = state.options.bulletOrdered || '.'\n\n  if (marker !== '.' && marker !== ')') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        marker +\n        '` for `options.bulletOrdered`, expected `.` or `)`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['rule'], null | undefined>}\n */\nexport function checkRule(state) {\n  const marker = state.options.rule || '*'\n\n  if (marker !== '*' && marker !== '-' && marker !== '_') {\n    throw new Error(\n      'Cannot serialize rules with `' +\n        marker +\n        '` for `options.rule`, expected `*`, `-`, or `_`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {List, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkBulletOther} from '../util/check-bullet-other.js'\nimport {checkBulletOrdered} from '../util/check-bullet-ordered.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {List} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function list(node, parent, state, info) {\n  const exit = state.enter('list')\n  const bulletCurrent = state.bulletCurrent\n  /** @type {string} */\n  let bullet = node.ordered ? checkBulletOrdered(state) : checkBullet(state)\n  /** @type {string} */\n  const bulletOther = node.ordered\n    ? bullet === '.'\n      ? ')'\n      : '.'\n    : checkBulletOther(state)\n  let useDifferentMarker =\n    parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false\n\n  if (!node.ordered) {\n    const firstListItem = node.children ? node.children[0] : undefined\n\n    // If there’s an empty first list item directly in two list items,\n    // we have to use a different bullet:\n    //\n    // ```markdown\n    // * - *\n    // ```\n    //\n    // …because otherwise it would become one big thematic break.\n    if (\n      // Bullet could be used as a thematic break marker:\n      (bullet === '*' || bullet === '-') &&\n      // Empty first list item:\n      firstListItem &&\n      (!firstListItem.children || !firstListItem.children[0]) &&\n      // Directly in two other list items:\n      state.stack[state.stack.length - 1] === 'list' &&\n      state.stack[state.stack.length - 2] === 'listItem' &&\n      state.stack[state.stack.length - 3] === 'list' &&\n      state.stack[state.stack.length - 4] === 'listItem' &&\n      // That are each the first child.\n      state.indexStack[state.indexStack.length - 1] === 0 &&\n      state.indexStack[state.indexStack.length - 2] === 0 &&\n      state.indexStack[state.indexStack.length - 3] === 0\n    ) {\n      useDifferentMarker = true\n    }\n\n    // If there’s a thematic break at the start of the first list item,\n    // we have to use a different bullet:\n    //\n    // ```markdown\n    // * ---\n    // ```\n    //\n    // …because otherwise it would become one big thematic break.\n    if (checkRule(state) === bullet && firstListItem) {\n      let index = -1\n\n      while (++index < node.children.length) {\n        const item = node.children[index]\n\n        if (\n          item &&\n          item.type === 'listItem' &&\n          item.children &&\n          item.children[0] &&\n          item.children[0].type === 'thematicBreak'\n        ) {\n          useDifferentMarker = true\n          break\n        }\n      }\n    }\n  }\n\n  if (useDifferentMarker) {\n    bullet = bulletOther\n  }\n\n  state.bulletCurrent = bullet\n  const value = state.containerFlow(node, info)\n  state.bulletLastUsed = bullet\n  state.bulletCurrent = bulletCurrent\n  exit()\n  return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['listItemIndent'], null | undefined>}\n */\nexport function checkListItemIndent(state) {\n  const style = state.options.listItemIndent || 'one'\n\n  if (style !== 'tab' && style !== 'one' && style !== 'mixed') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        style +\n        '` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`'\n    )\n  }\n\n  return style\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {ListItem, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkListItemIndent} from '../util/check-list-item-indent.js'\n\n/**\n * @param {ListItem} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function listItem(node, parent, state, info) {\n  const listItemIndent = checkListItemIndent(state)\n  let bullet = state.bulletCurrent || checkBullet(state)\n\n  // Add the marker value for ordered lists.\n  if (parent && parent.type === 'list' && parent.ordered) {\n    bullet =\n      (typeof parent.start === 'number' && parent.start > -1\n        ? parent.start\n        : 1) +\n      (state.options.incrementListMarker === false\n        ? 0\n        : parent.children.indexOf(node)) +\n      bullet\n  }\n\n  let size = bullet.length + 1\n\n  if (\n    listItemIndent === 'tab' ||\n    (listItemIndent === 'mixed' &&\n      ((parent && parent.type === 'list' && parent.spread) || node.spread))\n  ) {\n    size = Math.ceil(size / 4) * 4\n  }\n\n  const tracker = state.createTracker(info)\n  tracker.move(bullet + ' '.repeat(size - bullet.length))\n  tracker.shift(size)\n  const exit = state.enter('listItem')\n  const value = state.indentLines(\n    state.containerFlow(node, tracker.current()),\n    map\n  )\n  exit()\n\n  return value\n\n  /** @type {Map} */\n  function map(line, index, blank) {\n    if (index) {\n      return (blank ? '' : ' '.repeat(size)) + line\n    }\n\n    return (blank ? bullet : bullet + ' '.repeat(size - bullet.length)) + line\n  }\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Paragraph, Parents} from 'mdast'\n */\n\n/**\n * @param {Paragraph} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function paragraph(node, _, state, info) {\n  const exit = state.enter('paragraph')\n  const subexit = state.enter('phrasing')\n  const value = state.containerPhrasing(node, info)\n  subexit()\n  exit()\n  return value\n}\n","/**\n * @typedef {import('mdast').Html} Html\n * @typedef {import('mdast').PhrasingContent} PhrasingContent\n */\n\nimport {convert} from 'unist-util-is'\n\n/**\n * Check if the given value is *phrasing content*.\n *\n * > 👉 **Note**: Excludes `html`, which can be both phrasing or flow.\n *\n * @param node\n *   Thing to check, typically `Node`.\n * @returns\n *   Whether `value` is phrasing content.\n */\n\nexport const phrasing =\n  /** @type {(node?: unknown) => node is Exclude<PhrasingContent, Html>} */\n  (\n    convert([\n      'break',\n      'delete',\n      'emphasis',\n      // To do: next major: removed since footnotes were added to GFM.\n      'footnote',\n      'footnoteReference',\n      'image',\n      'imageReference',\n      'inlineCode',\n      // Enabled by `mdast-util-math`:\n      'inlineMath',\n      'link',\n      'linkReference',\n      // Enabled by `mdast-util-mdx`:\n      'mdxJsxTextElement',\n      // Enabled by `mdast-util-mdx`:\n      'mdxTextExpression',\n      'strong',\n      'text',\n      // Enabled by `mdast-util-directive`:\n      'textDirective'\n    ])\n  )\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Root} from 'mdast'\n */\n\nimport {phrasing} from 'mdast-util-phrasing'\n\n/**\n * @param {Root} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function root(node, _, state, info) {\n  // Note: `html` nodes are ambiguous.\n  const hasPhrasing = node.children.some(function (d) {\n    return phrasing(d)\n  })\n\n  const container = hasPhrasing ? state.containerPhrasing : state.containerFlow\n  return container.call(state, node, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['strong'], null | undefined>}\n */\nexport function checkStrong(state) {\n  const marker = state.options.strong || '*'\n\n  if (marker !== '*' && marker !== '_') {\n    throw new Error(\n      'Cannot serialize strong with `' +\n        marker +\n        '` for `options.strong`, expected `*`, or `_`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Strong} from 'mdast'\n */\n\nimport {checkStrong} from '../util/check-strong.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nstrong.peek = strongPeek\n\n/**\n * @param {Strong} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function strong(node, _, state, info) {\n  const marker = checkStrong(state)\n  const exit = state.enter('strong')\n  const tracker = state.createTracker(info)\n  const before = tracker.move(marker + marker)\n\n  let between = tracker.move(\n    state.containerPhrasing(node, {\n      after: marker,\n      before,\n      ...tracker.current()\n    })\n  )\n  const betweenHead = between.charCodeAt(0)\n  const open = encodeInfo(\n    info.before.charCodeAt(info.before.length - 1),\n    betweenHead,\n    marker\n  )\n\n  if (open.inside) {\n    between = encodeCharacterReference(betweenHead) + between.slice(1)\n  }\n\n  const betweenTail = between.charCodeAt(between.length - 1)\n  const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n  if (close.inside) {\n    between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n  }\n\n  const after = tracker.move(marker + marker)\n\n  exit()\n\n  state.attentionEncodeSurroundingInfo = {\n    after: close.outside,\n    before: open.outside\n  }\n  return before + between + after\n}\n\n/**\n * @param {Strong} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction strongPeek(_, _1, state) {\n  return state.options.strong || '*'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Text} from 'mdast'\n */\n\n/**\n * @param {Text} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function text(node, _, state, info) {\n  return state.safe(node.value, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['ruleRepetition'], null | undefined>}\n */\nexport function checkRuleRepetition(state) {\n  const repetition = state.options.ruleRepetition || 3\n\n  if (repetition < 3) {\n    throw new Error(\n      'Cannot serialize rules with repetition `' +\n        repetition +\n        '` for `options.ruleRepetition`, expected `3` or more'\n    )\n  }\n\n  return repetition\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Parents, ThematicBreak} from 'mdast'\n */\n\nimport {checkRuleRepetition} from '../util/check-rule-repetition.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {ThematicBreak} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nexport function thematicBreak(_, _1, state) {\n  const value = (\n    checkRule(state) + (state.options.ruleSpaces ? ' ' : '')\n  ).repeat(checkRuleRepetition(state))\n\n  return state.options.ruleSpaces ? value.slice(0, -1) : value\n}\n","import {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {definition} from './definition.js'\nimport {emphasis} from './emphasis.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {image} from './image.js'\nimport {imageReference} from './image-reference.js'\nimport {inlineCode} from './inline-code.js'\nimport {link} from './link.js'\nimport {linkReference} from './link-reference.js'\nimport {list} from './list.js'\nimport {listItem} from './list-item.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\n/**\n * Default (CommonMark) handlers.\n */\nexport const handle = {\n  blockquote,\n  break: hardBreak,\n  code,\n  definition,\n  emphasis,\n  hardBreak,\n  heading,\n  html,\n  image,\n  imageReference,\n  inlineCode,\n  link,\n  linkReference,\n  list,\n  listItem,\n  paragraph,\n  root,\n  strong,\n  text,\n  thematicBreak\n}\n","/**\n * @typedef {import('mdast').InlineCode} InlineCode\n * @typedef {import('mdast').Table} Table\n * @typedef {import('mdast').TableCell} TableCell\n * @typedef {import('mdast').TableRow} TableRow\n *\n * @typedef {import('markdown-table').Options} MarkdownTableOptions\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').State} State\n * @typedef {import('mdast-util-to-markdown').Info} Info\n */\n\n/**\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [tableCellPadding=true]\n *   Whether to add a space of padding between delimiters and cells (default:\n *   `true`).\n * @property {boolean | null | undefined} [tablePipeAlign=true]\n *   Whether to align the delimiters (default: `true`).\n * @property {MarkdownTableOptions['stringLength'] | null | undefined} [stringLength]\n *   Function to detect the length of table cell content, used when aligning\n *   the delimiters between cells (optional).\n */\n\nimport {ok as assert} from 'devlop'\nimport {markdownTable} from 'markdown-table'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM tables in\n * markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown` to enable GFM tables.\n */\nexport function gfmTableFromMarkdown() {\n  return {\n    enter: {\n      table: enterTable,\n      tableData: enterCell,\n      tableHeader: enterCell,\n      tableRow: enterRow\n    },\n    exit: {\n      codeText: exitCodeText,\n      table: exitTable,\n      tableData: exit,\n      tableHeader: exit,\n      tableRow: exit\n    }\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterTable(token) {\n  const align = token._align\n  assert(align, 'expected `_align` on table')\n  this.enter(\n    {\n      type: 'table',\n      align: align.map(function (d) {\n        return d === 'none' ? null : d\n      }),\n      children: []\n    },\n    token\n  )\n  this.data.inTable = true\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitTable(token) {\n  this.exit(token)\n  this.data.inTable = undefined\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterRow(token) {\n  this.enter({type: 'tableRow', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exit(token) {\n  this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterCell(token) {\n  this.enter({type: 'tableCell', children: []}, token)\n}\n\n// Overwrite the default code text data handler to unescape escaped pipes when\n// they are in tables.\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCodeText(token) {\n  let value = this.resume()\n\n  if (this.data.inTable) {\n    value = value.replace(/\\\\([\\\\|])/g, replace)\n  }\n\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'inlineCode')\n  node.value = value\n  this.exit(token)\n}\n\n/**\n * @param {string} $0\n * @param {string} $1\n * @returns {string}\n */\nfunction replace($0, $1) {\n  // Pipes work, backslashes don’t (but can’t escape pipes).\n  return $1 === '|' ? $1 : $0\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM tables in\n * markdown.\n *\n * @param {Options | null | undefined} [options]\n *   Configuration.\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM tables.\n */\nexport function gfmTableToMarkdown(options) {\n  const settings = options || {}\n  const padding = settings.tableCellPadding\n  const alignDelimiters = settings.tablePipeAlign\n  const stringLength = settings.stringLength\n  const around = padding ? ' ' : '|'\n\n  return {\n    unsafe: [\n      {character: '\\r', inConstruct: 'tableCell'},\n      {character: '\\n', inConstruct: 'tableCell'},\n      // A pipe, when followed by a tab or space (padding), or a dash or colon\n      // (unpadded delimiter row), could result in a table.\n      {atBreak: true, character: '|', after: '[\\t :-]'},\n      // A pipe in a cell must be encoded.\n      {character: '|', inConstruct: 'tableCell'},\n      // A colon must be followed by a dash, in which case it could start a\n      // delimiter row.\n      {atBreak: true, character: ':', after: '-'},\n      // A delimiter row can also start with a dash, when followed by more\n      // dashes, a colon, or a pipe.\n      // This is a stricter version than the built in check for lists, thematic\n      // breaks, and setex heading underlines though:\n      // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>\n      {atBreak: true, character: '-', after: '[:|-]'}\n    ],\n    handlers: {\n      inlineCode: inlineCodeWithTable,\n      table: handleTable,\n      tableCell: handleTableCell,\n      tableRow: handleTableRow\n    }\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {Table} node\n   */\n  function handleTable(node, _, state, info) {\n    return serializeData(handleTableAsData(node, state, info), node.align)\n  }\n\n  /**\n   * This function isn’t really used normally, because we handle rows at the\n   * table level.\n   * But, if someone passes in a table row, this ensures we make somewhat sense.\n   *\n   * @type {ToMarkdownHandle}\n   * @param {TableRow} node\n   */\n  function handleTableRow(node, _, state, info) {\n    const row = handleTableRowAsData(node, state, info)\n    const value = serializeData([row])\n    // `markdown-table` will always add an align row\n    return value.slice(0, value.indexOf('\\n'))\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {TableCell} node\n   */\n  function handleTableCell(node, _, state, info) {\n    const exit = state.enter('tableCell')\n    const subexit = state.enter('phrasing')\n    const value = state.containerPhrasing(node, {\n      ...info,\n      before: around,\n      after: around\n    })\n    subexit()\n    exit()\n    return value\n  }\n\n  /**\n   * @param {Array<Array<string>>} matrix\n   * @param {Array<string | null | undefined> | null | undefined} [align]\n   */\n  function serializeData(matrix, align) {\n    return markdownTable(matrix, {\n      align,\n      // @ts-expect-error: `markdown-table` types should support `null`.\n      alignDelimiters,\n      // @ts-expect-error: `markdown-table` types should support `null`.\n      padding,\n      // @ts-expect-error: `markdown-table` types should support `null`.\n      stringLength\n    })\n  }\n\n  /**\n   * @param {Table} node\n   * @param {State} state\n   * @param {Info} info\n   */\n  function handleTableAsData(node, state, info) {\n    const children = node.children\n    let index = -1\n    /** @type {Array<Array<string>>} */\n    const result = []\n    const subexit = state.enter('table')\n\n    while (++index < children.length) {\n      result[index] = handleTableRowAsData(children[index], state, info)\n    }\n\n    subexit()\n\n    return result\n  }\n\n  /**\n   * @param {TableRow} node\n   * @param {State} state\n   * @param {Info} info\n   */\n  function handleTableRowAsData(node, state, info) {\n    const children = node.children\n    let index = -1\n    /** @type {Array<string>} */\n    const result = []\n    const subexit = state.enter('tableRow')\n\n    while (++index < children.length) {\n      // Note: the positional info as used here is incorrect.\n      // Making it correct would be impossible due to aligning cells?\n      // And it would need copy/pasting `markdown-table` into this project.\n      result[index] = handleTableCell(children[index], node, state, info)\n    }\n\n    subexit()\n\n    return result\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {InlineCode} node\n   */\n  function inlineCodeWithTable(node, parent, state) {\n    let value = defaultHandlers.inlineCode(node, parent, state)\n\n    if (state.stack.includes('tableCell')) {\n      value = value.replace(/\\|/g, '\\\\$&')\n    }\n\n    return value\n  }\n}\n","/**\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n */\n\nimport {ok as assert} from 'devlop'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM task\n * list items in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemFromMarkdown() {\n  return {\n    exit: {\n      taskListCheckValueChecked: exitCheck,\n      taskListCheckValueUnchecked: exitCheck,\n      paragraph: exitParagraphWithTaskListItem\n    }\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM task list\n * items in markdown.\n *\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemToMarkdown() {\n  return {\n    unsafe: [{atBreak: true, character: '-', after: '[:|-]'}],\n    handlers: {listItem: listItemWithTaskListItem}\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCheck(token) {\n  // We’re always in a paragraph, in a list item.\n  const node = this.stack[this.stack.length - 2]\n  assert(node.type === 'listItem')\n  node.checked = token.type === 'taskListCheckValueChecked'\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitParagraphWithTaskListItem(token) {\n  const parent = this.stack[this.stack.length - 2]\n\n  if (\n    parent &&\n    parent.type === 'listItem' &&\n    typeof parent.checked === 'boolean'\n  ) {\n    const node = this.stack[this.stack.length - 1]\n    assert(node.type === 'paragraph')\n    const head = node.children[0]\n\n    if (head && head.type === 'text') {\n      const siblings = parent.children\n      let index = -1\n      /** @type {Paragraph | undefined} */\n      let firstParaghraph\n\n      while (++index < siblings.length) {\n        const sibling = siblings[index]\n        if (sibling.type === 'paragraph') {\n          firstParaghraph = sibling\n          break\n        }\n      }\n\n      if (firstParaghraph === node) {\n        // Must start with a space or a tab.\n        head.value = head.value.slice(1)\n\n        if (head.value.length === 0) {\n          node.children.shift()\n        } else if (\n          node.position &&\n          head.position &&\n          typeof head.position.start.offset === 'number'\n        ) {\n          head.position.start.column++\n          head.position.start.offset++\n          node.position.start = Object.assign({}, head.position.start)\n        }\n      }\n    }\n  }\n\n  this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {ListItem} node\n */\nfunction listItemWithTaskListItem(node, parent, state, info) {\n  const head = node.children[0]\n  const checkable =\n    typeof node.checked === 'boolean' && head && head.type === 'paragraph'\n  const checkbox = '[' + (node.checked ? 'x' : ' ') + '] '\n  const tracker = state.createTracker(info)\n\n  if (checkable) {\n    tracker.move(checkbox)\n  }\n\n  let value = defaultHandlers.listItem(node, parent, state, {\n    ...info,\n    ...tracker.current()\n  })\n\n  if (checkable) {\n    value = value.replace(/^(?:[*+-]|\\d+\\.)([\\r\\n]| {1,3})/, check)\n  }\n\n  return value\n\n  /**\n   * @param {string} $0\n   * @returns {string}\n   */\n  function check($0) {\n    return $0 + checkbox\n  }\n}\n","/**\n * @import {Extension as FromMarkdownExtension} from 'mdast-util-from-markdown'\n * @import {Options} from 'mdast-util-gfm'\n * @import {Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n */\n\nimport {\n  gfmAutolinkLiteralFromMarkdown,\n  gfmAutolinkLiteralToMarkdown\n} from 'mdast-util-gfm-autolink-literal'\nimport {\n  gfmFootnoteFromMarkdown,\n  gfmFootnoteToMarkdown\n} from 'mdast-util-gfm-footnote'\nimport {\n  gfmStrikethroughFromMarkdown,\n  gfmStrikethroughToMarkdown\n} from 'mdast-util-gfm-strikethrough'\nimport {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'\nimport {\n  gfmTaskListItemFromMarkdown,\n  gfmTaskListItemToMarkdown\n} from 'mdast-util-gfm-task-list-item'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @returns {Array<FromMarkdownExtension>}\n *   Extension for `mdast-util-from-markdown` to enable GFM (autolink literals,\n *   footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmFromMarkdown() {\n  return [\n    gfmAutolinkLiteralFromMarkdown(),\n    gfmFootnoteFromMarkdown(),\n    gfmStrikethroughFromMarkdown(),\n    gfmTableFromMarkdown(),\n    gfmTaskListItemFromMarkdown()\n  ]\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM (autolink literals,\n *   footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmToMarkdown(options) {\n  return {\n    extensions: [\n      gfmAutolinkLiteralToMarkdown(),\n      gfmFootnoteToMarkdown(options),\n      gfmStrikethroughToMarkdown(),\n      gfmTableToMarkdown(options),\n      gfmTaskListItemToMarkdown()\n    ]\n  }\n}\n","/**\n * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { asciiAlpha, asciiAlphanumeric, asciiControl, markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\nconst wwwPrefix = {\n  tokenize: tokenizeWwwPrefix,\n  partial: true\n};\nconst domain = {\n  tokenize: tokenizeDomain,\n  partial: true\n};\nconst path = {\n  tokenize: tokenizePath,\n  partial: true\n};\nconst trail = {\n  tokenize: tokenizeTrail,\n  partial: true\n};\nconst emailDomainDotTrail = {\n  tokenize: tokenizeEmailDomainDotTrail,\n  partial: true\n};\nconst wwwAutolink = {\n  name: 'wwwAutolink',\n  tokenize: tokenizeWwwAutolink,\n  previous: previousWww\n};\nconst protocolAutolink = {\n  name: 'protocolAutolink',\n  tokenize: tokenizeProtocolAutolink,\n  previous: previousProtocol\n};\nconst emailAutolink = {\n  name: 'emailAutolink',\n  tokenize: tokenizeEmailAutolink,\n  previous: previousEmail\n};\n\n/** @type {ConstructRecord} */\nconst text = {};\n\n/**\n * Create an extension for `micromark` to support GitHub autolink literal\n * syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to enable GFM\n *   autolink literal syntax.\n */\nexport function gfmAutolinkLiteral() {\n  return {\n    text\n  };\n}\n\n/** @type {Code} */\nlet code = 48;\n\n// Add alphanumerics.\nwhile (code < 123) {\n  text[code] = emailAutolink;\n  code++;\n  if (code === 58) code = 65;else if (code === 91) code = 97;\n}\ntext[43] = emailAutolink;\ntext[45] = emailAutolink;\ntext[46] = emailAutolink;\ntext[95] = emailAutolink;\ntext[72] = [emailAutolink, protocolAutolink];\ntext[104] = [emailAutolink, protocolAutolink];\ntext[87] = [emailAutolink, wwwAutolink];\ntext[119] = [emailAutolink, wwwAutolink];\n\n// To do: perform email autolink literals on events, afterwards.\n// That’s where `markdown-rs` and `cmark-gfm` perform it.\n// It should look for `@`, then for atext backwards, and then for a label\n// forwards.\n// To do: `mailto:`, `xmpp:` protocol as prefix.\n\n/**\n * Email autolink literal.\n *\n * ```markdown\n * > | a contact@example.org b\n *       ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailAutolink(effects, ok, nok) {\n  const self = this;\n  /** @type {boolean | undefined} */\n  let dot;\n  /** @type {boolean} */\n  let data;\n  return start;\n\n  /**\n   * Start of email autolink literal.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (!gfmAtext(code) || !previousEmail.call(self, self.previous) || previousUnbalanced(self.events)) {\n      return nok(code);\n    }\n    effects.enter('literalAutolink');\n    effects.enter('literalAutolinkEmail');\n    return atext(code);\n  }\n\n  /**\n   * In email atext.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atext(code) {\n    if (gfmAtext(code)) {\n      effects.consume(code);\n      return atext;\n    }\n    if (code === 64) {\n      effects.consume(code);\n      return emailDomain;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In email domain.\n   *\n   * The reference code is a bit overly complex as it handles the `@`, of which\n   * there may be just one.\n   * Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L318>\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailDomain(code) {\n    // Dot followed by alphanumerical (not `-` or `_`).\n    if (code === 46) {\n      return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code);\n    }\n\n    // Alphanumerical, `-`, and `_`.\n    if (code === 45 || code === 95 || asciiAlphanumeric(code)) {\n      data = true;\n      effects.consume(code);\n      return emailDomain;\n    }\n\n    // To do: `/` if xmpp.\n\n    // Note: normally we’d truncate trailing punctuation from the link.\n    // However, email autolink literals cannot contain any of those markers,\n    // except for `.`, but that can only occur if it isn’t trailing.\n    // So we can ignore truncating!\n    return emailDomainAfter(code);\n  }\n\n  /**\n   * In email domain, on dot that is not a trail.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *                      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailDomainDot(code) {\n    effects.consume(code);\n    dot = true;\n    return emailDomain;\n  }\n\n  /**\n   * After email domain.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *                          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailDomainAfter(code) {\n    // Domain must not be empty, must include a dot, and must end in alphabetical.\n    // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L332>.\n    if (data && dot && asciiAlpha(self.previous)) {\n      effects.exit('literalAutolinkEmail');\n      effects.exit('literalAutolink');\n      return ok(code);\n    }\n    return nok(code);\n  }\n}\n\n/**\n * `www` autolink literal.\n *\n * ```markdown\n * > | a www.example.org b\n *       ^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwAutolink(effects, ok, nok) {\n  const self = this;\n  return wwwStart;\n\n  /**\n   * Start of www autolink literal.\n   *\n   * ```markdown\n   * > | www.example.com/a?b#c\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwStart(code) {\n    if (code !== 87 && code !== 119 || !previousWww.call(self, self.previous) || previousUnbalanced(self.events)) {\n      return nok(code);\n    }\n    effects.enter('literalAutolink');\n    effects.enter('literalAutolinkWww');\n    // Note: we *check*, so we can discard the `www.` we parsed.\n    // If it worked, we consider it as a part of the domain.\n    return effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path, wwwAfter), nok), nok)(code);\n  }\n\n  /**\n   * After a www autolink literal.\n   *\n   * ```markdown\n   * > | www.example.com/a?b#c\n   *                          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwAfter(code) {\n    effects.exit('literalAutolinkWww');\n    effects.exit('literalAutolink');\n    return ok(code);\n  }\n}\n\n/**\n * Protocol autolink literal.\n *\n * ```markdown\n * > | a https://example.org b\n *       ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeProtocolAutolink(effects, ok, nok) {\n  const self = this;\n  let buffer = '';\n  let seen = false;\n  return protocolStart;\n\n  /**\n   * Start of protocol autolink literal.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolStart(code) {\n    if ((code === 72 || code === 104) && previousProtocol.call(self, self.previous) && !previousUnbalanced(self.events)) {\n      effects.enter('literalAutolink');\n      effects.enter('literalAutolinkHttp');\n      buffer += String.fromCodePoint(code);\n      effects.consume(code);\n      return protocolPrefixInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In protocol.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *     ^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolPrefixInside(code) {\n    // `5` is size of `https`\n    if (asciiAlpha(code) && buffer.length < 5) {\n      // @ts-expect-error: definitely number.\n      buffer += String.fromCodePoint(code);\n      effects.consume(code);\n      return protocolPrefixInside;\n    }\n    if (code === 58) {\n      const protocol = buffer.toLowerCase();\n      if (protocol === 'http' || protocol === 'https') {\n        effects.consume(code);\n        return protocolSlashesInside;\n      }\n    }\n    return nok(code);\n  }\n\n  /**\n   * In slashes.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *           ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolSlashesInside(code) {\n    if (code === 47) {\n      effects.consume(code);\n      if (seen) {\n        return afterProtocol;\n      }\n      seen = true;\n      return protocolSlashesInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After protocol, before domain.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterProtocol(code) {\n    // To do: this is different from `markdown-rs`:\n    // https://github.com/wooorm/markdown-rs/blob/b3a921c761309ae00a51fe348d8a43adbc54b518/src/construct/gfm_autolink_literal.rs#L172-L182\n    return code === null || asciiControl(code) || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || unicodePunctuation(code) ? nok(code) : effects.attempt(domain, effects.attempt(path, protocolAfter), nok)(code);\n  }\n\n  /**\n   * After a protocol autolink literal.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *                              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolAfter(code) {\n    effects.exit('literalAutolinkHttp');\n    effects.exit('literalAutolink');\n    return ok(code);\n  }\n}\n\n/**\n * `www` prefix.\n *\n * ```markdown\n * > | a www.example.org b\n *       ^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwPrefix(effects, ok, nok) {\n  let size = 0;\n  return wwwPrefixInside;\n\n  /**\n   * In www prefix.\n   *\n   * ```markdown\n   * > | www.example.com\n   *     ^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwPrefixInside(code) {\n    if ((code === 87 || code === 119) && size < 3) {\n      size++;\n      effects.consume(code);\n      return wwwPrefixInside;\n    }\n    if (code === 46 && size === 3) {\n      effects.consume(code);\n      return wwwPrefixAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After www prefix.\n   *\n   * ```markdown\n   * > | www.example.com\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwPrefixAfter(code) {\n    // If there is *anything*, we can link.\n    return code === null ? nok(code) : ok(code);\n  }\n}\n\n/**\n * Domain.\n *\n * ```markdown\n * > | a https://example.org b\n *               ^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDomain(effects, ok, nok) {\n  /** @type {boolean | undefined} */\n  let underscoreInLastSegment;\n  /** @type {boolean | undefined} */\n  let underscoreInLastLastSegment;\n  /** @type {boolean | undefined} */\n  let seen;\n  return domainInside;\n\n  /**\n   * In domain.\n   *\n   * ```markdown\n   * > | https://example.com/a\n   *             ^^^^^^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function domainInside(code) {\n    // Check whether this marker, which is a trailing punctuation\n    // marker, optionally followed by more trailing markers, and then\n    // followed by an end.\n    if (code === 46 || code === 95) {\n      return effects.check(trail, domainAfter, domainAtPunctuation)(code);\n    }\n\n    // GH documents that only alphanumerics (other than `-`, `.`, and `_`) can\n    // occur, which sounds like ASCII only, but they also support `www.點看.com`,\n    // so that’s Unicode.\n    // Instead of some new production for Unicode alphanumerics, markdown\n    // already has that for Unicode punctuation and whitespace, so use those.\n    // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L12>.\n    if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || code !== 45 && unicodePunctuation(code)) {\n      return domainAfter(code);\n    }\n    seen = true;\n    effects.consume(code);\n    return domainInside;\n  }\n\n  /**\n   * In domain, at potential trailing punctuation, that was not trailing.\n   *\n   * ```markdown\n   * > | https://example.com\n   *                    ^\n   * ```\n   *\n   * @type {State}\n   */\n  function domainAtPunctuation(code) {\n    // There is an underscore in the last segment of the domain\n    if (code === 95) {\n      underscoreInLastSegment = true;\n    }\n    // Otherwise, it’s a `.`: save the last segment underscore in the\n    // penultimate segment slot.\n    else {\n      underscoreInLastLastSegment = underscoreInLastSegment;\n      underscoreInLastSegment = undefined;\n    }\n    effects.consume(code);\n    return domainInside;\n  }\n\n  /**\n   * After domain.\n   *\n   * ```markdown\n   * > | https://example.com/a\n   *                        ^\n   * ```\n   *\n   * @type {State} */\n  function domainAfter(code) {\n    // Note: that’s GH says a dot is needed, but it’s not true:\n    // <https://github.com/github/cmark-gfm/issues/279>\n    if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {\n      return nok(code);\n    }\n    return ok(code);\n  }\n}\n\n/**\n * Path.\n *\n * ```markdown\n * > | a https://example.org/stuff b\n *                          ^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePath(effects, ok) {\n  let sizeOpen = 0;\n  let sizeClose = 0;\n  return pathInside;\n\n  /**\n   * In path.\n   *\n   * ```markdown\n   * > | https://example.com/a\n   *                        ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function pathInside(code) {\n    if (code === 40) {\n      sizeOpen++;\n      effects.consume(code);\n      return pathInside;\n    }\n\n    // To do: `markdown-rs` also needs this.\n    // If this is a paren, and there are less closings than openings,\n    // we don’t check for a trail.\n    if (code === 41 && sizeClose < sizeOpen) {\n      return pathAtPunctuation(code);\n    }\n\n    // Check whether this trailing punctuation marker is optionally\n    // followed by more trailing markers, and then followed\n    // by an end.\n    if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 63 || code === 93 || code === 95 || code === 126) {\n      return effects.check(trail, ok, pathAtPunctuation)(code);\n    }\n    if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n      return ok(code);\n    }\n    effects.consume(code);\n    return pathInside;\n  }\n\n  /**\n   * In path, at potential trailing punctuation, that was not trailing.\n   *\n   * ```markdown\n   * > | https://example.com/a\"b\n   *                          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function pathAtPunctuation(code) {\n    // Count closing parens.\n    if (code === 41) {\n      sizeClose++;\n    }\n    effects.consume(code);\n    return pathInside;\n  }\n}\n\n/**\n * Trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the entire trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | https://example.com\").\n *                        ^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTrail(effects, ok, nok) {\n  return trail;\n\n  /**\n   * In trail of domain or path.\n   *\n   * ```markdown\n   * > | https://example.com\").\n   *                        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trail(code) {\n    // Regular trailing punctuation.\n    if (code === 33 || code === 34 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 63 || code === 95 || code === 126) {\n      effects.consume(code);\n      return trail;\n    }\n\n    // `&` followed by one or more alphabeticals and then a `;`, is\n    // as a whole considered as trailing punctuation.\n    // In all other cases, it is considered as continuation of the URL.\n    if (code === 38) {\n      effects.consume(code);\n      return trailCharacterReferenceStart;\n    }\n\n    // Needed because we allow literals after `[`, as we fix:\n    // <https://github.com/github/cmark-gfm/issues/278>.\n    // Check that it is not followed by `(` or `[`.\n    if (code === 93) {\n      effects.consume(code);\n      return trailBracketAfter;\n    }\n    if (\n    // `<` is an end.\n    code === 60 ||\n    // So is whitespace.\n    code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n      return ok(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In trail, after `]`.\n   *\n   * > 👉 **Note**: this deviates from `cmark-gfm` to fix a bug.\n   * > See end of <https://github.com/github/cmark-gfm/issues/278> for more.\n   *\n   * ```markdown\n   * > | https://example.com](\n   *                         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trailBracketAfter(code) {\n    // Whitespace or something that could start a resource or reference is the end.\n    // Switch back to trail otherwise.\n    if (code === null || code === 40 || code === 91 || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n      return ok(code);\n    }\n    return trail(code);\n  }\n\n  /**\n   * In character-reference like trail, after `&`.\n   *\n   * ```markdown\n   * > | https://example.com&amp;).\n   *                         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trailCharacterReferenceStart(code) {\n    // When non-alpha, it’s not a trail.\n    return asciiAlpha(code) ? trailCharacterReferenceInside(code) : nok(code);\n  }\n\n  /**\n   * In character-reference like trail.\n   *\n   * ```markdown\n   * > | https://example.com&amp;).\n   *                         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trailCharacterReferenceInside(code) {\n    // Switch back to trail if this is well-formed.\n    if (code === 59) {\n      effects.consume(code);\n      return trail;\n    }\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return trailCharacterReferenceInside;\n    }\n\n    // It’s not a trail.\n    return nok(code);\n  }\n}\n\n/**\n * Dot in email domain trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | contact@example.org.\n *                        ^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailDomainDotTrail(effects, ok, nok) {\n  return start;\n\n  /**\n   * Dot.\n   *\n   * ```markdown\n   * > | contact@example.org.\n   *                    ^   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // Must be dot.\n    effects.consume(code);\n    return after;\n  }\n\n  /**\n   * After dot.\n   *\n   * ```markdown\n   * > | contact@example.org.\n   *                     ^   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // Not a trail if alphanumeric.\n    return asciiAlphanumeric(code) ? nok(code) : ok(code);\n  }\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L156>.\n *\n * @type {Previous}\n */\nfunction previousWww(code) {\n  return code === null || code === 40 || code === 42 || code === 95 || code === 91 || code === 93 || code === 126 || markdownLineEndingOrSpace(code);\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L214>.\n *\n * @type {Previous}\n */\nfunction previousProtocol(code) {\n  return !asciiAlpha(code);\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Previous}\n */\nfunction previousEmail(code) {\n  // Do not allow a slash “inside” atext.\n  // The reference code is a bit weird, but that’s what it results in.\n  // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L307>.\n  // Other than slash, every preceding character is allowed.\n  return !(code === 47 || gfmAtext(code));\n}\n\n/**\n * @param {Code} code\n * @returns {boolean}\n */\nfunction gfmAtext(code) {\n  return code === 43 || code === 45 || code === 46 || code === 95 || asciiAlphanumeric(code);\n}\n\n/**\n * @param {Array<Event>} events\n * @returns {boolean}\n */\nfunction previousUnbalanced(events) {\n  let index = events.length;\n  let result = false;\n  while (index--) {\n    const token = events[index][1];\n    if ((token.type === 'labelLink' || token.type === 'labelImage') && !token._balanced) {\n      result = true;\n      break;\n    }\n\n    // If we’ve seen this token, and it was marked as not having any unbalanced\n    // bracket before it, we can exit.\n    if (token._gfmAutolinkLiteralWalkedInto) {\n      result = false;\n      break;\n    }\n  }\n  if (events.length > 0 && !result) {\n    // Mark the last token as “walked into” w/o finding\n    // anything.\n    events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;\n  }\n  return result;\n}","/**\n * @import {Event, Exiter, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { blankLine } from 'micromark-core-commonmark';\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEndingOrSpace } from 'micromark-util-character';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nconst indent = {\n  tokenize: tokenizeIndent,\n  partial: true\n};\n\n// To do: micromark should support a `_hiddenGfmFootnoteSupport`, which only\n// affects label start (image).\n// That will let us drop `tokenizePotentialGfmFootnote*`.\n// It currently has a `_hiddenFootnoteSupport`, which affects that and more.\n// That can be removed when `micromark-extension-footnote` is archived.\n\n/**\n * Create an extension for `micromark` to enable GFM footnote syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to\n *   enable GFM footnote syntax.\n */\nexport function gfmFootnote() {\n  /** @type {Extension} */\n  return {\n    document: {\n      [91]: {\n        name: 'gfmFootnoteDefinition',\n        tokenize: tokenizeDefinitionStart,\n        continuation: {\n          tokenize: tokenizeDefinitionContinuation\n        },\n        exit: gfmFootnoteDefinitionEnd\n      }\n    },\n    text: {\n      [91]: {\n        name: 'gfmFootnoteCall',\n        tokenize: tokenizeGfmFootnoteCall\n      },\n      [93]: {\n        name: 'gfmPotentialFootnoteCall',\n        add: 'after',\n        tokenize: tokenizePotentialGfmFootnoteCall,\n        resolveTo: resolveToPotentialGfmFootnoteCall\n      }\n    }\n  };\n}\n\n// To do: remove after micromark update.\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePotentialGfmFootnoteCall(effects, ok, nok) {\n  const self = this;\n  let index = self.events.length;\n  const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n  /** @type {Token} */\n  let labelStart;\n\n  // Find an opening.\n  while (index--) {\n    const token = self.events[index][1];\n    if (token.type === \"labelImage\") {\n      labelStart = token;\n      break;\n    }\n\n    // Exit if we’ve walked far enough.\n    if (token.type === 'gfmFootnoteCall' || token.type === \"labelLink\" || token.type === \"label\" || token.type === \"image\" || token.type === \"link\") {\n      break;\n    }\n  }\n  return start;\n\n  /**\n   * @type {State}\n   */\n  function start(code) {\n    if (!labelStart || !labelStart._balanced) {\n      return nok(code);\n    }\n    const id = normalizeIdentifier(self.sliceSerialize({\n      start: labelStart.end,\n      end: self.now()\n    }));\n    if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) {\n      return nok(code);\n    }\n    effects.enter('gfmFootnoteCallLabelMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteCallLabelMarker');\n    return ok(code);\n  }\n}\n\n// To do: remove after micromark update.\n/** @type {Resolver} */\nfunction resolveToPotentialGfmFootnoteCall(events, context) {\n  let index = events.length;\n  /** @type {Token | undefined} */\n  let labelStart;\n\n  // Find an opening.\n  while (index--) {\n    if (events[index][1].type === \"labelImage\" && events[index][0] === 'enter') {\n      labelStart = events[index][1];\n      break;\n    }\n  }\n  // Change the `labelImageMarker` to a `data`.\n  events[index + 1][1].type = \"data\";\n  events[index + 3][1].type = 'gfmFootnoteCallLabelMarker';\n\n  // The whole (without `!`):\n  /** @type {Token} */\n  const call = {\n    type: 'gfmFootnoteCall',\n    start: Object.assign({}, events[index + 3][1].start),\n    end: Object.assign({}, events[events.length - 1][1].end)\n  };\n  // The `^` marker\n  /** @type {Token} */\n  const marker = {\n    type: 'gfmFootnoteCallMarker',\n    start: Object.assign({}, events[index + 3][1].end),\n    end: Object.assign({}, events[index + 3][1].end)\n  };\n  // Increment the end 1 character.\n  marker.end.column++;\n  marker.end.offset++;\n  marker.end._bufferIndex++;\n  /** @type {Token} */\n  const string = {\n    type: 'gfmFootnoteCallString',\n    start: Object.assign({}, marker.end),\n    end: Object.assign({}, events[events.length - 1][1].start)\n  };\n  /** @type {Token} */\n  const chunk = {\n    type: \"chunkString\",\n    contentType: 'string',\n    start: Object.assign({}, string.start),\n    end: Object.assign({}, string.end)\n  };\n\n  /** @type {Array<Event>} */\n  const replacement = [\n  // Take the `labelImageMarker` (now `data`, the `!`)\n  events[index + 1], events[index + 2], ['enter', call, context],\n  // The `[`\n  events[index + 3], events[index + 4],\n  // The `^`.\n  ['enter', marker, context], ['exit', marker, context],\n  // Everything in between.\n  ['enter', string, context], ['enter', chunk, context], ['exit', chunk, context], ['exit', string, context],\n  // The ending (`]`, properly parsed and labelled).\n  events[events.length - 2], events[events.length - 1], ['exit', call, context]];\n  events.splice(index, events.length - index + 1, ...replacement);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeGfmFootnoteCall(effects, ok, nok) {\n  const self = this;\n  const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n  let size = 0;\n  /** @type {boolean} */\n  let data;\n\n  // Note: the implementation of `markdown-rs` is different, because it houses\n  // core *and* extensions in one project.\n  // Therefore, it can include footnote logic inside `label-end`.\n  // We can’t do that, but luckily, we can parse footnotes in a simpler way than\n  // needed for labels.\n  return start;\n\n  /**\n   * Start of footnote label.\n   *\n   * ```markdown\n   * > | a [^b] c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter('gfmFootnoteCall');\n    effects.enter('gfmFootnoteCallLabelMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteCallLabelMarker');\n    return callStart;\n  }\n\n  /**\n   * After `[`, at `^`.\n   *\n   * ```markdown\n   * > | a [^b] c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function callStart(code) {\n    if (code !== 94) return nok(code);\n    effects.enter('gfmFootnoteCallMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteCallMarker');\n    effects.enter('gfmFootnoteCallString');\n    effects.enter('chunkString').contentType = 'string';\n    return callData;\n  }\n\n  /**\n   * In label.\n   *\n   * ```markdown\n   * > | a [^b] c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function callData(code) {\n    if (\n    // Too long.\n    size > 999 ||\n    // Closing brace with nothing.\n    code === 93 && !data ||\n    // Space or tab is not supported by GFM for some reason.\n    // `\\n` and `[` not being supported makes sense.\n    code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.exit('chunkString');\n      const token = effects.exit('gfmFootnoteCallString');\n      if (!defined.includes(normalizeIdentifier(self.sliceSerialize(token)))) {\n        return nok(code);\n      }\n      effects.enter('gfmFootnoteCallLabelMarker');\n      effects.consume(code);\n      effects.exit('gfmFootnoteCallLabelMarker');\n      effects.exit('gfmFootnoteCall');\n      return ok;\n    }\n    if (!markdownLineEndingOrSpace(code)) {\n      data = true;\n    }\n    size++;\n    effects.consume(code);\n    return code === 92 ? callEscape : callData;\n  }\n\n  /**\n   * On character after escape.\n   *\n   * ```markdown\n   * > | a [^b\\c] d\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function callEscape(code) {\n    if (code === 91 || code === 92 || code === 93) {\n      effects.consume(code);\n      size++;\n      return callData;\n    }\n    return callData(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionStart(effects, ok, nok) {\n  const self = this;\n  const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n  /** @type {string} */\n  let identifier;\n  let size = 0;\n  /** @type {boolean | undefined} */\n  let data;\n  return start;\n\n  /**\n   * Start of GFM footnote definition.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter('gfmFootnoteDefinition')._container = true;\n    effects.enter('gfmFootnoteDefinitionLabel');\n    effects.enter('gfmFootnoteDefinitionLabelMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteDefinitionLabelMarker');\n    return labelAtMarker;\n  }\n\n  /**\n   * In label, at caret.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelAtMarker(code) {\n    if (code === 94) {\n      effects.enter('gfmFootnoteDefinitionMarker');\n      effects.consume(code);\n      effects.exit('gfmFootnoteDefinitionMarker');\n      effects.enter('gfmFootnoteDefinitionLabelString');\n      effects.enter('chunkString').contentType = 'string';\n      return labelInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In label.\n   *\n   * > 👉 **Note**: `cmark-gfm` prevents whitespace from occurring in footnote\n   * > definition labels.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelInside(code) {\n    if (\n    // Too long.\n    size > 999 ||\n    // Closing brace with nothing.\n    code === 93 && !data ||\n    // Space or tab is not supported by GFM for some reason.\n    // `\\n` and `[` not being supported makes sense.\n    code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.exit('chunkString');\n      const token = effects.exit('gfmFootnoteDefinitionLabelString');\n      identifier = normalizeIdentifier(self.sliceSerialize(token));\n      effects.enter('gfmFootnoteDefinitionLabelMarker');\n      effects.consume(code);\n      effects.exit('gfmFootnoteDefinitionLabelMarker');\n      effects.exit('gfmFootnoteDefinitionLabel');\n      return labelAfter;\n    }\n    if (!markdownLineEndingOrSpace(code)) {\n      data = true;\n    }\n    size++;\n    effects.consume(code);\n    return code === 92 ? labelEscape : labelInside;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * > 👉 **Note**: `cmark-gfm` currently does not support escaped brackets:\n   * > <https://github.com/github/cmark-gfm/issues/240>\n   *\n   * ```markdown\n   * > | [^a\\*b]: c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEscape(code) {\n    if (code === 91 || code === 92 || code === 93) {\n      effects.consume(code);\n      size++;\n      return labelInside;\n    }\n    return labelInside(code);\n  }\n\n  /**\n   * After definition label.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelAfter(code) {\n    if (code === 58) {\n      effects.enter('definitionMarker');\n      effects.consume(code);\n      effects.exit('definitionMarker');\n      if (!defined.includes(identifier)) {\n        defined.push(identifier);\n      }\n\n      // Any whitespace after the marker is eaten, forming indented code\n      // is not possible.\n      // No space is also fine, just like a block quote marker.\n      return factorySpace(effects, whitespaceAfter, 'gfmFootnoteDefinitionWhitespace');\n    }\n    return nok(code);\n  }\n\n  /**\n   * After definition prefix.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function whitespaceAfter(code) {\n    // `markdown-rs` has a wrapping token for the prefix that is closed here.\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionContinuation(effects, ok, nok) {\n  /// Start of footnote definition continuation.\n  ///\n  /// ```markdown\n  ///   | [^a]: b\n  /// > |     c\n  ///     ^\n  /// ```\n  //\n  // Either a blank line, which is okay, or an indented thing.\n  return effects.check(blankLine, ok, effects.attempt(indent, ok, nok));\n}\n\n/** @type {Exiter} */\nfunction gfmFootnoteDefinitionEnd(effects) {\n  effects.exit('gfmFootnoteDefinition');\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeIndent(effects, ok, nok) {\n  const self = this;\n  return factorySpace(effects, afterPrefix, 'gfmFootnoteDefinitionIndent', 4 + 1);\n\n  /**\n   * @type {State}\n   */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === 'gfmFootnoteDefinitionIndent' && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok(code) : nok(code);\n  }\n}","/**\n * @import {Options} from 'micromark-extension-gfm-strikethrough'\n * @import {Event, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { splice } from 'micromark-util-chunked';\nimport { classifyCharacter } from 'micromark-util-classify-character';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/**\n * Create an extension for `micromark` to enable GFM strikethrough syntax.\n *\n * @param {Options | null | undefined} [options={}]\n *   Configuration.\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions`, to\n *   enable GFM strikethrough syntax.\n */\nexport function gfmStrikethrough(options) {\n  const options_ = options || {};\n  let single = options_.singleTilde;\n  const tokenizer = {\n    name: 'strikethrough',\n    tokenize: tokenizeStrikethrough,\n    resolveAll: resolveAllStrikethrough\n  };\n  if (single === null || single === undefined) {\n    single = true;\n  }\n  return {\n    text: {\n      [126]: tokenizer\n    },\n    insideSpan: {\n      null: [tokenizer]\n    },\n    attentionMarkers: {\n      null: [126]\n    }\n  };\n\n  /**\n   * Take events and resolve strikethrough.\n   *\n   * @type {Resolver}\n   */\n  function resolveAllStrikethrough(events, context) {\n    let index = -1;\n\n    // Walk through all events.\n    while (++index < events.length) {\n      // Find a token that can close.\n      if (events[index][0] === 'enter' && events[index][1].type === 'strikethroughSequenceTemporary' && events[index][1]._close) {\n        let open = index;\n\n        // Now walk back to find an opener.\n        while (open--) {\n          // Find a token that can open the closer.\n          if (events[open][0] === 'exit' && events[open][1].type === 'strikethroughSequenceTemporary' && events[open][1]._open &&\n          // If the sizes are the same:\n          events[index][1].end.offset - events[index][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {\n            events[index][1].type = 'strikethroughSequence';\n            events[open][1].type = 'strikethroughSequence';\n\n            /** @type {Token} */\n            const strikethrough = {\n              type: 'strikethrough',\n              start: Object.assign({}, events[open][1].start),\n              end: Object.assign({}, events[index][1].end)\n            };\n\n            /** @type {Token} */\n            const text = {\n              type: 'strikethroughText',\n              start: Object.assign({}, events[open][1].end),\n              end: Object.assign({}, events[index][1].start)\n            };\n\n            // Opening.\n            /** @type {Array<Event>} */\n            const nextEvents = [['enter', strikethrough, context], ['enter', events[open][1], context], ['exit', events[open][1], context], ['enter', text, context]];\n            const insideSpan = context.parser.constructs.insideSpan.null;\n            if (insideSpan) {\n              // Between.\n              splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context));\n            }\n\n            // Closing.\n            splice(nextEvents, nextEvents.length, 0, [['exit', text, context], ['enter', events[index][1], context], ['exit', events[index][1], context], ['exit', strikethrough, context]]);\n            splice(events, open - 1, index - open + 3, nextEvents);\n            index = open + nextEvents.length - 2;\n            break;\n          }\n        }\n      }\n    }\n    index = -1;\n    while (++index < events.length) {\n      if (events[index][1].type === 'strikethroughSequenceTemporary') {\n        events[index][1].type = \"data\";\n      }\n    }\n    return events;\n  }\n\n  /**\n   * @this {TokenizeContext}\n   * @type {Tokenizer}\n   */\n  function tokenizeStrikethrough(effects, ok, nok) {\n    const previous = this.previous;\n    const events = this.events;\n    let size = 0;\n    return start;\n\n    /** @type {State} */\n    function start(code) {\n      if (previous === 126 && events[events.length - 1][1].type !== \"characterEscape\") {\n        return nok(code);\n      }\n      effects.enter('strikethroughSequenceTemporary');\n      return more(code);\n    }\n\n    /** @type {State} */\n    function more(code) {\n      const before = classifyCharacter(previous);\n      if (code === 126) {\n        // If this is the third marker, exit.\n        if (size > 1) return nok(code);\n        effects.consume(code);\n        size++;\n        return more;\n      }\n      if (size < 2 && !single) return nok(code);\n      const token = effects.exit('strikethroughSequenceTemporary');\n      const after = classifyCharacter(code);\n      token._open = !after || after === 2 && Boolean(before);\n      token._close = !before || before === 2 && Boolean(after);\n      return ok(code);\n    }\n  }\n}","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n// Port of `edit_map.rs` from `markdown-rs`.\n// This should move to `markdown-js` later.\n\n// Deal with several changes in events, batching them together.\n//\n// Preferably, changes should be kept to a minimum.\n// Sometimes, it’s needed to change the list of events, because parsing can be\n// messy, and it helps to expose a cleaner interface of events to the compiler\n// and other users.\n// It can also help to merge many adjacent similar events.\n// And, in other cases, it’s needed to parse subcontent: pass some events\n// through another tokenizer and inject the result.\n\n/**\n * @typedef {[number, number, Array<Event>]} Change\n * @typedef {[number, number, number]} Jump\n */\n\n/**\n * Tracks a bunch of edits.\n */\nexport class EditMap {\n  /**\n   * Create a new edit map.\n   */\n  constructor() {\n    /**\n     * Record of changes.\n     *\n     * @type {Array<Change>}\n     */\n    this.map = [];\n  }\n\n  /**\n   * Create an edit: a remove and/or add at a certain place.\n   *\n   * @param {number} index\n   * @param {number} remove\n   * @param {Array<Event>} add\n   * @returns {undefined}\n   */\n  add(index, remove, add) {\n    addImplementation(this, index, remove, add);\n  }\n\n  // To do: add this when moving to `micromark`.\n  // /**\n  //  * Create an edit: but insert `add` before existing additions.\n  //  *\n  //  * @param {number} index\n  //  * @param {number} remove\n  //  * @param {Array<Event>} add\n  //  * @returns {undefined}\n  //  */\n  // addBefore(index, remove, add) {\n  //   addImplementation(this, index, remove, add, true)\n  // }\n\n  /**\n   * Done, change the events.\n   *\n   * @param {Array<Event>} events\n   * @returns {undefined}\n   */\n  consume(events) {\n    this.map.sort(function (a, b) {\n      return a[0] - b[0];\n    });\n\n    /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n    if (this.map.length === 0) {\n      return;\n    }\n\n    // To do: if links are added in events, like they are in `markdown-rs`,\n    // this is needed.\n    // // Calculate jumps: where items in the current list move to.\n    // /** @type {Array<Jump>} */\n    // const jumps = []\n    // let index = 0\n    // let addAcc = 0\n    // let removeAcc = 0\n    // while (index < this.map.length) {\n    //   const [at, remove, add] = this.map[index]\n    //   removeAcc += remove\n    //   addAcc += add.length\n    //   jumps.push([at, removeAcc, addAcc])\n    //   index += 1\n    // }\n    //\n    // . shiftLinks(events, jumps)\n\n    let index = this.map.length;\n    /** @type {Array<Array<Event>>} */\n    const vecs = [];\n    while (index > 0) {\n      index -= 1;\n      vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]);\n\n      // Truncate rest.\n      events.length = this.map[index][0];\n    }\n    vecs.push(events.slice());\n    events.length = 0;\n    let slice = vecs.pop();\n    while (slice) {\n      for (const element of slice) {\n        events.push(element);\n      }\n      slice = vecs.pop();\n    }\n\n    // Truncate everything.\n    this.map.length = 0;\n  }\n}\n\n/**\n * Create an edit.\n *\n * @param {EditMap} editMap\n * @param {number} at\n * @param {number} remove\n * @param {Array<Event>} add\n * @returns {undefined}\n */\nfunction addImplementation(editMap, at, remove, add) {\n  let index = 0;\n\n  /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n  if (remove === 0 && add.length === 0) {\n    return;\n  }\n  while (index < editMap.map.length) {\n    if (editMap.map[index][0] === at) {\n      editMap.map[index][1] += remove;\n\n      // To do: before not used by tables, use when moving to micromark.\n      // if (before) {\n      //   add.push(...editMap.map[index][2])\n      //   editMap.map[index][2] = add\n      // } else {\n      editMap.map[index][2].push(...add);\n      // }\n\n      return;\n    }\n    index += 1;\n  }\n  editMap.map.push([at, remove, add]);\n}\n\n// /**\n//  * Shift `previous` and `next` links according to `jumps`.\n//  *\n//  * This fixes links in case there are events removed or added between them.\n//  *\n//  * @param {Array<Event>} events\n//  * @param {Array<Jump>} jumps\n//  */\n// function shiftLinks(events, jumps) {\n//   let jumpIndex = 0\n//   let index = 0\n//   let add = 0\n//   let rm = 0\n\n//   while (index < events.length) {\n//     const rmCurr = rm\n\n//     while (jumpIndex < jumps.length && jumps[jumpIndex][0] <= index) {\n//       add = jumps[jumpIndex][2]\n//       rm = jumps[jumpIndex][1]\n//       jumpIndex += 1\n//     }\n\n//     // Ignore items that will be removed.\n//     if (rm > rmCurr) {\n//       index += rm - rmCurr\n//     } else {\n//       // ?\n//       // if let Some(link) = &events[index].link {\n//       //     if let Some(next) = link.next {\n//       //         events[next].link.as_mut().unwrap().previous = Some(index + add - rm);\n//       //         while jumpIndex < jumps.len() && jumps[jumpIndex].0 <= next {\n//       //             add = jumps[jumpIndex].2;\n//       //             rm = jumps[jumpIndex].1;\n//       //             jumpIndex += 1;\n//       //         }\n//       //         events[index].link.as_mut().unwrap().next = Some(next + add - rm);\n//       //         index = next;\n//       //         continue;\n//       //     }\n//       // }\n//       index += 1\n//     }\n//   }\n// }","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n/**\n * @typedef {'center' | 'left' | 'none' | 'right'} Align\n */\n\n/**\n * Figure out the alignment of a GFM table.\n *\n * @param {Readonly<Array<Event>>} events\n *   List of events.\n * @param {number} index\n *   Table enter event.\n * @returns {Array<Align>}\n *   List of aligns.\n */\nexport function gfmTableAlign(events, index) {\n  let inDelimiterRow = false;\n  /** @type {Array<Align>} */\n  const align = [];\n  while (index < events.length) {\n    const event = events[index];\n    if (inDelimiterRow) {\n      if (event[0] === 'enter') {\n        // Start of alignment value: set a new column.\n        // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n        if (event[1].type === 'tableContent') {\n          align.push(events[index + 1][1].type === 'tableDelimiterMarker' ? 'left' : 'none');\n        }\n      }\n      // Exits:\n      // End of alignment value: change the column.\n      // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n      else if (event[1].type === 'tableContent') {\n        if (events[index - 1][1].type === 'tableDelimiterMarker') {\n          const alignIndex = align.length - 1;\n          align[alignIndex] = align[alignIndex] === 'left' ? 'center' : 'right';\n        }\n      }\n      // Done!\n      else if (event[1].type === 'tableDelimiterRow') {\n        break;\n      }\n    } else if (event[0] === 'enter' && event[1].type === 'tableDelimiterRow') {\n      inDelimiterRow = true;\n    }\n    index += 1;\n  }\n  return align;\n}","/**\n * @import {Event, Extension, Point, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\n/**\n * @typedef {[number, number, number, number]} Range\n *   Cell info.\n *\n * @typedef {0 | 1 | 2 | 3} RowKind\n *   Where we are: `1` for head row, `2` for delimiter row, `3` for body row.\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nimport { EditMap } from './edit-map.js';\nimport { gfmTableAlign } from './infer.js';\n\n/**\n * Create an HTML extension for `micromark` to support GitHub tables syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to enable GFM\n *   table syntax.\n */\nexport function gfmTable() {\n  return {\n    flow: {\n      null: {\n        name: 'table',\n        tokenize: tokenizeTable,\n        resolveAll: resolveTable\n      }\n    }\n  };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTable(effects, ok, nok) {\n  const self = this;\n  let size = 0;\n  let sizeB = 0;\n  /** @type {boolean | undefined} */\n  let seen;\n  return start;\n\n  /**\n   * Start of a GFM table.\n   *\n   * If there is a valid table row or table head before, then we try to parse\n   * another row.\n   * Otherwise, we try to parse a head.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *   | | - |\n   * > | | b |\n   *     ^\n   * ```\n   * @type {State}\n   */\n  function start(code) {\n    let index = self.events.length - 1;\n    while (index > -1) {\n      const type = self.events[index][1].type;\n      if (type === \"lineEnding\" ||\n      // Note: markdown-rs uses `whitespace` instead of `linePrefix`\n      type === \"linePrefix\") index--;else break;\n    }\n    const tail = index > -1 ? self.events[index][1].type : null;\n    const next = tail === 'tableHead' || tail === 'tableRow' ? bodyRowStart : headRowBefore;\n\n    // Don’t allow lazy body rows.\n    if (next === bodyRowStart && self.parser.lazy[self.now().line]) {\n      return nok(code);\n    }\n    return next(code);\n  }\n\n  /**\n   * Before table head row.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowBefore(code) {\n    effects.enter('tableHead');\n    effects.enter('tableRow');\n    return headRowStart(code);\n  }\n\n  /**\n   * Before table head row, after whitespace.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowStart(code) {\n    if (code === 124) {\n      return headRowBreak(code);\n    }\n\n    // To do: micromark-js should let us parse our own whitespace in extensions,\n    // like `markdown-rs`:\n    //\n    // ```js\n    // // 4+ spaces.\n    // if (markdownSpace(code)) {\n    //   return nok(code)\n    // }\n    // ```\n\n    seen = true;\n    // Count the first character, that isn’t a pipe, double.\n    sizeB += 1;\n    return headRowBreak(code);\n  }\n\n  /**\n   * At break in table head row.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *       ^\n   *         ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowBreak(code) {\n    if (code === null) {\n      // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n      return nok(code);\n    }\n    if (markdownLineEnding(code)) {\n      // If anything other than one pipe (ignoring whitespace) was used, it’s fine.\n      if (sizeB > 1) {\n        sizeB = 0;\n        // To do: check if this works.\n        // Feel free to interrupt:\n        self.interrupt = true;\n        effects.exit('tableRow');\n        effects.enter(\"lineEnding\");\n        effects.consume(code);\n        effects.exit(\"lineEnding\");\n        return headDelimiterStart;\n      }\n\n      // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n      return nok(code);\n    }\n    if (markdownSpace(code)) {\n      // To do: check if this is fine.\n      // effects.attempt(State::Next(StateName::GfmTableHeadRowBreak), State::Nok)\n      // State::Retry(space_or_tab(tokenizer))\n      return factorySpace(effects, headRowBreak, \"whitespace\")(code);\n    }\n    sizeB += 1;\n    if (seen) {\n      seen = false;\n      // Header cell count.\n      size += 1;\n    }\n    if (code === 124) {\n      effects.enter('tableCellDivider');\n      effects.consume(code);\n      effects.exit('tableCellDivider');\n      // Whether a delimiter was seen.\n      seen = true;\n      return headRowBreak;\n    }\n\n    // Anything else is cell data.\n    effects.enter(\"data\");\n    return headRowData(code);\n  }\n\n  /**\n   * In table head row data.\n   *\n   * ```markdown\n   * > | | a |\n   *       ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowData(code) {\n    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"data\");\n      return headRowBreak(code);\n    }\n    effects.consume(code);\n    return code === 92 ? headRowEscape : headRowData;\n  }\n\n  /**\n   * In table head row escape.\n   *\n   * ```markdown\n   * > | | a\\-b |\n   *         ^\n   *   | | ---- |\n   *   | | c    |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowEscape(code) {\n    if (code === 92 || code === 124) {\n      effects.consume(code);\n      return headRowData;\n    }\n    return headRowData(code);\n  }\n\n  /**\n   * Before delimiter row.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *     ^\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterStart(code) {\n    // Reset `interrupt`.\n    self.interrupt = false;\n\n    // Note: in `markdown-rs`, we need to handle piercing here too.\n    if (self.parser.lazy[self.now().line]) {\n      return nok(code);\n    }\n    effects.enter('tableDelimiterRow');\n    // Track if we’ve seen a `:` or `|`.\n    seen = false;\n    if (markdownSpace(code)) {\n      return factorySpace(effects, headDelimiterBefore, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n    }\n    return headDelimiterBefore(code);\n  }\n\n  /**\n   * Before delimiter row, after optional whitespace.\n   *\n   * Reused when a `|` is found later, to parse another cell.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *     ^\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterBefore(code) {\n    if (code === 45 || code === 58) {\n      return headDelimiterValueBefore(code);\n    }\n    if (code === 124) {\n      seen = true;\n      // If we start with a pipe, we open a cell marker.\n      effects.enter('tableCellDivider');\n      effects.consume(code);\n      effects.exit('tableCellDivider');\n      return headDelimiterCellBefore;\n    }\n\n    // More whitespace / empty row not allowed at start.\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * After `|`, before delimiter cell.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterCellBefore(code) {\n    if (markdownSpace(code)) {\n      return factorySpace(effects, headDelimiterValueBefore, \"whitespace\")(code);\n    }\n    return headDelimiterValueBefore(code);\n  }\n\n  /**\n   * Before delimiter cell value.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterValueBefore(code) {\n    // Align: left.\n    if (code === 58) {\n      sizeB += 1;\n      seen = true;\n      effects.enter('tableDelimiterMarker');\n      effects.consume(code);\n      effects.exit('tableDelimiterMarker');\n      return headDelimiterLeftAlignmentAfter;\n    }\n\n    // Align: none.\n    if (code === 45) {\n      sizeB += 1;\n      // To do: seems weird that this *isn’t* left aligned, but that state is used?\n      return headDelimiterLeftAlignmentAfter(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      return headDelimiterCellAfter(code);\n    }\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * After delimiter cell left alignment marker.\n   *\n   * ```markdown\n   *   | | a  |\n   * > | | :- |\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterLeftAlignmentAfter(code) {\n    if (code === 45) {\n      effects.enter('tableDelimiterFiller');\n      return headDelimiterFiller(code);\n    }\n\n    // Anything else is not ok after the left-align colon.\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * In delimiter cell filler.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterFiller(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return headDelimiterFiller;\n    }\n\n    // Align is `center` if it was `left`, `right` otherwise.\n    if (code === 58) {\n      seen = true;\n      effects.exit('tableDelimiterFiller');\n      effects.enter('tableDelimiterMarker');\n      effects.consume(code);\n      effects.exit('tableDelimiterMarker');\n      return headDelimiterRightAlignmentAfter;\n    }\n    effects.exit('tableDelimiterFiller');\n    return headDelimiterRightAlignmentAfter(code);\n  }\n\n  /**\n   * After delimiter cell right alignment marker.\n   *\n   * ```markdown\n   *   | |  a |\n   * > | | -: |\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterRightAlignmentAfter(code) {\n    if (markdownSpace(code)) {\n      return factorySpace(effects, headDelimiterCellAfter, \"whitespace\")(code);\n    }\n    return headDelimiterCellAfter(code);\n  }\n\n  /**\n   * After delimiter cell.\n   *\n   * ```markdown\n   *   | |  a |\n   * > | | -: |\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterCellAfter(code) {\n    if (code === 124) {\n      return headDelimiterBefore(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      // Exit when:\n      // * there was no `:` or `|` at all (it’s a thematic break or setext\n      //   underline instead)\n      // * the header cell count is not the delimiter cell count\n      if (!seen || size !== sizeB) {\n        return headDelimiterNok(code);\n      }\n\n      // Note: in markdown-rs`, a reset is needed here.\n      effects.exit('tableDelimiterRow');\n      effects.exit('tableHead');\n      // To do: in `markdown-rs`, resolvers need to be registered manually.\n      // effects.register_resolver(ResolveName::GfmTable)\n      return ok(code);\n    }\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * In delimiter row, at a disallowed byte.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | x |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterNok(code) {\n    // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n    return nok(code);\n  }\n\n  /**\n   * Before table body row.\n   *\n   * ```markdown\n   *   | | a |\n   *   | | - |\n   * > | | b |\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowStart(code) {\n    // Note: in `markdown-rs` we need to manually take care of a prefix,\n    // but in `micromark-js` that is done for us, so if we’re here, we’re\n    // never at whitespace.\n    effects.enter('tableRow');\n    return bodyRowBreak(code);\n  }\n\n  /**\n   * At break in table body row.\n   *\n   * ```markdown\n   *   | | a |\n   *   | | - |\n   * > | | b |\n   *     ^\n   *       ^\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowBreak(code) {\n    if (code === 124) {\n      effects.enter('tableCellDivider');\n      effects.consume(code);\n      effects.exit('tableCellDivider');\n      return bodyRowBreak;\n    }\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit('tableRow');\n      return ok(code);\n    }\n    if (markdownSpace(code)) {\n      return factorySpace(effects, bodyRowBreak, \"whitespace\")(code);\n    }\n\n    // Anything else is cell content.\n    effects.enter(\"data\");\n    return bodyRowData(code);\n  }\n\n  /**\n   * In table body row data.\n   *\n   * ```markdown\n   *   | | a |\n   *   | | - |\n   * > | | b |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowData(code) {\n    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"data\");\n      return bodyRowBreak(code);\n    }\n    effects.consume(code);\n    return code === 92 ? bodyRowEscape : bodyRowData;\n  }\n\n  /**\n   * In table body row escape.\n   *\n   * ```markdown\n   *   | | a    |\n   *   | | ---- |\n   * > | | b\\-c |\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowEscape(code) {\n    if (code === 92 || code === 124) {\n      effects.consume(code);\n      return bodyRowData;\n    }\n    return bodyRowData(code);\n  }\n}\n\n/** @type {Resolver} */\n\nfunction resolveTable(events, context) {\n  let index = -1;\n  let inFirstCellAwaitingPipe = true;\n  /** @type {RowKind} */\n  let rowKind = 0;\n  /** @type {Range} */\n  let lastCell = [0, 0, 0, 0];\n  /** @type {Range} */\n  let cell = [0, 0, 0, 0];\n  let afterHeadAwaitingFirstBodyRow = false;\n  let lastTableEnd = 0;\n  /** @type {Token | undefined} */\n  let currentTable;\n  /** @type {Token | undefined} */\n  let currentBody;\n  /** @type {Token | undefined} */\n  let currentCell;\n  const map = new EditMap();\n  while (++index < events.length) {\n    const event = events[index];\n    const token = event[1];\n    if (event[0] === 'enter') {\n      // Start of head.\n      if (token.type === 'tableHead') {\n        afterHeadAwaitingFirstBodyRow = false;\n\n        // Inject previous (body end and) table end.\n        if (lastTableEnd !== 0) {\n          flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n          currentBody = undefined;\n          lastTableEnd = 0;\n        }\n\n        // Inject table start.\n        currentTable = {\n          type: 'table',\n          start: Object.assign({}, token.start),\n          // Note: correct end is set later.\n          end: Object.assign({}, token.end)\n        };\n        map.add(index, 0, [['enter', currentTable, context]]);\n      } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n        inFirstCellAwaitingPipe = true;\n        currentCell = undefined;\n        lastCell = [0, 0, 0, 0];\n        cell = [0, index + 1, 0, 0];\n\n        // Inject table body start.\n        if (afterHeadAwaitingFirstBodyRow) {\n          afterHeadAwaitingFirstBodyRow = false;\n          currentBody = {\n            type: 'tableBody',\n            start: Object.assign({}, token.start),\n            // Note: correct end is set later.\n            end: Object.assign({}, token.end)\n          };\n          map.add(index, 0, [['enter', currentBody, context]]);\n        }\n        rowKind = token.type === 'tableDelimiterRow' ? 2 : currentBody ? 3 : 1;\n      }\n      // Cell data.\n      else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n        inFirstCellAwaitingPipe = false;\n\n        // First value in cell.\n        if (cell[2] === 0) {\n          if (lastCell[1] !== 0) {\n            cell[0] = cell[1];\n            currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n            lastCell = [0, 0, 0, 0];\n          }\n          cell[2] = index;\n        }\n      } else if (token.type === 'tableCellDivider') {\n        if (inFirstCellAwaitingPipe) {\n          inFirstCellAwaitingPipe = false;\n        } else {\n          if (lastCell[1] !== 0) {\n            cell[0] = cell[1];\n            currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n          }\n          lastCell = cell;\n          cell = [lastCell[1], index, 0, 0];\n        }\n      }\n    }\n    // Exit events.\n    else if (token.type === 'tableHead') {\n      afterHeadAwaitingFirstBodyRow = true;\n      lastTableEnd = index;\n    } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n      lastTableEnd = index;\n      if (lastCell[1] !== 0) {\n        cell[0] = cell[1];\n        currentCell = flushCell(map, context, lastCell, rowKind, index, currentCell);\n      } else if (cell[1] !== 0) {\n        currentCell = flushCell(map, context, cell, rowKind, index, currentCell);\n      }\n      rowKind = 0;\n    } else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n      cell[3] = index;\n    }\n  }\n  if (lastTableEnd !== 0) {\n    flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n  }\n  map.consume(context.events);\n\n  // To do: move this into `html`, when events are exposed there.\n  // That’s what `markdown-rs` does.\n  // That needs updates to `mdast-util-gfm-table`.\n  index = -1;\n  while (++index < context.events.length) {\n    const event = context.events[index];\n    if (event[0] === 'enter' && event[1].type === 'table') {\n      event[1]._align = gfmTableAlign(context.events, index);\n    }\n  }\n  return events;\n}\n\n/**\n * Generate a cell.\n *\n * @param {EditMap} map\n * @param {Readonly<TokenizeContext>} context\n * @param {Readonly<Range>} range\n * @param {RowKind} rowKind\n * @param {number | undefined} rowEnd\n * @param {Token | undefined} previousCell\n * @returns {Token | undefined}\n */\n// eslint-disable-next-line max-params\nfunction flushCell(map, context, range, rowKind, rowEnd, previousCell) {\n  // `markdown-rs` uses:\n  // rowKind === 2 ? 'tableDelimiterCell' : 'tableCell'\n  const groupName = rowKind === 1 ? 'tableHeader' : rowKind === 2 ? 'tableDelimiter' : 'tableData';\n  // `markdown-rs` uses:\n  // rowKind === 2 ? 'tableDelimiterCellValue' : 'tableCellText'\n  const valueName = 'tableContent';\n\n  // Insert an exit for the previous cell, if there is one.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //          ^-- exit\n  //           ^^^^-- this cell\n  // ```\n  if (range[0] !== 0) {\n    previousCell.end = Object.assign({}, getPoint(context.events, range[0]));\n    map.add(range[0], 0, [['exit', previousCell, context]]);\n  }\n\n  // Insert enter of this cell.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //           ^-- enter\n  //           ^^^^-- this cell\n  // ```\n  const now = getPoint(context.events, range[1]);\n  previousCell = {\n    type: groupName,\n    start: Object.assign({}, now),\n    // Note: correct end is set later.\n    end: Object.assign({}, now)\n  };\n  map.add(range[1], 0, [['enter', previousCell, context]]);\n\n  // Insert text start at first data start and end at last data end, and\n  // remove events between.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //            ^-- enter\n  //             ^-- exit\n  //           ^^^^-- this cell\n  // ```\n  if (range[2] !== 0) {\n    const relatedStart = getPoint(context.events, range[2]);\n    const relatedEnd = getPoint(context.events, range[3]);\n    /** @type {Token} */\n    const valueToken = {\n      type: valueName,\n      start: Object.assign({}, relatedStart),\n      end: Object.assign({}, relatedEnd)\n    };\n    map.add(range[2], 0, [['enter', valueToken, context]]);\n    if (rowKind !== 2) {\n      // Fix positional info on remaining events\n      const start = context.events[range[2]];\n      const end = context.events[range[3]];\n      start[1].end = Object.assign({}, end[1].end);\n      start[1].type = \"chunkText\";\n      start[1].contentType = \"text\";\n\n      // Remove if needed.\n      if (range[3] > range[2] + 1) {\n        const a = range[2] + 1;\n        const b = range[3] - range[2] - 1;\n        map.add(a, b, []);\n      }\n    }\n    map.add(range[3] + 1, 0, [['exit', valueToken, context]]);\n  }\n\n  // Insert an exit for the last cell, if at the row end.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //                    ^-- exit\n  //               ^^^^^^-- this cell (the last one contains two “between” parts)\n  // ```\n  if (rowEnd !== undefined) {\n    previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));\n    map.add(rowEnd, 0, [['exit', previousCell, context]]);\n    previousCell = undefined;\n  }\n  return previousCell;\n}\n\n/**\n * Generate table end (and table body end).\n *\n * @param {Readonly<EditMap>} map\n * @param {Readonly<TokenizeContext>} context\n * @param {number} index\n * @param {Token} table\n * @param {Token | undefined} tableBody\n */\n// eslint-disable-next-line max-params\nfunction flushTableEnd(map, context, index, table, tableBody) {\n  /** @type {Array<Event>} */\n  const exits = [];\n  const related = getPoint(context.events, index);\n  if (tableBody) {\n    tableBody.end = Object.assign({}, related);\n    exits.push(['exit', tableBody, context]);\n  }\n  table.end = Object.assign({}, related);\n  exits.push(['exit', table, context]);\n  map.add(index + 1, 0, exits);\n}\n\n/**\n * @param {Readonly<Array<Event>>} events\n * @param {number} index\n * @returns {Readonly<Point>}\n */\nfunction getPoint(events, index) {\n  const event = events[index];\n  const side = event[0] === 'enter' ? 'start' : 'end';\n  return event[1][side];\n}","/**\n * @import {Extension, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nconst tasklistCheck = {\n  name: 'tasklistCheck',\n  tokenize: tokenizeTasklistCheck\n};\n\n/**\n * Create an HTML extension for `micromark` to support GFM task list items\n * syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `htmlExtensions` to\n *   support GFM task list items when serializing to HTML.\n */\nexport function gfmTaskListItem() {\n  return {\n    text: {\n      [91]: tasklistCheck\n    }\n  };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTasklistCheck(effects, ok, nok) {\n  const self = this;\n  return open;\n\n  /**\n   * At start of task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (\n    // Exit if there’s stuff before.\n    self.previous !== null ||\n    // Exit if not in the first content that is the first child of a list\n    // item.\n    !self._gfmTasklistFirstContentOfListItem) {\n      return nok(code);\n    }\n    effects.enter('taskListCheck');\n    effects.enter('taskListCheckMarker');\n    effects.consume(code);\n    effects.exit('taskListCheckMarker');\n    return inside;\n  }\n\n  /**\n   * In task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    // Currently we match how GH works in files.\n    // To match how GH works in comments, use `markdownSpace` (`[\\t ]`) instead\n    // of `markdownLineEndingOrSpace` (`[\\t\\n\\r ]`).\n    if (markdownLineEndingOrSpace(code)) {\n      effects.enter('taskListCheckValueUnchecked');\n      effects.consume(code);\n      effects.exit('taskListCheckValueUnchecked');\n      return close;\n    }\n    if (code === 88 || code === 120) {\n      effects.enter('taskListCheckValueChecked');\n      effects.consume(code);\n      effects.exit('taskListCheckValueChecked');\n      return close;\n    }\n    return nok(code);\n  }\n\n  /**\n   * At close of task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function close(code) {\n    if (code === 93) {\n      effects.enter('taskListCheckMarker');\n      effects.consume(code);\n      effects.exit('taskListCheckMarker');\n      effects.exit('taskListCheck');\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * @type {State}\n   */\n  function after(code) {\n    // EOL in paragraph means there must be something else after it.\n    if (markdownLineEnding(code)) {\n      return ok(code);\n    }\n\n    // Space or tab?\n    // Check what comes after.\n    if (markdownSpace(code)) {\n      return effects.check({\n        tokenize: spaceThenNonSpace\n      }, ok, nok)(code);\n    }\n\n    // EOF, or non-whitespace, both wrong.\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction spaceThenNonSpace(effects, ok, nok) {\n  return factorySpace(effects, after, \"whitespace\");\n\n  /**\n   * After whitespace, after task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // EOF means there was nothing, so bad.\n    // EOL means there’s content after it, so good.\n    // Impossible to have more spaces.\n    // Anything else is good.\n    return code === null ? nok(code) : ok(code);\n  }\n}","/**\n * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions\n * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options\n * @typedef {import('micromark-util-types').Extension} Extension\n * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension\n */\n\nimport {\n  combineExtensions,\n  combineHtmlExtensions\n} from 'micromark-util-combine-extensions'\nimport {\n  gfmAutolinkLiteral,\n  gfmAutolinkLiteralHtml\n} from 'micromark-extension-gfm-autolink-literal'\nimport {gfmFootnote, gfmFootnoteHtml} from 'micromark-extension-gfm-footnote'\nimport {\n  gfmStrikethrough,\n  gfmStrikethroughHtml\n} from 'micromark-extension-gfm-strikethrough'\nimport {gfmTable, gfmTableHtml} from 'micromark-extension-gfm-table'\nimport {gfmTagfilterHtml} from 'micromark-extension-gfm-tagfilter'\nimport {\n  gfmTaskListItem,\n  gfmTaskListItemHtml\n} from 'micromark-extension-gfm-task-list-item'\n\n/**\n * Create an extension for `micromark` to enable GFM syntax.\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n *\n *   Passed to `micromark-extens-gfm-strikethrough`.\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to enable GFM\n *   syntax.\n */\nexport function gfm(options) {\n  return combineExtensions([\n    gfmAutolinkLiteral(),\n    gfmFootnote(),\n    gfmStrikethrough(options),\n    gfmTable(),\n    gfmTaskListItem()\n  ])\n}\n\n/**\n * Create an extension for `micromark` to support GFM when serializing to HTML.\n *\n * @param {HtmlOptions | null | undefined} [options]\n *   Configuration (optional).\n *\n *   Passed to `micromark-extens-gfm-footnote`.\n * @returns {HtmlExtension}\n *   Extension for `micromark` that can be passed in `htmlExtensions` to\n *   support GFM when serializing to HTML.\n */\nexport function gfmHtml(options) {\n  return combineHtmlExtensions([\n    gfmAutolinkLiteralHtml(),\n    gfmFootnoteHtml(options),\n    gfmStrikethroughHtml(),\n    gfmTableHtml(),\n    gfmTagfilterHtml(),\n    gfmTaskListItemHtml()\n  ])\n}\n","/**\n * @import {Root} from 'mdast'\n * @import {Options} from 'remark-gfm'\n * @import {} from 'remark-parse'\n * @import {} from 'remark-stringify'\n * @import {Processor} from 'unified'\n */\n\nimport {gfmFromMarkdown, gfmToMarkdown} from 'mdast-util-gfm'\nimport {gfm} from 'micromark-extension-gfm'\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Add support GFM (autolink literals, footnotes, strikethrough, tables,\n * tasklists).\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function remarkGfm(options) {\n  // @ts-expect-error: TS is wrong about `this`.\n  // eslint-disable-next-line unicorn/no-this-assignment\n  const self = /** @type {Processor<Root>} */ (this)\n  const settings = options || emptyOptions\n  const data = self.data()\n\n  const micromarkExtensions =\n    data.micromarkExtensions || (data.micromarkExtensions = [])\n  const fromMarkdownExtensions =\n    data.fromMarkdownExtensions || (data.fromMarkdownExtensions = [])\n  const toMarkdownExtensions =\n    data.toMarkdownExtensions || (data.toMarkdownExtensions = [])\n\n  micromarkExtensions.push(gfm(settings))\n  fromMarkdownExtensions.push(gfmFromMarkdown())\n  toMarkdownExtensions.push(gfmToMarkdown(settings))\n}\n","import { Bot, User } from 'lucide-react';\nimport ReactMarkdown from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport type { ChatMessageData } from './ChatWidget.types';\n\ninterface ChatMessageProps {\n  message: ChatMessageData;\n  locale?: string;\n}\n\n/**\n * Componente que renderiza un mensaje individual del chat.\n *\n * Los mensajes del asistente se renderizan con soporte completo de Markdown\n * (negrita, cursiva, código inline, bloques de código, listas, headers, links, etc.).\n * Los mensajes del usuario se muestran como texto plano.\n *\n * @see docs/colors.md - Sistema de colores\n */\nexport function ChatMessage({ message, locale = 'en' }: ChatMessageProps) {\n  const isUser = message.role === 'user';\n\n  const formattedTime = new Intl.DateTimeFormat(locale, {\n    hour: '2-digit',\n    minute: '2-digit',\n  }).format(message.timestamp);\n\n  return (\n    <div\n      className={`flex gap-2 ${isUser ? 'flex-row-reverse' : 'flex-row'}`}\n      data-testid={`chat-message-${message.role}`}\n    >\n      {/* Avatar */}\n      <div\n        className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full ${\n          isUser\n            ? 'bg-blue-100 dark:bg-blue-900/30'\n            : 'bg-gray-100 dark:bg-gray-700'\n        }`}\n      >\n        {isUser ? (\n          <User className=\"h-4 w-4 text-blue-600 dark:text-blue-400\" />\n        ) : (\n          <Bot className=\"h-4 w-4 text-gray-600 dark:text-gray-400\" />\n        )}\n      </div>\n\n      {/* Burbuja de mensaje */}\n      <div className={`max-w-[75%] ${isUser ? 'text-right' : 'text-left'}`}>\n        <div\n          className={`inline-block rounded-2xl px-4 py-2 text-sm ${\n            isUser\n              ? 'rounded-br-md bg-blue-600 text-white dark:bg-blue-500'\n              : 'rounded-bl-md bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-gray-100'\n          }`}\n        >\n          {isUser ? (\n            // Mensajes del usuario: texto plano\n            <span>{message.content}</span>\n          ) : (\n            // Mensajes del asistente: Markdown completo\n            <div className=\"chat-markdown\">\n              <ReactMarkdown\n                remarkPlugins={[remarkGfm]}\n                components={{\n                  // Párrafos\n                  p: ({ children }) => (\n                    <p className=\"mb-2 last:mb-0 leading-relaxed\">{children}</p>\n                  ),\n                  // Headers\n                  h1: ({ children }) => (\n                    <h1 className=\"mb-2 mt-3 text-base font-bold first:mt-0\">{children}</h1>\n                  ),\n                  h2: ({ children }) => (\n                    <h2 className=\"mb-2 mt-3 text-sm font-bold first:mt-0\">{children}</h2>\n                  ),\n                  h3: ({ children }) => (\n                    <h3 className=\"mb-1 mt-2 text-sm font-semibold first:mt-0\">{children}</h3>\n                  ),\n                  h4: ({ children }) => (\n                    <h4 className=\"mb-1 mt-2 text-sm font-semibold first:mt-0\">{children}</h4>\n                  ),\n                  // Énfasis\n                  strong: ({ children }) => (\n                    <strong className=\"font-semibold\">{children}</strong>\n                  ),\n                  em: ({ children }) => (\n                    <em className=\"italic\">{children}</em>\n                  ),\n                  // Código inline\n                  code: ({ children, className }) => {\n                    const isBlock = className?.includes('language-');\n                    if (isBlock) {\n                      return (\n                        <code className={className}>{children}</code>\n                      );\n                    }\n                    return (\n                      <code className=\"rounded bg-gray-200 px-1 py-0.5 font-mono text-xs dark:bg-gray-600 dark:text-gray-100\">\n                        {children}\n                      </code>\n                    );\n                  },\n                  // Bloque de código\n                  pre: ({ children }) => (\n                    <pre className=\"my-2 overflow-x-auto rounded-lg bg-gray-800 p-3 font-mono text-xs text-gray-100 dark:bg-gray-900 dark:text-gray-100\">\n                      {children}\n                    </pre>\n                  ),\n                  // Listas\n                  ul: ({ children }) => (\n                    <ul className=\"mb-2 ml-4 list-disc space-y-0.5 last:mb-0\">{children}</ul>\n                  ),\n                  ol: ({ children }) => (\n                    <ol className=\"mb-2 ml-4 list-decimal space-y-0.5 last:mb-0\">{children}</ol>\n                  ),\n                  li: ({ children }) => (\n                    <li className=\"leading-relaxed\">{children}</li>\n                  ),\n                  // Cita\n                  blockquote: ({ children }) => (\n                    <blockquote className=\"my-2 border-l-2 border-gray-400 pl-3 italic text-gray-600 dark:border-gray-500 dark:text-gray-300\">\n                      {children}\n                    </blockquote>\n                  ),\n                  // Separador\n                  hr: () => (\n                    <hr className=\"my-2 border-gray-300 dark:border-gray-600\" />\n                  ),\n                  // Links\n                  a: ({ href, children }) => (\n                    <a\n                      href={href}\n                      target=\"_blank\"\n                      rel=\"noopener noreferrer\"\n                      className=\"underline decoration-blue-500 underline-offset-2 hover:text-blue-600 dark:hover:text-blue-300\"\n                    >\n                      {children}\n                    </a>\n                  ),\n                  // Tabla (GFM)\n                  table: ({ children }) => (\n                    <div className=\"my-2 overflow-x-auto\">\n                      <table className=\"min-w-full border-collapse text-xs\">\n                        {children}\n                      </table>\n                    </div>\n                  ),\n                  thead: ({ children }) => (\n                    <thead className=\"border-b border-gray-300 dark:border-gray-600\">\n                      {children}\n                    </thead>\n                  ),\n                  tbody: ({ children }) => <tbody>{children}</tbody>,\n                  tr: ({ children }) => (\n                    <tr className=\"border-b border-gray-200 dark:border-gray-700\">{children}</tr>\n                  ),\n                  th: ({ children }) => (\n                    <th className=\"px-2 py-1 text-left font-semibold\">{children}</th>\n                  ),\n                  td: ({ children }) => (\n                    <td className=\"px-2 py-1\">{children}</td>\n                  ),\n                }}\n              >\n                {message.content}\n              </ReactMarkdown>\n            </div>\n          )}\n        </div>\n        <p className=\"mt-1 text-xs text-gray-400 dark:text-gray-500\">\n          {formattedTime}\n        </p>\n      </div>\n    </div>\n  );\n}\n","import { useState, useRef, useCallback } from 'react';\nimport { Send } from 'lucide-react';\nimport { Button } from '../Button';\n\ninterface ChatInputLabels {\n  placeholder: string;\n  send: string;\n}\n\ninterface ChatInputProps {\n  onSend: (message: string) => void;\n  isLoading?: boolean;\n  labels?: ChatInputLabels;\n}\n\nconst DEFAULT_INPUT_LABELS: ChatInputLabels = {\n  placeholder: 'Type a message...',\n  send: 'Send',\n};\n\nexport function ChatInput({ onSend, isLoading = false, labels: labelsProp }: ChatInputProps) {\n  const labels = { ...DEFAULT_INPUT_LABELS, ...labelsProp };\n  const [value, setValue] = useState('');\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n  const handleSend = useCallback(() => {\n    const trimmed = value.trim();\n    if (!trimmed || isLoading) return;\n    onSend(trimmed);\n    setValue('');\n    if (textareaRef.current) {\n      textareaRef.current.style.height = 'auto';\n    }\n  }, [value, isLoading, onSend]);\n\n  const handleKeyDown = useCallback(\n    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n      if (e.key === 'Enter' && !e.shiftKey) {\n        e.preventDefault();\n        handleSend();\n      }\n    },\n    [handleSend]\n  );\n\n  const handleInput = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {\n    setValue(e.target.value);\n    const el = e.target;\n    el.style.height = 'auto';\n    el.style.height = `${Math.min(el.scrollHeight, 120)}px`;\n  }, []);\n\n  return (\n    <div className=\"flex items-end gap-2 border-t border-gray-200 p-3 dark:border-gray-700\">\n      <textarea\n        ref={textareaRef}\n        value={value}\n        onChange={handleInput}\n        onKeyDown={handleKeyDown}\n        placeholder={labels.placeholder}\n        rows={1}\n        className=\"flex-1 resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder-gray-500 dark:focus:border-blue-400\"\n        aria-label={labels.placeholder}\n        data-testid=\"chat-input\"\n      />\n      <Button\n        variant=\"default\"\n        size=\"sm\"\n        onClick={handleSend}\n        disabled={!value.trim() || isLoading}\n        aria-label={labels.send}\n        data-testid=\"chat-send-button\"\n      >\n        <Send className=\"h-4 w-4\" />\n      </Button>\n    </div>\n  );\n}\n","import type { SuggestedAction } from './ChatWidget.types';\n\ninterface QuickActionsProps {\n  actions: SuggestedAction[];\n  onActionClick: (message: string) => void;\n}\n\nexport function QuickActions({ actions, onActionClick }: QuickActionsProps) {\n  if (actions.length === 0) return null;\n\n  return (\n    <div className=\"flex flex-wrap gap-2 px-4 py-3\" data-testid=\"quick-actions\">\n      {actions.map((action) => (\n        <button\n          key={action.message}\n          type=\"button\"\n          onClick={() => onActionClick(action.message)}\n          className=\"rounded-full border border-blue-200 bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-100 dark:border-blue-800 dark:bg-blue-900/20 dark:text-blue-300 dark:hover:bg-blue-900/40\"\n          data-testid=\"quick-action-chip\"\n        >\n          {action.label}\n        </button>\n      ))}\n    </div>\n  );\n}\n","import { useEffect, useRef, useCallback } from 'react';\nimport { X, Minus, Loader2 } from 'lucide-react';\nimport { motion } from 'framer-motion';\nimport { ChatMessage } from './ChatMessage';\nimport { ChatInput } from './ChatInput';\nimport { QuickActions } from './QuickActions';\nimport type { ChatMessageData, SuggestedAction, ChatLabels } from './ChatWidget.types';\n\ninterface ChatWindowProps {\n  messages: ChatMessageData[];\n  isLoading?: boolean;\n  suggestedActions?: SuggestedAction[];\n  onSendMessage: (message: string) => void;\n  onClose: () => void;\n  onMinimize: () => void;\n  labels: Required<ChatLabels>;\n  locale?: string;\n}\n\nexport function ChatWindow({\n  messages,\n  isLoading = false,\n  suggestedActions = [],\n  onSendMessage,\n  onClose,\n  onMinimize,\n  labels,\n  locale = 'en',\n}: ChatWindowProps) {\n  const messagesEndRef = useRef<HTMLDivElement>(null);\n  const panelRef = useRef<HTMLDivElement>(null);\n  const previousActiveElement = useRef<HTMLElement | null>(null);\n\n  // Auto-scroll to bottom on new messages\n  useEffect(() => {\n    if (messagesEndRef.current && typeof messagesEndRef.current.scrollIntoView === 'function') {\n      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });\n    }\n  }, [messages, isLoading]);\n\n  // Focus management and Escape key\n  useEffect(() => {\n    previousActiveElement.current = document.activeElement as HTMLElement;\n\n    const handleKeyDown = (e: KeyboardEvent) => {\n      if (e.key === 'Escape') {\n        onClose();\n      }\n\n      // Focus trap\n      if (e.key === 'Tab' && panelRef.current) {\n        const focusable = panelRef.current.querySelectorAll<HTMLElement>(\n          'button, textarea, [tabindex]:not([tabindex=\"-1\"])'\n        );\n        const first = focusable[0];\n        const last = focusable[focusable.length - 1];\n\n        if (e.shiftKey && document.activeElement === first) {\n          e.preventDefault();\n          last?.focus();\n        } else if (!e.shiftKey && document.activeElement === last) {\n          e.preventDefault();\n          first?.focus();\n        }\n      }\n    };\n\n    document.addEventListener('keydown', handleKeyDown);\n\n    return () => {\n      document.removeEventListener('keydown', handleKeyDown);\n      previousActiveElement.current?.focus();\n    };\n  }, [onClose]);\n\n  const handleActionClick = useCallback(\n    (message: string) => {\n      onSendMessage(message);\n    },\n    [onSendMessage]\n  );\n\n  const showWelcome = messages.length === 0;\n\n  return (\n    <motion.div\n      ref={panelRef}\n      role=\"dialog\"\n      aria-modal=\"true\"\n      aria-label={labels.title}\n      initial={{ opacity: 0, y: 20, scale: 0.95 }}\n      animate={{ opacity: 1, y: 0, scale: 1 }}\n      exit={{ opacity: 0, y: 20, scale: 0.95 }}\n      transition={{ type: 'spring', damping: 30, stiffness: 300 }}\n      className=\"fixed bottom-20 right-4 z-40 flex w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl dark:border-gray-700 dark:bg-gray-900 sm:bottom-20 sm:right-6 sm:w-96 sm:max-h-[500px] max-h-[calc(100vh-6rem)] md:max-h-[500px]\"\n      data-testid=\"chat-window\"\n    >\n      {/* Header */}\n      <div className=\"flex items-center justify-between border-b border-gray-200 bg-blue-600 px-4 py-3 dark:border-gray-700 dark:bg-blue-700\">\n        <h2 className=\"text-sm font-semibold text-white\">{labels.title}</h2>\n        <div className=\"flex items-center gap-1\">\n          <button\n            type=\"button\"\n            onClick={onMinimize}\n            className=\"rounded-lg p-1.5 text-blue-100 transition-colors hover:bg-blue-500 hover:text-white\"\n            aria-label={labels.close}\n            data-testid=\"chat-minimize-button\"\n          >\n            <Minus className=\"h-4 w-4\" />\n          </button>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"rounded-lg p-1.5 text-blue-100 transition-colors hover:bg-blue-500 hover:text-white\"\n            aria-label={labels.close}\n            data-testid=\"chat-close-button\"\n          >\n            <X className=\"h-4 w-4\" />\n          </button>\n        </div>\n      </div>\n\n      {/* Messages Area */}\n      <div className=\"flex-1 overflow-y-auto p-4 space-y-4 min-h-[200px]\">\n        {showWelcome && (\n          <div className=\"text-center\">\n            <p className=\"mb-3 text-sm text-gray-500 dark:text-gray-400\">\n              {labels.welcome}\n            </p>\n            {suggestedActions.length > 0 && (\n              <QuickActions\n                actions={suggestedActions}\n                onActionClick={handleActionClick}\n              />\n            )}\n          </div>\n        )}\n\n        {messages.map((msg) => (\n          <ChatMessage key={msg.id} message={msg} locale={locale} />\n        ))}\n\n        {isLoading && (\n          <div className=\"flex items-center gap-2 text-sm text-gray-400 dark:text-gray-500\" data-testid=\"chat-typing-indicator\">\n            <Loader2 className=\"h-4 w-4 animate-spin\" />\n            <span>{labels.typing}</span>\n          </div>\n        )}\n\n        <div ref={messagesEndRef} />\n      </div>\n\n      {/* Input */}\n      <ChatInput\n        onSend={onSendMessage}\n        isLoading={isLoading}\n        labels={{ placeholder: labels.placeholder, send: labels.send }}\n      />\n    </motion.div>\n  );\n}\n","export interface ChatMessageData {\n  id: string;\n  role: 'user' | 'assistant';\n  content: string;\n  timestamp: Date;\n  isStreaming?: boolean;\n}\n\nexport interface SuggestedAction {\n  label: string;\n  message: string;\n}\n\nexport interface MockConfig {\n  enabled: boolean;\n  responseDelay?: number;\n}\n\nexport interface ChatLabels {\n  title?: string;\n  placeholder?: string;\n  send?: string;\n  close?: string;\n  welcome?: string;\n  typing?: string;\n  fabLabel?: string;\n}\n\nexport const DEFAULT_CHAT_LABELS: Required<ChatLabels> = {\n  title: 'Customer Support',\n  placeholder: 'Type a message...',\n  send: 'Send',\n  close: 'Close chat',\n  welcome: 'Hi! How can I help you today?',\n  typing: 'Assistant is typing...',\n  fabLabel: 'Open chat assistant',\n};\n\nexport interface ChatWidgetProps {\n  onSendMessage: (message: string) => void;\n  messages: ChatMessageData[];\n  isLoading?: boolean;\n  suggestedActions?: SuggestedAction[];\n  isOpen?: boolean;\n  onToggle?: () => void;\n  className?: string;\n  mockConfig?: MockConfig;\n  labels?: ChatLabels;\n  locale?: string;\n}\n","import { useCallback, useMemo } from 'react';\nimport { MessageCircle } from 'lucide-react';\nimport { AnimatePresence } from 'framer-motion';\nimport { Button } from '../Button';\nimport { ChatWindow } from './ChatWindow';\nimport type { ChatWidgetProps } from './ChatWidget.types';\nimport { DEFAULT_CHAT_LABELS } from './ChatWidget.types';\n\nexport function ChatWidget({\n  onSendMessage,\n  messages,\n  isLoading = false,\n  suggestedActions = [],\n  isOpen = false,\n  onToggle,\n  className = '',\n  labels: labelsProp,\n  locale = 'en',\n}: ChatWidgetProps) {\n  const labels = useMemo(\n    () => ({ ...DEFAULT_CHAT_LABELS, ...labelsProp }),\n    [labelsProp]\n  );\n\n  const handleToggle = useCallback(() => {\n    onToggle?.();\n  }, [onToggle]);\n\n  const handleClose = useCallback(() => {\n    if (isOpen) onToggle?.();\n  }, [isOpen, onToggle]);\n\n  return (\n    <div className={className}>\n      <AnimatePresence>\n        {isOpen && (\n          <ChatWindow\n            messages={messages}\n            isLoading={isLoading}\n            suggestedActions={suggestedActions}\n            onSendMessage={onSendMessage}\n            onClose={handleClose}\n            onMinimize={handleClose}\n            labels={labels}\n            locale={locale}\n          />\n        )}\n      </AnimatePresence>\n\n      <Button\n        onClick={handleToggle}\n        className=\"fixed bottom-4 right-4 z-50 flex h-14 w-14 items-center justify-center rounded-full bg-blue-600 text-white shadow-lg transition-all hover:bg-blue-700 hover:shadow-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:bg-blue-500 dark:hover:bg-blue-600 dark:focus:ring-offset-gray-900 sm:bottom-6 sm:right-6\"\n        aria-label={labels.fabLabel}\n        aria-expanded={isOpen}\n        data-testid=\"chat-fab\"\n      >\n        <MessageCircle className=\"h-6 w-6\" />\n      </Button>\n    </div>\n  );\n}\n","import React from 'react';\nimport { ArrowPathIcon } from '@heroicons/react/24/outline';\n\nexport interface LoadingProps {\n  /**\n   * Mensaje ya traducido por el padre (p. ej. `t('master_document.crossing.loading')`).\n   * Si se omite, no se dibuja texto y el indicador queda solo con el icono.\n   */\n  label?: string;\n  /**\n   * Tamaño del indicador.\n   * - 'sm': inline dentro de texto o de un control (celda de tabla, campo que\n   *   resuelve un lookup, icono a la izquierda de un botón)\n   * - 'md': bloque dentro de un panel o modal (sección de un FactBox, cuerpo de\n   *   un modal de listado)\n   * - 'lg': bloque en un área grande (modal a pantalla casi completa)\n   * @default 'md'\n   */\n  size?: 'sm' | 'md' | 'lg';\n  /**\n   * Disposición: 'block' centra en columna; 'inline' fluye con el texto.\n   * @default 'block'\n   */\n  layout?: 'block' | 'inline';\n  /** Icono personalizado. Reemplaza el spinner por defecto (el consumidor controla su animación y tamaño). */\n  icon?: React.ReactNode;\n  /**\n   * El icono por defecto toma el color del texto de su contenedor\n   * (`currentColor`) en lugar de `primary-600`.\n   *\n   * **Obligatorio sobre superficies de color.** Un botón primario pinta\n   * `bg-primary-600`, que es exactamente el color del spinner por defecto: sin\n   * esto el indicador está en el DOM pero es invisible. Dentro de un control,\n   * el spinner sustituye a su icono y debe verse como él.\n   */\n  inheritColor?: boolean;\n  /**\n   * Etiqueta accesible **ya traducida por el padre**, para cuando no hay `label` visible\n   * (p. ej. `t('master_document.chrome.updating')`).\n   *\n   * No tiene valor por defecto a propósito: el componente no traduce, y un literal fijo\n   * ('Cargando') se anunciaría en español a un usuario en inglés. Si no se provee ni `label`\n   * ni `ariaLabel`, el indicador queda sin nombre accesible.\n   */\n  ariaLabel?: string;\n  /** Clases adicionales para el contenedor */\n  className?: string;\n}\n\n/**\n * Mapa de tamaños: icono, escala de texto, separación y padding vertical.\n *\n * `sm` (w-3.5) es el tamaño que ya usan a mano los spinners de campo de\n * `LineFormModal` / `MasterDocumentFormModal` y el buscador de\n * `CrossingSourceSelector`. `md` y `lg` son los bloques centrados de panel y de\n * modal grande. No se añaden más tamaños: cada uno nuevo es una decisión de\n * diseño, no un parámetro.\n */\nconst SIZE_CLASSES = {\n  sm: { icon: 'w-3.5 h-3.5', text: 'text-[11px]', gap: 'gap-1.5', pad: 'py-2' },\n  md: { icon: 'w-8 h-8', text: 'text-sm', gap: 'gap-4', pad: 'py-16' },\n  lg: { icon: 'w-12 h-12', text: 'text-sm', gap: 'gap-4', pad: 'py-20' },\n} as const;\n\n/**\n * Loading - Indicador de operación en curso (estado indeterminado).\n *\n * Componente presentacional puro: el padre decide *cuándo* mostrarlo y provee todo el\n * texto ya traducido (`label` y/o `ariaLabel`). No tiene diccionario propio, no recibe `t`\n * y no contiene ningún literal visible para el usuario, así que respeta el idioma activo\n * del consumidor sin acoplarse a su mecanismo de i18n.\n *\n * Aporta la semántica accesible que ninguno de los spinners a mano de\n * `MasterDocument` tiene: `role=\"status\"` + `aria-live=\"polite\"`, con el icono\n * marcado `aria-hidden` para evitar la lectura doble.\n *\n * **Es el destino de unificación de los indicadores indeterminados del feature,\n * y la migración es progresiva:** `MasterDocument` todavía arrastra spinners\n * escritos a mano en tres paletas distintas. El plan, sitio por sitio y con\n * prioridades, está en `MasterDocument/LOADING-INTEGRATION.md` (Fase 1 aplicada:\n * spinners de campo, lookups solo-lectura y los \"Cargando…\" de texto plano). No\n * escribas un spinner nuevo a mano: usa este componente.\n *\n * **Cuándo NO usarlo** — son semánticas distintas y ya tienen su propio sitio:\n * - Progreso medible (total/procesados) → `BulkConversionProgress`.\n * - Máscara de layout de una vista completa → `SkeletonDocument` / `SkeletonList`\n *   (`Skeletons.tsx`), `StepSkeleton` (`DocumentCreationWizard`).\n */\nexport const Loading: React.FC<LoadingProps> = ({\n  label,\n  size = 'md',\n  layout = 'block',\n  icon,\n  inheritColor = false,\n  ariaLabel,\n  className = '',\n}) => {\n  const sizes = SIZE_CLASSES[size];\n\n  const containerClasses = [\n    layout === 'inline'\n      ? `inline-flex items-center ${sizes.gap}`\n      : `flex flex-col items-center justify-center ${sizes.gap} ${sizes.pad}`,\n    className,\n  ].join(' ').trim();\n\n  // El contenedor inline es un <span>: sus consumidores lo insertan dentro de texto\n  // o de contenido en línea (una celda, un <p>, el leftIcon de un Button), y un\n  // <div> ahí produce HTML inválido — React avisa con \"<p> cannot contain a\n  // nested <div>\". El layout visual no cambia: inline-flex se comporta igual en\n  // span que en div.\n  const Container = layout === 'inline' ? 'span' : 'div';\n\n  return (\n    <Container\n      role=\"status\"\n      aria-live=\"polite\"\n      aria-label={label ? undefined : ariaLabel}\n      className={containerClasses}\n    >\n      {icon ?? (\n        <ArrowPathIcon\n          className={`${sizes.icon} animate-spin ${\n            inheritColor ? 'text-current' : 'text-primary-600 dark:text-primary-300'\n          }`}\n          aria-hidden=\"true\"\n        />\n      )}\n      {label && (\n        <span className={`${sizes.text} text-content-secondary dark:text-dark-content-secondary`}>\n          {label}\n        </span>\n      )}\n    </Container>\n  );\n};\n","import { createTranslationHook } from './i18nFactory';\nimport type { TranslateFn } from './i18nFactory';\n\n/**\n * i18n del core de MasterDocument.\n *\n * Cubre el \"chrome\" que el kit renderiza por su cuenta: `aria-label`, `title`,\n * `placeholder`, textos de estado vacío, carga y paginación. NO cubre el texto\n * que es dato del host (`FieldDescriptor.label`, `action.label`,\n * `ValidationRule.message`, `identity.breadcrumbLabel`): ese pertenece al\n * template y el kit no debe traducirlo.\n *\n * Usa `useTranslation` de siesa-ui-kit vía `createTranslationHook`; si el host no\n * registró las claves `master_document.*` (el motor devuelve la propia clave),\n * cae al diccionario local del idioma activo y, en último término, al español.\n * Mismo contrato que `WithholdingsPanel/i18n.ts`, `SerialPanel/i18n.ts`, etc.\n *\n * Convención de claves: planas con puntos (`DefaultTranslationEngine` indexa\n * `resources[key]` directo), prefijo `master_document.` en snake_case por ser\n * multipalabra, grupo y hoja en camelCase.\n *\n * ## Namespaces reservados por el feature\n *\n * El catálogo del backend es GLOBAL: todas las claves de todos los features viven\n * en el mismo espacio de nombres, así que estos prefijos están reservados y no\n * deben reutilizarse en otro módulo.\n *\n * | Prefijo                  | Dueño                      |\n * |--------------------------|----------------------------|\n * | `master_document.*`      | core de MasterDocument     |\n * | `serial_panel.*`         | SerialPanel                |\n * | `withholdings.*`         | WithholdingsPanel          |\n * | `installments.*`         | InstallmentsPanel          |\n * | `advances.*`             | AdvanceApplicationsPanel   |\n * | `financial_instrument.*` | FinancialInstrumentPanel   |\n *\n * Deuda conocida: los cinco sub-paneles no llevan prefijo de feature, y\n * `advances.*` / `installments.*` son lo bastante genéricos para colisionar con\n * otro módulo. NO se renombraron a `master_document.<panel>.*` a propósito: esas\n * claves pueden estar ya servidas por el backend y el renombrado dejaría sin\n * traducción a los hosts que las tengan registradas. Es un cambio que hay que\n * coordinar con backend, no un refactor unilateral.\n *\n * @see src/components/MasterDocument/i18nFactory.ts - Resolución y fallback\n * @see src/components/MasterDocument/commonTexts.ts - Textos genéricos compartidos\n */\n\nexport const MASTER_DOCUMENT_TRANSLATIONS_ES: Record<string, string> = {\n  // ─── Chrome de modales / diálogos ───\n  'master_document.chrome.close': 'Cerrar',\n  'master_document.chrome.closeDialog': 'Cerrar diálogo',\n  'master_document.chrome.closeNotice': 'Cerrar aviso',\n  'master_document.chrome.restoreSize': 'Restaurar tamaño',\n  'master_document.chrome.maximize': 'Maximizar',\n  'master_document.chrome.updating': 'Actualizando',\n  'master_document.chrome.updatingTitle': 'Actualizando…',\n  // Campo solo-lectura resolviendo la etiqueta de su lookup (LookupReadonlyValue).\n  'master_document.chrome.loadingValue': 'Cargando valor',\n  'master_document.chrome.actionRunning': 'Ejecutando acción',\n  'master_document.chrome.confirm': 'Confirmar',\n  'master_document.chrome.cancel': 'Cancelar',\n  'master_document.chrome.back': 'Atrás',\n  // Salida de la pantalla de detalle. NO se reutiliza `chrome.back` ('Atrás'),\n  // que es el paso anterior de un asistente: son dos ideas distintas.\n  'master_document.chrome.backToList': 'Volver',\n  'master_document.chrome.next': 'Siguiente',\n  'master_document.chrome.error': 'Error',\n\n  // ─── Barra de acciones / encabezado ───\n  'master_document.actionBar.aria': 'Barra de acciones del documento',\n  'master_document.actionBar.moreActions': 'Más acciones',\n  'master_document.actionBar.transitions': 'Transiciones',\n  'master_document.actionBar.actions': 'Acciones',\n  'master_document.header.sectionsAria': 'Secciones del encabezado',\n  'master_document.contextStrip.aria': 'Contexto del documento',\n\n  // ─── FactBox ───\n  'master_document.factBox.aria': 'Panel de información',\n\n  // ─── FactBox: condiciones de pago ───\n  'master_document.factBox.paymentTerms.dueDays': 'Días vencimiento',\n  'master_document.factBox.paymentTerms.earlyPaymentEnabled': 'Pronto pago habilitado',\n  'master_document.factBox.paymentTerms.window': 'Ventana',\n  'master_document.factBox.paymentTerms.advanceRequired': 'Anticipo requerido',\n  'master_document.factBox.paymentTerms.advanceAmount': 'Monto anticipo',\n  'master_document.factBox.paymentTerms.days_one': '{count} día',\n  'master_document.factBox.paymentTerms.days_other': '{count} días',\n  'master_document.factBox.paymentTerms.installments': 'Cuotas',\n  'master_document.factBox.paymentTerms.mode': 'Modo',\n  'master_document.factBox.paymentTerms.discount': 'Descuento',\n  'master_document.factBox.paymentTerms.periodDays': 'Dias',\n  'master_document.factBox.paymentTerms.periodMonths': 'Meses',\n  'master_document.factBox.paymentTerms.periodCustom': 'Personalizado',\n\n  // ─── FactBox: financiero ───\n  'master_document.factBox.financial.receivables': 'Cuentas por cobrar',\n  'master_document.factBox.financial.payables': 'Cuentas por pagar',\n  'master_document.factBox.financial.crossedAdvances': 'Anticipos cruzados',\n  'master_document.factBox.financial.localReceivables': 'CxC local',\n  'master_document.factBox.financial.localPayables': 'CxP local',\n  'master_document.factBox.financial.cash': 'Efectivo',\n\n  // ─── FactBox CFDE / factura electrónica ───\n  'master_document.cfde.dianStatus': 'Estado DIAN',\n  'master_document.cfde.feNumber': 'Número FE',\n  'master_document.cfde.issueDate': 'Fecha emisión',\n  'master_document.cfde.prints': 'Impresiones',\n  'master_document.cfde.retransmit': 'Retransmitir documento a la DIAN',\n  'master_document.cfde.downloadPdf': 'Descargar PDF de la factura electrónica',\n  'master_document.cfde.status.pending': 'Pendiente',\n  'master_document.cfde.status.sent': 'Enviada',\n  'master_document.cfde.status.accepted': 'Aceptada',\n  'master_document.cfde.status.rejected': 'Rechazada',\n  'master_document.cfde.status.error': 'Error',\n  'master_document.cfde.statusAria': 'Estado: {status}',\n\n  // ─── Historial de estados: etiquetas de transición del backend ───\n  'master_document.statusHistory.action.create': 'Crear documento',\n  'master_document.statusHistory.action.save': 'Guardar',\n  'master_document.statusHistory.action.approve': 'Aprobar',\n  'master_document.statusHistory.action.reject': 'Rechazar',\n  'master_document.statusHistory.action.void': 'Anular',\n  'master_document.statusHistory.action.print': 'Imprimir',\n  'master_document.statusHistory.action.sendToApproval': 'Enviar a aprobación',\n  'master_document.statusHistory.action.hold': 'Retener',\n  'master_document.statusHistory.action.release': 'Liberar',\n  'master_document.statusHistory.action.commit': 'Comprometer',\n  'master_document.statusHistory.action.dispatch': 'Despachar',\n  'master_document.statusHistory.action.post': 'Contabilizar',\n  'master_document.statusHistory.action.invoice': 'Facturar',\n  'master_document.statusHistory.action.fulfill': 'Cumplir',\n  'master_document.statusHistory.action.partialFulfillment': 'Cumplimiento parcial',\n  'master_document.statusHistory.action.advance': 'Anticipo',\n  'master_document.statusHistory.action.collection': 'Recaudo',\n\n  // ─── Banner de aprobación ───\n  'master_document.approval.approve': 'Aprobar',\n  'master_document.approval.reject': 'Rechazar',\n\n  // ─── Badge de cumplimiento de línea ───\n  'master_document.lineFulfillment.pending': 'Pendiente',\n  'master_document.lineFulfillment.partial': 'Parcial',\n  'master_document.lineFulfillment.fulfilled': 'Cumplida',\n  'master_document.lineFulfillment.closed': 'Cerrada',\n\n  // ─── Listado de documentos ───\n  'master_document.list.rowActions': 'Acciones',\n  'master_document.list.rowOptions': 'Opciones',\n  'master_document.list.selectAll': 'Seleccionar todos',\n  'master_document.list.selectRow': 'Seleccionar fila',\n  'master_document.list.previousPage': 'Página anterior',\n  'master_document.list.nextPage': 'Página siguiente',\n  'master_document.list.reload': 'Recargar',\n  'master_document.list.selectCompany': 'Seleccionar compañía',\n  'master_document.list.noneSelected': 'Ningún documento seleccionado',\n  'master_document.list.noRecords': 'No hay registros',\n  'master_document.list.loadError': 'Error al cargar los datos',\n  'master_document.list.new': 'Nuevo',\n  // Barra del listado y paginador, alineados al canon de MasterCrud.\n  'master_document.list.moreActions': 'Más acciones',\n  // Acción de ESTADO del documento. El rótulo es del paquete, como el\n  // `ui-mastercrud.deactivateRecord` de MasterCrud, para que todos los documentos\n  // digan lo mismo; el catálogo del host puede sobrescribirlo.\n  'master_document.list.viewDetail': 'Ver detalle',\n  'master_document.list.deactivateRecord': 'Desactivar registro',\n  'master_document.list.activateRecord': 'Activar registro',\n  'master_document.list.moreOptions': 'Más opciones',\n  'master_document.list.hideAdvancedSearch': 'Ocultar búsqueda avanzada',\n  'master_document.list.perPage': 'por página',\n  'master_document.list.records': 'registros',\n  'master_document.list.goToPage': 'Página',\n  'master_document.list.noResults': 'No se encontraron documentos',\n  'master_document.list.export': 'Exportar',\n  'master_document.list.print': 'Imprimir',\n  'master_document.list.confirmAction': '¿Desea ejecutar esta acción?',\n  'master_document.list.allCompanies': 'Global — Todas las compañías',\n  'master_document.list.action.delete': 'Eliminar',\n  'master_document.list.action.void': 'Anular',\n\n  // ─── Sección de líneas ───\n  'master_document.lines.selectLine': 'Seleccionar línea',\n  'master_document.lines.selectAllLines': 'Seleccionar todas las líneas',\n  'master_document.lines.editLine': 'Editar línea',\n  'master_document.lines.view': 'Ver',\n  'master_document.lines.viewLine': 'Ver línea',\n  'master_document.lines.moreOptions': 'Más opciones',\n  'master_document.lines.moreLineOptions': 'Más opciones de línea',\n  'master_document.lines.closeLine': 'Cerrar línea',\n  'master_document.lines.reopenLine': 'Reabrir línea',\n  // Mensaje de obligatorio cuando el descriptor trae solo el flag `required` y no una\n  // regla `{ type: 'required' }` con su propio texto. En el módulo comercial son 5 campos.\n  'master_document.lines.fieldRequired': 'Este campo es obligatorio.',\n  'master_document.lines.emptyTitle': 'No hay líneas de detalle',\n  'master_document.lines.emptyHint': 'Agrega una nueva línea para comenzar',\n  'master_document.lines.closeReasonPlaceholder': 'Describe el motivo del cierre...',\n  'master_document.lines.title': 'Líneas del documento',\n  'master_document.lines.newLine': 'Nueva línea',\n  'master_document.lines.addLine': 'Agregar línea',\n  'master_document.lines.saveChanges': 'Guardar cambios',\n  'master_document.lines.edit': 'Editar',\n  'master_document.lines.duplicate': 'Duplicar',\n  'master_document.lines.delete': 'Eliminar',\n  'master_document.lines.deleteConfirm': '¿Eliminar esta línea? Esta acción no se puede deshacer.',\n\n  // ─── Documento ───\n  'master_document.document.deleteConfirm':\n    '¿Eliminar este documento? Esta acción no se puede deshacer.',\n  'master_document.document.traceability': 'Trazabilidad',\n  'master_document.document.auditTitle': 'Historial de cambios',\n  'master_document.document.print': 'Imprimir',\n  'master_document.document.printNotImplemented':\n    'La función de impresión de este documento aún no está implementada.',\n  'master_document.document.conflictBody':\n    'Otra sesión modificó este documento. Tus cambios no se guardaron. Recarga para ver la versión actual y vuelve a aplicarlos.',\n\n  // ─── Campos / búsqueda ───\n  'master_document.field.search': 'Buscar',\n  'master_document.field.searchPlaceholder': 'Buscar...',\n  'master_document.field.selectPlaceholder': 'Seleccionar...',\n  'master_document.field.required': 'Este campo es obligatorio',\n  'master_document.field.lockTooltip': 'Elimine las líneas para poder cambiar este campo.',\n\n  // ─── Asistente de creación ───\n  'master_document.wizard.aria': 'Nuevo documento',\n  'master_document.wizard.selectCompany': 'Seleccionar compañía...',\n  'master_document.wizard.selectDocumentClass': 'Seleccionar clase de documento...',\n  'master_document.wizard.selectOperationCenter': 'Seleccionar centro de operación...',\n\n  // ─── Moneda ───\n  'master_document.currency.searchPlaceholder': 'Buscar moneda...',\n  'master_document.currency.listAria': 'Monedas disponibles',\n\n  // ─── Descuento global ───\n  'master_document.discount.applyPercent': 'Aplicar descuento en porcentaje',\n  'master_document.discount.applyAmount': 'Aplicar descuento en monto fijo',\n  'master_document.discount.valueAria': 'Valor de descuento',\n\n  // ─── Cruce de documentos ───\n  'master_document.crossing.searchPlaceholder': 'Buscar por número de documento...',\n  'master_document.crossing.addPlaceholder': 'N° de documento y Enter para agregar...',\n  'master_document.crossing.selectRow': 'Seleccionar',\n  'master_document.crossing.bulkProgress': 'Procesando documentos...',\n  'master_document.crossing.bulkCompleted': 'Completado exitosamente',\n  'master_document.crossing.traceabilityLoading': 'Cargando árbol de trazabilidad',\n  'master_document.crossing.pending.item': 'Ítem',\n  'master_document.crossing.pending.document': 'Documento',\n  'master_document.crossing.pending.pending': 'Pendiente',\n  'master_document.crossing.pending.state': 'Estado',\n  'master_document.crossing.pending.quantityToCross': 'Cantidad a cruzar',\n  'master_document.crossing.selectLineToGenerate':\n    'Selecciona al menos una línea para generar el documento.',\n  'master_document.crossing.noGeneratedDocument': 'El backend no devolvió el documento generado.',\n  'master_document.crossing.pending.selectLineAria': 'Seleccionar línea {item}',\n  'master_document.crossing.pending.selectDocumentAria': 'Seleccionar {document}',\n  'master_document.crossing.pending.quantityAria': 'Cantidad a cruzar para {item}',\n\n  // ─── Panel de cruce: textos con canal de override por template ───\n  // El default deja de ser un literal y pasa por `t()`, para que el kit respete\n  // el idioma activo cuando el host no sobreescribe el texto.\n  'master_document.crossing.panelTitle': 'Cruzar documentos origen',\n  'master_document.crossing.emptyAvailable': 'No hay documentos origen disponibles para cruzar.',\n  'master_document.crossing.emptyCrossed': 'Sin documentos origen cruzados.',\n  'master_document.crossing.subtotalLabel': 'Subtotal de cruce',\n  'master_document.crossing.crossButton': 'Cruzar seleccionados',\n  'master_document.crossing.uncross': 'Desvincular',\n  'master_document.crossing.loading': 'Cargando…',\n  'master_document.crossing.crossing': 'Cruzando…',\n  'master_document.crossing.blockedLinesCount_one': '{count} línea no cruzada',\n  'master_document.crossing.blockedLinesCount_other': '{count} líneas no cruzadas',\n  'master_document.crossing.lineCount_one': '{count} línea',\n  'master_document.crossing.lineCount_other': '{count} líneas',\n  'master_document.crossing.terminalLineMessage':\n    'No se puede seleccionar una línea cerrada o cumplida',\n  'master_document.crossing.quantityRequired': 'Ingresa una cantidad a cruzar.',\n  'master_document.crossing.quantityPositive': 'La cantidad debe ser mayor que cero.',\n  'master_document.crossing.quantityExceedsPending':\n    'La cantidad no puede superar lo pendiente ({pending}{uom}).',\n\n  // ─── Asistente \"crear desde origen\" (canal `config.i18n`) ───\n  'master_document.createFromSource.originSelectorTitle': 'Nuevo documento',\n  'master_document.createFromSource.step1Title': 'Seleccionar documentos origen',\n  'master_document.createFromSource.step2Title': 'Seleccionar líneas',\n  'master_document.createFromSource.fromSourceOption': 'Generar desde origen',\n  'master_document.createFromSource.freeCaptureOption': 'Captura directa (sin origen)',\n  'master_document.createFromSource.loadingSources': 'Cargando documentos origen…',\n  'master_document.createFromSource.emptyState': 'No hay documentos origen disponibles.',\n  'master_document.createFromSource.singleSelectHint':\n    'Solo se puede seleccionar un documento origen.',\n  'master_document.createFromSource.loadingLines': 'Cargando líneas pendientes…',\n  'master_document.createFromSource.emptyLines_one':\n    'No hay líneas pendientes en el documento seleccionado.',\n  'master_document.createFromSource.emptyLines_other':\n    'No hay líneas pendientes en los documentos seleccionados.',\n  'master_document.createFromSource.quantityColumn': 'Cantidad a cruzar',\n  'master_document.createFromSource.confirmSummary':\n    'Se crearán {lines} {linesLabel} desde {sources} {sourcesLabel}.',\n  'master_document.createFromSource.lineNoun_one': 'línea',\n  'master_document.createFromSource.lineNoun_other': 'líneas',\n  'master_document.createFromSource.sourceNoun_one': 'documento origen',\n  'master_document.createFromSource.sourceNoun_other': 'documentos origen',\n  'master_document.createFromSource.incompatibleReason':\n    'Incompatible con el primer origen ({keys}).',\n  'master_document.createFromSource.columns.document': 'Documento',\n  'master_document.createFromSource.columns.thirdParty': 'Tercero',\n  'master_document.createFromSource.columns.date': 'Fecha',\n  'master_document.createFromSource.columns.state': 'Estado',\n  'master_document.createFromSource.columns.total': 'Total',\n\n  // ─── Estados de carga ───\n  'master_document.loading.document': 'Cargando documento...',\n  'master_document.loading.list': 'Cargando lista...',\n  'master_document.staleData.refresh': 'Actualizar datos',\n\n  // ─── Errores genéricos ───\n  // Los usan módulos puros (`smart/lineActionGating`, `smart/crossingFetch`) que no\n  // pueden llamar a un hook: propagan la clave y el hook llamante la resuelve.\n  'master_document.error.actionFailed': 'No se pudo completar la acción.',\n  'master_document.error.unexpected': 'Ocurrió un error inesperado. Intenta de nuevo.',\n  'master_document.error.autoSaveTotals': 'Auto-save totales: {detail}',\n  // Clasificación de errores para el usuario (ver smart/userFacingError.ts). El\n  // texto del backend, cuando existe, tiene prioridad sobre estas claves.\n  'master_document.error.unauthorized': 'Tu sesión expiró. Vuelve a iniciar sesión.',\n  'master_document.error.forbidden': 'No tienes permiso para esta operación.',\n  'master_document.error.notFound': 'El documento no existe o fue eliminado.',\n  'master_document.error.conflict':\n    'El documento cambió desde que lo abriste. Recarga para ver la versión actual.',\n  'master_document.error.validation': 'Revisa los datos ingresados.',\n  'master_document.error.serverUnavailable':\n    'El servicio no está disponible. Intenta de nuevo en unos minutos.',\n  'master_document.error.network':\n    'No hay conexión con el servidor. Revisa tu red e intenta de nuevo.',\n\n  // ═══════════════════════════════════════════════════════════════════════\n  // TEXTO JSX MIGRADO AL CERRAR EL GATE G2\n  // ═══════════════════════════════════════════════════════════════════════\n  // Nodos de texto JSX (títulos, botones, cabeceras de tabla, estados vacíos) que\n  // los barridos por línea no detectaban porque son multilínea. Los destapó la\n  // regla `i18next/no-literal-string`.\n\n  // ─── Conversión masiva: progreso ───\n  'master_document.crossing.bulkTitle': 'Conversión masiva',\n  'master_document.crossing.bulkBackgroundNote': 'Este proceso continúa en segundo plano.',\n  'master_document.crossing.bulkFailed': 'La conversión falló.',\n  'master_document.crossing.bulkViewResults': 'Ver resultados',\n  // Frase con cláusula opcional y DOS contadores: el detalle se compone de los\n  // fragmentos ya pluralizados de abajo.\n  'master_document.crossing.bulkCompletedWith': 'Completado — {detail}',\n  'master_document.crossing.bulkErrorCount_one': '{count} error',\n  'master_document.crossing.bulkErrorCount_other': '{count} errores',\n  'master_document.crossing.bulkPartialCount_one': '{count} parcial',\n  'master_document.crossing.bulkPartialCount_other': '{count} parciales',\n  'master_document.crossing.bulkCancelled_one':\n    'Cancelado — {count} documento procesado antes de cancelar.',\n  'master_document.crossing.bulkCancelled_other':\n    'Cancelado — {count} documentos procesados antes de cancelar.',\n\n  // ─── Conversión masiva: resultados ───\n  'master_document.crossing.bulkResultsTitle': 'Resultados de la conversión masiva',\n  'master_document.crossing.bulkSuccessCount_one': '{count} exitoso',\n  'master_document.crossing.bulkSuccessCount_other': '{count} exitosos',\n  'master_document.crossing.bulkWithErrorCount_one': '{count} con error',\n  'master_document.crossing.bulkWithErrorCount_other': '{count} con error',\n  'master_document.crossing.bulkColumn.sourceDocument': 'Documento fuente',\n  'master_document.crossing.bulkColumn.result': 'Resultado',\n  'master_document.crossing.bulkColumn.generatedDocument': 'Documento generado',\n  'master_document.crossing.bulkStatus.success': 'Exitoso',\n  'master_document.crossing.bulkBlockedLines_one': '{count} línea bloqueada',\n  'master_document.crossing.bulkBlockedLines_other': '{count} líneas bloqueadas',\n  'master_document.crossing.bulkSelectFailed': 'Seleccionar fallidos y reintentar:',\n  'master_document.crossing.bulkRetryFailed_one': 'Reintentar {count} fallido',\n  'master_document.crossing.bulkRetryFailed_other': 'Reintentar {count} fallidos',\n\n  // ─── Cruce: generar y seleccionar orígenes ───\n  'master_document.crossing.generateTitle': 'Generar {class}',\n  'master_document.crossing.generateQuestion':\n    '¿Generar {class} a partir de las líneas seleccionadas?',\n  'master_document.crossing.generateDocument': 'Generar documento',\n  'master_document.crossing.sourceDocuments': 'Documentos fuente',\n  'master_document.crossing.selectSourceHint': 'Selecciona uno o más documentos fuente',\n  'master_document.crossing.addSourceDocument': 'Agregar documento fuente',\n  'master_document.crossing.noRelations':\n    'Este documento no tiene relaciones de cruce registradas.',\n  'master_document.crossing.current': 'Actual',\n  // Se rediseñó para no depender del número: el estado vacío no tiene el contador\n  // de orígenes en alcance, así que `documento(s)` se resolvió en plural genérico.\n  'master_document.crossing.noPendingLinesAll':\n    'No hay líneas pendientes. Todas las líneas de los documentos seleccionados ya fueron cumplidas o cerradas.',\n\n  // ─── Chrome adicional ───\n  'master_document.chrome.retry': 'Reintentar',\n  'master_document.chrome.refresh': 'Actualizar',\n  'master_document.chrome.understood': 'Entendido',\n  'master_document.chrome.noData': 'Sin datos',\n\n  // ─── Conflicto de concurrencia ───\n  'master_document.document.conflictTitle': 'Alguien más editó este documento',\n  'master_document.document.conflictModifiedBy': '{user} guardó cambios {when}.',\n  'master_document.document.conflictRecently': 'recientemente',\n  'master_document.document.conflictReloadWarning':\n    'Si recargas, verás los cambios más recientes pero perderás lo que acabas de modificar.',\n  'master_document.document.conflictWhatToDo': '¿Qué quieres hacer?',\n  'master_document.document.conflictKeepChanges': 'Seguir con mis cambios',\n  'master_document.document.conflictReload': 'Recargar documento',\n  'master_document.document.printAvailableSoon': 'Estará disponible próximamente.',\n\n  // ─── Asistente de creación ───\n  'master_document.wizard.subtitle': 'Selecciona la configuración para crear el documento',\n  'master_document.wizard.company': 'Compañía',\n  'master_document.wizard.documentClass': 'Clase de documento',\n  'master_document.wizard.operationCenter': 'Centro de operación',\n  'master_document.wizard.documentType': 'Tipo de documento',\n  'master_document.wizard.selectOperationCenterHint':\n    'Selecciona un centro de operación para ver los tipos disponibles',\n\n  // ─── Listado ───\n  'master_document.list.advancedSearch': 'Búsqueda avanzada',\n  'master_document.list.clear': 'Limpiar',\n  'master_document.list.filterColumn': 'Filtrar',\n  'master_document.list.filterAll': 'Todos',\n  'master_document.list.filterPlaceholder': 'Filtrar...',\n  'master_document.list.recordCount_one': '{count} registro',\n  'master_document.list.recordCount_other': '{count} registros',\n  'master_document.list.selectedCount_one': '{count} documento seleccionado',\n  'master_document.list.selectedCount_other': '{count} documentos seleccionados',\n  'master_document.list.previousShort': '‹ Anterior',\n  'master_document.list.nextShort': 'Siguiente ›',\n\n  // ─── Moneda ───\n  'master_document.currency.changeTitle': 'Cambiar moneda',\n  'master_document.currency.notFound': 'No se encontraron monedas',\n  'master_document.currency.base': 'Base',\n\n  // ─── FactBox / historial / CFDE ───\n  'master_document.factBox.info': 'Datos +',\n  'master_document.factBox.financial.pendingPosting': 'Pendiente de contabilización',\n  'master_document.factBox.financial.localEquivalent': 'Equivalente en moneda local (COP)',\n  'master_document.factBox.customWidget': 'Widget personalizado: {key}',\n  'master_document.statusHistory.empty': 'Sin historial de estados',\n  'master_document.statusHistory.creation': 'Creación',\n  'master_document.cfde.viewQr': 'Ver QR DIAN',\n  'master_document.cfde.retransmitButton': 'Retransmitir',\n  'master_document.cfde.downloadPdfButton': 'Descargar PDF',\n\n  // ─── Líneas ───\n  'master_document.lines.closeReason': 'Razón de cierre',\n  'master_document.lines.reopenConfirm':\n    '¿Confirmas que deseas reabrir esta línea para que vuelva al flujo de cumplimiento?',\n  'master_document.lines.saveAndAddAnother': 'Guardar y agregar otra',\n  'master_document.lines.calculated': '(calculado)',\n  'master_document.lines.tab': 'Líneas',\n  'master_document.lines.tabsLabel': 'Listados de líneas',\n  'master_document.lines.tabUnavailable': 'Este listado no está disponible',\n\n  // ─── Campos adicionales (entidades dinámicas / EAV) ───\n  'master_document.dynamicEntities.headerTitle': 'Campos adicionales',\n  'master_document.dynamicEntities.lineTitle': 'Campos adicionales de la línea',\n\n  // ─── Varios ───\n  'master_document.discount.globalLabel': 'Descuento global',\n  'master_document.staleData.note': 'Los estados de cumplimiento pueden haber cambiado.',\n};\n\nexport const MASTER_DOCUMENT_TRANSLATIONS_EN: Record<string, string> = {\n  // ─── Chrome de modales / diálogos ───\n  'master_document.chrome.close': 'Close',\n  'master_document.chrome.closeDialog': 'Close dialog',\n  'master_document.chrome.closeNotice': 'Dismiss notice',\n  'master_document.chrome.restoreSize': 'Restore size',\n  'master_document.chrome.maximize': 'Maximize',\n  'master_document.chrome.updating': 'Updating',\n  'master_document.chrome.updatingTitle': 'Updating…',\n  'master_document.chrome.loadingValue': 'Loading value',\n  'master_document.chrome.actionRunning': 'Running action',\n  'master_document.chrome.confirm': 'Confirm',\n  'master_document.chrome.cancel': 'Cancel',\n  'master_document.chrome.back': 'Back',\n  'master_document.chrome.backToList': 'Back',\n  'master_document.chrome.next': 'Next',\n  'master_document.chrome.error': 'Error',\n\n  // ─── Barra de acciones / encabezado ───\n  'master_document.actionBar.aria': 'Document action bar',\n  'master_document.actionBar.moreActions': 'More actions',\n  'master_document.actionBar.transitions': 'Transitions',\n  'master_document.actionBar.actions': 'Actions',\n  'master_document.header.sectionsAria': 'Header sections',\n  'master_document.contextStrip.aria': 'Document context',\n\n  // ─── FactBox ───\n  'master_document.factBox.aria': 'Information panel',\n\n  // ─── FactBox: condiciones de pago ───\n  'master_document.factBox.paymentTerms.dueDays': 'Due days',\n  'master_document.factBox.paymentTerms.earlyPaymentEnabled': 'Early payment enabled',\n  'master_document.factBox.paymentTerms.window': 'Window',\n  'master_document.factBox.paymentTerms.advanceRequired': 'Advance required',\n  'master_document.factBox.paymentTerms.advanceAmount': 'Advance amount',\n  'master_document.factBox.paymentTerms.days_one': '{count} day',\n  'master_document.factBox.paymentTerms.days_other': '{count} days',\n  'master_document.factBox.paymentTerms.installments': 'Installments',\n  'master_document.factBox.paymentTerms.mode': 'Mode',\n  'master_document.factBox.paymentTerms.discount': 'Discount',\n  'master_document.factBox.paymentTerms.periodDays': 'Days',\n  'master_document.factBox.paymentTerms.periodMonths': 'Months',\n  'master_document.factBox.paymentTerms.periodCustom': 'Custom',\n\n  // ─── FactBox: financiero ───\n  'master_document.factBox.financial.receivables': 'Accounts receivable',\n  'master_document.factBox.financial.payables': 'Accounts payable',\n  'master_document.factBox.financial.crossedAdvances': 'Crossed advances',\n  'master_document.factBox.financial.localReceivables': 'Local AR',\n  'master_document.factBox.financial.localPayables': 'Local AP',\n  'master_document.factBox.financial.cash': 'Cash',\n\n  // ─── FactBox CFDE / factura electrónica ───\n  'master_document.cfde.dianStatus': 'DIAN status',\n  'master_document.cfde.feNumber': 'E-invoice number',\n  'master_document.cfde.issueDate': 'Issue date',\n  'master_document.cfde.prints': 'Prints',\n  'master_document.cfde.retransmit': 'Retransmit document to DIAN',\n  'master_document.cfde.downloadPdf': 'Download e-invoice PDF',\n  'master_document.cfde.status.pending': 'Pending',\n  'master_document.cfde.status.sent': 'Sent',\n  'master_document.cfde.status.accepted': 'Accepted',\n  'master_document.cfde.status.rejected': 'Rejected',\n  'master_document.cfde.status.error': 'Error',\n  'master_document.cfde.statusAria': 'Status: {status}',\n\n  // ─── Historial de estados: etiquetas de transición del backend ───\n  'master_document.statusHistory.action.create': 'Create document',\n  'master_document.statusHistory.action.save': 'Save',\n  'master_document.statusHistory.action.approve': 'Approve',\n  'master_document.statusHistory.action.reject': 'Reject',\n  'master_document.statusHistory.action.void': 'Void',\n  'master_document.statusHistory.action.print': 'Print',\n  'master_document.statusHistory.action.sendToApproval': 'Send for approval',\n  'master_document.statusHistory.action.hold': 'Hold',\n  'master_document.statusHistory.action.release': 'Release',\n  'master_document.statusHistory.action.commit': 'Commit',\n  'master_document.statusHistory.action.dispatch': 'Dispatch',\n  'master_document.statusHistory.action.post': 'Post',\n  'master_document.statusHistory.action.invoice': 'Invoice',\n  'master_document.statusHistory.action.fulfill': 'Fulfill',\n  'master_document.statusHistory.action.partialFulfillment': 'Partial fulfillment',\n  'master_document.statusHistory.action.advance': 'Advance',\n  'master_document.statusHistory.action.collection': 'Collection',\n\n  // ─── Banner de aprobación ───\n  'master_document.approval.approve': 'Approve',\n  'master_document.approval.reject': 'Reject',\n\n  // ─── Badge de cumplimiento de línea ───\n  'master_document.lineFulfillment.pending': 'Pending',\n  'master_document.lineFulfillment.partial': 'Partial',\n  'master_document.lineFulfillment.fulfilled': 'Fulfilled',\n  'master_document.lineFulfillment.closed': 'Closed',\n\n  // ─── Listado de documentos ───\n  'master_document.list.rowActions': 'Actions',\n  'master_document.list.rowOptions': 'Options',\n  'master_document.list.selectAll': 'Select all',\n  'master_document.list.selectRow': 'Select row',\n  'master_document.list.previousPage': 'Previous page',\n  'master_document.list.nextPage': 'Next page',\n  'master_document.list.reload': 'Reload',\n  'master_document.list.selectCompany': 'Select company',\n  'master_document.list.noneSelected': 'No document selected',\n  'master_document.list.noRecords': 'No records',\n  'master_document.list.loadError': 'Error loading data',\n  'master_document.list.new': 'New',\n  // List toolbar and paginator, aligned with the MasterCrud canon.\n  'master_document.list.moreActions': 'More actions',\n  'master_document.list.viewDetail': 'View detail',\n  'master_document.list.deactivateRecord': 'Deactivate record',\n  'master_document.list.activateRecord': 'Activate record',\n  'master_document.list.moreOptions': 'More options',\n  'master_document.list.hideAdvancedSearch': 'Hide advanced search',\n  'master_document.list.perPage': 'per page',\n  'master_document.list.records': 'records',\n  'master_document.list.goToPage': 'Page',\n  'master_document.list.noResults': 'No documents found',\n  'master_document.list.export': 'Export',\n  'master_document.list.print': 'Print',\n  'master_document.list.confirmAction': 'Do you want to run this action?',\n  'master_document.list.allCompanies': 'Global — All companies',\n  'master_document.list.action.delete': 'Delete',\n  'master_document.list.action.void': 'Void',\n\n  // ─── Sección de líneas ───\n  'master_document.lines.selectLine': 'Select line',\n  'master_document.lines.selectAllLines': 'Select all lines',\n  'master_document.lines.editLine': 'Edit line',\n  'master_document.lines.view': 'View',\n  'master_document.lines.viewLine': 'View line',\n  'master_document.lines.moreOptions': 'More options',\n  'master_document.lines.moreLineOptions': 'More line options',\n  'master_document.lines.closeLine': 'Close line',\n  'master_document.lines.reopenLine': 'Reopen line',\n  'master_document.lines.fieldRequired': 'This field is required.',\n  'master_document.lines.emptyTitle': 'No detail lines',\n  'master_document.lines.emptyHint': 'Add a new line to get started',\n  'master_document.lines.closeReasonPlaceholder': 'Describe the reason for closing...',\n  'master_document.lines.title': 'Document lines',\n  'master_document.lines.newLine': 'New line',\n  'master_document.lines.addLine': 'Add line',\n  'master_document.lines.saveChanges': 'Save changes',\n  'master_document.lines.edit': 'Edit',\n  'master_document.lines.duplicate': 'Duplicate',\n  'master_document.lines.delete': 'Delete',\n  'master_document.lines.deleteConfirm': 'Delete this line? This action cannot be undone.',\n\n  // ─── Documento ───\n  'master_document.document.deleteConfirm': 'Delete this document? This action cannot be undone.',\n  'master_document.document.traceability': 'Traceability',\n  'master_document.document.auditTitle': 'Change history',\n  'master_document.document.print': 'Print',\n  'master_document.document.printNotImplemented':\n    'Printing is not implemented yet for this document.',\n  'master_document.document.conflictBody':\n    'Another session modified this document. Your changes were not saved. Reload to see the current version and reapply them.',\n\n  // ─── Campos / búsqueda ───\n  'master_document.field.search': 'Search',\n  'master_document.field.searchPlaceholder': 'Search...',\n  'master_document.field.selectPlaceholder': 'Select...',\n  'master_document.field.required': 'This field is required',\n  'master_document.field.lockTooltip': 'Remove the lines to be able to change this field.',\n\n  // ─── Asistente de creación ───\n  'master_document.wizard.aria': 'New document',\n  'master_document.wizard.selectCompany': 'Select company...',\n  'master_document.wizard.selectDocumentClass': 'Select document class...',\n  'master_document.wizard.selectOperationCenter': 'Select operation center...',\n\n  // ─── Moneda ───\n  'master_document.currency.searchPlaceholder': 'Search currency...',\n  'master_document.currency.listAria': 'Available currencies',\n\n  // ─── Descuento global ───\n  'master_document.discount.applyPercent': 'Apply percentage discount',\n  'master_document.discount.applyAmount': 'Apply fixed amount discount',\n  'master_document.discount.valueAria': 'Discount value',\n\n  // ─── Cruce de documentos ───\n  'master_document.crossing.searchPlaceholder': 'Search by document number...',\n  'master_document.crossing.addPlaceholder': 'Document no. and Enter to add...',\n  'master_document.crossing.selectRow': 'Select',\n  'master_document.crossing.bulkProgress': 'Processing documents...',\n  'master_document.crossing.bulkCompleted': 'Completed successfully',\n  'master_document.crossing.traceabilityLoading': 'Loading traceability tree',\n  'master_document.crossing.pending.item': 'Item',\n  'master_document.crossing.pending.document': 'Document',\n  'master_document.crossing.pending.pending': 'Pending',\n  'master_document.crossing.pending.state': 'State',\n  'master_document.crossing.pending.quantityToCross': 'Quantity to cross',\n  'master_document.crossing.selectLineToGenerate': 'Select at least one line to generate the document.',\n  'master_document.crossing.noGeneratedDocument': 'The backend did not return the generated document.',\n  'master_document.crossing.pending.selectLineAria': 'Select line {item}',\n  'master_document.crossing.pending.selectDocumentAria': 'Select {document}',\n  'master_document.crossing.pending.quantityAria': 'Quantity to cross for {item}',\n\n  // ─── Panel de cruce: textos con canal de override por template ───\n  'master_document.crossing.panelTitle': 'Cross source documents',\n  'master_document.crossing.emptyAvailable': 'No source documents available to cross.',\n  'master_document.crossing.emptyCrossed': 'No crossed source documents.',\n  'master_document.crossing.subtotalLabel': 'Crossing subtotal',\n  'master_document.crossing.crossButton': 'Cross selected',\n  'master_document.crossing.uncross': 'Unlink',\n  'master_document.crossing.loading': 'Loading…',\n  'master_document.crossing.crossing': 'Crossing…',\n  'master_document.crossing.blockedLinesCount_one': '{count} line not crossed',\n  'master_document.crossing.blockedLinesCount_other': '{count} lines not crossed',\n  'master_document.crossing.lineCount_one': '{count} line',\n  'master_document.crossing.lineCount_other': '{count} lines',\n  'master_document.crossing.terminalLineMessage': 'A closed or fulfilled line cannot be selected',\n  'master_document.crossing.quantityRequired': 'Enter a quantity to cross.',\n  'master_document.crossing.quantityPositive': 'The quantity must be greater than zero.',\n  'master_document.crossing.quantityExceedsPending':\n    'The quantity cannot exceed the pending amount ({pending}{uom}).',\n\n  // ─── Asistente \"crear desde origen\" (canal `config.i18n`) ───\n  'master_document.createFromSource.originSelectorTitle': 'New document',\n  'master_document.createFromSource.step1Title': 'Select source documents',\n  'master_document.createFromSource.step2Title': 'Select lines',\n  'master_document.createFromSource.fromSourceOption': 'Generate from source',\n  'master_document.createFromSource.freeCaptureOption': 'Direct capture (no source)',\n  'master_document.createFromSource.loadingSources': 'Loading source documents…',\n  'master_document.createFromSource.emptyState': 'No source documents available.',\n  'master_document.createFromSource.singleSelectHint':\n    'Only one source document can be selected.',\n  'master_document.createFromSource.loadingLines': 'Loading pending lines…',\n  'master_document.createFromSource.emptyLines_one': 'No pending lines in the selected document.',\n  'master_document.createFromSource.emptyLines_other':\n    'No pending lines in the selected documents.',\n  'master_document.createFromSource.quantityColumn': 'Quantity to cross',\n  'master_document.createFromSource.confirmSummary':\n    '{lines} {linesLabel} will be created from {sources} {sourcesLabel}.',\n  'master_document.createFromSource.lineNoun_one': 'line',\n  'master_document.createFromSource.lineNoun_other': 'lines',\n  'master_document.createFromSource.sourceNoun_one': 'source document',\n  'master_document.createFromSource.sourceNoun_other': 'source documents',\n  'master_document.createFromSource.incompatibleReason':\n    'Incompatible with the first source ({keys}).',\n  'master_document.createFromSource.columns.document': 'Document',\n  'master_document.createFromSource.columns.thirdParty': 'Third party',\n  'master_document.createFromSource.columns.date': 'Date',\n  'master_document.createFromSource.columns.state': 'State',\n  'master_document.createFromSource.columns.total': 'Total',\n\n  // ─── Estados de carga ───\n  'master_document.loading.document': 'Loading document...',\n  'master_document.loading.list': 'Loading list...',\n  'master_document.staleData.refresh': 'Refresh data',\n\n  // ─── Errores genéricos ───\n  'master_document.error.actionFailed': 'The action could not be completed.',\n  'master_document.error.unexpected': 'An unexpected error occurred. Please try again.',\n  'master_document.error.autoSaveTotals': 'Totals auto-save: {detail}',\n  'master_document.error.unauthorized': 'Your session expired. Please sign in again.',\n  'master_document.error.forbidden': 'You do not have permission for this operation.',\n  'master_document.error.notFound': 'The document does not exist or was deleted.',\n  'master_document.error.conflict':\n    'The document changed since you opened it. Reload to see the current version.',\n  'master_document.error.validation': 'Check the entered data.',\n  'master_document.error.serverUnavailable':\n    'The service is unavailable. Please try again in a few minutes.',\n  'master_document.error.network':\n    'No connection to the server. Check your network and try again.',\n\n  // ═══════════════════════════════════════════════════════════════════════\n  // TEXTO JSX MIGRADO AL CERRAR EL GATE G2\n  // ═══════════════════════════════════════════════════════════════════════\n\n  // ─── Conversión masiva: progreso ───\n  'master_document.crossing.bulkTitle': 'Bulk conversion',\n  'master_document.crossing.bulkBackgroundNote': 'This process continues in the background.',\n  'master_document.crossing.bulkFailed': 'The conversion failed.',\n  'master_document.crossing.bulkViewResults': 'View results',\n  'master_document.crossing.bulkCompletedWith': 'Completed — {detail}',\n  'master_document.crossing.bulkErrorCount_one': '{count} error',\n  'master_document.crossing.bulkErrorCount_other': '{count} errors',\n  'master_document.crossing.bulkPartialCount_one': '{count} partial',\n  'master_document.crossing.bulkPartialCount_other': '{count} partial',\n  'master_document.crossing.bulkCancelled_one':\n    'Cancelled — {count} document processed before cancelling.',\n  'master_document.crossing.bulkCancelled_other':\n    'Cancelled — {count} documents processed before cancelling.',\n\n  // ─── Conversión masiva: resultados ───\n  'master_document.crossing.bulkResultsTitle': 'Bulk conversion results',\n  'master_document.crossing.bulkSuccessCount_one': '{count} successful',\n  'master_document.crossing.bulkSuccessCount_other': '{count} successful',\n  'master_document.crossing.bulkWithErrorCount_one': '{count} with an error',\n  'master_document.crossing.bulkWithErrorCount_other': '{count} with errors',\n  'master_document.crossing.bulkColumn.sourceDocument': 'Source document',\n  'master_document.crossing.bulkColumn.result': 'Result',\n  'master_document.crossing.bulkColumn.generatedDocument': 'Generated document',\n  'master_document.crossing.bulkStatus.success': 'Successful',\n  'master_document.crossing.bulkBlockedLines_one': '{count} blocked line',\n  'master_document.crossing.bulkBlockedLines_other': '{count} blocked lines',\n  'master_document.crossing.bulkSelectFailed': 'Select failed and retry:',\n  'master_document.crossing.bulkRetryFailed_one': 'Retry {count} failed',\n  'master_document.crossing.bulkRetryFailed_other': 'Retry {count} failed',\n\n  // ─── Cruce: generar y seleccionar orígenes ───\n  'master_document.crossing.generateTitle': 'Generate {class}',\n  'master_document.crossing.generateQuestion': 'Generate {class} from the selected lines?',\n  'master_document.crossing.generateDocument': 'Generate document',\n  'master_document.crossing.sourceDocuments': 'Source documents',\n  'master_document.crossing.selectSourceHint': 'Select one or more source documents',\n  'master_document.crossing.addSourceDocument': 'Add source document',\n  'master_document.crossing.noRelations': 'This document has no recorded crossing relations.',\n  'master_document.crossing.current': 'Current',\n  'master_document.crossing.noPendingLinesAll':\n    'No pending lines. Every line in the selected documents has been fulfilled or closed.',\n\n  // ─── Chrome adicional ───\n  'master_document.chrome.retry': 'Retry',\n  'master_document.chrome.refresh': 'Refresh',\n  'master_document.chrome.understood': 'Understood',\n  'master_document.chrome.noData': 'No data',\n\n  // ─── Conflicto de concurrencia ───\n  'master_document.document.conflictTitle': 'Someone else edited this document',\n  'master_document.document.conflictModifiedBy': '{user} saved changes {when}.',\n  'master_document.document.conflictRecently': 'recently',\n  'master_document.document.conflictReloadWarning':\n    'If you reload you will see the latest changes but lose what you just modified.',\n  'master_document.document.conflictWhatToDo': 'What do you want to do?',\n  'master_document.document.conflictKeepChanges': 'Keep my changes',\n  'master_document.document.conflictReload': 'Reload document',\n  'master_document.document.printAvailableSoon': 'It will be available soon.',\n\n  // ─── Asistente de creación ───\n  'master_document.wizard.subtitle': 'Select the configuration to create the document',\n  'master_document.wizard.company': 'Company',\n  'master_document.wizard.documentClass': 'Document class',\n  'master_document.wizard.operationCenter': 'Operation center',\n  'master_document.wizard.documentType': 'Document type',\n  'master_document.wizard.selectOperationCenterHint':\n    'Select an operation center to see the available types',\n\n  // ─── Listado ───\n  'master_document.list.advancedSearch': 'Advanced search',\n  'master_document.list.filterColumn': 'Filter',\n  'master_document.list.filterAll': 'All',\n  'master_document.list.filterPlaceholder': 'Filter...',\n  'master_document.list.clear': 'Clear',\n  'master_document.list.recordCount_one': '{count} record',\n  'master_document.list.recordCount_other': '{count} records',\n  'master_document.list.selectedCount_one': '{count} document selected',\n  'master_document.list.selectedCount_other': '{count} documents selected',\n  'master_document.list.previousShort': '‹ Previous',\n  'master_document.list.nextShort': 'Next ›',\n\n  // ─── Moneda ───\n  'master_document.currency.changeTitle': 'Change currency',\n  'master_document.currency.notFound': 'No currencies found',\n  'master_document.currency.base': 'Base',\n\n  // ─── FactBox / historial / CFDE ───\n  'master_document.factBox.info': 'Data +',\n  'master_document.factBox.financial.pendingPosting': 'Pending posting',\n  'master_document.factBox.financial.localEquivalent': 'Local currency equivalent (COP)',\n  'master_document.factBox.customWidget': 'Custom widget: {key}',\n  'master_document.statusHistory.empty': 'No status history',\n  'master_document.statusHistory.creation': 'Creation',\n  'master_document.cfde.viewQr': 'View DIAN QR',\n  'master_document.cfde.retransmitButton': 'Retransmit',\n  'master_document.cfde.downloadPdfButton': 'Download PDF',\n\n  // ─── Líneas ───\n  'master_document.lines.closeReason': 'Reason for closing',\n  'master_document.lines.reopenConfirm':\n    'Do you confirm reopening this line so it returns to the fulfillment flow?',\n  'master_document.lines.saveAndAddAnother': 'Save and add another',\n  'master_document.lines.calculated': '(calculated)',\n  'master_document.lines.tab': 'Lines',\n  'master_document.lines.tabsLabel': 'Line lists',\n  'master_document.lines.tabUnavailable': 'This list is not available',\n\n  // ─── Campos adicionales (entidades dinámicas / EAV) ───\n  'master_document.dynamicEntities.headerTitle': 'Additional fields',\n  'master_document.dynamicEntities.lineTitle': 'Line additional fields',\n\n  // ─── Varios ───\n  'master_document.discount.globalLabel': 'Global discount',\n  'master_document.staleData.note': 'Fulfillment statuses may have changed.',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const MASTER_DOCUMENT_TRANSLATIONS = {\n  es: MASTER_DOCUMENT_TRANSLATIONS_ES,\n  en: MASTER_DOCUMENT_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción del core con interpolación `{var}`. */\nexport type MasterDocumentT = TranslateFn;\n\n/**\n * Hook de traducción del core de MasterDocument.\n *\n * @example\n * ```tsx\n * const { t } = useMasterDocumentTranslation();\n * <button aria-label={t('master_document.chrome.close')} />\n * ```\n */\nexport const useMasterDocumentTranslation = createTranslationHook(MASTER_DOCUMENT_TRANSLATIONS);\n","import { Loading } from './Loading';\nimport { useMasterDocumentTranslation } from '../../i18n';\n\n/**\n * Spinner de campo, idéntico al que `LineFormModal` y `MasterDocumentFormModal`\n * tenían escrito a mano (mismo path, mismas opacidades, mismas clases).\n *\n * ⚠️ **Transitorio.** Existe solo para migrar esos dos sitios a `Loading` sin\n * cambiar un pixel (opción A de `LOADING-INTEGRATION.md` §8.2). Cuando diseño\n * valide unificar la paleta del feature (opción B), este icono se borra y\n * `FieldLoadingIndicator` deja de pasar `icon`, quedándose con el `ArrowPathIcon`\n * por defecto de `Loading`.\n *\n * ⚠️ `text-primary-custom-500` **no existe** como token del kit — `src/index.css`\n * define `dark-bg-custom`, `dark-content-custom` y `dark-border-custom`, ninguna\n * variante `primary-custom`. Se conserva tal cual estaba para no cambiar el\n * aspecto, pero en modo claro no pinta: el spinner hereda el color del texto.\n * Es un bug preexistente y transversal (34 archivos del repo usan esa clase), no\n * de este componente.\n */\nfunction FieldSpinnerIcon() {\n  return (\n    <svg\n      className=\"w-3.5 h-3.5 animate-spin text-primary-custom-500 dark:text-dark-border-custom\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      aria-hidden=\"true\"\n    >\n      <circle className=\"opacity-25\" cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"3\" />\n      <path className=\"opacity-80\" fill=\"currentColor\" d=\"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z\" />\n    </svg>\n  );\n}\n\n/**\n * Indicador de \"este campo se está recalculando en el servidor\", anclado a la\n * esquina superior derecha del campo.\n *\n * Lo dispara `evaluateServerRule`: el usuario cambia un campo observado por una\n * regla de servidor y el valor destino tarda en llegar. Ambos modales de\n * formulario lo pintaban con el MISMO bloque de 16 líneas copiado; aquí vive una\n * sola vez.\n *\n * A diferencia de `Loading`, este componente **sí traduce**: es de feature, no un\n * primitivo, y sus dos consumidores usan el mismo catálogo del core. El\n * contenedor posicionado lleva el `title` (tooltip nativo para ratón) y `Loading`\n * aporta la semántica accesible (`role=\"status\"` + `aria-live` + `aria-label`),\n * que el bloque original no tenía. El `title` va fuera a propósito: en el mismo\n * elemento que el `aria-label` competiría con él como nombre accesible.\n *\n * @see Loading — el primitivo indeterminado\n * @see MasterDocument/LOADING-INTEGRATION.md — plan de migración (punto P2)\n */\nexport function FieldLoadingIndicator() {\n  const { t } = useMasterDocumentTranslation();\n\n  return (\n    <span\n      className=\"absolute top-0 right-0 flex items-center justify-center w-5 h-5\"\n      title={t('master_document.chrome.updatingTitle')}\n    >\n      <Loading\n        size=\"sm\"\n        layout=\"inline\"\n        ariaLabel={t('master_document.chrome.updating')}\n        icon={<FieldSpinnerIcon />}\n      />\n    </span>\n  );\n}\n","import React, { useEffect, useRef, useState } from 'react';\nimport { clsx } from 'clsx';\nimport { EllipsisVerticalIcon } from '@heroicons/react/24/outline';\nimport { Loading } from './components/loading';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/** Entrada del menú: acción, encabezado de grupo o separador. */\nexport interface MoreOption {\n  key: string;\n  /** Encabezado de grupo: no es pulsable. */\n  isHeading?: boolean;\n  /** Separador horizontal. */\n  isDivider?: boolean;\n  label?: React.ReactNode;\n  icon?: React.ReactNode;\n  /** Texto secundario bajo el rótulo (p. ej. el motivo por el que está deshabilitada). */\n  description?: string;\n  disabled?: boolean;\n  /** Pinta la entrada en el tono de error. */\n  danger?: boolean;\n  onClick?: () => void;\n}\n\n/**\n * Kebab «Más opciones» del canon de MasterCrud (`MasterCrudToolbar`), único\n * dueño de ese control en `MasterDocument`: lo usan la barra del listado y la\n * cabecera del detalle, así que no pueden volver a divergir.\n *\n * Reemplaza al `Dropdown` del kit en estos dos sitios por una razón concreta,\n * no por gusto: con `variant=\"icon-only\"` el `Dropdown` **descarta sus\n * `children`** y pinta siempre su propio chevron (`Dropdown.tsx`, la rama del\n * trigger). La cabecera le pasaba un icono de puntos suspensivos que nunca se\n * llegó a renderizar, y no había forma de poner el indicador de «acción en\n * vuelo» en el disparador — que es donde tiene que ir cuando la acción vive en\n * un menú cerrado.\n *\n * Geometría literal del canon: disparador 36x36 con borde y `rounded-md`; menú\n * anclado a la derecha, 256px, `shadow-md`.\n */\nexport function MoreOptionsMenu({\n  options,\n  busy = false,\n  ariaLabel,\n  className,\n}: {\n  options: MoreOption[];\n  /** Hay una acción del menú en vuelo: el indicador sustituye al icono. */\n  busy?: boolean;\n  ariaLabel?: string;\n  className?: string;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const [open, setOpen] = useState(false);\n  const ref = useRef<HTMLDivElement>(null);\n  const label = ariaLabel ?? t('master_document.list.moreOptions');\n\n  useEffect(() => {\n    if (!open) return;\n    const onDocClick = (e: MouseEvent) => {\n      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };\n    document.addEventListener('mousedown', onDocClick);\n    document.addEventListener('keydown', onKey);\n    return () => {\n      document.removeEventListener('mousedown', onDocClick);\n      document.removeEventListener('keydown', onKey);\n    };\n  }, [open]);\n\n  if (options.length === 0) return null;\n\n  return (\n    <div className={clsx('relative', className)} ref={ref}>\n      <button\n        type=\"button\"\n        onClick={() => setOpen((v) => !v)}\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        title={label}\n        aria-label={label}\n        className={clsx(\n          'inline-flex items-center justify-center w-9 h-9 rounded-md transition-colors',\n          'border border-border-primary dark:border-dark-border-primary',\n          'bg-background-secondary dark:bg-dark-bg-secondary hover:bg-[#ebebec] dark:hover:bg-dark-bg-primary',\n          'text-content-tertiary dark:text-dark-content-secondary',\n        )}\n      >\n        {busy\n          ? <Loading size=\"sm\" layout=\"inline\" inheritColor ariaLabel={t('master_document.chrome.actionRunning')} />\n          : <EllipsisVerticalIcon className=\"w-4 h-4\" aria-hidden=\"true\" />}\n      </button>\n\n      {open && (\n        <div\n          role=\"menu\"\n          className={clsx(\n            'absolute right-0 top-full mt-1 w-64 z-50 py-1',\n            'bg-white dark:bg-dark-bg-primary rounded-md shadow-md',\n            'border border-border-primary dark:border-dark-border-primary',\n          )}\n        >\n          {options.map((o) => {\n            if (o.isDivider) {\n              return <hr key={o.key} className=\"my-1 border-border-primary dark:border-dark-border-primary\" />;\n            }\n            if (o.isHeading) {\n              return (\n                <p key={o.key} className=\"px-3 pt-2 pb-1 text-[11px] font-semibold text-content-tertiary tracking-[0.3px]\">\n                  {o.label}\n                </p>\n              );\n            }\n            return (\n              <button\n                key={o.key}\n                type=\"button\"\n                role=\"menuitem\"\n                disabled={o.disabled}\n                onClick={() => { o.onClick?.(); setOpen(false); }}\n                className={clsx(\n                  'w-full flex items-start gap-3 px-3 py-2 text-sm text-left transition-colors',\n                  'disabled:opacity-50 disabled:cursor-not-allowed',\n                  o.danger\n                    ? 'text-error-content enabled:hover:bg-error-bg/10'\n                    : 'text-content-primary dark:text-dark-content-primary enabled:hover:bg-background-secondary dark:enabled:hover:bg-dark-bg-secondary',\n                )}\n              >\n                {o.icon && <span className=\"w-4 h-4 shrink-0 mt-0.5 inline-flex items-center justify-center\">{o.icon}</span>}\n                <span className=\"min-w-0 flex-1\">\n                  <span className=\"block\">{o.label}</span>\n                  {/* El motivo por el que una acción no se puede usar va como\n                      texto visible, no como `title`: en un menú, un tooltip\n                      obliga a descubrirlo por hover sobre algo que además\n                      declara `pointer-events-none` al estar deshabilitado. */}\n                  {o.description && (\n                    <span className=\"block text-xs text-content-tertiary dark:text-dark-content-tertiary\">\n                      {o.description}\n                    </span>\n                  )}\n                </span>\n              </button>\n            );\n          })}\n        </div>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport type { StateBadgeProps } from './MasterDocument.types';\n\n/**\n * StateBadge — insignia visual que muestra el estado actual de un documento.\n *\n * Renderiza una etiqueta con colores personalizados (fondo y texto) definidos\n * por la máquina de estados del template. En modo oscuro aplica un filtro\n * de brillo/saturación para mantener la legibilidad.\n *\n * @see MasterDocument.types — `StateBadgeProps` para la definición de colores\n *\n * @example\n * ```tsx\n * <StateBadge label=\"Aprobado\" bg=\"#d1fae5\" color=\"#065f46\" />\n * ```\n */\nexport function StateBadge({ label, bg, color, className }: StateBadgeProps) {\n  return (\n    <span\n      role=\"status\"\n      className={clsx(\n        // Geometría del canon de MasterCrud (ADR-027 §E): medida el 2026-09-04 sobre\n        // /app/items — 20px de alto, 12px/500, radio 4px, padding 2/8, interlineado 16px.\n        // Antes era una píldora 22px 12px/600 con padding 3/10, que junto a un badge de\n        // MasterCrud se leía como otro producto.\n        'inline-flex items-center px-2 py-0.5 rounded text-xs leading-4 font-medium transition-colors duration-200 select-none',\n        'dark:[filter:brightness(0.85)_saturate(1.2)]',\n        className,\n      )}\n      style={{ backgroundColor: bg, color }}\n    >\n      {label}\n    </span>\n  );\n}\n","import React from 'react';\nimport { CircleCheck, CircleMinus } from 'lucide-react';\nimport {\n  DocumentIcon as HeroDocumentIcon,\n  ArrowDownTrayIcon,\n  CheckIcon as HeroCheckIcon,\n  PrinterIcon,\n  DocumentDuplicateIcon,\n  XMarkIcon,\n  ShoppingCartIcon,\n  ShoppingBagIcon,\n  PlusIcon as HeroPlusIcon,\n  CubeIcon,\n  ClockIcon,\n} from '@heroicons/react/24/outline';\n\n/**\n * Ícono de documento genérico\n */\nexport const DocumentIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <HeroDocumentIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de guardar (descargar)\n */\nexport const SaveIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <ArrowDownTrayIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de check / aprobar\n */\nexport const CheckIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <HeroCheckIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de imprimir\n */\nexport const PrintIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <PrinterIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de historial / auditoría (reloj)\n */\nexport const HistoryIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <ClockIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de duplicar\n */\nexport const DuplicateIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <DocumentDuplicateIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de cancelar (X)\n */\nexport const XIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <XMarkIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de compras (carrito)\n */\nexport const PurchasesIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <ShoppingCartIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de ventas (bolsa)\n */\nexport const SalesIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <ShoppingBagIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de agregar (+)\n */\nexport const PlusIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <HeroPlusIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Ícono de inventario (cubo)\n */\nexport const InventoryIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (\n  <CubeIcon {...props} aria-hidden=\"true\" />\n);\n\n/**\n * Iconos de la acción de ESTADO del documento, los MISMOS que usa MasterCrud para\n * «Desactivar registro» / «Activar registro» (lucide `CircleMinus` / `CircleCheck`).\n * Medido renderizado en `/app/items` el 2026-09-09: el check de «Activar» emite el\n * path `m9 12 2 2 4-4`, que es el de `CircleCheck`.\n */\nexport const DeactivateRecordIcon: React.FC<{ className?: string }> = ({ className }) => (\n  <CircleMinus className={className} aria-hidden=\"true\" />\n);\n\nexport const ActivateRecordIcon: React.FC<{ className?: string }> = ({ className }) => (\n  <CircleCheck className={className} aria-hidden=\"true\" />\n);\n","import type React from 'react';\n\nimport { ActivateRecordIcon, DeactivateRecordIcon } from './icons';\nimport type { RowAction } from './MasterDocument.types';\nimport type { TranslateFn } from './i18nFactory';\n\n/** Tono semántico de una acción por registro. Espeja `actionSemantics` de MasterCrud. */\nexport type AccionTono = 'danger' | 'success' | 'neutral';\n\n/**\n * Verde de «Activar», tomado del canon de badges de MasterCrud (estado `success`).\n *\n * Va como hex y no como clase por la razón que documenta `badgeTokens.ts` de\n * MasterCrud: el kit no declara ningún `--color-success-*`, así que una clase\n * arbitraria no se emitiría en el CSS del consumidor. Medido renderizado en\n * `/app/items` el 2026-09-09: `rgb(4, 120, 87)`.\n */\nexport const ACTIVAR_FG = '#047857';\n\n/** Tono con el que se pinta la acción de estado cuando el canon no la reconoce. */\nexport const TONO_ANULAR: AccionTono = 'danger';\n\n/** Devuelve el COMPONENTE del icono, no un elemento: así este módulo no lleva JSX. */\nexport interface CanonDeEstado {\n  label: string;\n  Icon: React.FC<{ className?: string }>;\n  tone: AccionTono;\n}\n\n/**\n * Lleva la acción de ESTADO de un documento al canon de MasterCrud: su icono, su\n * tono y —sólo si la plantilla no dice nada— su rótulo.\n *\n * ## Qué impone el kit y qué NO\n *\n * El kit impone lo VISUAL: el icono (`MinusCircle` / `CheckCircle`) y el tono\n * (`#dc2626` / `#047857`), que es lo que hace que la acción se reconozca igual en\n * cualquier pantalla del producto.\n *\n * El RÓTULO se queda en la plantilla. Esta función lo imponía también, y fue un\n * error medible: pisaba el verbo que cada plantilla declara con su propia clave\n * i18n. En entradas de compra —`ecd.ui.actions.cancel` = «Anular»— el botón pasó a\n * decir «Desactivar registro» sin que nadie lo pidiera, y cinco pruebas de\n * `EcdPage.cancelGating.integration` se pusieron rojas con la publicación de\n * 1.0.332 (ellas buscan el botón por su texto). El fallo no es de las pruebas: un\n * paquete no debe renombrar los botones de módulos que no participaron en el\n * cambio, y menos en silencio.\n *\n * Quien quiera el verbo del canon lo pone en su plantilla, que es donde se ve.\n *\n * `t` sigue haciendo falta para el caso sin rótulo, y también para las acciones que\n * el kit sintetiza por su cuenta.\n *\n * Devuelve `null` para cualquier otra acción: las personalizadas del consumidor\n * conservan su rótulo y su icono.\n */\nexport function accionDeEstadoAlCanon(\n  action: Pick<RowAction, 'key' | 'label' | 'variant'>,\n  t: TranslateFn,\n): CanonDeEstado | null {\n  // SÓLO `cancel`. `delete` NO entra: borrar un borrador y anular un documento\n  // aprobado son operaciones distintas —una lo quita antes de existir para nadie, la\n  // otra lo retira ya emitido— y darles el mismo rótulo escondería esa diferencia.\n  // `delete` conserva su propio verbo y su papelera.\n  if (action.key === 'cancel') {\n    return {\n      label: action.label || t('master_document.list.deactivateRecord'),\n      Icon: DeactivateRecordIcon,\n      tone: 'danger',\n    };\n  }\n  if (action.key === 'activate' || action.key === 'restore') {\n    return {\n      label: action.label || t('master_document.list.activateRecord'),\n      Icon: ActivateRecordIcon,\n      tone: 'success',\n    };\n  }\n  return null;\n}\n\n/**\n * Clases de color para un tono, sobre la geometría de 28x28 que ya fija\n * `ROW_ACTION_BTN`. Sólo cambia el color: tamaño, radio y foco son los mismos para\n * los tres tonos, porque lo que distingue una acción destructiva es su color y no su\n * forma.\n *\n * MasterCrud no tiene precedente de una acción de estado como botón DIRECTO —allí\n * vive siempre en el kebab—, así que el tono se traslada al botón conservando el\n * control `outline` del canon.\n */\nexport function clasesDeTonoBoton(tone: AccionTono | undefined): string {\n  switch (tone) {\n    case 'danger':\n      return '!text-error-content !border-error-border hover:!bg-error-bg';\n    case 'success':\n      return '!border-[#047857]/40 hover:!bg-[#047857]/10';\n    default:\n      return '';\n  }\n}\n","import React from 'react';\nimport { clsx } from 'clsx';\nimport { ArrowLeftIcon, XMarkIcon, BuildingOffice2Icon } from '@heroicons/react/24/outline';\nimport { Button } from '../Button/Button';\nimport { Loading } from './components/loading';\nimport { MoreOptionsMenu, type MoreOption } from './MoreOptionsMenu';\nimport { StateBadge } from './StateBadge';\nimport { accionDeEstadoAlCanon, clasesDeTonoBoton, TONO_ANULAR, type AccionTono } from './stateActionCanon';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { ActionBarProps } from './MasterDocument.types';\n\n// ─── ActionBar ─────────────────────────────────────────────\n\n/**\n * Cabecera del documento, al canon del detalle de MasterCrud (ADR-027 §H.1).\n *\n * **Cambio de forma deliberado.** Antes era una barra horizontal de 52px con\n * todo en una línea —«Devolución» como breadcrumb, el número, los badges y\n * tantos botones como cupieran, repartidos midiendo anchos— y no se parecía a\n * la cabecera de un maestro. Ahora reproduce la de MasterCrud, que apila:\n *\n * ```\n * ← Volver\n * Devolución de Venta · DEV-0001            [Cancelar] [Guardar] [⋮]\n * [🏢 Compañía] [Aprobado] [Nota crédito]\n * ```\n *\n * Lo que fija el canon y aquí se copia literal (Regla A.2 — copiar, nunca\n * aproximar): el enlace «Volver» en `text-sm` `content-tertiary` con hover a\n * `#1355b7`; el título en `text-xl font-semibold tracking-tight text-[#1355b7]`;\n * y las acciones en `h-9`.\n *\n * **Sólo `Cancelar` y `Guardar` quedan visibles** (§H.1: «dos botones, dos\n * palabras»); el resto —transiciones incluidas— vive en «Más acciones». El\n * reparto ya no depende de cuánto mida cada rótulo: antes lo decidía un cálculo\n * de anchos, así que la misma pantalla ofrecía distintos botones según el ancho\n * de la ventana o el idioma. Ahora es una regla, no una medición.\n *\n * Se conserva TODA la maquinaria de comportamiento previa: `disabled` con su\n * `disabledReason` como `title`, el indicador de acción en vuelo por `leftIcon`\n * (el `Button` del kit no tiene prop `loading`) y el agrupado\n * transiciones/acciones del desplegable.\n *\n * @see MasterDocument.types - ActionBarProps\n */\nexport function ActionBar({\n  breadcrumbLabel,\n  documentTitle,\n  companyName,\n  onBreadcrumbClick,\n  documentId,\n  documentNumber,\n  stateBadge,\n  docTypeBadge,\n  transitions,\n  onTransition,\n  actions,\n  className,\n}: ActionBarProps) {\n  const { t } = useMasterDocumentTranslation();\n\n  type UnifiedAction = {\n    key: string;\n    label: string;\n    icon?: React.ReactNode;\n    variant: 'primary' | 'secondary' | 'danger' | 'ghost';\n    onClick: () => void;\n    disabled?: boolean;\n    disabledReason?: string;\n    loading?: boolean;\n    group: 'transition' | 'action';\n  };\n\n  /**\n   * Acciones que se ofrecen como BOTÓN, por clave y no por rótulo —el rótulo es dato\n   * de catálogo y cambia con el idioma—. El resto (auditoría, transiciones) vive en\n   * «Más acciones».\n   *\n   * `save` es la primaria del canon; `cancel` e `print` se promueven porque son las\n   * dos operaciones que el usuario busca sobre un documento ya emitido y tenerlas a\n   * dos clics dentro de un menú cerrado las escondía.\n   */\n  const CLAVES_DIRECTAS = ['save', 'cancel', 'print'];\n  const directas = actions.filter((a) => CLAVES_DIRECTAS.includes(a.key) && a.position !== 'moreMenu');\n  const guardar = directas.find((a) => a.key === 'save');\n  const anular = directas.find((a) => a.key === 'cancel');\n  const imprimir = directas.find((a) => a.key === 'print');\n\n  const overflowActions: UnifiedAction[] = [\n    ...transitions.map((tr) => ({\n      key: `t-${tr.actionKey ?? tr.to}`,\n      label: tr.label,\n      icon: tr.icon,\n      variant: tr.style,\n      onClick: () => onTransition(tr.to),\n      disabled: tr.disabled,\n      loading: tr.loading,\n      group: 'transition' as const,\n    })),\n    ...actions\n      .filter((a) => !directas.includes(a) && a.position !== 'moreMenu')\n      .map((a) => ({\n        key: `a-${a.key}`,\n        label: a.label,\n        icon: a.icon,\n        variant: a.variant ?? ('ghost' as const),\n        onClick: a.onClick,\n        disabled: a.disabled,\n        disabledReason: a.disabledReason,\n        loading: a.loading,\n        group: 'action' as const,\n      })),\n  ];\n\n  const moreMenuActions = actions.filter((a) => a.position === 'moreMenu');\n\n  // El `Button` del kit no tiene prop `loading` (ver Button.types.ts), así que\n  // el indicador entra por `leftIcon`, sustituyendo al icono de la acción. En el\n  // desplegable ocupa el mismo hueco `icon`.\n  const iconOf = (item: { icon?: React.ReactNode; loading?: boolean }): React.ReactNode =>\n    item.loading\n      // `inheritColor`: el fondo del botón varía con la variante — un primario\n      // pinta `bg-primary-600`, el mismo color del spinner por defecto, y ahí\n      // sería invisible. Tomando `currentColor` se ve como el icono al que\n      // sustituye, sea cual sea la variante.\n      ? (\n        <Loading\n          size=\"sm\"\n          layout=\"inline\"\n          inheritColor\n          ariaLabel={t('master_document.chrome.actionRunning')}\n        />\n      )\n      : item.icon;\n\n  const dropdownItems: MoreOption[] = [];\n\n  const overflowTransitions = overflowActions.filter((i) => i.group === 'transition');\n  const overflowPlain = overflowActions.filter((i) => i.group === 'action');\n\n  if (overflowTransitions.length > 0) {\n    dropdownItems.push({ key: 'h-transitions', isHeading: true, label: t('master_document.actionBar.transitions') });\n    overflowTransitions.forEach((item) => {\n      dropdownItems.push({\n        key: item.key,\n        label: item.label,\n        icon: iconOf(item),\n        onClick: item.onClick,\n        disabled: item.disabled,\n        danger: item.variant === 'danger',\n      });\n    });\n  }\n\n  if (overflowPlain.length > 0) {\n    if (overflowTransitions.length > 0) dropdownItems.push({ key: 'd-1', isDivider: true });\n    dropdownItems.push({ key: 'h-actions', isHeading: true, label: t('master_document.actionBar.actions') });\n    overflowPlain.forEach((item) => {\n      dropdownItems.push({\n        key: item.key,\n        label: item.label,\n        icon: iconOf(item),\n        onClick: item.onClick,\n        disabled: item.disabled,\n        description: item.disabled ? item.disabledReason : undefined,\n        danger: item.variant === 'danger',\n      });\n    });\n  }\n\n  if (moreMenuActions.length > 0) {\n    if (dropdownItems.length > 0) dropdownItems.push({ key: 'd-2', isDivider: true });\n    moreMenuActions.forEach((a) => {\n      dropdownItems.push({\n        key: `m-${a.key}`,\n        label: a.label,\n        icon: iconOf(a),\n        onClick: a.onClick,\n        disabled: a.disabled,\n        description: a.disabled ? a.disabledReason : undefined,\n        danger: a.variant === 'danger',\n      });\n    });\n  }\n\n  const showOverflowBtn = dropdownItems.length > 0;\n  // Una acción del desplegable en vuelo no se vería: el menú está cerrado. El\n  // indicador sube al disparador, que es el único punto visible de esa acción —\n  // el mismo criterio que la celda de acciones del listado.\n  const algoEnVuelo = [...overflowActions, ...moreMenuActions].some((a) => a.loading);\n  const numero = documentNumber || documentId;\n\n  return (\n    <div\n      className={clsx('w-full px-4 md:px-6 pt-4 md:pt-5 pb-4 space-y-3', className)}\n      role=\"toolbar\"\n      aria-label={t('master_document.actionBar.aria')}\n    >\n      {/* «Volver»: el canon nombra el destino, no la dirección. Antes decía el\n          nombre del documento («Devolución»), que se leía como una migaja de pan\n          y no como la salida de la pantalla. */}\n      <nav>\n        <button\n          type=\"button\"\n          onClick={onBreadcrumbClick}\n          className={clsx(\n            'inline-flex items-center gap-1 text-sm text-content-tertiary dark:text-dark-content-tertiary',\n            'hover:text-[#1355b7] transition-colors',\n            'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 rounded-md',\n            'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n          )}\n        >\n          <ArrowLeftIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          <span>{t('master_document.chrome.backToList')}</span>\n        </button>\n      </nav>\n\n      <div className=\"flex flex-col md:flex-row md:items-start md:justify-between gap-4\">\n        <div className=\"flex flex-col gap-2 min-w-0\">\n          {/* Título + número: la identidad del documento. El título es el rótulo\n              de la clase (`identity.label`), que es el análogo del nombre del\n              maestro en MasterCrud; el número lo acompaña porque es lo que el\n              usuario busca al llegar. */}\n          <div className=\"flex items-baseline gap-2 min-w-0\">\n            <h1 className=\"text-xl font-semibold tracking-tight text-[#1355b7] dark:text-primary-600 truncate\">\n              {documentTitle || breadcrumbLabel}\n            </h1>\n            {numero && (\n              <>\n                <span className=\"text-content-tertiary dark:text-dark-content-tertiary shrink-0\" aria-hidden=\"true\">·</span>\n                <span className=\"text-xl font-semibold tracking-tight text-content-primary dark:text-dark-content-primary tabular-nums truncate\">\n                  {numero}\n                </span>\n              </>\n            )}\n          </div>\n\n          {/* Compañía + estado + tipo, todos como BADGE. La compañía reproduce el\n              `CompanySelector` de MasterCrud en su modo de sólo lectura —un\n              `<span>`, no un control—, porque aquí no se puede cambiar. */}\n          <div className=\"flex items-center gap-2 flex-wrap\">\n            {companyName && (\n              <span className={clsx(\n                'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold leading-none select-none',\n                'bg-[#eff8ff] dark:bg-primary-900/20 border border-[#93d1fd] dark:border-primary-800',\n                'text-[#1355b7] dark:text-primary-300',\n              )}>\n                <BuildingOffice2Icon className=\"w-3.5 h-3.5 flex-shrink-0\" aria-hidden=\"true\" />\n                <span className=\"max-w-[180px] truncate\" title={companyName}>{companyName}</span>\n              </span>\n            )}\n            {stateBadge && <StateBadge {...stateBadge} />}\n            {docTypeBadge && (\n              // Badge, no píldora: misma geometría que `StateBadge` (radio 4px,\n              // 12px/500, padding 2/8). Antes era `rounded-full` 10.5px/600, que\n              // junto al badge de estado se leía como dos sistemas distintos.\n              <span className={clsx(\n                'inline-flex items-center px-2 py-0.5 rounded text-xs leading-4 font-medium select-none',\n                'bg-background-secondary text-content-secondary',\n                'dark:bg-dark-bg-secondary dark:text-dark-content-secondary',\n              )}>\n                {docTypeBadge}\n              </span>\n            )}\n          </div>\n        </div>\n\n        {/* Acciones: Cancelar · Guardar · kebab (§H.1) */}\n        <div className=\"flex items-center gap-2 flex-shrink-0\">\n          {guardar && (\n            <Button\n              type=\"outline\"\n              size=\"base\"\n              className=\"!h-9 !px-3 !text-sm font-medium\"\n              leftIcon={<XMarkIcon className=\"w-4 h-4\" />}\n              onClick={onBreadcrumbClick}\n            >\n              {t('master_document.chrome.cancel')}\n            </Button>\n          )}\n\n          {/* «Anular» va SEPARADA de «Guardar» por «Imprimir» a propósito: es la única\n              acción destructiva de la barra y dejarla pegada a la primaria invita al\n              clic equivocado. Su rótulo, su icono y su tono salen del canon de la\n              acción de estado, los mismos que en la fila del listado. */}\n          {anular && (() => {\n            const canon = accionDeEstadoAlCanon({ key: anular.key, label: anular.label, variant: anular.variant }, t);\n            const tone: AccionTono = canon?.tone ?? TONO_ANULAR;\n            const rotulo = canon?.label ?? anular.label;\n            return (\n              <span title={anular.disabled && anular.disabledReason ? anular.disabledReason : undefined} className=\"inline-flex\">\n                <Button\n                  type=\"outline\"\n                  size=\"base\"\n                  className={clsx('!h-9 !px-3 !text-sm font-medium', clasesDeTonoBoton(tone))}\n                  leftIcon={anular.loading ? iconOf(anular) : (canon ? <canon.Icon className=\"w-4 h-4\" /> : anular.icon)}\n                  onClick={anular.onClick}\n                  disabled={anular.disabled}\n                  title={!anular.disabled ? rotulo : undefined}\n                  ariaLabel={rotulo}\n                >\n                  {rotulo}\n                </Button>\n              </span>\n            );\n          })()}\n\n          {imprimir && (\n            <span title={imprimir.disabled && imprimir.disabledReason ? imprimir.disabledReason : undefined} className=\"inline-flex\">\n              <Button\n                type=\"outline\"\n                size=\"base\"\n                className=\"!h-9 !px-3 !text-sm font-medium\"\n                leftIcon={iconOf(imprimir)}\n                onClick={imprimir.onClick}\n                disabled={imprimir.disabled}\n                title={!imprimir.disabled ? imprimir.label : undefined}\n                ariaLabel={imprimir.label}\n              >\n                {imprimir.label}\n              </Button>\n            </span>\n          )}\n\n          {guardar && (\n            <span\n              title={guardar.disabled && guardar.disabledReason ? guardar.disabledReason : undefined}\n              className=\"inline-flex\"\n            >\n              <Button\n                type=\"default\"\n                size=\"base\"\n                className=\"!h-9 !px-3 !text-sm font-medium\"\n                leftIcon={iconOf(guardar)}\n                onClick={guardar.onClick}\n                disabled={guardar.disabled}\n                title={!guardar.disabled ? guardar.label : undefined}\n                ariaLabel={guardar.label}\n              >\n                {guardar.label}\n              </Button>\n            </span>\n          )}\n\n          {showOverflowBtn && (\n            <MoreOptionsMenu\n              options={dropdownItems}\n              busy={algoEnVuelo}\n              ariaLabel={t('master_document.actionBar.moreActions')}\n            />\n          )}\n        </div>\n      </div>\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { Breakpoint, ContextStripProps } from './MasterDocument.types';\n\n/**\n * Mapa breakpoint → clase responsive de Tailwind que oculta el item únicamente\n * dentro de ese rango de ancho. Las cadenas son literales para que el JIT de\n * Tailwind las detecte al hacer build.\n *\n *   xs  → <640px      |  sm → 640–767px\n *   md  → 768–1023px  |  lg → 1024–1279px\n *   xl  → 1280–1535px |  2xl → ≥1536px\n */\nconst HIDE_ON_BREAKPOINT_CLASS: Record<Breakpoint, string> = {\n  xs: 'max-sm:hidden',\n  sm: 'sm:max-md:hidden',\n  md: 'md:max-lg:hidden',\n  lg: 'lg:max-xl:hidden',\n  xl: 'xl:max-2xl:hidden',\n  '2xl': '2xl:hidden',\n};\n\nfunction hideClasses(breakpoints?: Breakpoint[]): string {\n  if (!breakpoints?.length) return '';\n  return breakpoints.map((bp) => HIDE_ON_BREAKPOINT_CLASS[bp]).join(' ');\n}\n\n/**\n * Franja de identidad del documento: centro de operación, tipo, número, fecha,\n * tercero… Se pinta como primera banda DENTRO de la tarjeta del detalle.\n *\n * **Rediseño (canon ADR-027).** Antes era una tira horizontal con los datos\n * separados por barras verticales y envolviendo con `flex-wrap`: al reflowear,\n * cada dato caía donde le tocaba y ni las etiquetas ni los valores compartían\n * eje, así que la franja se leía como una lista desordenada y no como la ficha\n * del documento. Ahora es una REJILLA: las columnas fijan el eje vertical, de\n * modo que todas las etiquetas se alinean entre sí y todos los valores también,\n * y el bloque sigue cuadrado con el resto del detalle al reflowear.\n *\n * La tipografía es la del canon: etiqueta de grupo en `text-[11px] font-bold\n * uppercase tracking-[0.4px] text-[#a1a1aa]` (§D.5) y valor en 14px/600. El\n * fondo es la banda `#f8f9fc` del canon de tabla (§E.1), que la separa del\n * formulario sin necesidad de una caja propia.\n *\n * La compañía NO viaja aquí: sube a la cabecera como badge junto al estado\n * (ver `SmartMasterDocument`), que es donde la pone el detalle de MasterCrud.\n *\n * @see MasterDocument.types - ContextStripProps / ContextStripItem\n */\nexport function ContextStrip({ items, currencyPanel, className }: ContextStripProps) {\n  const { t } = useMasterDocumentTranslation();\n  if (items.length === 0 && !currencyPanel) return null;\n\n  return (\n    <div\n      className={clsx(\n        'shrink-0 flex items-start justify-between gap-4',\n        'bg-[#f8f9fc] dark:bg-dark-bg-secondary',\n        'border-b border-border-secondary dark:border-dark-border-primary',\n        'px-4 md:px-6 py-3',\n        className,\n      )}\n      role=\"region\"\n      aria-label={t('master_document.contextStrip.aria')}\n    >\n      {/* `dl` y no una tira de `div`s: es literalmente una lista de pares\n          término/descripción, y así un lector de pantalla anuncia cada valor\n          con su etiqueta en vez de leer doce cadenas sueltas. */}\n      <dl className=\"flex-1 min-w-0 grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-x-6 gap-y-3\">\n        {items.map((item) => (\n          <div\n            key={item.label}\n            className={clsx('flex flex-col gap-0.5 min-w-0', hideClasses(item.hideOnBreakpoints))}\n          >\n            <dt className=\"text-[11px] font-bold uppercase tracking-[0.4px] leading-4 text-[#a1a1aa] dark:text-dark-content-tertiary truncate\">\n              {item.label}\n            </dt>\n            <dd\n              title={item.value || undefined}\n              className={clsx(\n                'text-sm font-semibold leading-5 truncate',\n                item.accent\n                  ? 'text-primary-custom-600 dark:text-primary-custom-500'\n                  : 'text-content-primary dark:text-dark-content-primary',\n                item.mono && 'tabular-nums',\n              )}\n            >\n              {/* Un dato ausente se dice con una raya, no con un hueco: un valor\n                  vacío deja la etiqueta suelta y parece que la ficha se rompió. */}\n              {item.value?.trim() || '—'}\n            </dd>\n          </div>\n        ))}\n      </dl>\n\n      {currencyPanel && (\n        <div className=\"shrink-0 pl-4\">\n          {currencyPanel}\n        </div>\n      )}\n    </div>\n  );\n}\n","/**\n * react-number-format - 5.4.5\n * Author : Sudhanshu Yadav\n * Copyright (c) 2016, 2026 to Sudhanshu Yadav, released under the MIT license.\n * https://github.com/s-yadav/react-number-format\n */\n\nimport React, { useState, useMemo, useEffect, useRef, useLayoutEffect } from 'react';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        { t[p] = s[p]; } }\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                { t[p[i]] = s[p[i]]; }\r\n        } }\r\n    return t;\r\n}\n\nvar SourceType;\n(function (SourceType) {\n    SourceType[\"event\"] = \"event\";\n    SourceType[\"props\"] = \"prop\";\n})(SourceType || (SourceType = {}));\n\n// basic noop function\nfunction noop() { }\nfunction memoizeOnce(cb) {\n    var lastArgs;\n    var lastValue = undefined;\n    return function () {\n        var args = [], len = arguments.length;\n        while ( len-- ) args[ len ] = arguments[ len ];\n\n        if (lastArgs &&\n            args.length === lastArgs.length &&\n            args.every(function (value, index) { return value === lastArgs[index]; })) {\n            return lastValue;\n        }\n        lastArgs = args;\n        lastValue = cb.apply(void 0, args);\n        return lastValue;\n    };\n}\nfunction charIsNumber(char) {\n    return !!(char || '').match(/\\d/);\n}\nfunction isNil(val) {\n    return val === null || val === undefined;\n}\nfunction isNanValue(val) {\n    return typeof val === 'number' && isNaN(val);\n}\nfunction isNotValidValue(val) {\n    return isNil(val) || isNanValue(val) || (typeof val === 'number' && !isFinite(val));\n}\nfunction escapeRegExp(str) {\n    return str.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&');\n}\nfunction getThousandsGroupRegex(thousandsGroupStyle) {\n    switch (thousandsGroupStyle) {\n        case 'lakh':\n            return /(\\d+?)(?=(\\d\\d)+(\\d)(?!\\d))(\\.\\d+)?/g;\n        case 'wan':\n            return /(\\d)(?=(\\d{4})+(?!\\d))/g;\n        case 'thousand':\n        default:\n            return /(\\d)(?=(\\d{3})+(?!\\d))/g;\n    }\n}\nfunction applyThousandSeparator(str, thousandSeparator, thousandsGroupStyle) {\n    var thousandsGroupRegex = getThousandsGroupRegex(thousandsGroupStyle);\n    var index = str.search(/[1-9]/);\n    index = index === -1 ? str.length : index;\n    return (str.substring(0, index) +\n        str.substring(index, str.length).replace(thousandsGroupRegex, '$1' + thousandSeparator));\n}\nfunction usePersistentCallback(cb) {\n    var callbackRef = useRef(cb);\n    // keep the callback ref upto date\n    callbackRef.current = cb;\n    /**\n     * initialize a persistent callback which never changes\n     * through out the component lifecycle\n     */\n    var persistentCbRef = useRef(function () {\n        var args = [], len = arguments.length;\n        while ( len-- ) args[ len ] = arguments[ len ];\n\n        return callbackRef.current.apply(callbackRef, args);\n    });\n    return persistentCbRef.current;\n}\n//spilt a float number into different parts beforeDecimal, afterDecimal, and negation\nfunction splitDecimal(numStr, allowNegative) {\n    if ( allowNegative === void 0 ) allowNegative = true;\n\n    var hasNegation = numStr[0] === '-';\n    var addNegation = hasNegation && allowNegative;\n    numStr = numStr.replace('-', '');\n    var parts = numStr.split('.');\n    var beforeDecimal = parts[0];\n    var afterDecimal = parts[1] || '';\n    return {\n        beforeDecimal: beforeDecimal,\n        afterDecimal: afterDecimal,\n        hasNegation: hasNegation,\n        addNegation: addNegation,\n    };\n}\nfunction fixLeadingZero(numStr) {\n    if (!numStr)\n        { return numStr; }\n    var isNegative = numStr[0] === '-';\n    if (isNegative)\n        { numStr = numStr.substring(1, numStr.length); }\n    var parts = numStr.split('.');\n    var beforeDecimal = parts[0].replace(/^0+/, '') || '0';\n    var afterDecimal = parts[1] || '';\n    return (\"\" + (isNegative ? '-' : '') + beforeDecimal + (afterDecimal ? (\".\" + afterDecimal) : ''));\n}\n/**\n * limit decimal numbers to given scale\n * Not used .fixedTo because that will break with big numbers\n */\nfunction limitToScale(numStr, scale, fixedDecimalScale) {\n    var str = '';\n    var filler = fixedDecimalScale ? '0' : '';\n    for (var i = 0; i <= scale - 1; i++) {\n        str += numStr[i] || filler;\n    }\n    return str;\n}\nfunction repeat(str, count) {\n    return Array(count + 1).join(str);\n}\nfunction toNumericString(num) {\n    var _num = num + ''; // typecast number to string\n    // store the sign and remove it from the number.\n    var sign = _num[0] === '-' ? '-' : '';\n    if (sign)\n        { _num = _num.substring(1); }\n    // split the number into cofficient and exponent\n    var ref = _num.split(/[eE]/g);\n    var coefficient = ref[0];\n    var exponent = ref[1];\n    // covert exponent to number;\n    exponent = Number(exponent);\n    // if there is no exponent part or its 0, return the coffiecient with sign\n    if (!exponent)\n        { return sign + coefficient; }\n    coefficient = coefficient.replace('.', '');\n    /**\n     * for scientific notation the current decimal index will be after first number (index 0)\n     * So effective decimal index will always be 1 + exponent value\n     */\n    var decimalIndex = 1 + exponent;\n    var coffiecientLn = coefficient.length;\n    if (decimalIndex < 0) {\n        // if decimal index is less then 0 add preceding 0s\n        // add 1 as join will have\n        coefficient = '0.' + repeat('0', Math.abs(decimalIndex)) + coefficient;\n    }\n    else if (decimalIndex >= coffiecientLn) {\n        // if decimal index is less then 0 add leading 0s\n        coefficient = coefficient + repeat('0', decimalIndex - coffiecientLn);\n    }\n    else {\n        // else add decimal point at proper index\n        coefficient =\n            (coefficient.substring(0, decimalIndex) || '0') + '.' + coefficient.substring(decimalIndex);\n    }\n    return sign + coefficient;\n}\n/**\n * This method is required to round prop value to given scale.\n * Not used .round or .fixedTo because that will break with big numbers\n */\nfunction roundToPrecision(numStr, scale, fixedDecimalScale) {\n    //if number is empty don't do anything return empty string\n    if (['', '-'].indexOf(numStr) !== -1)\n        { return numStr; }\n    var shouldHaveDecimalSeparator = (numStr.indexOf('.') !== -1 || fixedDecimalScale) && scale;\n    var ref = splitDecimal(numStr);\n    var beforeDecimal = ref.beforeDecimal;\n    var afterDecimal = ref.afterDecimal;\n    var hasNegation = ref.hasNegation;\n    var floatValue = parseFloat((\"0.\" + (afterDecimal || '0')));\n    var floatValueStr = afterDecimal.length <= scale ? (\"0.\" + afterDecimal) : floatValue.toFixed(scale);\n    var roundedDecimalParts = floatValueStr.split('.');\n    var intPart = beforeDecimal;\n    // if we have cary over from rounding decimal part, add that on before decimal\n    if (beforeDecimal && Number(roundedDecimalParts[0])) {\n        intPart = beforeDecimal\n            .split('')\n            .reverse()\n            .reduce(function (roundedStr, current, idx) {\n            if (roundedStr.length > idx) {\n                return ((Number(roundedStr[0]) + Number(current)).toString() +\n                    roundedStr.substring(1, roundedStr.length));\n            }\n            return current + roundedStr;\n        }, roundedDecimalParts[0]);\n    }\n    var decimalPart = limitToScale(roundedDecimalParts[1] || '', scale, fixedDecimalScale);\n    var negation = hasNegation ? '-' : '';\n    var decimalSeparator = shouldHaveDecimalSeparator ? '.' : '';\n    return (\"\" + negation + intPart + decimalSeparator + decimalPart);\n}\n/** set the caret positon in an input field **/\nfunction setCaretPosition(el, caretPos) {\n    el.value = el.value;\n    // ^ this is used to not only get 'focus', but\n    // to make sure we don't have it everything -selected-\n    // (it causes an issue in chrome, and having it doesn't hurt any other browser)\n    if (el !== null) {\n        /* @ts-ignore */\n        if (el.createTextRange) {\n            /* @ts-ignore */\n            var range = el.createTextRange();\n            range.move('character', caretPos);\n            range.select();\n            return true;\n        }\n        // (el.selectionStart === 0 added for Firefox bug)\n        if (el.selectionStart || el.selectionStart === 0) {\n            el.focus();\n            el.setSelectionRange(caretPos, caretPos);\n            return true;\n        }\n        // fail city, fortunately this never happens (as far as I've tested) :)\n        el.focus();\n        return false;\n    }\n}\n/**\n * TODO: remove dependency of findChangeRange, findChangedRangeFromCaretPositions is better way to find what is changed\n * currently this is mostly required by test and isCharacterSame util\n * Given previous value and newValue it returns the index\n * start - end to which values have changed.\n * This function makes assumption about only consecutive\n * characters are changed which is correct assumption for caret input.\n */\nvar findChangeRange = memoizeOnce(function (prevValue, newValue) {\n    var i = 0, j = 0;\n    var prevLength = prevValue.length;\n    var newLength = newValue.length;\n    while (prevValue[i] === newValue[i] && i < prevLength)\n        { i++; }\n    //check what has been changed from last\n    while (prevValue[prevLength - 1 - j] === newValue[newLength - 1 - j] &&\n        newLength - j > i &&\n        prevLength - j > i) {\n        j++;\n    }\n    return {\n        from: { start: i, end: prevLength - j },\n        to: { start: i, end: newLength - j },\n    };\n});\nvar findChangedRangeFromCaretPositions = function (lastCaretPositions, currentCaretPosition) {\n    var startPosition = Math.min(lastCaretPositions.selectionStart, currentCaretPosition);\n    return {\n        from: { start: startPosition, end: lastCaretPositions.selectionEnd },\n        to: { start: startPosition, end: currentCaretPosition },\n    };\n};\n/*\n  Returns a number whose value is limited to the given range\n*/\nfunction clamp(num, min, max) {\n    return Math.min(Math.max(num, min), max);\n}\nfunction geInputCaretPosition(el) {\n    /*Max of selectionStart and selectionEnd is taken for the patch of pixel and other mobile device caret bug*/\n    return Math.max(el.selectionStart, el.selectionEnd);\n}\nfunction addInputMode() {\n    return (typeof navigator !== 'undefined' &&\n        !(navigator.platform && /iPhone|iPod/.test(navigator.platform)));\n}\nfunction getDefaultChangeMeta(value) {\n    return {\n        from: {\n            start: 0,\n            end: 0,\n        },\n        to: {\n            start: 0,\n            end: value.length,\n        },\n        lastValue: '',\n    };\n}\nfunction getMaskAtIndex(mask, index) {\n    if ( mask === void 0 ) mask = ' ';\n\n    if (typeof mask === 'string') {\n        return mask;\n    }\n    return mask[index] || ' ';\n}\nfunction defaultIsCharacterSame(ref) {\n    var currentValue = ref.currentValue;\n    var formattedValue = ref.formattedValue;\n    var currentValueIndex = ref.currentValueIndex;\n    var formattedValueIndex = ref.formattedValueIndex;\n\n    return currentValue[currentValueIndex] === formattedValue[formattedValueIndex];\n}\nfunction getCaretPosition(newFormattedValue, lastFormattedValue, curValue, curCaretPos, boundary, isValidInputCharacter, \n/**\n * format function can change the character, the caret engine relies on mapping old value and new value\n * In such case if character is changed, parent can tell which chars are equivalent\n * Some example, all allowedDecimalCharacters are updated to decimalCharacters, 2nd case if user is coverting\n * number to different numeric system.\n */\nisCharacterSame) {\n    if ( isCharacterSame === void 0 ) isCharacterSame = defaultIsCharacterSame;\n\n    /**\n     * if something got inserted on empty value, add the formatted character before the current value,\n     * This is to avoid the case where typed character is present on format characters\n     */\n    var firstAllowedPosition = boundary.findIndex(function (b) { return b; });\n    var prefixFormat = newFormattedValue.slice(0, firstAllowedPosition);\n    if (!lastFormattedValue && !curValue.startsWith(prefixFormat)) {\n        lastFormattedValue = prefixFormat;\n        curValue = prefixFormat + curValue;\n        curCaretPos = curCaretPos + prefixFormat.length;\n    }\n    var curValLn = curValue.length;\n    var formattedValueLn = newFormattedValue.length;\n    // create index map\n    var addedIndexMap = {};\n    var indexMap = new Array(curValLn);\n    for (var i = 0; i < curValLn; i++) {\n        indexMap[i] = -1;\n        for (var j = 0, jLn = formattedValueLn; j < jLn; j++) {\n            var isCharSame = isCharacterSame({\n                currentValue: curValue,\n                lastValue: lastFormattedValue,\n                formattedValue: newFormattedValue,\n                currentValueIndex: i,\n                formattedValueIndex: j,\n            });\n            if (isCharSame && addedIndexMap[j] !== true) {\n                indexMap[i] = j;\n                addedIndexMap[j] = true;\n                break;\n            }\n        }\n    }\n    /**\n     * For current caret position find closest characters (left and right side)\n     * which are properly mapped to formatted value.\n     * The idea is that the new caret position will exist always in the boundary of\n     * that mapped index\n     */\n    var pos = curCaretPos;\n    while (pos < curValLn && (indexMap[pos] === -1 || !isValidInputCharacter(curValue[pos]))) {\n        pos++;\n    }\n    // if the caret position is on last keep the endIndex as last for formatted value\n    var endIndex = pos === curValLn || indexMap[pos] === -1 ? formattedValueLn : indexMap[pos];\n    pos = curCaretPos - 1;\n    while (pos > 0 && indexMap[pos] === -1)\n        { pos--; }\n    var startIndex = pos === -1 || indexMap[pos] === -1 ? 0 : indexMap[pos] + 1;\n    /**\n     * case where a char is added on suffix and removed from middle, example 2sq345 becoming $2,345 sq\n     * there is still a mapping but the order of start index and end index is changed\n     */\n    if (startIndex > endIndex)\n        { return endIndex; }\n    /**\n     * given the current caret position if it closer to startIndex\n     * keep the new caret position on start index or keep it closer to endIndex\n     */\n    return curCaretPos - startIndex < endIndex - curCaretPos ? startIndex : endIndex;\n}\n/* This keeps the caret within typing area so people can't type in between prefix or suffix or format characters */\nfunction getCaretPosInBoundary(value, caretPos, boundary, direction) {\n    var valLn = value.length;\n    // clamp caret position to [0, value.length]\n    caretPos = clamp(caretPos, 0, valLn);\n    if (direction === 'left') {\n        while (caretPos >= 0 && !boundary[caretPos])\n            { caretPos--; }\n        // if we don't find any suitable caret position on left, set it on first allowed position\n        if (caretPos === -1)\n            { caretPos = boundary.indexOf(true); }\n    }\n    else {\n        while (caretPos <= valLn && !boundary[caretPos])\n            { caretPos++; }\n        // if we don't find any suitable caret position on right, set it on last allowed position\n        if (caretPos > valLn)\n            { caretPos = boundary.lastIndexOf(true); }\n    }\n    // if we still don't find caret position, set it at the end of value\n    if (caretPos === -1)\n        { caretPos = valLn; }\n    return caretPos;\n}\nfunction caretUnknownFormatBoundary(formattedValue) {\n    var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n    for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n        // consider caret to be in boundary if it is before or after numeric value\n        boundaryAry[i] = Boolean(charIsNumber(formattedValue[i]) || charIsNumber(formattedValue[i - 1]));\n    }\n    return boundaryAry;\n}\nfunction useInternalValues(value, defaultValue, valueIsNumericString, format, removeFormatting, onValueChange) {\n    if ( onValueChange === void 0 ) onValueChange = noop;\n\n    var getValues = usePersistentCallback(function (value, valueIsNumericString) {\n        var formattedValue, numAsString;\n        if (isNotValidValue(value)) {\n            numAsString = '';\n            formattedValue = '';\n        }\n        else if (typeof value === 'number' || valueIsNumericString) {\n            numAsString = typeof value === 'number' ? toNumericString(value) : value;\n            formattedValue = format(numAsString);\n        }\n        else {\n            numAsString = removeFormatting(value, undefined);\n            formattedValue = format(numAsString);\n        }\n        return { formattedValue: formattedValue, numAsString: numAsString };\n    });\n    var ref = useState(function () {\n        return getValues(isNil(value) ? defaultValue : value, valueIsNumericString);\n    });\n    var values = ref[0];\n    var setValues = ref[1];\n    var _onValueChange = usePersistentCallback(function (newValues, sourceInfo) {\n        if (newValues.formattedValue !== values.formattedValue) {\n            setValues({\n                formattedValue: newValues.formattedValue,\n                numAsString: newValues.value,\n            });\n        }\n        // call parent on value change if only if formatted value is changed\n        onValueChange(newValues, sourceInfo);\n    });\n    // if value is switch from controlled to uncontrolled, use the internal state's value to format with new props\n    var _value = value;\n    var _valueIsNumericString = valueIsNumericString;\n    if (isNil(value)) {\n        _value = values.numAsString;\n        _valueIsNumericString = true;\n    }\n    var newValues = getValues(_value, _valueIsNumericString);\n    useMemo(function () {\n        setValues(newValues);\n    }, [newValues.formattedValue]);\n    /**\n     * When only a defaultValue is provided (value prop is nil), the initial formatted value is\n     * derived by the library — the parent has not yet been informed of this formatted result.\n     * Fire onValueChange once on mount so the parent can sync to the formatted value.\n     */\n    useEffect(function () {\n        if (!isNil(defaultValue) && isNil(value) && values.formattedValue !== '') {\n            var floatValue = parseFloat(values.numAsString);\n            _onValueChange({\n                formattedValue: values.formattedValue,\n                value: values.numAsString,\n                floatValue: isNaN(floatValue) ? undefined : floatValue,\n            }, { event: undefined, source: SourceType.props });\n        }\n    }, []);\n    return [values, _onValueChange];\n}\n\nfunction defaultRemoveFormatting(value) {\n    return value.replace(/[^0-9]/g, '');\n}\nfunction defaultFormat(value) {\n    return value;\n}\nfunction NumberFormatBase(props) {\n    var type = props.type; if ( type === void 0 ) type = 'text';\n    var displayType = props.displayType; if ( displayType === void 0 ) displayType = 'input';\n    var customInput = props.customInput;\n    var renderText = props.renderText;\n    var getInputRef = props.getInputRef;\n    var format = props.format; if ( format === void 0 ) format = defaultFormat;\n    var removeFormatting = props.removeFormatting; if ( removeFormatting === void 0 ) removeFormatting = defaultRemoveFormatting;\n    var defaultValue = props.defaultValue;\n    var valueIsNumericString = props.valueIsNumericString;\n    var onValueChange = props.onValueChange;\n    var isAllowed = props.isAllowed;\n    var onChange = props.onChange; if ( onChange === void 0 ) onChange = noop;\n    var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n    var onMouseUp = props.onMouseUp; if ( onMouseUp === void 0 ) onMouseUp = noop;\n    var onFocus = props.onFocus; if ( onFocus === void 0 ) onFocus = noop;\n    var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n    var propValue = props.value;\n    var getCaretBoundary = props.getCaretBoundary; if ( getCaretBoundary === void 0 ) getCaretBoundary = caretUnknownFormatBoundary;\n    var isValidInputCharacter = props.isValidInputCharacter; if ( isValidInputCharacter === void 0 ) isValidInputCharacter = charIsNumber;\n    var isCharacterSame = props.isCharacterSame;\n    var otherProps = __rest(props, [\"type\", \"displayType\", \"customInput\", \"renderText\", \"getInputRef\", \"format\", \"removeFormatting\", \"defaultValue\", \"valueIsNumericString\", \"onValueChange\", \"isAllowed\", \"onChange\", \"onKeyDown\", \"onMouseUp\", \"onFocus\", \"onBlur\", \"value\", \"getCaretBoundary\", \"isValidInputCharacter\", \"isCharacterSame\"]);\n    var ref = useInternalValues(propValue, defaultValue, Boolean(valueIsNumericString), format, removeFormatting, onValueChange);\n    var ref_0 = ref[0];\n    var formattedValue = ref_0.formattedValue;\n    var numAsString = ref_0.numAsString;\n    var onFormattedValueChange = ref[1];\n    var caretPositionBeforeChange = useRef();\n    var lastUpdatedValue = useRef({ formattedValue: formattedValue, numAsString: numAsString });\n    var _onValueChange = function (values, source) {\n        lastUpdatedValue.current = { formattedValue: values.formattedValue, numAsString: values.value };\n        onFormattedValueChange(values, source);\n    };\n    var ref$1 = useState(false);\n    var mounted = ref$1[0];\n    var setMounted = ref$1[1];\n    var focusedElm = useRef(null);\n    var timeout = useRef({\n        setCaretTimeout: null,\n        focusTimeout: null,\n    });\n    useEffect(function () {\n        setMounted(true);\n        return function () {\n            clearTimeout(timeout.current.setCaretTimeout);\n            clearTimeout(timeout.current.focusTimeout);\n        };\n    }, []);\n    var _format = format;\n    var getValueObject = function (formattedValue, numAsString) {\n        var floatValue = parseFloat(numAsString);\n        return {\n            formattedValue: formattedValue,\n            value: numAsString,\n            floatValue: isNaN(floatValue) ? undefined : floatValue,\n        };\n    };\n    var setPatchedCaretPosition = function (el, caretPos, currentValue) {\n        // don't reset the caret position when the whole input content is selected\n        if (el.selectionStart === 0 && el.selectionEnd === el.value.length)\n            { return; }\n        /* setting caret position within timeout of 0ms is required for mobile chrome,\n        otherwise browser resets the caret position after we set it\n        We are also setting it without timeout so that in normal browser we don't see the flickering */\n        setCaretPosition(el, caretPos);\n        timeout.current.setCaretTimeout = setTimeout(function () {\n            if (el.value === currentValue && el.selectionStart !== caretPos) {\n                setCaretPosition(el, caretPos);\n            }\n        }, 0);\n    };\n    /* This keeps the caret within typing area so people can't type in between prefix or suffix */\n    var correctCaretPosition = function (value, caretPos, direction) {\n        return getCaretPosInBoundary(value, caretPos, getCaretBoundary(value), direction);\n    };\n    var getNewCaretPosition = function (inputValue, newFormattedValue, caretPos) {\n        var caretBoundary = getCaretBoundary(newFormattedValue);\n        var updatedCaretPos = getCaretPosition(newFormattedValue, formattedValue, inputValue, caretPos, caretBoundary, isValidInputCharacter, isCharacterSame);\n        //correct caret position if its outside of editable area\n        updatedCaretPos = getCaretPosInBoundary(newFormattedValue, updatedCaretPos, caretBoundary);\n        return updatedCaretPos;\n    };\n    var updateValueAndCaretPosition = function (params) {\n        var newFormattedValue = params.formattedValue; if ( newFormattedValue === void 0 ) newFormattedValue = '';\n        var input = params.input;\n        var source = params.source;\n        var event = params.event;\n        var numAsString = params.numAsString;\n        var caretPos;\n        if (input) {\n            var inputValue = params.inputValue || input.value;\n            var currentCaretPosition = geInputCaretPosition(input);\n            /**\n             * set the value imperatively, this is required for IE fix\n             * This is also required as if new caret position is beyond the previous value.\n             * Caret position will not be set correctly\n             */\n            input.value = newFormattedValue;\n            //get the caret position\n            caretPos = getNewCaretPosition(inputValue, newFormattedValue, currentCaretPosition);\n            //set caret position imperatively\n            if (caretPos !== undefined) {\n                setPatchedCaretPosition(input, caretPos, newFormattedValue);\n            }\n        }\n        if (newFormattedValue !== formattedValue) {\n            // trigger onValueChange synchronously, so parent is updated along with the number format. Fix for #277, #287\n            _onValueChange(getValueObject(newFormattedValue, numAsString), { event: event, source: source });\n        }\n    };\n    /**\n     * if the formatted value is not synced to parent, or if the formatted value is different from last synced value sync it\n     * if the formatting props is removed, in which case last formatted value will be different from the numeric string value\n     * in such case we need to inform the parent.\n     */\n    useEffect(function () {\n        var ref = lastUpdatedValue.current;\n        var lastFormattedValue = ref.formattedValue;\n        var lastNumAsString = ref.numAsString;\n        if (formattedValue !== lastFormattedValue || numAsString !== lastNumAsString) {\n            _onValueChange(getValueObject(formattedValue, numAsString), {\n                event: undefined,\n                source: SourceType.props,\n            });\n        }\n    }, [formattedValue, numAsString]);\n    // also if formatted value is changed from the props, we need to update the caret position\n    // keep the last caret position if element is focused\n    var currentCaretPosition = focusedElm.current\n        ? geInputCaretPosition(focusedElm.current)\n        : undefined;\n    // needed to prevent warning with useLayoutEffect on server\n    var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n    useIsomorphicLayoutEffect(function () {\n        var input = focusedElm.current;\n        if (formattedValue !== lastUpdatedValue.current.formattedValue && input) {\n            var caretPos = getNewCaretPosition(lastUpdatedValue.current.formattedValue, formattedValue, currentCaretPosition);\n            /**\n             * set the value imperatively, as we set the caret position as well imperatively.\n             * This is to keep value and caret position in sync\n             */\n            input.value = formattedValue;\n            setPatchedCaretPosition(input, caretPos, formattedValue);\n        }\n    }, [formattedValue]);\n    var formatInputValue = function (inputValue, event, source) {\n        var input = event.target;\n        var changeRange = caretPositionBeforeChange.current\n            ? findChangedRangeFromCaretPositions(caretPositionBeforeChange.current, input.selectionEnd)\n            : findChangeRange(formattedValue, inputValue);\n        var changeMeta = Object.assign(Object.assign({}, changeRange), { lastValue: formattedValue });\n        var _numAsString = removeFormatting(inputValue, changeMeta);\n        var _formattedValue = _format(_numAsString);\n        // formatting can remove some of the number chars, so we need to fine number string again\n        _numAsString = removeFormatting(_formattedValue, undefined);\n        if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {\n            //reset the caret position\n            var input$1 = event.target;\n            var currentCaretPosition = geInputCaretPosition(input$1);\n            var caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);\n            input$1.value = formattedValue;\n            setPatchedCaretPosition(input$1, caretPos, formattedValue);\n            return false;\n        }\n        updateValueAndCaretPosition({\n            formattedValue: _formattedValue,\n            numAsString: _numAsString,\n            inputValue: inputValue,\n            event: event,\n            source: source,\n            input: event.target,\n        });\n        return true;\n    };\n    var setCaretPositionInfoBeforeChange = function (el, endOffset) {\n        if ( endOffset === void 0 ) endOffset = 0;\n\n        var selectionStart = el.selectionStart;\n        var selectionEnd = el.selectionEnd;\n        caretPositionBeforeChange.current = { selectionStart: selectionStart, selectionEnd: selectionEnd + endOffset };\n    };\n    var _onChange = function (e) {\n        var el = e.target;\n        var inputValue = el.value;\n        var changed = formatInputValue(inputValue, e, SourceType.event);\n        if (changed)\n            { onChange(e); }\n        // reset the position, as we have already handled the caret position\n        caretPositionBeforeChange.current = undefined;\n    };\n    var _onKeyDown = function (e) {\n        var el = e.target;\n        var key = e.key;\n        var selectionStart = el.selectionStart;\n        var selectionEnd = el.selectionEnd;\n        var value = el.value; if ( value === void 0 ) value = '';\n        var expectedCaretPosition;\n        //Handle backspace and delete against non numerical/decimal characters or arrow keys\n        if (key === 'ArrowLeft' || key === 'Backspace') {\n            expectedCaretPosition = Math.max(selectionStart - 1, 0);\n        }\n        else if (key === 'ArrowRight') {\n            expectedCaretPosition = Math.min(selectionStart + 1, value.length);\n        }\n        else if (key === 'Delete') {\n            expectedCaretPosition = selectionStart;\n        }\n        // if key is delete and text is not selected keep the end offset to 1, as it deletes one character\n        // this is required as selection is not changed on delete case, which changes the change range calculation\n        var endOffset = 0;\n        if (key === 'Delete' && selectionStart === selectionEnd) {\n            endOffset = 1;\n        }\n        var isArrowKey = key === 'ArrowLeft' || key === 'ArrowRight';\n        //if expectedCaretPosition is not set it means we don't want to Handle keyDown\n        // also if multiple characters are selected don't handle\n        if (expectedCaretPosition === undefined || (selectionStart !== selectionEnd && !isArrowKey)) {\n            onKeyDown(e);\n            // keep information of what was the caret position before keyDown\n            // set it after onKeyDown, in case parent updates the position manually\n            setCaretPositionInfoBeforeChange(el, endOffset);\n            return;\n        }\n        var newCaretPosition = expectedCaretPosition;\n        if (isArrowKey) {\n            var direction = key === 'ArrowLeft' ? 'left' : 'right';\n            newCaretPosition = correctCaretPosition(value, expectedCaretPosition, direction);\n            // arrow left or right only moves the caret, so no need to handle the event, if we are handling it manually\n            if (newCaretPosition !== expectedCaretPosition) {\n                e.preventDefault();\n            }\n        }\n        else if (key === 'Delete' && !isValidInputCharacter(value[expectedCaretPosition])) {\n            // in case of delete go to closest caret boundary on the right side\n            newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'right');\n        }\n        else if (key === 'Backspace' && !isValidInputCharacter(value[expectedCaretPosition])) {\n            // in case of backspace go to closest caret boundary on the left side\n            newCaretPosition = correctCaretPosition(value, expectedCaretPosition, 'left');\n        }\n        if (newCaretPosition !== expectedCaretPosition) {\n            setPatchedCaretPosition(el, newCaretPosition, value);\n        }\n        onKeyDown(e);\n        setCaretPositionInfoBeforeChange(el, endOffset);\n    };\n    /** required to handle the caret position when click anywhere within the input **/\n    var _onMouseUp = function (e) {\n        var el = e.target;\n        /**\n         * NOTE: we have to give default value for value as in case when custom input is provided\n         * value can come as undefined when nothing is provided on value prop.\n         */\n        var correctCaretPositionIfRequired = function () {\n            var selectionStart = el.selectionStart;\n            var selectionEnd = el.selectionEnd;\n            var value = el.value; if ( value === void 0 ) value = '';\n            if (selectionStart === selectionEnd) {\n                var caretPosition = correctCaretPosition(value, selectionStart);\n                if (caretPosition !== selectionStart) {\n                    setPatchedCaretPosition(el, caretPosition, value);\n                }\n            }\n        };\n        correctCaretPositionIfRequired();\n        // try to correct after selection has updated by browser\n        // this case is required when user clicks on some position while a text is selected on input\n        requestAnimationFrame(function () {\n            correctCaretPositionIfRequired();\n        });\n        onMouseUp(e);\n        setCaretPositionInfoBeforeChange(el);\n    };\n    var _onFocus = function (e) {\n        // Workaround Chrome and Safari bug https://bugs.chromium.org/p/chromium/issues/detail?id=779328\n        // (onFocus event target selectionStart is always 0 before setTimeout)\n        if (e.persist)\n            { e.persist(); }\n        var el = e.target;\n        var currentTarget = e.currentTarget;\n        focusedElm.current = el;\n        timeout.current.focusTimeout = setTimeout(function () {\n            var selectionStart = el.selectionStart;\n            var selectionEnd = el.selectionEnd;\n            var value = el.value; if ( value === void 0 ) value = '';\n            var caretPosition = correctCaretPosition(value, selectionStart);\n            //setPatchedCaretPosition only when everything is not selected on focus (while tabbing into the field)\n            if (caretPosition !== selectionStart &&\n                !(selectionStart === 0 && selectionEnd === value.length)) {\n                setPatchedCaretPosition(el, caretPosition, value);\n            }\n            onFocus(Object.assign(Object.assign({}, e), { currentTarget: currentTarget }));\n        }, 0);\n    };\n    var _onBlur = function (e) {\n        focusedElm.current = null;\n        clearTimeout(timeout.current.focusTimeout);\n        clearTimeout(timeout.current.setCaretTimeout);\n        onBlur(e);\n    };\n    // add input mode on element based on format prop and device once the component is mounted\n    var inputMode = mounted && addInputMode() ? 'numeric' : undefined;\n    var inputProps = Object.assign({ inputMode: inputMode }, otherProps, {\n        type: type,\n        value: formattedValue,\n        onChange: _onChange,\n        onKeyDown: _onKeyDown,\n        onMouseUp: _onMouseUp,\n        onFocus: _onFocus,\n        onBlur: _onBlur,\n    });\n    if (displayType === 'text') {\n        return renderText ? (React.createElement(React.Fragment, null, renderText(formattedValue, otherProps) || null)) : (React.createElement(\"span\", Object.assign({}, otherProps, { ref: getInputRef }), formattedValue));\n    }\n    else if (customInput) {\n        var CustomInput = customInput;\n        /* @ts-ignore */\n        return React.createElement(CustomInput, Object.assign({}, inputProps, { ref: getInputRef }));\n    }\n    return React.createElement(\"input\", Object.assign({}, inputProps, { ref: getInputRef }));\n}\n\nfunction format(numStr, props) {\n    var decimalScale = props.decimalScale;\n    var fixedDecimalScale = props.fixedDecimalScale;\n    var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n    var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n    var allowNegative = props.allowNegative;\n    var thousandsGroupStyle = props.thousandsGroupStyle; if ( thousandsGroupStyle === void 0 ) thousandsGroupStyle = 'thousand';\n    // don't apply formatting on empty string or '-'\n    if (numStr === '' || numStr === '-') {\n        return numStr;\n    }\n    var ref = getSeparators(props);\n    var thousandSeparator = ref.thousandSeparator;\n    var decimalSeparator = ref.decimalSeparator;\n    /**\n     * Keep the decimal separator\n     * when decimalScale is not defined or non zero and the numStr has decimal in it\n     * Or if decimalScale is > 0 and fixeDecimalScale is true (even if numStr has no decimal)\n     */\n    var hasDecimalSeparator = (decimalScale !== 0 && numStr.indexOf('.') !== -1) || (decimalScale && fixedDecimalScale);\n    var ref$1 = splitDecimal(numStr, allowNegative);\n    var beforeDecimal = ref$1.beforeDecimal;\n    var afterDecimal = ref$1.afterDecimal;\n    var addNegation = ref$1.addNegation; // eslint-disable-line prefer-const\n    //apply decimal precision if its defined\n    if (decimalScale !== undefined) {\n        afterDecimal = limitToScale(afterDecimal, decimalScale, !!fixedDecimalScale);\n    }\n    if (thousandSeparator) {\n        beforeDecimal = applyThousandSeparator(beforeDecimal, thousandSeparator, thousandsGroupStyle);\n    }\n    //add prefix and suffix when there is a number present\n    if (prefix)\n        { beforeDecimal = prefix + beforeDecimal; }\n    if (suffix)\n        { afterDecimal = afterDecimal + suffix; }\n    //restore negation sign\n    if (addNegation)\n        { beforeDecimal = '-' + beforeDecimal; }\n    numStr = beforeDecimal + ((hasDecimalSeparator && decimalSeparator) || '') + afterDecimal;\n    return numStr;\n}\nfunction getSeparators(props) {\n    var decimalSeparator = props.decimalSeparator; if ( decimalSeparator === void 0 ) decimalSeparator = '.';\n    var thousandSeparator = props.thousandSeparator;\n    var allowedDecimalSeparators = props.allowedDecimalSeparators;\n    if (thousandSeparator === true) {\n        thousandSeparator = ',';\n    }\n    if (!allowedDecimalSeparators) {\n        allowedDecimalSeparators = [decimalSeparator, '.'];\n    }\n    return {\n        decimalSeparator: decimalSeparator,\n        thousandSeparator: thousandSeparator,\n        allowedDecimalSeparators: allowedDecimalSeparators,\n    };\n}\nfunction handleNegation(value, allowNegative) {\n    if ( value === void 0 ) value = '';\n\n    var negationRegex = new RegExp('(-)');\n    var doubleNegationRegex = new RegExp('(-)(.)*(-)');\n    // Check number has '-' value\n    var hasNegation = negationRegex.test(value);\n    // Check number has 2 or more '-' values\n    var removeNegation = doubleNegationRegex.test(value);\n    //remove negation\n    value = value.replace(/-/g, '');\n    if (hasNegation && !removeNegation && allowNegative) {\n        value = '-' + value;\n    }\n    return value;\n}\nfunction getNumberRegex(decimalSeparator, global) {\n    return new RegExp((\"(^-)|[0-9]|\" + (escapeRegExp(decimalSeparator))), global ? 'g' : undefined);\n}\nfunction isNumericString(val, prefix, suffix) {\n    // for empty value we can always treat it as numeric string\n    if (val === '')\n        { return true; }\n    return (!(prefix === null || prefix === void 0 ? void 0 : prefix.match(/\\d/)) && !(suffix === null || suffix === void 0 ? void 0 : suffix.match(/\\d/)) && typeof val === 'string' && !isNaN(Number(val)));\n}\nfunction removeFormatting(value, changeMeta, props) {\n    var assign;\n\n    if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n    var allowNegative = props.allowNegative;\n    var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n    var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n    var decimalScale = props.decimalScale;\n    var from = changeMeta.from;\n    var to = changeMeta.to;\n    var start = to.start;\n    var end = to.end;\n    var ref = getSeparators(props);\n    var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n    var decimalSeparator = ref.decimalSeparator;\n    var isBeforeDecimalSeparator = value[end] === decimalSeparator;\n    /**\n     * If only a number is added on empty input which matches with the prefix or suffix,\n     * then don't remove it, just return the same\n     */\n    if (charIsNumber(value) &&\n        (value === prefix || value === suffix) &&\n        changeMeta.lastValue === '') {\n        return value;\n    }\n    /** Check for any allowed decimal separator is added in the numeric format and replace it with decimal separator */\n    if (end - start === 1 && allowedDecimalSeparators.indexOf(value[start]) !== -1) {\n        var separator = decimalScale === 0 ? '' : decimalSeparator;\n        value = value.substring(0, start) + separator + value.substring(start + 1, value.length);\n    }\n    var stripNegation = function (value, start, end) {\n        /**\n         * if prefix starts with - we don't allow negative number to avoid confusion\n         * if suffix starts with - and the value length is same as suffix length, then the - sign is from the suffix\n         * In other cases, if the value starts with - then it is a negation\n         */\n        var hasNegation = false;\n        var hasDoubleNegation = false;\n        if (prefix.startsWith('-')) {\n            hasNegation = false;\n        }\n        else if (value.startsWith('--')) {\n            hasNegation = false;\n            hasDoubleNegation = true;\n        }\n        else if (suffix.startsWith('-') && value.length === suffix.length) {\n            hasNegation = false;\n        }\n        else if (value[0] === '-') {\n            hasNegation = true;\n        }\n        var charsToRemove = hasNegation ? 1 : 0;\n        if (hasDoubleNegation)\n            { charsToRemove = 2; }\n        // remove negation/double negation from start to simplify prefix logic as negation comes before prefix\n        if (charsToRemove) {\n            value = value.substring(charsToRemove);\n            // account for the removal of the negation for start and end index\n            start -= charsToRemove;\n            end -= charsToRemove;\n        }\n        return { value: value, start: start, end: end, hasNegation: hasNegation };\n    };\n    var toMetadata = stripNegation(value, start, end);\n    var hasNegation = toMetadata.hasNegation;\n    ((assign = toMetadata, value = assign.value, start = assign.start, end = assign.end));\n    var ref$1 = stripNegation(changeMeta.lastValue, from.start, from.end);\n    var fromStart = ref$1.start;\n    var fromEnd = ref$1.end;\n    var lastValue = ref$1.value;\n    // if only prefix and suffix part is updated reset the value to last value\n    // if the changed range is from suffix in the updated value, and the the suffix starts with the same characters, allow the change\n    var updatedSuffixPart = value.substring(start, end);\n    if (value.length &&\n        lastValue.length &&\n        (fromStart > lastValue.length - suffix.length || fromEnd < prefix.length) &&\n        !(updatedSuffixPart && suffix.startsWith(updatedSuffixPart))) {\n        value = lastValue;\n    }\n    /**\n     * remove prefix\n     * Remove whole prefix part if its present on the value\n     * If the prefix is partially deleted (in which case change start index will be less the prefix length)\n     * Remove only partial part of prefix.\n     */\n    var startIndex = 0;\n    if (value.startsWith(prefix))\n        { startIndex += prefix.length; }\n    else if (start < prefix.length)\n        { startIndex = start; }\n    value = value.substring(startIndex);\n    // account for deleted prefix for end\n    end -= startIndex;\n    /**\n     * Remove suffix\n     * Remove whole suffix part if its present on the value\n     * If the suffix is partially deleted (in which case change end index will be greater than the suffixStartIndex)\n     * remove the partial part of suffix\n     */\n    var endIndex = value.length;\n    var suffixStartIndex = value.length - suffix.length;\n    if (value.endsWith(suffix))\n        { endIndex = suffixStartIndex; }\n    // if the suffix is removed from the end\n    else if (end > suffixStartIndex)\n        { endIndex = end; }\n    // if the suffix is removed from start\n    else if (end > value.length - suffix.length)\n        { endIndex = end; }\n    value = value.substring(0, endIndex);\n    // add the negation back and handle for double negation\n    value = handleNegation(hasNegation ? (\"-\" + value) : value, allowNegative);\n    // remove non numeric characters\n    value = (value.match(getNumberRegex(decimalSeparator, true)) || []).join('');\n    // replace the decimalSeparator with ., and only keep the first separator, ignore following ones\n    var firstIndex = value.indexOf(decimalSeparator);\n    value = value.replace(new RegExp(escapeRegExp(decimalSeparator), 'g'), function (match, index) {\n        return index === firstIndex ? '.' : '';\n    });\n    //check if beforeDecimal got deleted and there is nothing after decimal,\n    //clear all numbers in such case while keeping the - sign\n    var ref$2 = splitDecimal(value, allowNegative);\n    var beforeDecimal = ref$2.beforeDecimal;\n    var afterDecimal = ref$2.afterDecimal;\n    var addNegation = ref$2.addNegation; // eslint-disable-line prefer-const\n    //clear only if something got deleted before decimal (cursor is before decimal)\n    if (to.end - to.start < from.end - from.start &&\n        beforeDecimal === '' &&\n        isBeforeDecimalSeparator &&\n        !parseFloat(afterDecimal)) {\n        value = addNegation ? '-' : '';\n    }\n    return value;\n}\nfunction getCaretBoundary(formattedValue, props) {\n    var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n    var suffix = props.suffix; if ( suffix === void 0 ) suffix = '';\n    var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n    var hasNegation = formattedValue[0] === '-';\n    // fill for prefix and negation\n    // Cap the fill range so we never exceed the array length when the formatted value\n    // is just '-' (negation only, e.g. during intermediate typing with a multi-char prefix)\n    boundaryAry.fill(false, 0, Math.min(prefix.length + (hasNegation ? 1 : 0), formattedValue.length));\n    // fill for suffix\n    var valLn = formattedValue.length;\n    boundaryAry.fill(false, valLn - suffix.length + 1, valLn + 1);\n    return boundaryAry;\n}\nfunction validateAndUpdateProps(props) {\n    var ref = getSeparators(props);\n    var thousandSeparator = ref.thousandSeparator;\n    var decimalSeparator = ref.decimalSeparator;\n    // eslint-disable-next-line prefer-const\n    var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n    var allowNegative = props.allowNegative; if ( allowNegative === void 0 ) allowNegative = true;\n    if (thousandSeparator === decimalSeparator) {\n        throw new Error((\"\\n        Decimal separator can't be same as thousand separator.\\n        thousandSeparator: \" + thousandSeparator + \" (thousandSeparator = {true} is same as thousandSeparator = \\\",\\\")\\n        decimalSeparator: \" + decimalSeparator + \" (default value for decimalSeparator is .)\\n     \"));\n    }\n    if (prefix.startsWith('-') && allowNegative) {\n        // TODO: throw error in next major version\n        console.error((\"\\n      Prefix can't start with '-' when allowNegative is true.\\n      prefix: \" + prefix + \"\\n      allowNegative: \" + allowNegative + \"\\n    \"));\n        allowNegative = false;\n    }\n    return Object.assign(Object.assign({}, props), { allowNegative: allowNegative });\n}\nfunction useNumericFormat(props) {\n    // validate props\n    props = validateAndUpdateProps(props);\n    var _decimalSeparator = props.decimalSeparator;\n    var _allowedDecimalSeparators = props.allowedDecimalSeparators;\n    var thousandsGroupStyle = props.thousandsGroupStyle;\n    var suffix = props.suffix;\n    var allowNegative = props.allowNegative;\n    var allowLeadingZeros = props.allowLeadingZeros;\n    var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n    var onBlur = props.onBlur; if ( onBlur === void 0 ) onBlur = noop;\n    var thousandSeparator = props.thousandSeparator;\n    var decimalScale = props.decimalScale;\n    var fixedDecimalScale = props.fixedDecimalScale;\n    var prefix = props.prefix; if ( prefix === void 0 ) prefix = '';\n    var defaultValue = props.defaultValue;\n    var value = props.value;\n    var valueIsNumericString = props.valueIsNumericString;\n    var onValueChange = props.onValueChange;\n    var restProps = __rest(props, [\"decimalSeparator\", \"allowedDecimalSeparators\", \"thousandsGroupStyle\", \"suffix\", \"allowNegative\", \"allowLeadingZeros\", \"onKeyDown\", \"onBlur\", \"thousandSeparator\", \"decimalScale\", \"fixedDecimalScale\", \"prefix\", \"defaultValue\", \"value\", \"valueIsNumericString\", \"onValueChange\"]);\n    // get derived decimalSeparator and allowedDecimalSeparators\n    var ref = getSeparators(props);\n    var decimalSeparator = ref.decimalSeparator;\n    var allowedDecimalSeparators = ref.allowedDecimalSeparators;\n    var _format = function (numStr) { return format(numStr, props); };\n    var _removeFormatting = function (inputValue, changeMeta) { return removeFormatting(inputValue, changeMeta, props); };\n    var _value = isNil(value) ? defaultValue : value;\n    // try to figure out isValueNumericString based on format prop and value\n    var _valueIsNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString(_value, prefix, suffix);\n    if (!isNil(value)) {\n        _valueIsNumericString = _valueIsNumericString || typeof value === 'number';\n    }\n    else if (!isNil(defaultValue)) {\n        _valueIsNumericString = _valueIsNumericString || typeof defaultValue === 'number';\n    }\n    var roundIncomingValueToPrecision = function (value) {\n        if (isNotValidValue(value))\n            { return value; }\n        if (typeof value === 'number') {\n            value = toNumericString(value);\n        }\n        /**\n         * only round numeric or float string values coming through props,\n         * we don't need to do it for onChange events, as we want to prevent typing there\n         */\n        if (_valueIsNumericString && typeof decimalScale === 'number') {\n            return roundToPrecision(value, decimalScale, Boolean(fixedDecimalScale));\n        }\n        return value;\n    };\n    var ref$1 = useInternalValues(roundIncomingValueToPrecision(value), roundIncomingValueToPrecision(defaultValue), Boolean(_valueIsNumericString), _format, _removeFormatting, onValueChange);\n    var ref$1_0 = ref$1[0];\n    var numAsString = ref$1_0.numAsString;\n    var formattedValue = ref$1_0.formattedValue;\n    var _onValueChange = ref$1[1];\n    var _onKeyDown = function (e) {\n        var el = e.target;\n        var key = e.key;\n        var selectionStart = el.selectionStart;\n        var selectionEnd = el.selectionEnd;\n        var value = el.value; if ( value === void 0 ) value = '';\n        // if user tries to delete partial prefix then ignore it\n        // Exception: when value is just '-' (negation-only, no prefix shown yet), the cursor\n        // is at position 1 which is < prefix.length for multi-char prefixes — we must allow\n        // backspace to delete the lone negation sign in this state\n        if ((key === 'Backspace' || key === 'Delete') && selectionEnd < prefix.length && value !== '-') {\n            e.preventDefault();\n            return;\n        }\n        // if multiple characters are selected and user hits backspace, no need to handle anything manually\n        if (selectionStart !== selectionEnd) {\n            onKeyDown(e);\n            return;\n        }\n        // if user hits backspace, while the cursor is before prefix, and the input has negation, remove the negation\n        if (key === 'Backspace' &&\n            value[0] === '-' &&\n            selectionStart === prefix.length + 1 &&\n            allowNegative) {\n            // bring the cursor to after negation\n            setCaretPosition(el, 1);\n        }\n        // don't allow user to delete decimal separator when decimalScale and fixedDecimalScale is set\n        if (decimalScale && fixedDecimalScale) {\n            if (key === 'Backspace' && value[selectionStart - 1] === decimalSeparator) {\n                setCaretPosition(el, selectionStart - 1);\n                e.preventDefault();\n            }\n            else if (key === 'Delete' && value[selectionStart] === decimalSeparator) {\n                e.preventDefault();\n            }\n        }\n        // if user presses the allowed decimal separator before the separator, move the cursor after the separator\n        if ((allowedDecimalSeparators === null || allowedDecimalSeparators === void 0 ? void 0 : allowedDecimalSeparators.includes(key)) && value[selectionStart] === decimalSeparator) {\n            setCaretPosition(el, selectionStart + 1);\n        }\n        var _thousandSeparator = thousandSeparator === true ? ',' : thousandSeparator;\n        // move cursor when delete or backspace is pressed before/after thousand separator\n        if (key === 'Backspace' && value[selectionStart - 1] === _thousandSeparator) {\n            setCaretPosition(el, selectionStart - 1);\n        }\n        if (key === 'Delete' && value[selectionStart] === _thousandSeparator) {\n            setCaretPosition(el, selectionStart + 1);\n        }\n        onKeyDown(e);\n    };\n    var _onBlur = function (e) {\n        var _value = numAsString;\n        // if there no no numeric value, clear the input\n        if (!_value.match(/\\d/g)) {\n            _value = '';\n        }\n        // clear leading 0s\n        if (!allowLeadingZeros) {\n            _value = fixLeadingZero(_value);\n        }\n        // apply fixedDecimalScale on blur event\n        if (fixedDecimalScale && decimalScale) {\n            _value = roundToPrecision(_value, decimalScale, fixedDecimalScale);\n        }\n        if (_value !== numAsString) {\n            var formattedValue = format(_value, props);\n            _onValueChange({\n                formattedValue: formattedValue,\n                value: _value,\n                floatValue: parseFloat(_value),\n            }, {\n                event: e,\n                source: SourceType.event,\n            });\n        }\n        onBlur(e);\n    };\n    var isValidInputCharacter = function (inputChar) {\n        if (inputChar === decimalSeparator)\n            { return true; }\n        return charIsNumber(inputChar);\n    };\n    var isCharacterSame = function (ref) {\n        var currentValue = ref.currentValue;\n        var lastValue = ref.lastValue;\n        var formattedValue = ref.formattedValue;\n        var currentValueIndex = ref.currentValueIndex;\n        var formattedValueIndex = ref.formattedValueIndex;\n\n        var curChar = currentValue[currentValueIndex];\n        var newChar = formattedValue[formattedValueIndex];\n        /**\n         * NOTE: as thousand separator and allowedDecimalSeparators can be same, we need to check on\n         * typed range if we have typed any character from allowedDecimalSeparators, in that case we\n         * consider different characters like , and . same within the range of updated value.\n         */\n        var typedRange = findChangeRange(lastValue, currentValue);\n        var to = typedRange.to;\n        // handle corner case where if we user types a decimal separator with fixedDecimalScale\n        // and pass back float value the cursor jumps. #851\n        var getDecimalSeparatorIndex = function (value) {\n            return _removeFormatting(value).indexOf('.') + prefix.length;\n        };\n        if (value === 0 &&\n            fixedDecimalScale &&\n            decimalScale &&\n            currentValue[to.start] === decimalSeparator &&\n            getDecimalSeparatorIndex(currentValue) < currentValueIndex &&\n            getDecimalSeparatorIndex(formattedValue) > formattedValueIndex) {\n            return false;\n        }\n        if (currentValueIndex >= to.start &&\n            currentValueIndex < to.end &&\n            allowedDecimalSeparators &&\n            allowedDecimalSeparators.includes(curChar) &&\n            newChar === decimalSeparator) {\n            return true;\n        }\n        return curChar === newChar;\n    };\n    return Object.assign(Object.assign({}, restProps), { value: formattedValue, valueIsNumericString: false, isValidInputCharacter: isValidInputCharacter,\n        isCharacterSame: isCharacterSame, onValueChange: _onValueChange, format: _format, removeFormatting: _removeFormatting, getCaretBoundary: function (formattedValue) { return getCaretBoundary(formattedValue, props); }, onKeyDown: _onKeyDown, onBlur: _onBlur });\n}\nfunction NumericFormat(props) {\n    var numericFormatProps = useNumericFormat(props);\n    return React.createElement(NumberFormatBase, Object.assign({}, numericFormatProps));\n}\n\nfunction format$1(numStr, props) {\n    var format = props.format;\n    var allowEmptyFormatting = props.allowEmptyFormatting;\n    var mask = props.mask;\n    var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n    if (numStr === '' && !allowEmptyFormatting)\n        { return ''; }\n    var hashCount = 0;\n    var formattedNumberAry = format.split('');\n    for (var i = 0, ln = format.length; i < ln; i++) {\n        if (format[i] === patternChar) {\n            formattedNumberAry[i] = numStr[hashCount] || getMaskAtIndex(mask, hashCount);\n            hashCount += 1;\n        }\n    }\n    return formattedNumberAry.join('');\n}\nfunction removeFormatting$1(value, changeMeta, props) {\n    if ( changeMeta === void 0 ) changeMeta = getDefaultChangeMeta(value);\n\n    var format = props.format;\n    var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n    var from = changeMeta.from;\n    var to = changeMeta.to;\n    var lastValue = changeMeta.lastValue; if ( lastValue === void 0 ) lastValue = '';\n    var isNumericSlot = function (caretPos) { return format[caretPos] === patternChar; };\n    var removeFormatChar = function (string, startIndex) {\n        var str = '';\n        for (var i = 0; i < string.length; i++) {\n            if (isNumericSlot(startIndex + i) && charIsNumber(string[i])) {\n                str += string[i];\n            }\n        }\n        return str;\n    };\n    var extractNumbers = function (str) { return str.replace(/[^0-9]/g, ''); };\n    // if format doesn't have any number, remove all the non numeric characters\n    if (!format.match(/\\d/)) {\n        return extractNumbers(value);\n    }\n    /**\n     * if user paste the whole formatted text in an empty input or doing select all and paste, check if matches to the pattern\n     * and remove the format characters, if there is a mismatch on the pattern, do plane number extract\n     */\n    if ((lastValue === '' || from.end - from.start === lastValue.length) &&\n        value.length === format.length) {\n        var str = '';\n        for (var i = 0; i < value.length; i++) {\n            if (isNumericSlot(i)) {\n                if (charIsNumber(value[i])) {\n                    str += value[i];\n                }\n            }\n            else if (value[i] !== format[i]) {\n                // if there is a mismatch on the pattern, do plane number extract\n                return extractNumbers(value);\n            }\n        }\n        return str;\n    }\n    /**\n     * For partial change,\n     * where ever there is a change on the input, we can break the number in three parts\n     * 1st: left part which is unchanged\n     * 2nd: middle part which is changed\n     * 3rd: right part which is unchanged\n     *\n     * The first and third section will be same as last value, only the middle part will change\n     * We can consider on the change part all the new characters are non format characters.\n     * And on the first and last section it can have partial format characters.\n     *\n     * We pick first and last section from the lastValue (as that has 1-1 mapping with format)\n     * and middle one from the update value.\n     */\n    var firstSection = lastValue.substring(0, from.start);\n    var middleSection = value.substring(to.start, to.end);\n    var lastSection = lastValue.substring(from.end);\n    return (\"\" + (removeFormatChar(firstSection, 0)) + (extractNumbers(middleSection)) + (removeFormatChar(lastSection, from.end)));\n}\nfunction getCaretBoundary$1(formattedValue, props) {\n    var format = props.format;\n    var mask = props.mask;\n    var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n    var boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(function () { return true; });\n    var hashCount = 0;\n    var firstEmptySlot = -1;\n    var maskAndIndexMap = {};\n    format.split('').forEach(function (char, index) {\n        var maskAtIndex = undefined;\n        if (char === patternChar) {\n            hashCount++;\n            maskAtIndex = getMaskAtIndex(mask, hashCount - 1);\n            if (firstEmptySlot === -1 && formattedValue[index] === maskAtIndex) {\n                firstEmptySlot = index;\n            }\n        }\n        maskAndIndexMap[index] = maskAtIndex;\n    });\n    var isPosAllowed = function (pos) {\n        // the position is allowed if the position is not masked and valid number area\n        return format[pos] === patternChar && formattedValue[pos] !== maskAndIndexMap[pos];\n    };\n    for (var i = 0, ln = boundaryAry.length; i < ln; i++) {\n        // consider caret to be in boundary if it is before or after numeric value\n        // Note: on pattern based format its denoted by patternCharacter\n        // we should also allow user to put cursor on first empty slot\n        boundaryAry[i] = i === firstEmptySlot || isPosAllowed(i) || isPosAllowed(i - 1);\n    }\n    // the first patternChar position is always allowed\n    boundaryAry[format.indexOf(patternChar)] = true;\n    return boundaryAry;\n}\nfunction validateProps(props) {\n    var mask = props.mask;\n    if (mask) {\n        var maskAsStr = mask === 'string' ? mask : mask.toString();\n        if (maskAsStr.match(/\\d/g)) {\n            throw new Error((\"Mask \" + mask + \" should not contain numeric character;\"));\n        }\n    }\n}\nfunction isNumericString$1(val, format) {\n    //we can treat empty string as numeric string\n    if (val === '')\n        { return true; }\n    return !(format === null || format === void 0 ? void 0 : format.match(/\\d/)) && typeof val === 'string' && (!!val.match(/^\\d+$/) || val === '');\n}\nfunction usePatternFormat(props) {\n    var mask = props.mask;\n    var allowEmptyFormatting = props.allowEmptyFormatting;\n    var formatProp = props.format;\n    var inputMode = props.inputMode; if ( inputMode === void 0 ) inputMode = 'numeric';\n    var onKeyDown = props.onKeyDown; if ( onKeyDown === void 0 ) onKeyDown = noop;\n    var patternChar = props.patternChar; if ( patternChar === void 0 ) patternChar = '#';\n    var value = props.value;\n    var defaultValue = props.defaultValue;\n    var valueIsNumericString = props.valueIsNumericString;\n    var restProps = __rest(props, [\"mask\", \"allowEmptyFormatting\", \"format\", \"inputMode\", \"onKeyDown\", \"patternChar\", \"value\", \"defaultValue\", \"valueIsNumericString\"]);\n    // validate props\n    validateProps(props);\n    var _getCaretBoundary = function (formattedValue) {\n        return getCaretBoundary$1(formattedValue, props);\n    };\n    var _onKeyDown = function (e) {\n        var key = e.key;\n        var el = e.target;\n        var selectionStart = el.selectionStart;\n        var selectionEnd = el.selectionEnd;\n        var value = el.value;\n        // if multiple characters are selected and user hits backspace, no need to handle anything manually\n        if (selectionStart !== selectionEnd) {\n            onKeyDown(e);\n            return;\n        }\n        // bring the cursor to closest numeric section\n        var caretPos = selectionStart;\n        // if backspace is pressed after the format characters, bring it to numeric section\n        // if delete is pressed before the format characters, bring it to numeric section\n        if (key === 'Backspace' || key === 'Delete') {\n            var direction = 'right';\n            if (key === 'Backspace') {\n                while (caretPos > 0 && formatProp[caretPos - 1] !== patternChar) {\n                    caretPos--;\n                }\n                direction = 'left';\n            }\n            else {\n                var formatLn = formatProp.length;\n                while (caretPos < formatLn && formatProp[caretPos] !== patternChar) {\n                    caretPos++;\n                }\n                direction = 'right';\n            }\n            caretPos = getCaretPosInBoundary(value, caretPos, _getCaretBoundary(value), direction);\n        }\n        else if (formatProp[caretPos] !== patternChar &&\n            key !== 'ArrowLeft' &&\n            key !== 'ArrowRight') {\n            // if user is typing on format character position, bring user to next allowed caret position\n            caretPos = getCaretPosInBoundary(value, caretPos + 1, _getCaretBoundary(value), 'right');\n        }\n        // if we changing caret position, set the caret position\n        if (caretPos !== selectionStart) {\n            setCaretPosition(el, caretPos);\n        }\n        onKeyDown(e);\n    };\n    // try to figure out isValueNumericString based on format prop and value\n    var _value = isNil(value) ? defaultValue : value;\n    var isValueNumericString = valueIsNumericString !== null && valueIsNumericString !== void 0 ? valueIsNumericString : isNumericString$1(_value, formatProp);\n    var _props = Object.assign(Object.assign({}, props), { valueIsNumericString: isValueNumericString });\n    return Object.assign(Object.assign({}, restProps), { value: value,\n        defaultValue: defaultValue, valueIsNumericString: isValueNumericString, inputMode: inputMode, format: function (numStr) { return format$1(numStr, _props); }, removeFormatting: function (inputValue, changeMeta) { return removeFormatting$1(inputValue, changeMeta, _props); }, getCaretBoundary: _getCaretBoundary, onKeyDown: _onKeyDown });\n}\nfunction PatternFormat(props) {\n    var patternFormatProps = usePatternFormat(props);\n    return React.createElement(NumberFormatBase, Object.assign({}, patternFormatProps));\n}\n\nexport { NumberFormatBase, NumericFormat, PatternFormat, getCaretBoundary as getNumericCaretBoundary, getCaretBoundary$1 as getPatternCaretBoundary, format as numericFormatter, format$1 as patternFormatter, removeFormatting as removeNumericFormat, removeFormatting$1 as removePatternFormat, useNumericFormat, usePatternFormat };\n","import { clsx } from 'clsx';\n\n/**\n * Estilos compartidos de los controles de formulario de MasterDocument.\n *\n * Viven aquí y no dentro de `FieldRenderer` porque había DOS copias de\n * `readonlyBase` —una en `FieldRenderer` y otra en `LookupReadonlyValue`— y\n * divergieron: la primera pasó a `flex items-center h-10` (§D.2, el alto del\n * control editable) y la segunda se quedó en `py-1.5`. Medido en dev el\n * 2026-09-09 sobre el modal de línea de una devolución de venta, pestaña\n * «Centros y Dimensiones»: los tres campos searcher de sólo lectura y sin dato\n * medían **12px de alto** —el padding y nada más— mientras sus vecinos con\n * texto medían 40. La rejilla del formulario quedaba dentada.\n *\n * `FieldRenderer` no puede exportarlos porque importa `LookupReadonlyValue`, y\n * la importación al revés cerraría el ciclo.\n */\n\n/**\n * Alto de control del canon (§D.2): `h-10` (40px) para todo control de UNA\n * línea. NO se mete en `inputBase` porque ahí lo heredaría también el\n * `textarea`, que es multilínea y tiene su propio `min-h-[72px]`.\n */\nexport const controlHeight = 'h-10';\n\n/**\n * Caja de un valor en SOLO LECTURA. Mismo alto que el control editable: si\n * difiere, la rejilla salta al pasar de vista a edición y las dos lecturas del\n * formulario no cuadran. `flex items-center` es lo que centra el texto dentro\n * de esos 40px y lo que sostiene la altura cuando el valor está vacío.\n */\nexport const readonlyBase = clsx(\n  'flex items-center w-full h-10 rounded-md bg-background-secondary px-3 text-sm text-content-primary select-none',\n  'dark:bg-dark-bg-secondary dark:text-dark-content-primary',\n);\n","import {\n  createContext,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n  type ReactNode,\n} from 'react';\nimport { clsx } from 'clsx';\nimport { interpolateTemplate } from '../LookupField/utils';\nimport { Loading } from './components/loading';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { Fetcher } from '../LookupField/services/api.types';\nimport type { LookupFieldConfig } from './MasterDocument.types';\n// La MISMA caja que pinta `ReadonlyField`, no una copia: la que vivía aquí se\n// quedó sin el `h-10` del canon y dejaba los campos vacíos en 12px de alto.\nimport { readonlyBase } from './fieldStyles';\n\n\n// ─── Caché de resolución por (entity, valueField, id) ──────\n//\n// Evita repetir el fetch-by-id cuando el mismo id aparece en varios campos o\n// filas de un mismo documento. Es el mismo costo que ya paga el modo edición;\n// la caché impide amplificarlo. Guardamos la *promesa* para deduplicar también\n// las consultas en vuelo (dos campos con el mismo id disparan un solo fetch).\n\ntype ResolveCache = Map<string, Promise<Record<string, unknown> | null>>;\n\nconst LookupResolveCacheContext = createContext<ResolveCache | null>(null);\n\n/**\n * Provee una caché de resolución de lookups compartida por todo el árbol del\n * documento. Montado por `MasterDocumentProvider`, garantiza un único fetch por\n * (entity, id) distinto dentro de un mismo documento. Si no hay provider, cada\n * `LookupReadonlyValue` cae a una caché local propia (sigue deduplicando sus\n * re-renders, sin fugar estado entre instancias).\n */\nexport function LookupResolveCacheProvider({ children }: { children: ReactNode }) {\n  const cacheRef = useRef<ResolveCache | null>(null);\n  if (!cacheRef.current) cacheRef.current = new Map();\n  return (\n    <LookupResolveCacheContext.Provider value={cacheRef.current}>\n      {children}\n    </LookupResolveCacheContext.Provider>\n  );\n}\n\n/** Deriva los campos de etiqueta del displayTemplate (o usa displayFields). */\nfunction labelFieldsOf(cfg: LookupFieldConfig): string[] {\n  return cfg.displayTemplate\n    ? [...cfg.displayTemplate.matchAll(/\\{(\\w+)\\}/g)].map((m) => m[1])\n    : cfg.displayFields;\n}\n\n/** Construye la etiqueta \"código - nombre\" idéntica a la del modo edición. */\nfunction computeLabel(record: Record<string, unknown>, cfg: LookupFieldConfig): string {\n  if (cfg.displayTemplate) {\n    const out = interpolateTemplate(cfg.displayTemplate, record).trim();\n    if (out) return out;\n  }\n  return cfg.displayFields\n    .map((f) => record[f])\n    .filter((v) => v != null && v !== '')\n    .map(String)\n    .join(' - ');\n}\n\n/**\n * Resuelve un id a su registro vía fetch-by-id, con caché compartida.\n *\n * Devuelve:\n *  - `undefined` mientras carga (o sin id),\n *  - el registro resuelto,\n *  - `null` si el id no resolvió a ningún registro.\n */\nfunction useResolvedLookupRecord(\n  id: unknown,\n  lookupConfig: LookupFieldConfig | undefined,\n  fetcher: unknown,\n): Record<string, unknown> | null | undefined {\n  const ctxCache = useContext(LookupResolveCacheContext);\n  const localCacheRef = useRef<ResolveCache | null>(null);\n  if (!ctxCache && !localCacheRef.current) localCacheRef.current = new Map();\n  const cache = ctxCache ?? localCacheRef.current!;\n\n  const [record, setRecord] = useState<Record<string, unknown> | null | undefined>(undefined);\n\n  useEffect(() => {\n    const hasValue = id != null && id !== '';\n    if (!hasValue || !lookupConfig || !fetcher) {\n      setRecord(undefined);\n      return;\n    }\n\n    let cancelled = false;\n    const valueField = lookupConfig.valueField ?? 'Id';\n    // El id puede ser string o number; lo normalizamos a un FilterValue primitivo\n    // (los GUID llegan como string; preservamos ids numéricos tal cual).\n    const filterValue: string | number =\n      typeof id === 'number' ? id : String(id);\n    const key = `${lookupConfig.entity}::${valueField}::${String(id)}`;\n\n    let promise = cache.get(key);\n    if (!promise) {\n      // Campos a traer: el valueField (para emparejar) + los de etiqueta + los\n      // displayFields originales (no se muestran de más, pero garantizan que el\n      // backend genérico devuelva lo necesario para la etiqueta).\n      const fields = [\n        ...new Set([valueField, ...labelFieldsOf(lookupConfig), ...lookupConfig.displayFields]),\n      ];\n      promise = (fetcher as Fetcher)(lookupConfig.entity, {\n        fields,\n        filters: [[{ [valueField]: filterValue }]],\n        page: 1,\n        pageSize: 1,\n      })\n        .then((res) => res.data?.[0] ?? null)\n        .catch(() => null);\n      cache.set(key, promise);\n    }\n\n    setRecord(undefined);\n    promise.then((rec) => {\n      if (!cancelled) setRecord(rec);\n    });\n\n    return () => {\n      cancelled = true;\n    };\n  }, [id, lookupConfig, fetcher, cache]);\n\n  return record;\n}\n\nexport interface LookupReadonlyValueProps {\n  /** Id crudo (p.ej. el GUID) almacenado en el campo. */\n  id: unknown;\n  lookupConfig: LookupFieldConfig;\n  fetcher: unknown;\n  isMono?: boolean;\n}\n\n/**\n * Render solo-lectura de un campo `searcher`/`autocomplete`: resuelve el id a su\n * etiqueta (\"código - nombre\") con el mismo fetcher/displayTemplate que el modo\n * edición, en vez de pintar el valor crudo. Campo plano, sin interacción.\n *\n * - id vacío → render vacío (no fuerza \"—\").\n * - resolviendo → `Loading` inline (antes era un hueco vacío, indistinguible de\n *   \"sin valor\"; sigue sin destellar el id crudo).\n * - id no resuelto → cae al valor crudo (comportamiento previo, sin pérdida de info).\n */\nexport function LookupReadonlyValue({ id, lookupConfig, fetcher, isMono }: LookupReadonlyValueProps) {\n  const record = useResolvedLookupRecord(id, lookupConfig, fetcher);\n  const { t } = useMasterDocumentTranslation();\n\n  // `record === undefined` cubre DOS casos distintos: \"no hay nada que resolver\"\n  // (sin id, sin config o sin fetcher) y \"se está resolviendo\". Solo el segundo\n  // lleva indicador — si no, un documento con campos vacíos giraría para siempre.\n  // De ahí que se repita aquí la misma guarda que corta el efecto del hook.\n  const resolving =\n    record === undefined && id != null && id !== '' && !!lookupConfig && !!fetcher;\n\n  if (resolving) {\n    return (\n      <div className={clsx(readonlyBase, isMono && 'tabular-nums')}>\n        <Loading size=\"sm\" layout=\"inline\" ariaLabel={t('master_document.chrome.loadingValue')} />\n      </div>\n    );\n  }\n\n  let content = '';\n  if (record) {\n    content = computeLabel(record, lookupConfig);\n  } else if (record === null && id != null && id !== '') {\n    // Resolvió a \"no encontrado\": preservamos el valor crudo (como antes del fix).\n    content = String(id);\n  }\n\n  return <div className={clsx(readonlyBase, isMono && 'tabular-nums')}>{content}</div>;\n}\n","import { useMemo } from 'react';\nimport { useTranslation } from '../LanguageManagement/hooks/useTranslation';\n\n/**\n * Formateadores de números, montos y fechas de MasterDocument, ligados al idioma\n * activo.\n *\n * El kit tenía 14 sitios con `new Intl.NumberFormat('es-CO', …)` y\n * `currency: 'COP'` a pelo, pese a que el adapter ya expone `locale` y `currency`\n * inyectables (`adapter/createDefaultAdapter.ts`). El resultado era que un host en\n * inglés seguía viendo separadores de miles colombianos.\n *\n * ## La moneda NO sigue al idioma\n *\n * Distinción deliberada, y es la parte fácil de equivocar: el **locale** decide\n * las convenciones de formato (separador de miles, orden de la fecha) y sí cambia\n * con el idioma; la **moneda** es un dato del documento y NO cambia nunca por\n * idioma. Un documento en COP se muestra en COP con la UI en inglés — cambia\n * `1.234,00` a `1,234.00`, no el código de moneda.\n *\n * ## Región por idioma\n *\n * `currentLanguage` es un código corto (`es`, `en`). Se mapea a un tag BCP 47 con\n * región para preservar el formato que el kit ya producía: `es` → `es-CO` mantiene\n * exactamente el render actual (punto como separador de miles), en vez del `es`\n * genérico.\n *\n * @see src/components/MasterDocument/adapter/createDefaultAdapter.ts - locale/currency del adapter\n */\n\n/** Tag BCP 47 por código corto de idioma. Fuera del mapa se usa el código tal cual. */\nconst REGION_POR_IDIOMA: Record<string, string> = {\n  es: 'es-CO',\n  en: 'en-US',\n};\n\n/** Moneda por defecto del kit, igual que la del adapter. */\nexport const MONEDA_POR_DEFECTO = 'COP';\n\n/** Resuelve el locale de formato a partir del código corto de idioma. */\nexport function resolveLocale(language: string | undefined): string {\n  if (!language) return REGION_POR_IDIOMA.es;\n  return REGION_POR_IDIOMA[language] ?? language;\n}\n\n/** Formateadores listos para usar en el render. */\nexport interface MasterDocumentFormatters {\n  /** Locale BCP 47 efectivo, por si hace falta un `Intl` ad hoc. */\n  locale: string;\n/**\n   * Monto con símbolo de moneda. Ver {@link createCurrencyFormatter} para la\n   * regla: un monto entero se muestra con los decimales propios de la moneda y\n   * uno con decimales nunca los pierde.\n   */\n  formatCurrency: (value: number) => string;\n  /**\n   * Alias de {@link MasterDocumentFormatters.formatCurrency}, conservado por\n   * compatibilidad: es lo que consumen las celdas de la tabla de líneas.\n   *\n   * Tuvo una regla propia —dejar que el CLDR de la moneda fijara el máximo de\n   * decimales, que para COP puede ser CERO— y por eso un precio de `33,33` se\n   * pintaba `$ 33`. Ocultar decimales capturados no es \"compacto\", es incorrecto,\n   * así que hoy las dos funciones son la misma.\n   */\n  formatCurrencyCompact: (value: number) => string;\n  /** Número con 2 decimales. */\n  formatAmount: (value: number) => string;\n  /**\n   * Tasa de cambio: mínimo 2 decimales y sin recortar la precisión adicional.\n   *\n   * Una TRM como `4185,567` debe mostrarse completa; `formatAmount` la redondearía\n   * a 2 decimales y falsearía el dato.\n   */\n  formatRate: (value: number) => string;\n  /** Número sin decimales forzados. */\n  formatNumber: (value: number) => string;\n  /** Fecha (`Date` o `YYYY-MM-DD`) en formato medio, sin desfase de zona horaria. */\n  formatDate: (value: Date | string | undefined | null) => string;\n  /** Fecha y hora en formato medio/corto. */\n  formatDateTime: (value: Date | string | undefined | null) => string;\n}\n\n/**\n * Convierte `YYYY-MM-DD` a `Date` local.\n *\n * `new Date('2026-08-06')` se interpreta como UTC y en zonas al oeste de Greenwich\n * retrocede un día. Se construye con componentes para evitarlo.\n */\nfunction parseDate(value: Date | string | undefined | null): Date | undefined {\n  if (value == null || value === '') return undefined;\n  if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value;\n  const soloFecha = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(value);\n  if (soloFecha) {\n    return new Date(Number(soloFecha[1]), Number(soloFecha[2]) - 1, Number(soloFecha[3]));\n  }\n  const parsed = new Date(value);\n  return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n}\n\n/**\n * Formateador de moneda del kit: **nunca oculta decimales capturados**.\n *\n * ## El bug que cierra\n *\n * Los tres formateadores de moneda del kit pedían `minimumFractionDigits: 0` y\n * dejaban el MÁXIMO en manos del CLDR de la moneda. Para monedas que el CLDR\n * declara sin fracción —COP entre ellas, según la versión de ICU— ese máximo es\n * CERO, así que un precio capturado de `33,33` se pintaba `$ 33` y un neto de\n * `424,9575` se pintaba `$ 425`: la grilla de líneas y el widget de Totales\n * mostraban cifras que el usuario lee como un error de cálculo, no como formato.\n *\n * Peor: el resultado dependía de la versión de ICU del navegador (Node 22 resuelve\n * COP con 2 decimales; runtimes con datos más viejos, con 0), así que el mismo\n * documento se veía distinto en dos máquinas. Por eso aquí NO se deriva nada del\n * CLDR hacia abajo.\n *\n * ## La regla\n *\n * Siempre 2 decimales, o los de la moneda si usa más (BHD/KWD usan 3). Es la\n * convención contable y alinea las columnas de montos:\n * `$ 1.500,00` · `$ 33,33` · `$ 424,96` · `$ 505,70`.\n *\n * Redondear a 2 decimales PARA MOSTRAR es distinto de esconderlos todos: el valor\n * de `documentState` no se toca y las sumas siguen siendo exactas.\n */\nexport function createCurrencyFormatter(\n  locale: string,\n  currency: string = MONEDA_POR_DEFECTO,\n): (value: number) => string {\n  // El CLDR solo puede SUBIR el número de decimales, nunca bajarlo de 2.\n  const delCldr = new Intl.NumberFormat(locale, { style: 'currency', currency })\n    .resolvedOptions().maximumFractionDigits ?? 2;\n  const decimales = Math.max(delCldr, 2);\n  const fmt = new Intl.NumberFormat(locale, {\n    style: 'currency',\n    currency,\n    minimumFractionDigits: decimales,\n    maximumFractionDigits: decimales,\n  });\n  return (value) => fmt.format(value);\n}\n\n/**\n * Construye los formateadores para un locale y una moneda dados.\n *\n * Función pura, para los módulos que no pueden usar un hook. Los componentes\n * deberían usar {@link useMasterDocumentFormatters}.\n */\nexport function createFormatters(\n  locale: string,\n  currency: string = MONEDA_POR_DEFECTO,\n): MasterDocumentFormatters {\n  const currencyFmt = createCurrencyFormatter(locale, currency);\n  const amountFmt = new Intl.NumberFormat(locale, {\n    minimumFractionDigits: 2,\n    maximumFractionDigits: 2,\n  });\n  // Sin `maximumFractionDigits`: se deja el default de `Intl` (3 para decimales),\n  // que es el comportamiento que ya tenía el panel de moneda.\n  const rateFmt = new Intl.NumberFormat(locale, { minimumFractionDigits: 2 });\n  const numberFmt = new Intl.NumberFormat(locale);\n  const dateFmt = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' });\n  const dateTimeFmt = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' });\n\n  return {\n    locale,\n    formatCurrency: currencyFmt,\n    formatCurrencyCompact: currencyFmt,\n    formatAmount: (value) => amountFmt.format(value),\n    formatRate: (value) => rateFmt.format(value),\n    formatNumber: (value) => numberFmt.format(value),\n    formatDate: (value) => {\n      const date = parseDate(value);\n      return date ? dateFmt.format(date) : '—';\n    },\n    formatDateTime: (value) => {\n      const date = parseDate(value);\n      return date ? dateTimeFmt.format(date) : '—';\n    },\n  };\n}\n\n/**\n * Formateadores del idioma activo.\n *\n * @param currency Código ISO de la moneda del documento. NO se deriva del idioma.\n *\n * @example\n * ```tsx\n * const { formatCurrency, formatDate } = useMasterDocumentFormatters();\n * <span>{formatCurrency(total)}</span>\n * ```\n */\nexport function useMasterDocumentFormatters(\n  currency: string = MONEDA_POR_DEFECTO,\n): MasterDocumentFormatters {\n  const { currentLanguage } = useTranslation();\n  const locale = resolveLocale(currentLanguage);\n  return useMemo(() => createFormatters(locale, currency), [locale, currency]);\n}\n","import type {\n  CustomFieldValidator,\n  CustomFieldValidators,\n  FieldDescriptor,\n  FieldError,\n  FieldErrorMap,\n  ValidationRule,\n} from './MasterDocument.types';\n\nexport type { CustomFieldValidator, CustomFieldValidators };\n\n/**\n * Motor de validación en cliente para `FieldDescriptor.validations`.\n *\n * Hasta ahora `validations` era **configuración muerta**: el tipo la declaraba, los\n * templates la escribían (231 reglas en 20 templates solo en el módulo comercial) y\n * ningún punto del kit la leía. El canal `error` que pinta `FieldRenderer` lo llenaba\n * únicamente el servidor, al guardar, así que el `message` que cada regla trae escrito\n * no llegaba nunca a la pantalla.\n *\n * Este módulo es deliberadamente **puro**: sin React, sin estado, sin i18n. Recibe el\n * descriptor y el valor y devuelve el primer incumplimiento. Eso lo hace testeable de\n * verdad y deja que cada contenedor decida CUÁNDO enseñarlo.\n *\n * @see FieldRenderer — lo consume y decide el momento (tras tocar el campo)\n */\n\n/**\n * Valor \"vacío\" a efectos de validación. Alineado con el criterio que ya usaba\n * `FieldRenderer` para el borde rojo de requerido-vacío, para que el borde y el\n * mensaje no puedan discrepar.\n */\nexport function isEmptyValue(value: unknown): boolean {\n  return (\n    value === null ||\n    value === undefined ||\n    (typeof value === 'string' && value.trim() === '') ||\n    (Array.isArray(value) && value.length === 0)\n  );\n}\n\nfunction asNumber(v: unknown): number | undefined {\n  if (typeof v === 'number') return Number.isFinite(v) ? v : undefined;\n  if (typeof v === 'string' && v.trim() !== '') {\n    const n = Number(v);\n    return Number.isFinite(n) ? n : undefined;\n  }\n  return undefined;\n}\n\n/**\n * ¿Incumple el valor esta regla concreta?\n *\n * Contrato deliberado: **sobre un valor vacío solo puede fallar `required`**. Apilar\n * \"demasiado corto\" o \"menor que el mínimo\" encima de un campo opcional en blanco es\n * ruido, y en un campo obligatorio taparía el mensaje que de verdad importa.\n *\n * Una regla que este motor NO sabe evaluar (un `custom` sin validador registrado, un\n * `pattern` con una expresión inválida, un `min` sin número) se considera **cumplida**:\n * el kit no puede bloquear al usuario por una regla que no entiende.\n */\nfunction incumple(\n  rule: ValidationRule,\n  value: unknown,\n  fieldDef: FieldDescriptor,\n  customValidators?: CustomFieldValidators,\n  values?: Record<string, unknown>,\n): boolean {\n  const vacio = isEmptyValue(value);\n\n  if (rule.type === 'required') return vacio;\n  if (vacio) return false;\n\n  switch (rule.type) {\n    case 'min': {\n      const cota = asNumber(rule.value);\n      const n = asNumber(value);\n      return cota !== undefined && n !== undefined && n < cota;\n    }\n    case 'max': {\n      const cota = asNumber(rule.value);\n      const n = asNumber(value);\n      return cota !== undefined && n !== undefined && n > cota;\n    }\n    case 'minLength': {\n      const cota = asNumber(rule.value);\n      return cota !== undefined && String(value).length < cota;\n    }\n    case 'maxLength': {\n      const cota = asNumber(rule.value);\n      return cota !== undefined && String(value).length > cota;\n    }\n    case 'pattern': {\n      if (typeof rule.value !== 'string' && !(rule.value instanceof RegExp)) return false;\n      try {\n        const re = rule.value instanceof RegExp ? rule.value : new RegExp(rule.value);\n        return !re.test(String(value));\n      } catch {\n        // Expresión inválida en el template: no es culpa del usuario.\n        return false;\n      }\n    }\n    case 'custom': {\n      const id = typeof rule.value === 'string' ? rule.value : undefined;\n      const fn = id ? customValidators?.[id] : undefined;\n      if (!fn) return false;\n      try {\n        return !fn(value, { fieldDef, values });\n      } catch {\n        return false;\n      }\n    }\n    default:\n      return false;\n  }\n}\n\n/**\n * Primer incumplimiento del campo, o `null` si cumple todo.\n *\n * Los `severity: 'error'` ganan a los `warning` aunque aparezcan después en el array:\n * si un campo incumple las dos cosas, lo que hay que enseñar es el error.\n */\nexport function evaluateFieldValidations(\n  fieldDef: FieldDescriptor,\n  value: unknown,\n  customValidators?: CustomFieldValidators,\n  values?: Record<string, unknown>,\n): FieldError | null {\n  const reglas = fieldDef.validations;\n  if (!reglas || reglas.length === 0) return null;\n\n  let warning: FieldError | null = null;\n  for (const rule of reglas) {\n    if (!incumple(rule, value, fieldDef, customValidators, values)) continue;\n    if (rule.severity === 'error') return { message: rule.message, severity: 'error' };\n    warning ??= { message: rule.message, severity: 'warning' };\n  }\n  return warning;\n}\n\n/**\n * Evalúa un conjunto de campos contra sus valores. Pensado para que un contenedor\n * decida si puede guardar; el kit NO bloquea ningún botón por su cuenta.\n */\nexport function evaluateFields(\n  fields: FieldDescriptor[],\n  values: Record<string, unknown>,\n  customValidators?: CustomFieldValidators,\n): FieldErrorMap {\n  const out: FieldErrorMap = {};\n  for (const f of fields) {\n    const e = evaluateFieldValidations(f, values[f.key], customValidators, values);\n    if (e) out[f.key] = e;\n  }\n  return out;\n}\n\n/**\n * Campos que IMPIDEN guardar, indexados por key. Lo que devuelve encaja tal cual en el\n * canal `error` que ya pinta `FieldRenderer`, así que el mensaje del campo y cualquier\n * otra señal que se derive de este mapa —el badge de la pestaña, p.ej.— salen de la MISMA\n * computación y no pueden contradecirse (ADR-027 §C.3b).\n *\n * Honra las DOS formas de declarar obligatoriedad, que en los templates reales no\n * coinciden: el flag `required` del descriptor y la regla `{ type: 'required' }` de\n * `validations`. De los 87 campos de línea obligatorios del módulo comercial, 5 traen\n * SOLO el flag; un guardián que mirara únicamente `validations` los dejaría pasar\n * mientras el asterisco de su pestaña sí los cuenta.\n *\n * Solo devuelve incumplimientos de severidad `error`: un `warning` avisa, no bloquea.\n *\n * El llamador decide QUÉ campos entran. Debe pasar únicamente los que el usuario puede\n * resolver ahora mismo —visibles y editables en el estado actual—: un campo oculto por\n * condición, no editable por estado, sin el permiso de edición (que llega con\n * `editableOn: []`) o calculado no puede bloquear a nadie, porque no habría forma de\n * desbloquearlo.\n */\nexport function evaluateBlockingFields(\n  fields: FieldDescriptor[],\n  values: Record<string, unknown>,\n  options: { requiredFallbackMessage: string; customValidators?: CustomFieldValidators },\n): FieldErrorMap {\n  const out: FieldErrorMap = {};\n  for (const f of fields) {\n    const value = values[f.key];\n\n    if (f.required && isEmptyValue(value)) {\n      // El mensaje del template si lo declara; si solo trae el flag, el genérico del kit.\n      const regla = f.validations?.find((r) => r.type === 'required' && r.severity === 'error');\n      out[f.key] = {\n        message: regla?.message ?? options.requiredFallbackMessage,\n        severity: 'error',\n      };\n      continue;\n    }\n\n    const e = evaluateFieldValidations(f, value, options.customValidators, values);\n    if (e && e.severity === 'error') out[f.key] = e;\n  }\n  return out;\n}\n","import { useMemo, useState } from 'react';\nimport { clsx } from 'clsx';\nimport { NumericFormat } from 'react-number-format';\nimport { LockClosedIcon } from '@heroicons/react/24/outline';\nimport { LookupField } from '../LookupField';\nimport type { Fetcher } from '../LookupField/services/api.types';\nimport { LookupReadonlyValue } from './LookupReadonlyValue';\nimport { readonlyBase, controlHeight } from './fieldStyles';\nimport type {\n  FieldRendererProps,\n  ControlType,\n  LookupFieldConfig,\n  ValidationRule,\n} from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { useMasterDocumentFormatters } from './formatters';\nimport { evaluateFieldValidations, isEmptyValue } from './fieldValidation';\n\n// ─── Estilos base (alineados con Input del UI Kit) ─────────\n\nconst inputBase = clsx(\n  // Sin padding vertical: la altura de los controles de una línea la fija `controlHeight`\n  // (§D.2) y la del `textarea` su propio `min-h`. `py-1.5` aquí daba 34px de control.\n  'w-full rounded-md border border-border-primary bg-bg-primary px-3 text-sm text-content-primary',\n  'placeholder:text-content-tertiary',\n  'hover:border-primary-600',\n  'focus:outline-hidden focus:border-primary-600 focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n  'disabled:opacity-50 disabled:cursor-not-allowed',\n  'transition-all duration-150',\n  'dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary',\n  'dark:placeholder:text-dark-content-tertiary',\n  'dark:hover:border-dark-border-custom',\n  'dark:focus:border-dark-border-custom dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n);\n\nconst inputError = 'border-error-border focus:border-error-border focus:ring-error-border/30 dark:border-error-border dark:focus:border-error-border dark:focus:ring-error-border/30';\n\n// Controles \"con valor\" sobre los que aplica el resaltado de requerido-vacío.\n// Se excluyen toggle/checkbox (un booleano nunca está \"vacío\" de forma útil) y\n// los de solo lectura (readonly/display).\nconst REQUIRED_HIGHLIGHT_CONTROLS: ControlType[] = [\n  'text', 'number', 'currency', 'percentage',\n  'date', 'select', 'searcher', 'autocomplete', 'textarea',\n];\n\n\n/**\n * Label del canon (ADR-027 §D.1), literal: `text-sm font-bold leading-5` en\n * `content-primary` con `mb-1.5`.\n *\n * Antes era `text-xs font-bold uppercase tracking-wide` en `content-secondary` (#a1a1aa):\n * un segundo estilo de etiqueta dentro del mismo producto. El margen inferior vive aquí\n * (`mb-1.5` = 6px) y no en el `gap` del contenedor, que es como lo hace el canon.\n */\nconst labelBase = clsx(\n  'block text-sm font-bold leading-5 text-content-primary mb-1.5',\n  'dark:text-dark-content-primary',\n);\n\n\n// ─── ReadonlyField ─────────────────────────────────────────\n\nfunction ReadonlyField({ value, isMono }: { value: unknown; isMono?: boolean }) {\n  const displayValue = value == null || value === '' ? '—' : String(value);\n  return (\n    <div className={clsx(readonlyBase, isMono && 'tabular-nums')} title={displayValue}>\n      {/* El contenedor pasó a alto fijo (40px, §D.2) para no saltar respecto al control\n          editable, así que un valor largo ya no puede crecer hacia abajo: se trunca con\n          elipsis y el valor completo queda en el `title`. Antes envolvía y desalineaba la\n          rejilla. */}\n      <span className=\"truncate\">{displayValue}</span>\n    </div>\n  );\n}\n\n// ─── Controles individuales ────────────────────────────────\n\nfunction TextInput({\n  value,\n  onChange,\n  placeholder,\n  hasError,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  placeholder?: string;\n  hasError: boolean;\n}) {\n  return (\n    <input\n      type=\"text\"\n      className={clsx(inputBase, controlHeight, hasError && inputError)}\n      value={value == null ? '' : String(value)}\n      onChange={(e) => onChange(e.target.value)}\n      placeholder={placeholder}\n    />\n  );\n}\n\n/**\n * Cota numérica declarada en `validations`. Acepta `number` y la cadena que lo\n * represente: los templates escriben `value: 0.0001`, pero el tipo del campo es\n * `unknown` y un consumidor puede haber escrito `'0'`.\n */\nfunction boundOf(validations: ValidationRule[] | undefined, type: 'min' | 'max'): number | undefined {\n  const raw = validations?.find((v) => v.type === type)?.value;\n  if (typeof raw === 'number') return Number.isFinite(raw) ? raw : undefined;\n  if (typeof raw === 'string' && raw.trim() !== '') {\n    const n = Number(raw);\n    return Number.isFinite(n) ? n : undefined;\n  }\n  return undefined;\n}\n\n/**\n * Importe editable: se ve FORMATEADO mientras se teclea —signo, separador de miles y\n * decimales— y al formulario sigue llegando el número crudo.\n *\n * Va con `react-number-format` y no a mano porque lo difícil aquí no es insertar los\n * puntos: es dónde queda el cursor después de insertarlos. Reformatear en cada\n * pulsación desplaza el texto, y un `setSelectionRange` ingenuo manda el cursor al\n * final en cuanto el usuario edita por el medio o borra un separador. Esa librería\n * resuelve exactamente ese caso; el resto de su superficie no se usa.\n *\n * El separador sale del locale activo, no de constantes: en `es-CO` es `.` para miles\n * y `,` para decimales, y en `en-US` al revés.\n */\nfunction CurrencyInput({\n  value,\n  onChange,\n  placeholder,\n  hasError,\n  prefijo,\n  sufijo,\n  decimales,\n  min,\n  max,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  placeholder?: string;\n  hasError: boolean;\n  prefijo?: string;\n  sufijo?: string;\n  decimales: number;\n  min?: number;\n  max?: number;\n}) {\n  const { locale } = useMasterDocumentFormatters();\n  const separadores = useMemo(() => {\n    const partes = new Intl.NumberFormat(locale).formatToParts(12345.6);\n    return {\n      miles: partes.find((p) => p.type === 'group')?.value ?? ',',\n      decimal: partes.find((p) => p.type === 'decimal')?.value ?? '.',\n    };\n  }, [locale]);\n\n  return (\n    <NumericFormat\n      value={value == null || value === '' ? '' : Number(value)}\n      onValueChange={(v) => onChange(v.floatValue ?? null)}\n      thousandSeparator={separadores.miles}\n      decimalSeparator={separadores.decimal}\n      decimalScale={decimales}\n      // Los decimales se completan al SALIR, no mientras se teclea: forzarlos en cada\n      // pulsación impide escribir «1.5» —al teclear el separador ya habría dos ceros\n      // detrás y el cursor delante de ellos.\n      fixedDecimalScale={false}\n      allowNegative={min === undefined || min < 0}\n      prefix={prefijo ? `${prefijo} ` : undefined}\n      suffix={sufijo ? ` ${sufijo}` : undefined}\n      placeholder={placeholder}\n      inputMode=\"decimal\"\n      className={clsx(inputBase, controlHeight, hasError && inputError, 'tabular-nums')}\n      onBlur={() => {\n        // Mismo clamp que el numérico normal: el `min`/`max` del formulario no lo\n        // aplica el control, así que teclear por debajo de la cota entraría igual.\n        if (value == null || value === '') return;\n        const n = Number(value);\n        if (!Number.isFinite(n)) return;\n        if (min !== undefined && n < min) onChange(min);\n        else if (max !== undefined && n > max) onChange(max);\n      }}\n    />\n  );\n}\n\nfunction NumberInput({\n  value,\n  onChange,\n  placeholder,\n  hasError,\n  prefix,\n  suffix,\n  min,\n  max,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  placeholder?: string;\n  hasError: boolean;\n  prefix?: string;\n  suffix?: string;\n  min?: number;\n  max?: number;\n}) {\n  const acotado = min !== undefined || max !== undefined;\n  return (\n    <div className=\"relative\">\n      {prefix && (\n        <span className=\"absolute left-3 top-1/2 -translate-y-1/2 text-sm text-content-secondary dark:text-dark-content-secondary pointer-events-none select-none\">\n          {prefix}\n        </span>\n      )}\n      <input\n        type=\"number\"\n        className={clsx(\n          inputBase,\n          controlHeight,\n          hasError && inputError,\n          'tabular-nums',\n          prefix && 'pl-7',\n          suffix && 'pr-7',\n        )}\n        min={min}\n        max={max}\n        /*\n         * `step=\"any\"` es OBLIGATORIO en cuanto hay cota, y no es cosmético. Sin `step`\n         * el valor por defecto es 1 y el navegador toma `min` como base del escalón: con\n         * `min=0.0001` los únicos valores válidos pasan a ser 0.0001, 1.0001, 2.0001...,\n         * así que un `1` normal queda `:invalid` (\"los dos valores válidos más aproximados\n         * son 0.0001 y 1.0001\") y la flecha de subir salta a 2.0001. Medido en Chrome 152.\n         * Con `step=\"any\"` la flecha avanza de 1 en 1 y se detiene al llegar a la cota:\n         * desde 5 con min=0.0001 baja 4,3,2,1 y ahí se queda; con min=0 llega a 0.\n         */\n        step={acotado ? 'any' : undefined}\n        value={value == null ? '' : String(value)}\n        onChange={(e) => {\n          const raw = e.target.value;\n          onChange(raw === '' ? null : Number(raw));\n        }}\n        /*\n         * El atributo `min` solo frena los botoncitos del control; TECLEAR un valor por\n         * debajo sigue permitido (el input queda `:invalid`, pero el valor llega al\n         * formulario igual). El clamp al perder el foco es lo que cierra esa vía.\n         *\n         * Efecto sobre el mensaje de `validations`: en un numérico acotado el clamp\n         * corre ANTES de que el mensaje de `min`/`max` pueda enseñarse, así que el\n         * usuario ve el valor ya corregido y ningún texto en rojo. Es deliberado —\n         * corregirlo es mejor que decirle que está mal y dejárselo puesto—; el mensaje\n         * de esas dos reglas queda como respaldo para donde el clamp no aplica.\n         */\n        onBlur={(e) => {\n          const raw = e.target.value;\n          if (raw === '') return;\n          const n = Number(raw);\n          if (!Number.isFinite(n)) return;\n          if (min !== undefined && n < min) onChange(min);\n          else if (max !== undefined && n > max) onChange(max);\n        }}\n        placeholder={placeholder}\n      />\n      {suffix && (\n        <span className=\"absolute right-3 top-1/2 -translate-y-1/2 text-sm text-content-secondary dark:text-dark-content-secondary pointer-events-none select-none\">\n          {suffix}\n        </span>\n      )}\n    </div>\n  );\n}\n\nfunction DateInput({\n  value,\n  onChange,\n  hasError,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  hasError: boolean;\n}) {\n  return (\n    <input\n      type=\"date\"\n      className={clsx(inputBase, controlHeight, hasError && inputError, 'tabular-nums')}\n      value={value == null ? '' : String(value)}\n      onChange={(e) => onChange(e.target.value)}\n    />\n  );\n}\n\nfunction SelectInput({\n  value,\n  onChange,\n  options,\n  placeholder,\n  hasError,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  options?: Array<{ label: string; value: string | number }>;\n  placeholder?: string;\n  hasError: boolean;\n}) {\n  return (\n    <select\n      className={clsx(inputBase, controlHeight, hasError && inputError, 'cursor-pointer')}\n      value={value == null ? '' : String(value)}\n      onChange={(e) => onChange(e.target.value)}\n    >\n      {placeholder && (\n        <option value=\"\" disabled>\n          {placeholder}\n        </option>\n      )}\n      {options?.map((opt) => (\n        <option key={opt.value} value={opt.value}>\n          {opt.label}\n        </option>\n      ))}\n    </select>\n  );\n}\n\n// ─── SearcherInput — LookupField real o fallback ──────────\n\n/**\n * Control de searcher (campo foráneo): renderiza el `LookupField` real cuando hay\n * `lookupConfig` + `fetcher`, y degrada a un input de texto con lupa cuando no.\n *\n * Se exporta porque el listado lo reutiliza para los filtros de columna foránea\n * (`SearchField.type: 'lookup'`): filtrar por una FK debe ofrecer el mismo\n * buscador que el campo del formulario, no un input donde escribir el id a mano.\n */\nexport function SearcherControl({\n  value,\n  onChange,\n  placeholder,\n  hasError,\n  lookupConfig,\n  fetcher,\n  onRecordSelect,\n  getLookupFilters,\n  lookupDependencies,\n  disabled,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  placeholder?: string;\n  hasError: boolean;\n  lookupConfig?: LookupFieldConfig;\n  fetcher?: unknown;\n  onRecordSelect?: (record: Record<string, unknown> | null) => void;\n  getLookupFilters?: () => unknown;\n  lookupDependencies?: unknown[];\n  disabled?: boolean;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  // Si hay lookupConfig y fetcher, renderizar LookupField real\n  if (lookupConfig && fetcher) {\n    // Campos de ETIQUETA del dropdown: se derivan del displayTemplate cuando\n    // existe (p.ej. \"{code} - {name}\" → [\"code\", \"name\"]); si no hay template\n    // se mantienen los displayFields configurados (sin regresión).\n    const labelFields = lookupConfig.displayTemplate\n      ? [...lookupConfig.displayTemplate.matchAll(/\\{(\\w+)\\}/g)].map((m) => m[1])\n      : lookupConfig.displayFields;\n    // Campos que SÍ deben traerse del backend: los displayFields originales más\n    // los campos de origen del bindFields (Record formulario→registro), para no\n    // romper el autollenado en endpoints genéricos que solo devuelven lo pedido.\n    // Se pasan como `bindFields` del LookupField (se piden pero NO se muestran).\n    const fetchFields = [\n      ...new Set([\n        ...lookupConfig.displayFields,\n        ...Object.values(lookupConfig.bindFields ?? {}),\n      ]),\n    ];\n    return (\n      <LookupField\n        entity={lookupConfig.entity}\n        displayFields={labelFields}\n        bindFields={fetchFields}\n        searchFields={lookupConfig.searchFields}\n        displayTemplate={lookupConfig.displayTemplate}\n        fetcher={fetcher as Fetcher}\n        value={value ? String(value) : null}\n        onChange={(record: Record<string, unknown> | null) => {\n          if (!record) {\n            onChange(null);\n            onRecordSelect?.(null);\n            return;\n          }\n          const valField = lookupConfig.valueField ?? 'Id';\n          let newValue = record[valField];\n          // Fallback Id → id\n          if (newValue === undefined && valField === 'Id' && record['id'] !== undefined) {\n            newValue = record['id'];\n          }\n          onChange(newValue ?? null);\n          onRecordSelect?.(record);\n        }}\n        placeholder={placeholder ?? t('master_document.field.searchPlaceholder')}\n        pageSize={lookupConfig.pageSize ?? 10}\n        filters={lookupConfig.filters as never}\n        getFilters={getLookupFilters as never}\n        dependencies={lookupDependencies}\n        disabled={disabled}\n        error={hasError}\n      />\n    );\n  }\n\n  // Fallback: input de texto simple con icono de búsqueda\n  return (\n    <div className=\"relative\">\n      <svg\n        className=\"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-content-secondary dark:text-dark-content-secondary pointer-events-none\"\n        fill=\"none\"\n        viewBox=\"0 0 24 24\"\n        stroke=\"currentColor\"\n        strokeWidth={2}\n        aria-hidden=\"true\"\n      >\n        <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z\" />\n      </svg>\n      <input\n        type=\"text\"\n        className={clsx(inputBase, controlHeight, hasError && inputError, 'pl-9')}\n        value={value == null ? '' : String(value)}\n        onChange={(e) => onChange(e.target.value)}\n        placeholder={placeholder ?? t('master_document.field.searchPlaceholder')}\n        aria-label={t('master_document.field.search')}\n        disabled={disabled}\n      />\n    </div>\n  );\n}\n\nfunction TextareaInput({\n  value,\n  onChange,\n  placeholder,\n  hasError,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n  placeholder?: string;\n  hasError: boolean;\n}) {\n  return (\n    <textarea\n      className={clsx(inputBase, hasError && inputError, 'min-h-[72px] resize-y')}\n      value={value == null ? '' : String(value)}\n      onChange={(e) => onChange(e.target.value)}\n      placeholder={placeholder}\n      rows={3}\n    />\n  );\n}\n\nfunction ToggleInput({\n  value,\n  onChange,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n}) {\n  const checked = Boolean(value);\n  return (\n    <button\n      type=\"button\"\n      role=\"switch\"\n      aria-checked={checked}\n      className={clsx(\n        'relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-all duration-150',\n        'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n        'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n        checked ? 'bg-primary-inverse-background dark:bg-dark-bg-inverse' : 'bg-border-primary dark:bg-dark-border-primary',\n      )}\n      onClick={() => onChange(!checked)}\n    >\n      <span\n        className={clsx(\n          'pointer-events-none inline-block h-5 w-5 transform rounded-full bg-bg-primary dark:bg-dark-content-primary shadow-sm transition-transform duration-150',\n          checked ? 'translate-x-5' : 'translate-x-0',\n        )}\n      />\n    </button>\n  );\n}\n\nfunction CheckboxInput({\n  value,\n  onChange,\n}: {\n  value: unknown;\n  onChange: (v: unknown) => void;\n}) {\n  const checked = Boolean(value);\n  return (\n    <button\n      type=\"button\"\n      role=\"checkbox\"\n      aria-checked={checked}\n      className={clsx(\n        'flex h-[18px] w-[18px] items-center justify-center rounded-sm border-2 transition-all duration-150 cursor-pointer',\n        'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n        'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n        checked\n          ? 'border-primary-600 bg-primary-inverse-background dark:bg-dark-bg-inverse'\n          : 'border-border-primary bg-bg-primary dark:border-dark-border-primary dark:bg-dark-bg-primary',\n      )}\n      onClick={() => onChange(!checked)}\n    >\n      {checked && (\n        <svg className=\"h-3 w-3 text-primary-inverse-content dark:text-dark-content-inverse\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" strokeWidth={3}>\n          <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M5 13l4 4L19 7\" />\n        </svg>\n      )}\n    </button>\n  );\n}\n\n// ─── FieldRenderer ─────────────────────────────────────────\n\n/**\n * Renderizador genérico de campos del documento maestro.\n *\n * Selecciona el control apropiado (text, number, currency, select, toggle, etc.)\n * según `fieldDef.control` y aplica el estado de solo lectura, error y accesibilidad.\n * Compatible con LookupField cuando se provee `lookupConfig` y `fetcher`.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - FieldRendererProps, FieldDescriptor, ControlType\n *\n * @example\n * ```tsx\n * <FieldRenderer\n *   fieldDef={{ key: 'cliente', label: 'Cliente', control: 'searcher', order: 1, span: 1, editableOn: ['DRAFT'] }}\n *   value=\"CLI-001\"\n *   onChange={(v) => updateField('cliente', v)}\n *   editable={true}\n * />\n * ```\n */\nexport function FieldRenderer({\n  fieldDef,\n  value,\n  onChange,\n  editable,\n  error,\n  readOnly,\n  className,\n  lookupConfig,\n  fetcher,\n  onRecordSelect,\n  getLookupFilters,\n  lookupDependencies,\n  disabled,\n  locked,\n  lockTooltip,\n  lockTooltipKey,\n  customValidators,\n}: FieldRendererProps) {\n  const { t } = useMasterDocumentTranslation();\n  // Los mismos formateadores que la grilla de líneas: un importe se ve igual en\n  // toda la pantalla, no según el sitio donde aparezca.\n  const { formatCurrency, formatAmount } = useMasterDocumentFormatters();\n  // El campo se considera \"tocado\" en cuanto el foco sale de su control. Antes de eso\n  // no se le grita al usuario por un campo que aun no ha llegado a llenar.\n  const [touched, setTouched] = useState(false);\n  // Un campo bloqueado siempre se muestra como solo-lectura, independientemente\n  // de su editabilidad por estado.\n  const isReadOnly =\n    locked ||\n    !editable ||\n    readOnly ||\n    fieldDef.control === 'readonly' ||\n    fieldDef.control === 'display';\n\n  // Precedencia: clave i18n del template > texto literal del template > default\n  // del kit. Antes `lockTooltipKey` estaba declarado y nunca se leia.\n  const lockTooltipText = lockTooltipKey\n    ? t(lockTooltipKey)\n    : lockTooltip ?? t('master_document.field.lockTooltip');\n\n  const isMono = ['number', 'currency', 'percentage', 'date'].includes(fieldDef.control);\n\n  // Validación en cliente de `validations`. Se evalúa siempre (es barato y puro) pero\n  // solo se ENSEÑA cuando el campo ya se tocó: así el formulario recién abierto no\n  // aparece sembrado de mensajes en rojo.\n  const clientError = useMemo(\n    () =>\n      isReadOnly || disabled\n        ? null\n        : evaluateFieldValidations(fieldDef, value, customValidators),\n    [fieldDef, value, customValidators, isReadOnly, disabled],\n  );\n\n  /*\n   * Precedencia: el error del SERVIDOR gana siempre. Es el autoritativo —llega tras\n   * intentar guardar y puede decir cosas que el cliente no puede saber—, y taparlo con\n   * un mensaje local sería mentirle al usuario sobre por qué no se guardó.\n   */\n  const shownError = error ?? (touched ? clientError : null);\n\n  const hasError = !!shownError && shownError.severity === 'error';\n  const hasWarning = !!shownError && shownError.severity === 'warning';\n  const errorId = shownError ? `field-error-${fieldDef.key}` : undefined;\n\n  // Un campo obligatorio editable y sin valor se resalta con borde rojo desde el\n  // primer render, sin esperar a que se toque: el asterisco ya avisa de que hace\n  // falta, y el borde solo lo hace visible. El MENSAJE sí espera al `touched`.\n  const isRequiredEmpty =\n    !!fieldDef.required &&\n    !isReadOnly &&\n    !disabled &&\n    REQUIRED_HIGHLIGHT_CONTROLS.includes(fieldDef.control) &&\n    isEmptyValue(value);\n\n  // El borde rojo se prende tanto por un error explícito como por requerido-vacío.\n  const showErrorBorder = hasError || isRequiredEmpty;\n\n  // Render control\n  function renderControl(control: ControlType) {\n    const placeholder = fieldDef.placeholder;\n    const options = fieldDef.options;\n    // Cotas declaradas en el template (`validations`) llevadas al control numérico.\n    // Hasta ahora `validations` no lo leía nadie en el kit, así que un `min` declarado\n    // era configuración muerta y la flecha de bajar entraba en 0 y en negativo.\n    const minNum = boundOf(fieldDef.validations, 'min');\n    const maxNum = boundOf(fieldDef.validations, 'max');\n\n    switch (control) {\n      case 'text':\n        return <TextInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} />;\n      case 'number':\n        // El formato manda sobre el control también EN EDICIÓN, no sólo en lectura\n        // (§M.45). Un importe declarado `control: 'number'` con `format: 'currency'`\n        // —que es como está media plantilla, porque `control` responde a «cómo se\n        // captura»— se veía sin signo y sin separador mientras su propia columna lo\n        // pintaba `$ 500.000,00`.\n        if (fieldDef.format === 'currency') {\n          return <CurrencyInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} prefijo=\"$\" decimales={2} min={minNum} max={maxNum} />;\n        }\n        if (fieldDef.format === 'percentage') {\n          return <CurrencyInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} sufijo=\"%\" decimales={2} min={minNum} max={maxNum} />;\n        }\n        return <NumberInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} min={minNum} max={maxNum} />;\n      case 'currency':\n        return <CurrencyInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} prefijo=\"$\" decimales={2} min={minNum} max={maxNum} />;\n      case 'percentage':\n        return <CurrencyInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} sufijo=\"%\" decimales={2} min={minNum} max={maxNum} />;\n      case 'date':\n        return <DateInput value={value} onChange={onChange} hasError={showErrorBorder} />;\n      case 'select':\n        return <SelectInput value={value} onChange={onChange} options={options} placeholder={placeholder} hasError={showErrorBorder} />;\n      case 'searcher':\n      case 'autocomplete':\n        return (\n          <SearcherControl\n            value={value}\n            onChange={onChange}\n            placeholder={placeholder}\n            hasError={showErrorBorder}\n            lookupConfig={lookupConfig}\n            fetcher={fetcher}\n            onRecordSelect={onRecordSelect}\n            getLookupFilters={getLookupFilters}\n            lookupDependencies={lookupDependencies}\n            disabled={disabled}\n          />\n        );\n      case 'textarea':\n        return <TextareaInput value={value} onChange={onChange} placeholder={placeholder} hasError={showErrorBorder} />;\n      case 'toggle':\n        return <ToggleInput value={value} onChange={onChange} />;\n      case 'checkbox':\n        return <CheckboxInput value={value} onChange={onChange} />;\n      case 'readonly':\n      case 'display':\n        return <ReadonlyField value={value} />;\n      default: {\n        const _exhaustive: never = control;\n        return <ReadonlyField value={_exhaustive} />;\n      }\n    }\n  }\n\n  // Render solo-lectura: para searcher/autocomplete resuelve el id a su etiqueta\n  // (\"código - nombre\") reutilizando fetcher + lookupConfig; para select resuelve\n  // el value crudo a la etiqueta de su opción (mismas options que en edición); el\n  // resto de controles mantienen el render plano del valor crudo (sin regresión).\n  function renderReadonly() {\n    const control = fieldDef.control;\n    /*\n     * Un importe en SOLO LECTURA se formatea como importe. Antes se pintaba\n     * `String(value)` —el número crudo, `500000`— mientras el mismo dato en la grilla\n     * de líneas salía `$ 500.000,00`: el mismo valor con dos caras según dónde\n     * apareciera. Se usa el MISMO formateador que la grilla, así que el signo, el\n     * separador de miles y los dos decimales son los mismos en toda la pantalla.\n     *\n     * El control editable ya no lo necesita: lleva `prefix=\"$\"`, que es lo que da a\n     * entender que el campo es un valor mientras se teclea.\n     */\n    // El formato manda sobre el control, y es la REGLA GENERAL: `control` dice cómo\n    // se captura el dato y `format` qué es. Mirando sólo el control, un importe\n    // calculado por el servidor —`control: 'readonly'`, porque no se teclea— se\n    // pintaba crudo (`500000`) mientras el mismo importe salía `$ 500.000,00` en la\n    // grilla. Medido en dev el 2026-09-09 en la pestaña «Costo» del modal de línea:\n    // seis campos de dinero sin separador, sin signo y sin decimales.\n    const formato = fieldDef.format ?? (control === 'currency' || control === 'percentage' ? control : undefined);\n    const esNumero = value != null && value !== '' && Number.isFinite(Number(value));\n    if (formato === 'currency' && esNumero) {\n      return <ReadonlyField value={formatCurrency(Number(value))} isMono />;\n    }\n    if (formato === 'percentage' && esNumero) {\n      return <ReadonlyField value={`${formatAmount(Number(value))} %`} isMono />;\n    }\n    if (formato === 'number' && esNumero) {\n      return <ReadonlyField value={formatAmount(Number(value))} isMono />;\n    }\n    if ((control === 'searcher' || control === 'autocomplete') && lookupConfig && fetcher) {\n      return <LookupReadonlyValue id={value} lookupConfig={lookupConfig} fetcher={fetcher} isMono={isMono} />;\n    }\n    if (control === 'select') {\n      // Buscar la opción cuyo value coincide con el valor del campo y mostrar su\n      // label. Si las opciones no cargaron o no hay match, fallback al value crudo.\n      const match = fieldDef.options?.find((opt) => String(opt.value) === String(value));\n      return <ReadonlyField value={match ? match.label : value} isMono={isMono} />;\n    }\n    return <ReadonlyField value={value} isMono={isMono} />;\n  }\n\n  return (\n    <div className={clsx('flex flex-col', className)}>\n      {/* Label */}\n      <label className={clsx(labelBase, 'flex items-center gap-1')}>\n        <span>{fieldDef.label}</span>\n        {fieldDef.required && !isReadOnly && (\n          <span className=\"text-error-content ml-0.5\">*</span>\n        )}\n        {locked && (\n          <span\n            className=\"inline-flex cursor-not-allowed text-content-tertiary dark:text-dark-content-tertiary\"\n            title={lockTooltipText}\n            aria-label={lockTooltipText}\n          >\n            <LockClosedIcon className=\"h-3.5 w-3.5\" aria-hidden=\"true\" />\n          </span>\n        )}\n      </label>\n\n      {/* Control */}\n      {locked ? (\n        <div className=\"cursor-not-allowed\" title={lockTooltipText}>\n          {renderReadonly()}\n        </div>\n      ) : isReadOnly ? (\n        renderReadonly()\n      ) : (\n        <div\n          className=\"relative\"\n          aria-invalid={showErrorBorder || undefined}\n          aria-describedby={errorId}\n          /*\n           * `onBlur` en el contenedor y no en cada control: en React el evento burbujea\n           * (usa la semántica de `focusout`), así que un solo manejador cubre todos los\n           * tipos de control, incluidos los que el kit compone por dentro.\n           */\n          onBlur={() => setTouched(true)}\n        >\n          {renderControl(fieldDef.control)}\n          {hasWarning && (\n            <svg\n              className=\"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-amber-600 dark:text-amber-400\"\n              fill=\"none\"\n              viewBox=\"0 0 24 24\"\n              stroke=\"currentColor\"\n              strokeWidth={2}\n            >\n              <path\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n                d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z\"\n              />\n            </svg>\n          )}\n        </div>\n      )}\n\n      {/* Error / Warning message */}\n      {/*\n        Mensaje del canon (ADR-027 §D.6): icono + texto, `flex items-center gap-[3px] mt-1\n        text-xs`, icono de 11x11 que NO es decoración — es lo que hace legible la línea como\n        error sin depender sólo del color. Antes era texto suelto sin icono ni margen.\n      */}\n      {shownError && (\n        <span\n          id={errorId}\n          role=\"alert\"\n          className={clsx(\n            'flex items-center gap-[3px] mt-1 text-xs',\n            shownError.severity === 'error' ? 'text-[#dc2626]' : 'text-amber-600 dark:text-amber-400',\n          )}\n        >\n          <svg\n            className=\"w-[11px] h-[11px] flex-shrink-0\"\n            viewBox=\"0 0 20 20\"\n            fill=\"currentColor\"\n            aria-hidden=\"true\"\n          >\n            <path\n              fillRule=\"evenodd\"\n              d=\"M10 18a8 8 0 100-16 8 8 0 000 16zM9 9a1 1 0 012 0v4a1 1 0 11-2 0V9zm1-4a1 1 0 100 2 1 1 0 000-2z\"\n              clipRule=\"evenodd\"\n            />\n          </svg>\n          {shownError.message}\n        </span>\n      )}\n    </div>\n  );\n}\n","import type { FieldDescriptor } from './MasterDocument.types';\n\n/**\n * Soporte declarativo de bloqueo de campos del MasterDocument (FEAT-104).\n *\n * A diferencia de `editableOn` (que decide si un campo es editable según el\n * estado), `lockedWhen` mantiene el campo visible y editable por estado pero lo\n * renderiza con un candado + tooltip cuando una condición de negocio impide\n * cambiarlo (p.ej. el documento ya tiene líneas).\n *\n * El bloqueo aplica cuando se cumplen TODAS las condiciones presentes en\n * `lockedWhen`. El estado `hasLines` lo deriva el kit (`lines.length > 0`); el\n * consumidor no lo inyecta.\n *\n * @see MasterDocument.types - FieldDescriptor.lockedWhen, FieldLockCondition\n */\nexport function isFieldLocked(\n  field: Pick<FieldDescriptor, 'lockedWhen'>,\n  docState: string,\n  hasLines: boolean,\n): boolean {\n  const lock = field.lockedWhen;\n  if (!lock) return false;\n  const stateMatch =\n    !lock.states || lock.states.length === 0 || lock.states.includes(docState);\n  // `hasLines: true` → bloquea solo con líneas; `hasLines: false` → solo sin líneas.\n  const linesMatch = lock.hasLines === undefined || lock.hasLines === hasLines;\n  return stateMatch && linesMatch;\n}\n","import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { clsx } from 'clsx';\n\n/**\n * CanonTabsBar — la barra de pestañas del canon de UI/UX, píxel a píxel.\n *\n * Reproduce la barra que `MasterCrud` dibuja a partir de `formTabs`, tal y como la fija el\n * **ADR-027 §C**. Existe para que `MasterDocument` deje de tener DOS diseños propios de\n * pestañas —el subrayado de `HeaderRenderer` (14px, `border-b-2`) y los chips redondeados de\n * `LineTabsBar`— y ninguno de los dos se pareciese al de MasterCrud. Al vivir el estilo en UN\n * solo sitio, los dos consumidores no pueden volver a divergir en el siguiente PR\n * (ADR-027 §Apéndice C, «un solo dueño del estilo»).\n *\n * Lo que el canon fija y aquí se copia literal (§C.2, Regla A.2 — copiar, nunca aproximar):\n *\n * - botón `px-3 py-1.5 text-xs font-semibold`, `rounded-t-lg`, fondo `#f8f9fc`;\n * - activa `text-[#0c6ade]`; inactiva en `content-tertiary` con hover a `content-primary`;\n * - indicador deslizante: UN solo `<span aria-hidden>` de `2.5px` de grosor CONSTANTE\n *   (Regla C.1 — no se deriva de la pestaña), `rounded-[3px]`, `bg-[#0e79fd]`;\n * - los dos ejes del movimiento llevan curvas DISTINTAS a propósito: el rebote de la barra\n *   sale del `overshoot` de `left`. Va en estilo inline porque son dos transiciones con\n *   curvas distintas por propiedad, no un valor de la escala de Tailwind.\n *\n * Los colores son hex literales y no clases de paleta: la paleta de Tailwind v4 es `oklch`\n * y no reproduce estos hex —`bg-blue-600` no es `#0e79fd`— (Regla C.2).\n *\n * El indicador se coloca MIDIENDO la pestaña activa, así que se recalcula al cambiar de\n * pestaña, al redimensionar y cuando las etiquetas se resuelven: un catálogo i18n que llega\n * tarde cambia el ancho de todas.\n *\n * Accesibilidad: emite `role=\"tablist\"` / `role=\"tab\"` con `aria-selected`, `aria-controls`\n * y el `tabIndex` rotatorio del patrón ARIA Tabs, más las flechas ←/→ e Inicio/Fin. Eso lo\n * traía `LineTabsBar` y se conserva aquí — el canon de MasterCrud no lo tiene, y perderlo\n * al homologar habría sido cambiar apariencia a costa de comportamiento.\n *\n * @see ADR-027 §C — el canon literal\n */\nexport interface CanonTab {\n  /** Identificador estable de la pestaña. Viaja a `data-tabkey` y a los `id` de ARIA. */\n  key: string;\n  /** Rótulo visible, ya traducido. */\n  label: React.ReactNode;\n  /** Icono opcional a la izquierda del rótulo. */\n  icon?: React.ReactNode;\n  /** `true` si la pestaña contiene algún campo obligatorio (§C.3: asterisco rojo). */\n  hasRequired?: boolean;\n  /** Nº de campos que siguen bloqueando el guardado (§C.3: badge rojo). `0` no pinta nada. */\n  missingCount?: number;\n}\n\nexport interface CanonTabsBarProps {\n  tabs: CanonTab[];\n  activeKey: string;\n  onChange: (key: string) => void;\n  /** Rótulo accesible de la barra. */\n  ariaLabel?: string;\n  /** Prefijo de los `id` de ARIA, para poder montar dos barras en una misma página. */\n  idPrefix?: string;\n  /**\n   * `data-testid` de la barra. Por defecto `tabs`, que es el gancho del canon (§C.6).\n   * Se puede cambiar porque `MasterDocument` monta DOS barras a la vez —la del encabezado y\n   * la de líneas— y dos elementos con el mismo testid hacen que `getByTestId` lance por\n   * ambigüedad en vez de encontrar el que se busca.\n   */\n  testId?: string;\n  className?: string;\n}\n\nexport function CanonTabsBar({\n  tabs,\n  activeKey,\n  onChange,\n  ariaLabel,\n  idPrefix = 'tab',\n  testId = 'tabs',\n  className,\n}: CanonTabsBarProps) {\n  const listRef = useRef<HTMLDivElement>(null);\n  const buttonRefs = useRef<Record<string, HTMLButtonElement | null>>({});\n  const [indicator, setIndicator] = useState<{ left: number; width: number } | null>(null);\n\n  // El indicador se posiciona midiendo la pestaña activa (§C.2). `data-tabkey` no es sólo un\n  // gancho de test: es cómo la barra encuentra el botón que tiene que medir.\n  const medirIndicador = useCallback(() => {\n    const list = listRef.current;\n    const btn = buttonRefs.current[activeKey];\n    if (!list || !btn) return;\n    const l = list.getBoundingClientRect();\n    const b = btn.getBoundingClientRect();\n    const left = Math.round(b.left - l.left + list.scrollLeft);\n    const width = Math.round(b.width);\n    // Sólo se re-renderiza si cambia: esto también cuelga de un ResizeObserver.\n    setIndicator((prev) => (prev && prev.left === left && prev.width === width ? prev : { left, width }));\n  }, [activeKey]);\n\n  // `useLayoutEffect`: se mide y se aplica ANTES del primer paint, así el indicador no se ve\n  // primero en el sitio equivocado y luego recolocado.\n  useLayoutEffect(() => { medirIndicador(); }, [medirIndicador, tabs]);\n\n  useEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n    window.addEventListener('resize', medirIndicador);\n    // Las etiquetas pueden cambiar de ancho después del primer render (el catálogo i18n que\n    // llega tarde), y eso no dispara `resize`.\n    const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(medirIndicador) : null;\n    if (ro) { ro.observe(list); Array.from(list.children).forEach((c) => ro.observe(c)); }\n    return () => { window.removeEventListener('resize', medirIndicador); ro?.disconnect(); };\n  }, [medirIndicador, tabs]);\n\n  const handleKeyDown = useCallback(\n    (event: React.KeyboardEvent<HTMLButtonElement>) => {\n      const keys = tabs.map((tab) => tab.key);\n      const current = keys.indexOf(activeKey);\n      if (current === -1) return;\n      let next = current;\n      switch (event.key) {\n        case 'ArrowLeft': next = current === 0 ? keys.length - 1 : current - 1; break;\n        case 'ArrowRight': next = current === keys.length - 1 ? 0 : current + 1; break;\n        case 'Home': next = 0; break;\n        case 'End': next = keys.length - 1; break;\n        default: return;\n      }\n      event.preventDefault();\n      const nextKey = keys[next];\n      onChange(nextKey);\n      // El foco sigue a la activación: es lo que espera el patrón ARIA Tabs cuando la\n      // activación es automática.\n      buttonRefs.current[nextKey]?.focus();\n    },\n    [tabs, activeKey, onChange],\n  );\n\n  return (\n    <div\n      ref={listRef}\n      role=\"tablist\"\n      aria-label={ariaLabel}\n      data-testid={testId}\n      className={clsx(\n        'relative flex items-end gap-0.5 overflow-x-auto',\n        'border-b border-border-secondary dark:border-dark-border-primary',\n        className,\n      )}\n    >\n      {tabs.map((tab) => {\n        const isActive = tab.key === activeKey;\n        return (\n          <button\n            key={tab.key}\n            ref={(node) => { buttonRefs.current[tab.key] = node; }}\n            type=\"button\"\n            role=\"tab\"\n            id={`${idPrefix}-${tab.key}`}\n            data-tabkey={tab.key}\n            data-testid={`tab-${tab.key}`}\n            aria-selected={isActive}\n            aria-controls={`${idPrefix}panel-${tab.key}`}\n            tabIndex={isActive ? 0 : -1}\n            onClick={() => onChange(tab.key)}\n            onKeyDown={handleKeyDown}\n            className={clsx(\n              'tab-btn relative shrink-0 flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold whitespace-nowrap',\n              'cursor-pointer rounded-t-lg bg-[#f8f9fc] dark:bg-dark-bg-secondary transition-colors focus:outline-none',\n              isActive\n                ? 'text-[#0c6ade]'\n                : 'text-content-tertiary dark:text-dark-content-tertiary hover:text-content-primary dark:hover:text-dark-content-primary hover:bg-[#eef0f3] dark:hover:bg-white/[0.06]',\n            )}\n          >\n            {tab.icon && (\n              <span className=\"shrink-0 [&>svg]:w-3.5 [&>svg]:h-3.5\" aria-hidden=\"true\">{tab.icon}</span>\n            )}\n            {tab.label}\n            {tab.hasRequired && <span className=\"text-[#dc2626]\">*</span>}\n            {(tab.missingCount ?? 0) > 0 && (\n              <span className=\"inline-flex items-center justify-center min-w-4 h-4 px-1 bg-[#dc2626] text-white rounded-full text-[9px] font-bold\">\n                {tab.missingCount}\n              </span>\n            )}\n          </button>\n        );\n      })}\n\n      {/* Indicador deslizante: UN solo span sobre la pestaña activa (§C.2). Grosor constante\n          de 2.5px (Regla C.1). Los dos ejes llevan curvas distintas a propósito — el\n          `overshoot` de `left` es lo que da el rebote de la barra. */}\n      {indicator && (\n        <span\n          aria-hidden=\"true\"\n          className=\"absolute bottom-0 h-[2.5px] rounded-[3px] bg-[#0e79fd] pointer-events-none\"\n          style={{\n            left: indicator.left,\n            width: indicator.width,\n            transition: 'left .5s cubic-bezier(.34,1.56,.64,1), width .42s cubic-bezier(.22,1,.36,1)',\n          }}\n        />\n      )}\n    </div>\n  );\n}\n","import type { LookupFieldConfig } from './MasterDocument.types';\n\n// ════════════════════════════════════════════════════════════\n// CASCADING LOOKUPS — runtime para filterDependencies\n// ════════════════════════════════════════════════════════════\n\n/** Un valor de filtro vacío (null/undefined/\"\") no debe enviarse al backend. */\nexport function isFilterValueEmpty(v: unknown): boolean {\n  return v === null || v === undefined || v === '';\n}\n\nexport interface DependentLookupProps {\n  /** getFilters dinámico: combina filters estáticos + dinámicos por padre. */\n  getFilters: () => Record<string, unknown>;\n  /** Valores actuales de los campos padre (disparan recarga al cambiar). */\n  dependencies: unknown[];\n  /** true si falta el valor de algún padre → el searcher debe deshabilitarse. */\n  parentMissing: boolean;\n}\n\n/**\n * Construye los props `getFilters`/`dependencies` para un LookupField cuyo\n * config declara `filterDependencies` (cascading lookups). Devuelve `undefined`\n * cuando el config no tiene `filterDependencies` (comportamiento legacy intacto).\n *\n * Semántica de filterDependencies: clave = campo de filtro que espera el backend;\n * valor = key del campo del formulario cuyo valor se usa como filtro.\n *\n * @param config   Config del LookupField (puede incluir `filters` estáticos).\n * @param resolve  Resuelve la key de un campo del formulario a su valor actual.\n */\nexport function buildDependentLookupProps(\n  config: LookupFieldConfig | undefined,\n  resolve: (formKey: string) => unknown,\n): DependentLookupProps | undefined {\n  const deps = config?.filterDependencies;\n  if (!config || !deps) return undefined;\n  const entries = Object.entries(deps); // [backendField, formKey]\n  if (entries.length === 0) return undefined;\n\n  const parentValues = entries.map(([, formKey]) => resolve(formKey));\n  const parentMissing = parentValues.some(isFilterValueEmpty);\n\n  // Sólo se mergea la forma de objeto simple; la forma de array (FilterExpression)\n  // no se combina con el objeto dinámico.\n  const staticFilters =\n    config.filters && !Array.isArray(config.filters)\n      ? (config.filters as Record<string, unknown>)\n      : undefined;\n\n  const getFilters = () => {\n    const dynamic: Record<string, unknown> = {};\n    entries.forEach(([backendField, formKey]) => {\n      const v = resolve(formKey);\n      // OMITE entradas vacías: nunca mandar `{ campo: undefined }`.\n      if (!isFilterValueEmpty(v)) dynamic[backendField] = v;\n    });\n    return { ...(staticFilters ?? {}), ...dynamic };\n  };\n\n  return { getFilters, dependencies: parentValues, parentMissing };\n}\n\n/**\n * Mapea, en reversa, key de campo padre → keys de searchers dependientes, a\n * partir de un conjunto de LookupFieldConfig. Se usa para limpiar el valor del\n * dependiente cuando cambia un padre (p.ej. al cambiar bodega, resetear ubicación).\n *\n * @param lookupConfigs  Mapa de configs por key de campo.\n * @param onlyKeys       Si se provee, sólo considera dependientes en este set\n *                       (p.ej. los campos presentes en el form de línea).\n */\nexport function buildDependentsByParent(\n  lookupConfigs: Record<string, LookupFieldConfig> | undefined,\n  onlyKeys?: Set<string>,\n): Record<string, string[]> {\n  const map: Record<string, string[]> = {};\n  if (!lookupConfigs) return map;\n  for (const [depKey, cfg] of Object.entries(lookupConfigs)) {\n    if (onlyKeys && !onlyKeys.has(depKey)) continue;\n    const deps = cfg.filterDependencies;\n    if (!deps) continue;\n    for (const parentKey of Object.values(deps)) {\n      if (parentKey === depKey) continue; // un campo no se depende de sí mismo\n      (map[parentKey] ??= []).push(depKey);\n    }\n  }\n  return map;\n}\n","import { useState, useCallback, useEffect, useMemo } from 'react';\nimport { clsx } from 'clsx';\nimport { FieldRenderer } from './FieldRenderer';\nimport { isFieldLocked } from './fieldLock';\nimport { isEmptyValue } from './fieldValidation';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { CanonTabsBar } from './CanonTabsBar';\nimport { buildDependentLookupProps, buildDependentsByParent, isFilterValueEmpty } from './lookupFilters';\nimport type {\n  HeaderRendererProps,\n  SectionConfig,\n  FieldDescriptor,\n  FieldErrorMap,\n  DocumentHeaderData,\n  LookupFieldConfig,\n} from './MasterDocument.types';\n\n// ─── Chevron icon ──────────────────────────────────────────\n\nfunction ChevronIcon({ open, className }: { open: boolean; className?: string }) {\n  return (\n    <svg\n      className={clsx(\n        'w-4 h-4 transition-transform duration-150',\n        open ? 'rotate-90' : 'rotate-0',\n        className,\n      )}\n      viewBox=\"0 0 20 20\"\n      fill=\"currentColor\"\n    >\n      <path fillRule=\"evenodd\" d=\"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z\" clipRule=\"evenodd\" />\n    </svg>\n  );\n}\n\n// ─── Fields Grid ───────────────────────────────────────────\n\nfunction FieldsGrid({\n  fields,\n  values,\n  errors,\n  onFieldChange,\n  docState,\n  modeForm,\n  hasLines,\n  gridColumns,\n  lookupConfigs,\n  fetcher,\n  onRecordSelect,\n  paddingX = 'px-4',\n}: {\n  fields: FieldDescriptor[];\n  values: DocumentHeaderData;\n  errors?: FieldErrorMap;\n  onFieldChange: (key: string, value: unknown) => void;\n  docState: string;\n  modeForm: 'create' | 'edit' | 'view';\n  hasLines: boolean;\n  gridColumns: 1 | 2 | 3 | 4;\n  lookupConfigs?: Record<string, LookupFieldConfig>;\n  fetcher?: unknown;\n  onRecordSelect?: (fieldKey: string, record: Record<string, unknown> | null) => void;\n  /**\n   * Padding horizontal de la rejilla. Lo decide el LLAMADOR porque los dos que hay\n   * viven en cajas distintas: en el acordeón la rejilla cuelga de una cabecera con\n   * `px-4` y tiene que cuadrar con ella, mientras que en el panel de pestañas el\n   * gutter ya lo pone la tarjeta y un `px-4` propio se le SUMABA —el primer campo\n   * quedaba 16px más adentro que la primera pestaña de su barra.\n   */\n  paddingX?: string;\n}) {\n  const sorted = [...fields].sort((a, b) => a.order - b.order);\n\n  const gridClass = {\n    1: 'grid-cols-1',\n    2: 'grid-cols-1 sm:grid-cols-2',\n    3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',\n    4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4',\n  }[gridColumns];\n\n  return (\n    <div className={clsx('grid gap-4 py-4', paddingX, gridClass)}>\n      {sorted.map((field) => {\n        const isEditable = field.editableOn.includes(docState) && modeForm !== 'view';\n        const locked = isFieldLocked(field, docState, hasLines);\n        const spanClass = {\n          1: '',\n          2: 'sm:col-span-2',\n          3: 'sm:col-span-2 lg:col-span-3',\n          4: 'sm:col-span-2 lg:col-span-4',\n        }[field.span];\n\n        const isSearcher = field.control === 'searcher' || field.control === 'autocomplete';\n        const lookupCfg = isSearcher ? lookupConfigs?.[field.key] : undefined;\n        // Cascading lookups: resuelve cada padre contra los valores de cabecera.\n        const depProps = buildDependentLookupProps(lookupCfg, (k) => values[k]);\n\n        return (\n          <div key={field.key} className={clsx(spanClass)}>\n            <FieldRenderer\n              fieldDef={field}\n              value={values[field.key]}\n              onChange={(v) => onFieldChange(field.key, v)}\n              editable={isEditable}\n              error={errors?.[field.key]}\n              readOnly={modeForm === 'view'}\n              lookupConfig={lookupCfg}\n              fetcher={isSearcher ? fetcher : undefined}\n              onRecordSelect={isSearcher ? (rec) => onRecordSelect?.(field.key, rec) : undefined}\n              getLookupFilters={depProps?.getFilters}\n              lookupDependencies={depProps?.dependencies}\n              disabled={depProps?.parentMissing}\n              locked={locked}\n              lockTooltip={field.lockTooltip}\n              lockTooltipKey={field.lockTooltipKey}\n            />\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\n// ─── Accordion Mode ────────────────────────────────────────\n\nfunction AccordionSection({\n  section,\n  fields,\n  values,\n  errors,\n  onFieldChange,\n  docState,\n  modeForm,\n  hasLines,\n  gridColumns,\n  lookupConfigs,\n  fetcher,\n  onRecordSelect,\n}: {\n  section: SectionConfig;\n  fields: FieldDescriptor[];\n  values: DocumentHeaderData;\n  errors?: FieldErrorMap;\n  onFieldChange: (key: string, value: unknown) => void;\n  docState: string;\n  modeForm: 'create' | 'edit' | 'view';\n  hasLines: boolean;\n  gridColumns: 1 | 2 | 3 | 4;\n  lookupConfigs?: Record<string, LookupFieldConfig>;\n  fetcher?: unknown;\n  onRecordSelect?: (fieldKey: string, record: Record<string, unknown> | null) => void;\n}) {\n  const [open, setOpen] = useState(section.defaultOpen);\n\n  return (\n    <div className=\"overflow-hidden\">\n      <button\n        type=\"button\"\n        onClick={() => setOpen((o) => !o)}\n        className={clsx(\n          'flex items-center justify-between w-full px-4 py-3',\n          'hover:bg-background-secondary transition-all duration-150',\n          'dark:hover:bg-dark-bg-secondary',\n          'focus:outline-hidden focus:ring-2 focus:ring-inset focus:ring-primary-400',\n          'dark:focus:ring-dark-border-custom',\n          open && section.accent && 'border-b-2',\n        )}\n        style={open && section.accent ? { borderBottomColor: section.accent } : undefined}\n        aria-expanded={open}\n      >\n        <div className=\"flex items-center gap-2\">\n          <ChevronIcon open={open} className=\"text-content-secondary dark:text-dark-content-secondary\" />\n          <span className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n            {section.label}\n          </span>\n          {section.subtitle && (\n            <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">\n              {section.subtitle}\n            </span>\n          )}\n        </div>\n      </button>\n\n      {open && (\n        <FieldsGrid\n          fields={fields}\n          values={values}\n          errors={errors}\n          onFieldChange={onFieldChange}\n          docState={docState}\n          modeForm={modeForm}\n          hasLines={hasLines}\n          gridColumns={gridColumns}\n          lookupConfigs={lookupConfigs}\n          fetcher={fetcher}\n          onRecordSelect={onRecordSelect}\n        />\n      )}\n    </div>\n  );\n}\n\n// ─── Tabs Mode ─────────────────────────────────────────────\n\nfunction TabsRenderer({\n  sections,\n  fieldsBySection,\n  values,\n  errors,\n  onFieldChange,\n  docState,\n  modeForm,\n  hasLines,\n  gridColumns,\n  lookupConfigs,\n  fetcher,\n  onRecordSelect,\n}: {\n  sections: SectionConfig[];\n  fieldsBySection: Record<string, FieldDescriptor[]>;\n  values: DocumentHeaderData;\n  errors?: FieldErrorMap;\n  onFieldChange: (key: string, value: unknown) => void;\n  docState: string;\n  modeForm: 'create' | 'edit' | 'view';\n  hasLines: boolean;\n  gridColumns: 1 | 2 | 3 | 4;\n  lookupConfigs?: Record<string, LookupFieldConfig>;\n  fetcher?: unknown;\n  onRecordSelect?: (fieldKey: string, record: Record<string, unknown> | null) => void;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const [activeTab, setActiveTab] = useState(sections[0]?.key ?? '');\n\n  useEffect(() => {\n    if (sections.length > 0 && !sections.find((s) => s.key === activeTab)) {\n      setActiveTab(sections[0].key);\n    }\n  }, [sections, activeTab]);\n\n  // `activeSection` se usaba sólo para pintar el subrayado con el `accent` de la sección.\n  // El indicador del canon es de un color fijo (#0e79fd), así que ya no hace falta aquí.\n  const activeFields = fieldsBySection[activeTab] ?? [];\n\n  /**\n   * Señalización de obligatorios por pestaña (ADR-027 §C.3).\n   *\n   * - **asterisco** (`hasRequired`): la pestaña contiene al menos un campo\n   *   obligatorio. Se ve desde el primer render, sin haber intentado guardar.\n   * - **badge** (`missingCount`): cuántos de esos obligatorios siguen bloqueando\n   *   el guardado. Sólo aparece DESPUÉS de un intento, que es cuando el\n   *   contenedor llena `errors`.\n   *\n   * Las dos marcas salen de la MISMA obligatoriedad que declara la plantilla, no\n   * de dos fuentes distintas: por eso el badge cuenta únicamente campos\n   * `required`, y así nunca puede haber una pestaña con número y sin asterisco\n   * —la contradicción que el §C.3b describe y que el usuario no puede resolver\n   * porque nada en esa pestaña parecía obligatorio—.\n   *\n   * `fieldsBySection` ya viene filtrado por visibilidad, así que un campo oculto\n   * por condición o por permiso no infla la cuenta.\n   */\n  const tabsMeta = useMemo(() => {\n    const errorMap = errors ?? {};\n    const seIntentoGuardar = Object.keys(errorMap).length > 0;\n    /*\n     * La noción de \"vacío\" es la MISMA que usa el borde rojo del campo y la regla\n     * `required` del motor de validación (`isEmptyValue`), no una copia local. Con una\n     * copia, un campo con solo espacios recibía borde rojo y mensaje de obligatorio y a\n     * la vez NO lo contaba este badge: dos señales de la misma obligatoriedad\n     * contradiciéndose, que es exactamente lo que el §C.3b prohíbe.\n     */\n\n    /*\n     * En SOLO LECTURA no se señala nada. El asterisco existe para decir «esto hay que\n     * llenarlo», y en un documento que no se puede editar no hay nada que llenar:\n     * marcarlo deja la pestaña afirmando un requisito que su propio campo no muestra\n     * —`FieldRenderer` sólo pinta el asterisco cuando el campo es editable—, que es\n     * exactamente la contradicción que el §C.3b prohíbe. Medido en dev el 2026-09-09\n     * sobre una devolución aprobada: la pestaña «Generales» traía `*` y su único campo,\n     * de sólo lectura, no.\n     */\n    const enSoloLectura = modeForm === 'view';\n\n    return sections.map((section) => {\n      const obligatorios = (fieldsBySection[section.key] ?? []).filter(\n        // `required` no basta: un campo de control `readonly`/`display` NUNCA pinta\n        // asterisco (ver `isReadOnly` en FieldRenderer) y el usuario tampoco puede\n        // rellenarlo, así que contarlo dejaba la pestaña marcada con un pendiente que\n        // nadie podía cerrar. El modo `view` es el mismo caso a nivel de documento.\n        (f) => f.required && f.control !== 'readonly' && f.control !== 'display',\n      );\n      return {\n        key: section.key,\n        label: section.label,\n        hasRequired: !enSoloLectura && obligatorios.length > 0,\n        missingCount: !enSoloLectura && seIntentoGuardar\n          ? obligatorios.filter((f) => errorMap[f.key] !== undefined || isEmptyValue(values[f.key])).length\n          : 0,\n      };\n    });\n  }, [sections, fieldsBySection, errors, values, modeForm]);\n\n  return (\n    <div>\n      {/*\n        Barra de pestañas del canon (ADR-027 §C.2), a través de `CanonTabsBar`.\n        Antes esta barra pintaba su propio diseño —14px/600 con `border-b-2` estático y el\n        fondo de la inactiva en `background-secondary`—, que no es el de MasterCrud: 12px,\n        `rounded-t-lg` sobre #f8f9fc, activa en #0c6ade e indicador deslizante de 2.5px.\n        Medido el 2026-09-04 sobre /app/items y /app/core/purchases/purchase-requests-direct.\n\n        El `accent` por sección deja de pintar el subrayado: el indicador del canon es de un\n        solo color (#0e79fd, Regla C.1/C.2) y admitir un color por pestaña reintroduciría la\n        divergencia que este cambio cierra. El `accent` sigue vivo en el modo acordeón.\n      */}\n      {/*\n        Con UNA sola sección no se pinta barra: una pestaña solitaria no ofrece ninguna\n        elección y sólo añade una franja que el usuario no puede usar. Cuatro documentos del\n        catálogo de core están en ese caso (solicitudes de compra directa, requisiciones de\n        consumo, traslados directos y conteos físicos), así que no es un caso de borde.\n      */}\n      {sections.length > 1 && (\n        <CanonTabsBar\n          tabs={tabsMeta}\n          activeKey={activeTab}\n          onChange={setActiveTab}\n          ariaLabel={t('master_document.header.sectionsAria')}\n          idPrefix=\"header-tab\"\n        />\n      )}\n\n      {/*\n        Panel con su relación ARIA completa. La barra emite `aria-controls`, así que sin\n        este `role=\"tabpanel\"` con el `id` que espera, el atributo apuntaba a un elemento\n        que no existe: un lector de pantalla anuncia la pestaña y no encuentra la región que\n        gobierna. De paso cierra, para el encabezado, el hueco que el ADR-027 §C.5a deja\n        declarado como conocido en el canon de MasterCrud.\n      */}\n      <div\n        role=\"tabpanel\"\n        id={`header-tabpanel-${activeTab}`}\n        aria-labelledby={sections.length > 1 ? `header-tab-${activeTab}` : undefined}\n      >\n      <FieldsGrid\n        fields={activeFields}\n        values={values}\n        errors={errors}\n        onFieldChange={onFieldChange}\n        docState={docState}\n        modeForm={modeForm}\n        hasLines={hasLines}\n        gridColumns={gridColumns}\n        lookupConfigs={lookupConfigs}\n        fetcher={fetcher}\n        onRecordSelect={onRecordSelect}\n        // Sin gutter propio: el de la tarjeta ya lo pone el contenedor de arriba, y\n        // sumar otro metía el primer campo 16px más adentro que la primera pestaña de\n        // su propia barra. En el acordeón sí hace falta (ver `paddingX`).\n        paddingX=\"\"\n      />\n      </div>\n    </div>\n  );\n}\n\n// ─── HeaderRenderer ────────────────────────────────────────\n\n/**\n * Renderizador del encabezado del documento maestro.\n *\n * Soporta dos modos de visualización: `accordion` (secciones colapsables)\n * y `tabs` (pestañas horizontales). Cada sección agrupa campos renderizados\n * por `FieldRenderer` en un grid responsivo configurable.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - HeaderRendererProps, SectionConfig\n *\n * @example\n * ```tsx\n * <HeaderRenderer\n *   mode=\"accordion\"\n *   columns={3}\n *   sections={[{ key: 'general', label: 'Información general', defaultOpen: true }]}\n *   fieldsBySection={{ general: fields }}\n *   values={headerData}\n *   onFieldChange={(key, value) => updateHeader(key, value)}\n *   docState=\"DRAFT\"\n *   mode_form=\"edit\"\n * />\n * ```\n */\nexport function HeaderRenderer({\n  mode,\n  columns,\n  sections,\n  fieldsBySection,\n  values,\n  errors,\n  onFieldChange,\n  docState,\n  mode_form,\n  hasLines = false,\n  className,\n  lookupConfigs,\n  fetcher,\n  onRecordSelect,\n}: HeaderRendererProps) {\n  // Mapa padre → dependientes para limpiar el dependiente al cambiar un padre.\n  const dependentsByParent = useMemo(\n    () => buildDependentsByParent(lookupConfigs),\n    [lookupConfigs],\n  );\n\n  const handleFieldChange = useCallback(\n    (key: string, value: unknown) => {\n      onFieldChange(key, value);\n      // Al cambiar un padre, resetea los searchers dependientes (sólo si tienen\n      // valor) para no dejar un valor inválido del padre anterior. Sólo ocurre en\n      // cambios del usuario, no en la carga programática (get-by-id).\n      const dependents = dependentsByParent[key];\n      if (dependents) {\n        dependents.forEach((depKey) => {\n          if (!isFilterValueEmpty(values[depKey])) onFieldChange(depKey, null);\n        });\n      }\n    },\n    [onFieldChange, dependentsByParent, values],\n  );\n\n  // Errores cuya key no coincide con ningún campo → banner form-level\n  const allFieldKeys = new Set(\n    Object.values(fieldsBySection).flat().map((f) => f.key),\n  );\n  const formLevelErrors = errors\n    ? Object.entries(errors).filter(([key]) => !allFieldKeys.has(key))\n    : [];\n\n  return (\n    // SIN tarjeta propia: el encabezado ya vive dentro de la tarjeta blanca del\n    // detalle, y envolverlo en otra pintaba una segunda caja concéntrica\n    // alrededor de la barra de pestañas (ADR-027 §E.7, «una caja, no dos»). Es\n    // justo lo que hacía que las pestañas de MasterDocument se vieran metidas en\n    // un recuadro y las de MasterCrud no.\n    <div className={clsx('min-w-0', className)}>\n      {formLevelErrors.length > 0 && (\n        <div\n          role=\"alert\"\n          className=\"mx-4 mt-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 dark:border-red-800 dark:bg-red-950/20\"\n        >\n          {formLevelErrors.map(([key, err]) => (\n            <p key={key} className=\"text-sm text-red-700 dark:text-red-400\">\n              {err.message}\n            </p>\n          ))}\n        </div>\n      )}\n      {mode === 'accordion' ? (\n        sections.map((section) => (\n          <AccordionSection\n            key={section.key}\n            section={section}\n            fields={fieldsBySection[section.key] ?? []}\n            values={values}\n            errors={errors}\n            onFieldChange={handleFieldChange}\n            docState={docState}\n            modeForm={mode_form}\n            hasLines={hasLines}\n            gridColumns={columns}\n            lookupConfigs={lookupConfigs}\n            fetcher={fetcher}\n            onRecordSelect={onRecordSelect}\n          />\n        ))\n      ) : (\n        <TabsRenderer\n          sections={sections}\n          fieldsBySection={fieldsBySection}\n          values={values}\n          errors={errors}\n          onFieldChange={handleFieldChange}\n          docState={docState}\n          modeForm={mode_form}\n          hasLines={hasLines}\n          gridColumns={columns}\n          lookupConfigs={lookupConfigs}\n          fetcher={fetcher}\n          onRecordSelect={onRecordSelect}\n        />\n      )}\n    </div>\n  );\n}\n","import { useEffect, useRef } from 'react';\nimport { clsx } from 'clsx';\nimport type { LineContextMenuProps } from './MasterDocument.types';\n\n/**\n * Menú contextual flotante para acciones sobre una línea de detalle\n * (editar, duplicar, eliminar). Se posiciona en las coordenadas del clic\n * y se cierra al hacer clic fuera o presionar Escape.\n *\n * @see MasterDocument.types - LineContextMenuProps\n */\nexport function LineContextMenu({\n  open,\n  position,\n  onClose,\n  items,\n  className,\n}: LineContextMenuProps) {\n  const menuRef = useRef<HTMLDivElement>(null);\n\n  // Close on click outside or Escape\n  useEffect(() => {\n    if (!open) return;\n\n    function handleClick(e: MouseEvent) {\n      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {\n        onClose();\n      }\n    }\n\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n\n    document.addEventListener('mousedown', handleClick);\n    document.addEventListener('keydown', handleKey);\n    return () => {\n      document.removeEventListener('mousedown', handleClick);\n      document.removeEventListener('keydown', handleKey);\n    };\n  }, [open, onClose]);\n\n  if (!open) return null;\n\n  return (\n    <div\n      ref={menuRef}\n      className={clsx(\n        'fixed z-[200] min-w-[190px] py-1.5 rounded-xl bg-bg-primary',\n        'shadow-lg',\n        'animate-[slideDown_150ms_ease-out]',\n        'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n        className,\n      )}\n      style={{ top: position.y, left: position.x }}\n      role=\"menu\"\n    >\n      {items.map((item, index) => (\n        <div key={index}>\n          {item.separator && (\n            <div className=\"h-px bg-border-secondary dark:bg-dark-border-primary my-1\" />\n          )}\n          <button\n            type=\"button\"\n            role=\"menuitem\"\n            disabled={item.disabled}\n            onClick={() => {\n              if (item.disabled) return;\n              item.onClick();\n              onClose();\n            }}\n            className={clsx(\n              'flex items-center gap-2.5 w-full px-4 py-[9px] text-sm text-left transition-all duration-150',\n              item.disabled\n                ? 'text-content-tertiary opacity-50 cursor-not-allowed dark:text-dark-content-secondary'\n                : item.danger\n                  ? 'text-error-content hover:bg-error-bg dark:hover:bg-error-content/10'\n                  : 'text-content-primary hover:bg-primary-100 dark:text-dark-content-primary dark:hover:bg-dark-bg-secondary',\n            )}\n          >\n            {item.icon && <span className=\"w-4 h-4 shrink-0\">{item.icon}</span>}\n            {item.label}\n          </button>\n        </div>\n      ))}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { LineFulfillmentBadgeProps, LineFulfillmentStatus } from './MasterDocument.types';\n\nconst STATUS_CONFIG: Record<\n  LineFulfillmentStatus,\n  { translationKey: string; bg: string; text: string; dot: string }\n> = {\n  Pending: {\n    translationKey: 'master_document.lineFulfillment.pending',\n    bg: 'bg-zinc-100',\n    text: 'text-zinc-600',\n    dot: 'bg-zinc-400',\n  },\n  Partial: {\n    translationKey: 'master_document.lineFulfillment.partial',\n    bg: 'bg-amber-100',\n    text: 'text-amber-700',\n    dot: 'bg-amber-500',\n  },\n  Fulfilled: {\n    translationKey: 'master_document.lineFulfillment.fulfilled',\n    bg: 'bg-green-100',\n    text: 'text-green-700',\n    dot: 'bg-green-500',\n  },\n  Closed: {\n    translationKey: 'master_document.lineFulfillment.closed',\n    bg: 'bg-red-100',\n    text: 'text-red-700',\n    dot: 'bg-red-500',\n  },\n};\n\n/**\n * LineFulfillmentBadge — indica el estado de cumplimiento de una línea de documento cruzado.\n *\n * Los colores se mantienen vibrantes en dark mode (mismo patrón que Badge),\n * sin necesidad de variantes dark: según la especificación Figma del sistema.\n *\n * @see docs/colors.md — Tokens de color del sistema\n */\nexport function LineFulfillmentBadge({ status, className }: LineFulfillmentBadgeProps) {\n  const { t } = useMasterDocumentTranslation();\n  const config = STATUS_CONFIG[status];\n  const label = t(config.translationKey);\n\n  return (\n    <span\n      role=\"status\"\n      aria-label={label}\n      className={clsx(\n        'inline-flex items-center gap-1 px-1.5 py-1 rounded-md font-sans text-xs leading-4 font-bold select-none',\n        config.bg,\n        config.text,\n        className,\n      )}\n    >\n      <span className={clsx('w-1.5 h-1.5 rounded-full flex-shrink-0', config.dot)} />\n      {label}\n    </span>\n  );\n}\n","import React from 'react';\n\n/**\n * Estilo de los botones de la columna «Acciones», literal del canon de\n * MasterCrud (`MasterCrudTable.tsx` → `ROW_ACTION_BTN`): es el MISMO diseño que\n * el botón secundario «Cancelar» del detalle, o sea el `Button` del kit con\n * `type=\"outline\" color=\"primary\" size=\"xs\" iconOnly` (28x28).\n *\n * Vive aquí y no en cada tabla porque `MasterDocument` tiene DOS rejillas con\n * acciones por fila —el listado de documentos y la grilla de líneas— y con una\n * copia en cada una vuelven a divergir en el siguiente PR (ADR-027 §Apéndice C,\n * «un solo dueño del estilo»).\n *\n * La cadena se copia en vez de montar el `Button` por dos razones que ya\n * documenta MasterCrud: el kebab necesita `ref` para posicionar su portal y el\n * `Button` del kit no es `forwardRef`, y `buttonVariants` no se exporta.\n */\nexport const ROW_ACTION_BTN =\n  'inline-flex items-center justify-center w-7 h-7 rounded-md font-medium whitespace-nowrap transition-all duration-150 cursor-pointer ' +\n  'focus:outline-hidden focus:ring-4 focus:ring-offset-2 ' +\n  'disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none ' +\n  'bg-transparent border shadow-xs hover:brightness-98 dark:hover:brightness-102 ' +\n  'text-primary-600 dark:text-primary-400 border-primary-300 dark:border-primary-700 ' +\n  'hover:bg-primary-100 dark:hover:bg-primary-950 ' +\n  'focus:ring-primary-400 focus:ring-offset-primary-100 dark:focus:ring-primary-500/50 dark:focus:ring-offset-gray-900';\n\n/** Utilidades de tamaño de Tailwind (`w-4`, `h-3.5`, `size-4`, `w-[15px]`…). */\nconst UTILIDADES_DE_TAMANO =\n  /(^|\\s)(?:w|h|size)-(?:\\d+(?:\\.\\d+)?|px|full|auto|screen|min|max|fit|\\[[^\\]]*\\])(?=\\s|$)/g;\n\n/**\n * Encaja el icono de una acción en la caja de 15x15 del contenedor.\n *\n * El consumidor declara el icono con SU propia clase de tamaño —`w-4 h-4`, es\n * decir 16px— y esos 16 no caben en 15: el flex encoge el ancho y deja el alto,\n * así que el icono sale deformado. Se sustituyen SOLO las clases de tamaño por\n * `size-full` y se conserva el resto (color, `shrink-0`, transiciones). Es la\n * misma función que MasterCrud aplica en su celda de acciones.\n */\nexport function ajustarTamanoIcono(icono: React.ReactNode): React.ReactNode {\n  if (!React.isValidElement<{ className?: string }>(icono)) return icono;\n  const previas = icono.props.className ?? '';\n  const sinTamano = previas.replace(UTILIDADES_DE_TAMANO, ' ').replace(/\\s+/g, ' ').trim();\n  return React.cloneElement(icono, { className: `${sinTamano} size-full`.trim() });\n}\n","import { useState, useCallback, useMemo } from 'react';\nimport { clsx } from 'clsx';\nimport { PencilIcon, EyeIcon, EllipsisVerticalIcon, PlusIcon, TrashIcon, DocumentDuplicateIcon, LockClosedIcon, LockOpenIcon } from '@heroicons/react/24/outline';\n// El MISMO `Table` que pinta el listado de documentos y el de MasterCrud, no una\n// grilla propia. La de antes era TanStack + virtualizador y por eso divergía en\n// todo lo que no se copiara a mano: el hover con acento, el reparto de anchos y el\n// paginador. Se pierde la virtualización, y a cambio la paginación acota el número\n// de filas montadas —que es lo que la virtualización venía a resolver.\nimport { Table } from '../Table';\nimport type { TableColumn } from '../Table/Table.types';\nimport { LineContextMenu } from './LineContextMenu';\nimport { LineFulfillmentBadge } from './LineFulfillmentBadge';\nimport { Loading } from './components/loading';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { ROW_ACTION_BTN } from './rowActionStyles';\n\n/**\n * Filas por página por defecto y suelo de alto de la tabla.\n *\n * Con una o dos líneas la caja quedaba tan baja que no se leía como una tabla —\n * cabecera, una fila y el paginador pegados—. Reservar el alto de cuatro filas le da\n * cuerpo sin inventar filas vacías: el hueco es del contenedor, no de la grilla.\n */\nconst FILAS_POR_DEFECTO = 4;\n/**\n * Suelo de alto de la caja de filas: la cabecera de columnas MÁS cuatro filas, a 44px\n * cada una (la densidad `dense` del canon). Se cuenta la cabecera porque vive DENTRO\n * del mismo `div[role=\"table\"]` al que se aplica el suelo. El paginador queda fuera y\n * suma su propio alto, que es lo correcto — el suelo es de la tabla, no de la caja.\n */\nconst ALTO_MINIMO_TABLA = (FILAS_POR_DEFECTO + 1) * 44;\n\n/**\n * Suelo de ancho de la columna «Acciones»: lo que ocupa su rótulo sin recortarse.\n *\n * Son los 100px del caso de dos botones, que ya es el ancho del canon, y cubren con\n * holgura tanto «Acciones» como «Actions». Va como constante y no medido en tiempo\n * de ejecución a propósito: medir texto obliga a un render intermedio y a leer del\n * layout en cada cambio de datos, y el margen que sobra aquí es de sobra suficiente.\n */\nconst ANCHO_MINIMO_ACCIONES = 100;\n\n/**\n * Por debajo de este ancho, una columna de datos NO se estira para repartirse el\n * espacio sobrante: se queda en lo que declara.\n *\n * Una columna declarada así de estrecha es, por construcción, de código, consecutivo\n * o unidad de medida — a una columna pensada para texto nadie le pone 60px. Sin esto\n * el `#` crecía igual que «Artículo» en cuanto había hueco, y una tabla con pocas\n * columnas acababa con el consecutivo tan ancho como la descripción.\n *\n * La plantilla puede saltárselo declarando `fixedWidth` en su columna.\n */\nconst ANCHO_COLUMNA_UTILITARIA = 100;\n\n/** Casilla de selección de fila, con el foco del canon. */\nconst CHECKBOX_CLS = clsx(\n  'w-4 h-4 rounded border-border-primary accent-primary-custom-600',\n  'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n  'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n);\nimport { Button } from '../Button';\nimport { useMasterDocumentFormatters } from './formatters';\nimport type {\n  LinesSectionProps,\n  DocumentLineData,\n  LineColumnConfig,\n  Breakpoint,\n  LineFulfillmentStatus,\n} from './MasterDocument.types';\n\n// ─── Helpers ───────────────────────────────────────────────\n\nfunction shouldHideColumn(hideOn: Breakpoint[] | undefined, current?: Breakpoint): boolean {\n  if (!hideOn || !current) return false;\n  return hideOn.includes(current);\n}\n\nfunction formatCellValue(\n  value: unknown,\n  format: string | undefined,\n  formatCurrencyCompact: (value: number) => string,\n  formatNumber: (value: number) => string,\n): string {\n  if (value == null) return '—';\n  switch (format) {\n    case 'currency':\n      return formatCurrencyCompact(Number(value));\n    case 'number':\n      return formatNumber(Number(value));\n    case 'percentage':\n      return `${Number(value).toFixed(2)}%`;\n    case 'date':\n      return String(value);\n    default:\n      return String(value);\n  }\n}\n\nfunction isMobileBreakpoint(bp?: Breakpoint): boolean {\n  if (!bp) return false;\n  return bp === 'xs' || bp === 'sm';\n}\n\nfunction isTerminalStatus(status?: LineFulfillmentStatus): boolean {\n  return status === 'Fulfilled' || status === 'Closed';\n}\n\n// ─── Line Card (mobile view) ───────────────────────────────\n\nfunction LineCard({\n  line,\n  columns,\n  onEdit,\n  onView,\n  onMenu,\n  isActive,\n  lineEditable = true,\n  selectionMode,\n  isSelected,\n  isDisabled,\n  onSelect,\n  status,\n  selectionError,\n  isBusy = false,\n}: {\n  line: DocumentLineData;\n  columns: LineColumnConfig[];\n  onEdit: () => void;\n  onView?: () => void;\n  onMenu: (e: React.MouseEvent) => void;\n  isActive: boolean;\n  lineEditable?: boolean;\n  selectionMode?: boolean;\n  isSelected?: boolean;\n  isDisabled?: boolean;\n  onSelect?: () => void;\n  status?: LineFulfillmentStatus;\n  selectionError?: string;\n  /** Mutación en vuelo sobre esta línea. */\n  isBusy?: boolean;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatCurrencyCompact, formatNumber } = useMasterDocumentFormatters();\n  const cardColumns = columns.filter((c) => c.showInCard !== false);\n\n  return (\n    <div\n      className={clsx(\n        'rounded-xl bg-bg-primary p-4',\n        'shadow-[0_1px_3px_rgba(60,64,67,.15),0_1px_2px_rgba(60,64,67,.10)]',\n        'transition-all duration-150',\n        isActive && 'ring-2 ring-primary-600',\n        'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n      )}\n    >\n      <div className=\"flex items-start justify-between gap-2 mb-2\">\n        <div className=\"flex items-center gap-2 min-w-0\">\n          {selectionMode && (\n            <div className=\"flex flex-col\">\n              <input\n                type=\"checkbox\"\n                checked={!!isSelected}\n                disabled={isDisabled}\n                onChange={onSelect}\n                className={clsx(\n                  'w-4 h-4 rounded border-border-primary accent-primary-custom-600',\n                  'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                  'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                  isDisabled && 'opacity-50 cursor-not-allowed',\n                )}\n                aria-label={t('master_document.lines.selectLine')}\n              />\n              {selectionError && (\n                <span className=\"text-xs text-red-600 dark:text-red-400 mt-0.5 whitespace-nowrap\">\n                  {selectionError}\n                </span>\n              )}\n            </div>\n          )}\n          <span className=\"text-xs font-bold text-content-secondary dark:text-dark-content-secondary tabular-nums\">\n            #{line.line_number}\n          </span>\n          {selectionMode && status && (\n            <LineFulfillmentBadge status={status} />\n          )}\n        </div>\n        <div className=\"flex items-center gap-1\">\n          {isBusy ? (\n            // Misma decisión que en la tabla: el indicador SUSTITUYE las acciones\n            // de la fila. En tarjeta ya son visibles siempre, así que aquí basta\n            // con ocupar su sitio.\n            <span className=\"p-1.5\">\n              <Loading size=\"sm\" layout=\"inline\" ariaLabel={t('master_document.chrome.updating')} />\n            </span>\n          ) : lineEditable ? (\n            <button\n              type=\"button\"\n              onClick={onEdit}\n              className=\"p-1.5 rounded-md hover:bg-primary-100 dark:hover:bg-dark-bg-secondary text-content-tertiary transition-colors focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary\"\n              aria-label={t('master_document.lines.editLine')}\n            >\n              <PencilIcon className=\"w-3.5 h-3.5\" aria-hidden=\"true\" />\n            </button>\n          ) : (\n            onView && (\n              <button\n                type=\"button\"\n                onClick={onView}\n                className=\"p-1.5 rounded-md hover:bg-primary-100 dark:hover:bg-dark-bg-secondary text-content-tertiary transition-colors focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary\"\n                // Misma condición que la fila de escritorio y que el título del\n                // modal: si abre en consulta, se anuncia como consulta.\n                aria-label={t('master_document.lines.viewLine')}\n              >\n                <EyeIcon className=\"w-3.5 h-3.5\" aria-hidden=\"true\" />\n              </button>\n            )\n          )}\n          {!isBusy && (\n            <button\n              type=\"button\"\n              onClick={onMenu}\n              className=\"p-1.5 rounded-md hover:bg-primary-100 dark:hover:bg-dark-bg-secondary text-content-tertiary transition-colors focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary\"\n              aria-label={t('master_document.lines.moreOptions')}\n            >\n              <EllipsisVerticalIcon className=\"w-3.5 h-3.5\" aria-hidden=\"true\" />\n            </button>\n          )}\n        </div>\n      </div>\n\n      <div className=\"grid grid-cols-2 gap-2\">\n        {cardColumns.map((col) => (\n          <div key={col.key} className=\"flex flex-col\">\n            <span className=\"text-xs font-bold uppercase text-content-secondary dark:text-dark-content-secondary tracking-wide\">\n              {col.header}\n            </span>\n            <span\n              className={clsx(\n                'text-xs font-medium text-content-primary',\n                ['currency', 'number', 'percentage', 'date'].includes(col.format ?? '') && 'tabular-nums',\n                col.align === 'right' && 'text-right',\n                'dark:text-dark-content-primary',\n              )}\n            >\n              {formatCellValue(line[col.key], col.format, formatCurrencyCompact, formatNumber)}\n            </span>\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n\n// ─── LinesSection ──────────────────────────────────────────\n\n/**\n * Sección de líneas de detalle del documento maestro.\n *\n * Renderiza una tabla virtualizada (TanStack Table + TanStack Virtual) en\n * escritorio y tarjetas apiladas en móvil. Incluye menú contextual por línea\n * (editar, duplicar, eliminar), estado activo visual y estado vacío.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - LinesSectionProps, DocumentLineData, LineColumnConfig\n *\n * @example\n * ```tsx\n * <LinesSection\n *   title=\"Líneas del documento\"\n *   lines={documentLines}\n *   columns={lineColumns}\n *   onEditLine={(id) => openLineModal(id)}\n *   onDeleteLine={(id) => removeLine(id)}\n *   canAddLine={isEditable}\n *   onAddLine={() => openNewLineModal()}\n * />\n * ```\n */\nexport function LinesSection({\n  title,\n  lines,\n  columns: columnConfigs,\n  alerts,\n  canAddLine,\n  onAddLine,\n  onEditLine,\n  onViewLine,\n  onDeleteLine,\n  lineDeletable = true,\n  onDuplicateLine,\n  lineEditable = true,\n  activeLineId,\n  busyLineId,\n  currentBreakpoint,\n  className,\n  selectionMode = false,\n  selectedLineIds = [],\n  onLineSelect,\n  lineStatuses,\n  lineSelectionErrors,\n  onOpenLineCloseModal,\n  lineActions,\n  getLineActions,\n  hideTitle = false,\n}: LinesSectionProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatCurrencyCompact, formatNumber } = useMasterDocumentFormatters();\n  const [contextMenu, setContextMenu] = useState<{\n    open: boolean;\n    position: { x: number; y: number };\n    lineId: string;\n    /** Abierto desde la celda de la fila (muestra sólo el desborde) o desde la tarjeta. */\n    desdeFila?: boolean;\n  }>({ open: false, position: { x: 0, y: 0 }, lineId: '' });\n\n  // Header de la tabla desktop: vive fuera del scroll vertical del cuerpo (para\n  // quedar fijo al hacer scroll vertical), pero su scroll HORIZONTAL se sincroniza\n  // con el del cuerpo para que columnas y encabezados se desplacen juntos.\n  const isMobile = isMobileBreakpoint(currentBreakpoint);\n\n  // Filter out hidden columns\n  const visibleColumns = useMemo(\n    () => columnConfigs.filter((c) => !shouldHideColumn(c.hideOn, currentBreakpoint)),\n    [columnConfigs, currentBreakpoint],\n  );\n\n  // TanStack table columns\n\n  /**\n   * Acciones de UNA línea, en el orden del canon. Antes esto era el contenido del\n   * menú contextual y además había un botón «Ver/Editar» suelto en la celda, así que\n   * la MISMA acción aparecía dos veces: como botón y como primer ítem del menú. Ahora\n   * es una sola lista y la celda decide cuáles se pintan de frente.\n   */\n  const construirAccionesDeLinea = useCallback((lineaId: string) => {\n    const items: Array<{\n      label: string;\n      icon?: React.ReactNode;\n      onClick: () => void;\n      danger?: boolean;\n      separator?: boolean;\n      disabled?: boolean;\n    }> = [];\n\n    // El rótulo y el icono siguen la MISMA condición que el título del modal que van\n    // a abrir (`MasterDocument`: `readOnly ? 'Ver línea' : 'Editar línea'`), y no una\n    // propia. Un intento anterior unificó las dos ramas en «Editar» con lápiz\n    // razonando que el destino es el mismo; lo es, pero el DESENLACE no, y eso es lo\n    // que el usuario decide al pulsar: no «a dónde voy» sino «¿puedo cambiar esto?».\n    // Con el lápiz esa respuesta sólo llega DESPUÉS de abrir el modal, campo por\n    // campo deshabilitado — en una grilla de 40 líneas de un documento ya\n    // contabilizado, 40 aperturas para averiguar lo que un icono decía de una.\n    //\n    // Además el propio kit ya distingue las dos puertas en el listado de documentos\n    // (ojo «Ver detalle» / lápiz «Editar»), así que mantener aquí un solo icono hacía\n    // que el mismo usuario viera dos criterios para la misma semántica.\n    if (lineEditable) {\n      items.push({\n        label: t('master_document.lines.edit'),\n        onClick: () => onEditLine(lineaId),\n        icon: <PencilIcon className=\"w-4 h-4\" aria-hidden=\"true\" />,\n      });\n    } else if (onViewLine) {\n      items.push({\n        label: t('master_document.lines.view'),\n        onClick: () => onViewLine(lineaId),\n        icon: <EyeIcon className=\"w-4 h-4\" aria-hidden=\"true\" />,\n      });\n    }\n\n    if (onDuplicateLine) {\n      items.push({\n        label: t('master_document.lines.duplicate'),\n        onClick: () => onDuplicateLine(lineaId),\n        icon: <DocumentDuplicateIcon className=\"w-4 h-4\" aria-hidden=\"true\" />,\n      });\n    }\n\n    if (onOpenLineCloseModal) {\n      const lineStatus = lineStatuses?.[lineaId];\n      const lineDesc = String(lines.find((l) => l.id === lineaId)?.description ?? lineaId);\n      if (lineActions?.close && lineStatus !== 'Closed') {\n        items.push({\n          label: t('master_document.lines.closeLine'),\n          onClick: () => onOpenLineCloseModal(lineaId, lineDesc, 'close'),\n          icon: <LockClosedIcon className=\"w-4 h-4\" aria-hidden=\"true\" />,\n          separator: true,\n        });\n      }\n      if (lineActions?.reopen && lineStatus === 'Closed') {\n        items.push({\n          label: t('master_document.lines.reopenLine'),\n          onClick: () => onOpenLineCloseModal(lineaId, lineDesc, 'reopen'),\n          icon: <LockOpenIcon className=\"w-4 h-4\" aria-hidden=\"true\" />,\n          separator: true,\n        });\n      }\n    }\n\n    // Acciones de línea ADICIONALES (declarativas): se anexan como un bloque\n    // separado, tras las quemadas y antes de \"Eliminar\". Aditivo: si no se provee\n    // `getLineActions` o no devuelve nada, el menú es idéntico al actual.\n    const line = lines.find((l) => l.id === lineaId);\n    const extraActions = line ? (getLineActions?.(line) ?? []) : [];\n    extraActions.forEach((action, idx) => {\n      items.push({\n        label: action.label,\n        icon: action.icon,\n        onClick: () => action.onClick(line as Record<string, unknown>),\n        danger: action.variant === 'danger',\n        disabled: action.disabled,\n        // Separador solo en la primera para delimitar el bloque extra.\n        separator: idx === 0,\n      });\n    });\n\n    // AC-1: con `lineDeletable === false` no se ofrece NINGUNA afordancia de\n    // borrado —ni botón de fila ni ítem de menú—, que es lo que pide una pestaña de\n    // sólo consulta. «Deshabilitada» no sirve: la acción no debe ofrecerse.\n    //\n    // Sin `icon` la celda caía al `EllipsisVerticalIcon` de reserva, así que\n    // «Eliminar» se pintaba con el icono de «más opciones»: el botón anunciaba un\n    // menú y borraba una línea.\n    if (lineDeletable && onDeleteLine) {\n      items.push({\n        label: t('master_document.lines.delete'),\n        onClick: () => onDeleteLine(lineaId),\n        icon: <TrashIcon className=\"w-4 h-4\" aria-hidden=\"true\" />,\n        danger: true,\n        separator: true,\n      });\n    }\n\n    return items;\n  }, [lines, lineStatuses, lineActions, lineEditable, lineDeletable, onEditLine, onViewLine, onDuplicateLine, onDeleteLine, onOpenLineCloseModal, getLineActions, t]);\n\n  /** Reparto del canon: hasta 3 de frente; de 4 en adelante, 2 + «Más opciones». */\n  const MAX_DIRECTAS_LINEA = 3;\n  const repartir = useCallback((lineaId: string) => {\n    const todas = construirAccionesDeLinea(lineaId);\n    return todas.length <= MAX_DIRECTAS_LINEA\n      ? { directas: todas, enMenu: [] as typeof todas }\n      : { directas: todas.slice(0, 2), enMenu: todas.slice(2) };\n  }, [construirAccionesDeLinea]);\n\n  /**\n   * Ancho de la columna «Acciones», calculado a partir de los botones que de verdad\n   * lleva. Estaba fijo en el ancho de tres y con dos controles sobraba un hueco que\n   * no explicaba nada. La fórmula es la del canon: n botones de 28px con `gap-3`,\n   * más los 16/16 de padding de celda.\n   */\n  const anchoColumnaAcciones = useMemo(() => {\n    let max = 1;\n    lines.forEach((l) => {\n      const { directas, enMenu } = repartir(String(l.id));\n      max = Math.max(max, directas.length + (enMenu.length > 0 ? 1 : 0));\n    });\n    // Los botones más el padding de celda… pero NUNCA por debajo del ancho que\n    // necesita el propio rótulo. Con un solo botón la fórmula daba 60px y\n    // «Acciones» se recortaba a la mitad (medido en dev: 46px de texto en 28px de\n    // hueco). Una cabecera que no se lee no nombra su columna.\n    return Math.max(max * 28 + (max - 1) * 12 + 32, ANCHO_MINIMO_ACCIONES);\n  }, [lines, repartir]);\n\n  const tableColumns = useMemo<TableColumn<DocumentLineData>[]>(() => {\n    const cols: TableColumn<DocumentLineData>[] = [];\n\n    // Columna de selección\n    if (selectionMode) {\n      const nonTerminalLines = lines.filter((l) => !isTerminalStatus(lineStatuses?.[l.id]));\n      const nonTerminalSelected = nonTerminalLines.filter((l) => selectedLineIds.includes(l.id));\n      const allSelected = nonTerminalLines.length > 0 && nonTerminalSelected.length === nonTerminalLines.length;\n      const someSelected = nonTerminalSelected.length > 0 && nonTerminalSelected.length < nonTerminalLines.length;\n\n      cols.push({\n        header: (\n          <input\n            type=\"checkbox\"\n            checked={allSelected}\n            ref={(el) => { if (el) el.indeterminate = someSelected; }}\n            onChange={(e) => { nonTerminalLines.forEach((l) => onLineSelect?.(l.id, e.target.checked)); }}\n            className={CHECKBOX_CLS}\n            aria-label={t('master_document.lines.selectAllLines')}\n          />\n        ),\n        headerRaw: true,\n        accessor: (row) => row.id,\n        // Utilitaria: NO reparte el espacio sobrante (§E.5).\n        width: '44px',\n        fixedWidth: true,\n        render: (_v, row) => {\n          const status = lineStatuses?.[row.id];\n          const disabled = isTerminalStatus(status);\n          const isSelected = selectedLineIds.includes(row.id);\n          const error = lineSelectionErrors?.[row.id];\n          return (\n            <div className=\"flex flex-col items-start\" onClick={(e) => e.stopPropagation()}>\n              <input\n                type=\"checkbox\"\n                checked={isSelected}\n                disabled={disabled}\n                onChange={() => onLineSelect?.(row.id, !isSelected)}\n                className={clsx(CHECKBOX_CLS, disabled && 'opacity-50 cursor-not-allowed')}\n                aria-label={t('master_document.lines.selectLine')}\n              />\n              {error && (\n                <span className=\"text-xs text-red-600 dark:text-red-400 mt-0.5 whitespace-nowrap\">{error}</span>\n              )}\n            </div>\n          );\n        },\n      });\n    }\n\n    // Columnas de datos. SIN `fixedWidth`: el `width` se convierte en\n    // `minmax(width, 1fr)` y son ellas las que se reparten el ancho sobrante, que es\n    // como lo hace MasterCrud. Antes cada columna iba a `flex: 0 0 Npx` y ninguna\n    // crecía, así que el sobrante se quedaba pegado a la última —la de acciones— y\n    // parecía una columna enorme.\n    visibleColumns.forEach((col) => {\n      const anchoDeclarado = col.width ? parseInt(col.width, 10) : NaN;\n      // `fixedWidth` explícito de la plantilla manda; si no lo hay, se deduce del\n      // ancho declarado (ver `ANCHO_COLUMNA_UTILITARIA`).\n      const noSeEstira = col.fixedWidth ?? (Number.isFinite(anchoDeclarado) && anchoDeclarado < ANCHO_COLUMNA_UTILITARIA);\n      cols.push({\n        header: col.header,\n        accessor: (row) => row[col.key],\n        width: col.width,\n        fixedWidth: noSeEstira,\n        align: col.align,\n        render: (value) => {\n          const isMono = ['currency', 'number', 'percentage', 'date'].includes(col.format ?? '');\n          return (\n            <span className={clsx('truncate', isMono && 'tabular-nums font-medium')}>\n              {formatCellValue(value, col.format, formatCurrencyCompact, formatNumber)}\n            </span>\n          );\n        },\n      });\n    });\n\n    // Badge de cumplimiento (modo selección)\n    if (selectionMode) {\n      cols.push({\n        header: t('master_document.crossing.pending.state'),\n        accessor: (row) => row.id,\n        width: '100px',\n        fixedWidth: true,\n        render: (_v, row) => {\n          const status = lineStatuses?.[row.id];\n          return status ? <LineFulfillmentBadge status={status} /> : null;\n        },\n      });\n    }\n\n    // Columna de acciones: ancho exacto de sus botones y FIJA — no crece.\n    cols.push({\n      header: t('master_document.list.rowActions'),\n      accessor: (row) => row.id,\n      width: `${anchoColumnaAcciones}px`,\n      fixedWidth: true,\n      stickyRight: true,\n      align: 'center',\n      render: (_v, row) => {\n        const lineId = String(row.id);\n        if (lineId === busyLineId) {\n          return (\n            // El indicador conserva la caja de 28px del botón al que sustituye:\n            // un spinner desnudo encogería esa fila y sólo esa.\n            <div className=\"flex items-center justify-center\">\n              <button type=\"button\" disabled className={ROW_ACTION_BTN}>\n                <Loading size=\"sm\" layout=\"inline\" ariaLabel={t('master_document.chrome.updating')} />\n              </button>\n            </div>\n          );\n        }\n\n        const { directas, enMenu } = repartir(lineId);\n        if (directas.length === 0 && enMenu.length === 0) return null;\n\n        return (\n          // Siempre visibles y con la separación del canon, igual que en el listado\n          // de documentos: una acción que sólo aparece al pasar el ratón no se\n          // alcanza con el teclado ni con el dedo.\n          <div className=\"flex items-center gap-3 justify-center\" onClick={(e) => e.stopPropagation()}>\n            {directas.map((a) => (\n              <button\n                key={a.label}\n                type=\"button\"\n                title={a.label}\n                aria-label={a.label}\n                disabled={a.disabled}\n                onClick={(e) => { e.stopPropagation(); a.onClick(); }}\n                className={clsx(ROW_ACTION_BTN, a.danger && '!text-error-content !border-error-border hover:!bg-error-bg')}\n              >\n                <span className=\"w-[15px] h-[15px] inline-flex items-center justify-center\">\n                  {a.icon ?? <EllipsisVerticalIcon className=\"w-full h-full\" aria-hidden=\"true\" />}\n                </span>\n              </button>\n            ))}\n\n            {enMenu.length > 0 && (\n              <button\n                type=\"button\"\n                title={t('master_document.lines.moreLineOptions')}\n                aria-label={t('master_document.lines.moreLineOptions')}\n                aria-haspopup=\"menu\"\n                onClick={(e) => {\n                  e.stopPropagation();\n                  const r = (e.currentTarget as HTMLElement).getBoundingClientRect();\n                  setContextMenu({ open: true, position: { x: r.right, y: r.bottom }, lineId, desdeFila: true });\n                }}\n                className={ROW_ACTION_BTN}\n              >\n                <EllipsisVerticalIcon className=\"w-[15px] h-[15px]\" aria-hidden=\"true\" />\n              </button>\n            )}\n          </div>\n        );\n      },\n    });\n\n    return cols;\n  }, [visibleColumns, busyLineId, selectionMode, selectedLineIds, lineStatuses, lineSelectionErrors, onLineSelect, lines, t, formatCurrencyCompact, formatNumber, repartir, anchoColumnaAcciones]);\n\n  // Paginación en cliente: las líneas ya están enteras en memoria, así que el\n  // paginador no pide nada, sólo recorta. Es lo que hace falta para que la caja se\n  // vea y se maneje como la del listado.\n  const [pagina, setPagina] = useState(1);\n  // Cuatro por defecto, no veinticinco: es el tamaño con el que la caja se ve\n  // proporcionada dentro de la tarjeta del detalle sin empujar el resto fuera de\n  // pantalla, y coincide con el alto mínimo que la tabla reserva (ver `MIN_FILAS`).\n  const [tamanoPagina, setTamanoPagina] = useState(FILAS_POR_DEFECTO);\n  const totalPaginas = Math.max(1, Math.ceil(lines.length / tamanoPagina));\n  // Si se borran líneas y la página actual deja de existir, hay que volver a una que\n  // sí: sin esto la tabla se queda en blanco con datos detrás.\n  const paginaSegura = Math.min(pagina, totalPaginas);\n  const lineasDeLaPagina = useMemo(\n    () => lines.slice((paginaSegura - 1) * tamanoPagina, paginaSegura * tamanoPagina),\n    [lines, paginaSegura, tamanoPagina],\n  );\n  // ¿La barra de la sección aporta algo? El contador ya NO cuenta: lo dice el\n  // paginador. Sin título, sin avisos y sin botón de añadir, la barra estaba vacía.\n  const mostrarBarra = (!hideTitle && !!title) || (alerts?.length ?? 0) > 0 || canAddLine;\n\n  const paginacion = {\n    currentPage: paginaSegura,\n    totalPages: totalPaginas,\n    onPageChange: setPagina,\n    pageSize: tamanoPagina,\n    pageSizeOptions: [4, 10, 25, 50, 100],\n    onPageSizeChange: (n: number) => { setTamanoPagina(n); setPagina(1); },\n    totalRecords: lines.length,\n    previousLabel: t('master_document.list.previousPage'),\n    nextLabel: t('master_document.list.nextPage'),\n    perPageLabel: t('master_document.list.perPage'),\n    recordsLabel: t('master_document.list.records'),\n    goToPageLabel: t('master_document.list.goToPage'),\n  };\n\n\n  // El menú contextual muestra SOLO lo que no cupo de frente cuando se abre desde la\n  // fila; desde la tarjeta (móvil), donde no hay botones, muestra todo.\n  const contextMenuItems = useMemo(() => {\n    if (!contextMenu.lineId) return [];\n    const { enMenu } = repartir(contextMenu.lineId);\n    return contextMenu.desdeFila ? enMenu : construirAccionesDeLinea(contextMenu.lineId);\n  }, [contextMenu.lineId, contextMenu.desdeFila, repartir, construirAccionesDeLinea]);\n\n  const handleMenuForCard = useCallback(\n    (lineId: string) => (e: React.MouseEvent) => {\n      setContextMenu({\n        open: true,\n        position: { x: e.clientX, y: e.clientY },\n        lineId,\n        desdeFila: false,\n      });\n    },\n    [],\n  );\n\n  return (\n    <div\n      className={clsx(\n        // Caja del canon: la MISMA que envuelve la tabla del listado de\n        // MasterCrud — borde de 1px y `rounded-xl`, sin sombra de tarjeta. La\n        // sombra pertenecía a la época en que esto flotaba sobre un fondo gris;\n        // dentro de la tarjeta del detalle sólo añadía relieve sobre relieve.\n        'bg-white dark:bg-dark-bg-primary rounded-xl overflow-hidden',\n        'border border-border-primary dark:border-dark-border-primary',\n        className,\n      )}\n    >\n      {/* Barra de la sección. Se pinta SÓLO si lleva algo que el paginador no diga\n          ya: un título, un aviso o el botón de añadir. Con las pestañas activas y el\n          documento en sólo lectura no quedaba nada dentro salvo el contador de\n          líneas —que el paginador del `Table` muestra abajo—, así que era una franja\n          de 53px que repetía un dato y separaba la caja de su propia cabecera.\n\n          Va en blanco: en gris quedaba pegada a la banda gris de los encabezados y\n          se leían como una sola franja de dos tonos. */}\n      {mostrarBarra && (\n        <div className=\"flex items-center justify-between gap-3 px-4 py-3 bg-white dark:bg-dark-bg-primary border-b border-border-primary dark:border-dark-border-primary\">\n          <div className=\"flex items-center gap-2 min-w-0\">\n            {!hideTitle && (\n              <h3 className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n                {title}\n              </h3>\n            )}\n            {alerts?.map((alert, i) => (\n              <span\n                key={i}\n                className=\"inline-flex items-center px-2 py-0.5 rounded-md text-xs font-semibold\"\n                style={{ backgroundColor: alert.bg, color: alert.color }}\n              >\n                {alert.label}\n              </span>\n            ))}\n          </div>\n\n          {canAddLine && (\n            // El MISMO `Button` que el «Nuevo» del listado, no una réplica a mano: la\n            // copia se había quedado en 12px y `py-1.5` mientras el canon iba por 14px.\n            <Button\n              type=\"default\"\n              size=\"base\"\n              className=\"!text-sm font-medium\"\n              leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n              onClick={onAddLine}\n            >\n              {t('master_document.lines.newLine')}\n            </Button>\n          )}\n        </div>\n      )}\n\n      {/* Mobile card view */}\n      {isMobile ? (\n        <div className=\"flex flex-col gap-3 p-4\">\n          {lines.length === 0 ? (\n            <EmptyLines />\n          ) : (\n            lines.map((line) => (\n              <LineCard\n                key={line.id}\n                line={line}\n                columns={columnConfigs}\n                onEdit={() => onEditLine(line.id)}\n                onView={onViewLine ? () => onViewLine(line.id) : undefined}\n                onMenu={handleMenuForCard(line.id)}\n                isActive={line.id === activeLineId}\n                lineEditable={lineEditable}\n                selectionMode={selectionMode}\n                isSelected={selectedLineIds.includes(line.id)}\n                isDisabled={isTerminalStatus(lineStatuses?.[line.id])}\n                onSelect={() => onLineSelect?.(line.id, !selectedLineIds.includes(line.id))}\n                status={lineStatuses?.[line.id]}\n                selectionError={lineSelectionErrors?.[line.id]}\n                isBusy={line.id === busyLineId}\n              />\n            ))\n          )}\n        </div>\n      ) : (\n        /* Desktop: el `Table` del kit, el mismo del listado de documentos */\n        <div className=\"flex flex-col min-h-0\">\n          <Table\n            columns={tableColumns}\n            data={lineasDeLaPagina}\n            emptyMessage={t('master_document.lines.emptyTitle')}\n            variant=\"basic\"\n            showBorder={false}\n            showShadow={false}\n            showPadding={false}\n            fullWidth\n            accentHover\n            dense\n            // La banda gris del canon en la cabecera, la misma del listado de\n            // documentos y de MasterCrud. Va por `headerBand` y NO por `stickyHeader`:\n            // aquel convierte la tabla en contenedor de scroll, y esta vive dentro de\n            // la tarjeta del detalle, que es quien scrollea.\n            headerBand\n            // El suelo va en la caja de FILAS (`div[role=\"table\"]`), no en este\n            // envoltorio: puesto aquí, el sobrante lo absorbía el contenedor del\n            // paginador —que es el que crece— y quedaba un paginador altísimo debajo\n            // de una tabla igual de estrecha, justo lo contrario de lo buscado.\n            minGridHeight={ALTO_MINIMO_TABLA}\n            // La fila no navega: la puerta a la línea es su botón de acción, igual\n            // que en el listado de documentos.\n            pagination={paginacion}\n            className=\"!bg-transparent !shadow-none !rounded-none !p-0\"\n          />\n        </div>\n      )}\n\n      {/* Context menu */}\n      <LineContextMenu\n        open={contextMenu.open}\n        position={contextMenu.position}\n        onClose={() => setContextMenu((prev) => ({ ...prev, open: false }))}\n        items={contextMenuItems}\n      />\n    </div>\n  );\n}\n\n// ─── Empty State ───────────────────────────────────────────\n\nfunction EmptyLines() {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div className=\"flex flex-col items-center justify-center py-12 text-center\">\n      <svg className=\"w-12 h-12 text-border-primary dark:text-dark-border-primary mb-3\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" strokeWidth={1}>\n        <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z\" />\n      </svg>\n      <p className=\"text-sm font-medium text-content-secondary dark:text-dark-content-secondary\">{t('master_document.lines.emptyTitle')}</p>\n      <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary mt-1\">{t('master_document.lines.emptyHint')}</p>\n    </div>\n  );\n}\n","import { useState } from 'react';\nimport { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { FactBoxProps, FactBoxSectionConfig } from './MasterDocument.types';\n\n// ─── Chevron icon ──────────────────────────────────────────\n\nfunction ChevronIcon({ open }: { open: boolean }) {\n  return (\n    <svg\n      className={clsx('w-3.5 h-3.5 transition-transform duration-200', open ? 'rotate-90' : 'rotate-0')}\n      viewBox=\"0 0 20 20\"\n      fill=\"currentColor\"\n    >\n      <path fillRule=\"evenodd\" d=\"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z\" clipRule=\"evenodd\" />\n    </svg>\n  );\n}\n\n\n// ─── FactBox Widget ────────────────────────────────────────\n\nfunction FactBoxWidget({ section }: { section: FactBoxSectionConfig }) {\n  const [open, setOpen] = useState(section.defaultOpen);\n\n  return (\n    <div\n      className={clsx(\n        // Tarjeta del canon, la MISMA que envuelve las tablas y la del detalle:\n        // `rounded-xl` + borde de 1px en `border-primary`, sin sombra.\n        //\n        // Antes era `rounded-[10px]` SIN borde y con una sombra doble muy tenue\n        // (`0 1px 3px rgba(60,64,67,.15)`). Sobre el blanco de la tarjeta del detalle\n        // esa sombra no dibuja un contorno: el widget flotaba sin bordes claros y no\n        // se distinguía dónde acababa uno y empezaba el siguiente. Un borde sólido a\n        // 1px es lo que separa dos superficies del mismo color; una sombra sirve para\n        // levantar algo por encima de un fondo distinto, que no es este caso.\n        'bg-bg-primary rounded-xl overflow-hidden',\n        'border border-border-primary dark:border-dark-border-primary',\n        'dark:bg-dark-bg-primary',\n      )}\n    >\n      <button\n        type=\"button\"\n        onClick={() => setOpen((o) => !o)}\n        className={clsx(\n          // 14px/600, el mismo peso y tamaño que la cabecera de una tabla: los 12px\n          // de antes hacían que el título del widget se leyera como una nota al pie.\n          // `px-4 py-3` iguala el ritmo horizontal con el resto de las cajas.\n          'flex items-center justify-between w-full px-4 py-3 text-left',\n          // Es un desplegable: tiene que anunciarse como pulsable al pasar por encima.\n          'hover:bg-background-secondary/70 dark:hover:bg-dark-bg-secondary/50 transition-colors duration-150',\n          'focus:outline-hidden focus:ring-2 focus:ring-inset focus:ring-primary-400 dark:focus:ring-dark-border-custom',\n        )}\n        aria-expanded={open}\n      >\n        <div className=\"flex items-center gap-2 min-w-0\">\n          <span className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary truncate\">\n            {section.label}\n          </span>\n          {section.badge}\n        </div>\n        <ChevronIcon open={open} />\n      </button>\n\n      {open && (\n        <div className=\"border-t border-border-secondary dark:border-dark-border-primary px-4 py-3\">\n          {section.children}\n        </div>\n      )}\n    </div>\n  );\n}\n\n// ─── FactBox Panel Content ─────────────────────────────────\n\nfunction FactBoxContent({ sections, grid }: { sections: FactBoxSectionConfig[]; grid?: boolean }) {\n  return (\n    <div\n      className={clsx(\n        // La separación vive en el contenedor (`gap-3`) y no en un `mb-2` dentro de\n        // cada tarjeta: así la última no arrastra un margen sobrante al final del riel.\n        grid\n          // Por debajo de `xl` los widgets se reparten en rejilla en vez de apilarse:\n          // en una tablet en horizontal tres columnas de una sola tarjeta desperdiciaban\n          // el ancho y estiraban la página a lo tonto.\n          ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 items-start'\n          : 'flex flex-col gap-3',\n      )}\n    >\n      {sections.map((section) => (\n        <FactBoxWidget key={section.key} section={section} />\n      ))}\n    </div>\n  );\n}\n\n// ─── FactBox ───────────────────────────────────────────────\n\n/**\n * Panel de información contextual (FactBox) del documento maestro.\n *\n * Se adapta a tres breakpoints:\n * - **xl+**: barra lateral estática a la derecha del formulario.\n * - **md–lg**: panel deslizante desde la derecha (drawer), controlado por `open`/`onClose`.\n * - **xs–sm**: hoja inferior deslizante (bottom sheet), controlada por `open`/`onClose`.\n *\n * Acepta un arreglo de `FactBoxSectionConfig`, cada una con su propia clave,\n * etiqueta, insignia opcional y nodo hijo. Cada sección se renderiza como un\n * widget colapsable independiente (acordeón).\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - FactBoxProps, FactBoxSectionConfig\n *\n * @example\n * ```tsx\n * <FactBox\n *   sections={[\n *     { key: 'totals', label: 'Totales', defaultOpen: true, children: <FactBoxTotals ... /> },\n *     { key: 'cfde',   label: 'DIAN',    defaultOpen: false, children: <FactBoxCfde ... /> },\n *   ]}\n *   open={drawerOpen}\n *   onClose={() => setDrawerOpen(false)}\n * />\n * ```\n */\nexport function FactBox({ sections, open: _open, onClose: _onClose, className }: FactBoxProps) {\n  const { t } = useMasterDocumentTranslation();\n\n  // `open`/`onClose` ya no gobiernan nada y se conservan sólo para no romper a los\n  // hosts que los pasan. Ver la nota de abajo sobre por qué desapareció el cajón.\n  void _open;\n  void _onClose;\n\n  return (\n    <>\n      {/* ────────────────────────────────────────────────────────────────────\n          xl y más: riel lateral fijo, junto al contenido.\n          ──────────────────────────────────────────────────────────────────── */}\n      <aside\n        className={clsx(\n          // `top-0`, no `top-[52px]`: aquel 52 era el alto de la barra de acciones\n          // que la cabecera apilada sustituyó, así que el riel quedaba anclado a\n          // un elemento que ya no existe y arrancaba 52px por debajo de la tarjeta.\n          'hidden xl:block w-[264px] shrink-0 sticky top-0 self-start',\n          'max-h-[calc(100vh-100px)] overflow-y-auto',\n          // Sin fondo propio: el panel principal dejó de pintar la bandeja gris\n          // (ver `ContentLayout`) y mantenerla sólo aquí dejaba media pantalla\n          // gris y media blanca.\n          //\n          // `pt-1` y no `pt-0`: el riel es un contenedor con `overflow-y-auto`, así que\n          // un widget pegado a su borde superior queda con la esquina redondeada\n          // RECORTADA por el propio scroller. Medido en dev el 2026-09-09: el primer\n          // widget arrancaba en la misma `y` que el riel y se le comía la línea de\n          // arriba. Cuatro píxeles bastan y no rompen la alineación.\n          'pl-0 pr-4 md:pr-6 pt-1 pb-4',\n          className,\n        )}\n        aria-label={t('master_document.factBox.aria')}\n      >\n        <FactBoxContent sections={sections} />\n      </aside>\n\n    </>\n  );\n}\n\n/**\n * Los mismos widgets, pero POR DEBAJO DE `xl` y dentro del flujo del documento.\n *\n * Se renderiza al final de la columna de contenido —no como hermano de ella— y por\n * eso es un componente aparte: `ContentLayout` coloca su `factBox` como columna de\n * una fila flex, así que un bloque «para pantallas pequeñas» puesto ahí se pondría\n * AL LADO del documento en vez de debajo.\n *\n * Antes, por debajo de `xl`, esto eran dos superficies modales —un cajón lateral\n * entre `md` y `lg`, y una hoja inferior al 70% de alto en móvil—, las dos con\n * `fixed inset-0` y un velo `bg-black/30` sobre el documento. El efecto era el\n * contrario del que se busca: para consultar un total había que tapar y oscurecer\n * el documento que se está editando, y en el móvil la hoja se comía la pantalla.\n * Un panel auxiliar no secuestra la ventana.\n *\n * En el flujo, el contenido sigue mandando: los widgets son la última sección de la\n * página, se llega a ellos bajando, comparten el scroll del documento y en una\n * tablet se reparten en rejilla en vez de apilarse en una columna de una.\n */\nexport function FactBoxInline({ sections, className }: { sections: FactBoxSectionConfig[]; className?: string }) {\n  const { t } = useMasterDocumentTranslation();\n  // Desplegado de entrada: en una pantalla pequeña estos widgets son la última\n  // sección del documento y nadie va a bajar hasta el final para descubrir que\n  // además hay que abrirlos. El plegado sirve para APARTARLOS cuando estorban, no\n  // para esconderlos por defecto.\n  const [abierto, setAbierto] = useState(true);\n  if (sections.length === 0) return null;\n  return (\n    <section\n      className={clsx('xl:hidden w-full', className)}\n      aria-label={t('master_document.factBox.aria')}\n    >\n      <button\n        type=\"button\"\n        onClick={() => setAbierto((v) => !v)}\n        aria-expanded={abierto}\n        className={clsx(\n          'flex items-center gap-1.5 mb-3 rounded-md px-1 -mx-1 py-0.5',\n          'text-sm font-bold text-content-primary dark:text-dark-content-primary',\n          'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary transition-colors duration-150',\n          'focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-dark-border-custom',\n        )}\n      >\n        <span>{t('master_document.factBox.info')}</span>\n        <ChevronIcon open={abierto} />\n      </button>\n      {abierto && <FactBoxContent sections={sections} grid />}\n    </section>\n  );\n}\n","import { clsx } from 'clsx';\nimport type { ContentLayoutProps } from './MasterDocument.types';\n\n/**\n * Layout flex que organiza el contenido principal y el panel FactBox.\n * El FactBox se renderiza como sidebar estática en xl+ o como overlay en pantallas menores.\n *\n * @see MasterDocument.types - ContentLayoutProps\n */\n// `factBoxOpen` / `onFactBoxClose` siguen en `ContentLayoutProps` —son parte de la\n// API publica y `MasterDocument` se las pasa—, pero este layout ya no los consume:\n// el propio FactBox resuelve su responsividad. No se desestructuran para no dejar\n// variables muertas, y no se quitan del tipo para no romper a los consumidores.\nexport function ContentLayout({\n  children,\n  factBox,\n  className,\n}: ContentLayoutProps) {\n  return (\n    <div\n      className={clsx(\n        'flex flex-1 min-h-0',\n        className,\n      )}\n    >\n      {/* Main panel */}\n      {/* Panel principal SIN fondo propio: el detalle de MasterCrud no pinta una\n          bandeja gris detrás del contenido — la única superficie es la tarjeta\n          blanca que envuelve al formulario. Con el gris, la tarjeta quedaba\n          flotando sobre un fondo que ningún maestro tiene. */}\n      {/* Ya NO scrollea aquí: el scroll bajó al contenedor de las pestañas dentro de\n          la tarjeta (ver `MasterDocument`), para que la franja de identidad y el borde\n          de la tarjeta no se vayan con el contenido. Este panel sólo acota la altura. */}\n      <div className=\"flex-1 min-w-0 min-h-0 overflow-hidden flex flex-col\">\n        {children}\n      </div>\n\n      {/* FactBox — rendered by the FactBox component itself handles responsiveness.\n          On xl+, it renders as a static sidebar within this flex container.\n          On smaller screens, it renders as overlay/drawer independently. */}\n      {factBox}\n    </div>\n  );\n}\n","// ─── Field Condition Engine ────────────────────────────────\n// Evaluates visibleWhen / hiddenWhen conditions against live form values.\n// Supports logical connectors ($and, $or, $not) and comparison operators\n// ($eq, $ne, $gt, $gte, $lt, $lte, $in). Plain key-value pairs use equality.\n\nexport type FieldValueComparison =\n  | { $eq: unknown }\n  | { $ne: unknown }\n  | { $gt: number }\n  | { $gte: number }\n  | { $lt: number }\n  | { $lte: number }\n  | { $in: unknown[] };\n\nexport type FieldConditionLeaf = Record<string, unknown>;\n\nexport type FieldCondition =\n  | { $and: FieldCondition[] }\n  | { $or: FieldCondition[] }\n  | { $not: FieldCondition }\n  | FieldConditionLeaf;\n\nfunction compareValue(actual: unknown, expected: unknown): boolean {\n  if (expected !== null && typeof expected === 'object' && !Array.isArray(expected)) {\n    const exp = expected as Record<string, unknown>;\n    if ('$eq' in exp) return actual === exp.$eq;\n    if ('$ne' in exp) return actual !== exp.$ne;\n    if ('$gt' in exp) return typeof actual === 'number' && actual > (exp.$gt as number);\n    if ('$gte' in exp) return typeof actual === 'number' && actual >= (exp.$gte as number);\n    if ('$lt' in exp) return typeof actual === 'number' && actual < (exp.$lt as number);\n    if ('$lte' in exp) return typeof actual === 'number' && actual <= (exp.$lte as number);\n    if ('$in' in exp) return Array.isArray(exp.$in) && (exp.$in as unknown[]).includes(actual);\n  }\n  return actual === expected;\n}\n\nexport function evaluateCondition(\n  condition: FieldCondition,\n  formValues: Record<string, unknown>,\n): boolean {\n  if ('$and' in condition) {\n    return (condition.$and as FieldCondition[]).every((c) => evaluateCondition(c, formValues));\n  }\n  if ('$or' in condition) {\n    return (condition.$or as FieldCondition[]).some((c) => evaluateCondition(c, formValues));\n  }\n  if ('$not' in condition) {\n    return !evaluateCondition(condition.$not as FieldCondition, formValues);\n  }\n  return Object.entries(condition).every(([fieldKey, expected]) =>\n    compareValue(formValues[fieldKey], expected),\n  );\n}\n\nexport function extractDependencyFields(condition: FieldCondition): string[] {\n  if ('$and' in condition) {\n    return (condition.$and as FieldCondition[]).flatMap(extractDependencyFields);\n  }\n  if ('$or' in condition) {\n    return (condition.$or as FieldCondition[]).flatMap(extractDependencyFields);\n  }\n  if ('$not' in condition) {\n    return extractDependencyFields(condition.$not as FieldCondition);\n  }\n  return Object.keys(condition);\n}\n","/**\n * Textos genéricos compartidos por los sub-paneles de MasterDocument.\n *\n * Seis conceptos —\"Agregar\", \"Cancelar\", \"Guardar\", \"Eliminar\" y los dos errores\n * genéricos— estaban escritos a mano 22 veces en español y otras tantas en inglés,\n * repartidos por los cinco catálogos. Un cambio de redacción exigía encontrar y\n * editar todas las copias, y bastaba olvidar una para que dos paneles dijeran cosas\n * distintas para la misma acción.\n *\n * ## Por qué esto y no un namespace `common.*`\n *\n * La opción evidente sería mover estos textos a claves `common.actions.add`,\n * `common.error.generic`, etc. NO se hace: las claves actuales\n * (`withholdings.actions.add`, `installments.error.generic`, …) pueden estar ya\n * registradas en el catálogo del backend, y renombrarlas dejaría a esos hosts sin\n * traducción de un día para otro. El riesgo no compensa: el problema real era la\n * duplicación del TEXTO, no el nombre de la clave.\n *\n * Así, cada catálogo conserva sus claves —contrato intacto— y toma el valor de un\n * único sitio. Si más adelante se decide unificar los namespaces, será un cambio\n * consciente y coordinado con backend, no un efecto colateral de un refactor.\n *\n * @see src/components/MasterDocument/i18n.ts - Catálogo del core\n */\n\n/** Textos genéricos en español (idioma base del kit). */\nexport const TEXTO_COMUN_ES = {\n  add: 'Agregar',\n  cancel: 'Cancelar',\n  save: 'Guardar',\n  delete: 'Eliminar',\n  errorForbidden: 'Sin permiso para esta operación.',\n  errorGeneric: 'No se pudo completar la operación.',\n} as const;\n\n/** Los mismos conceptos en inglés. */\nexport const TEXTO_COMUN_EN = {\n  add: 'Add',\n  cancel: 'Cancel',\n  save: 'Save',\n  delete: 'Delete',\n  errorForbidden: 'No permission for this operation.',\n  errorGeneric: 'The operation could not be completed.',\n} as const;\n","import { createTranslationHook } from '../i18nFactory';\nimport { TEXTO_COMUN_ES, TEXTO_COMUN_EN } from '../commonTexts';\nimport type { TranslateFn } from '../i18nFactory';\n\n/**\n * i18n del SerialPanel (soporte nativo de seriales en MasterDocument).\n *\n * Sigue el mismo patrón que el resto del kit: usa `useTranslation`; si la clave\n * no está registrada en el host (el motor devuelve la propia clave), cae al\n * diccionario local del idioma activo. Claves en formato plano (no anidado).\n *\n * ## Claves con número y SIN variantes de plural (decisión, no olvido)\n *\n * `counter_label`, `select_counter_label` y `count_mismatch` llevan números pero\n * no declaran `_one` / `_other`, porque en ninguna el número gobierna la\n * concordancia del texto:\n *\n * - `counter_label` / `select_counter_label` son contadores de progreso\n *   (`Capturados: 1 / 5`). El participio concuerda con la colección, no con el\n *   valor actual, así que un `_one` produciría \"Capturado: 1 / 5\", que es peor.\n * - `count_mismatch` pone las dos cantidades entre paréntesis, fuera de la\n *   sintaxis de la frase.\n *\n * Los call sites las invocan sin `count`, así que el sondeo de plural del factory\n * ni se activa. Si se añade el gate que exige variantes a toda clave con\n * `{count}`, estas tres quedan fuera por construcción.\n */\n\nexport const SERIAL_PANEL_TRANSLATIONS_ES: Record<string, string> = {\n  'serial_panel.alert_required':\n    'Este ítem requiere captura de serial. Ingrese un serial por unidad de la cantidad.',\n  'serial_panel.counter_label': 'Capturados: {captured} / {required}',\n  'serial_panel.select_counter_label': 'Seleccionados: {selected} / {required}',\n  'serial_panel.captured_section': 'Seriales capturados',\n  'serial_panel.selected_section': 'Seriales seleccionados para salida',\n  'serial_panel.add': TEXTO_COMUN_ES.add,\n  'serial_panel.duplicate_error': 'Este serial ya fue capturado en esta línea.',\n  'serial_panel.not_available_error': 'Serial no disponible en la bodega origen.',\n  'serial_panel.overcount_error_one':\n    'Ya seleccionó {count} serial — desmarque uno antes de seleccionar otro.',\n  'serial_panel.overcount_error_other':\n    'Ya seleccionó {count} seriales — desmarque uno antes de seleccionar otro.',\n  'serial_panel.count_mismatch':\n    'La cantidad de seriales ({captured}) no coincide con la cantidad del ítem ({required}).',\n  'serial_panel.save_tooltip_one': 'Capture {count} serial antes de guardar.',\n  'serial_panel.save_tooltip_other': 'Capture {count} seriales antes de guardar.',\n  'serial_panel.search_placeholder': 'Buscar por código de serial...',\n  'serial_panel.empty_state': 'No hay seriales disponibles para este ítem y bodega.',\n  'serial_panel.empty_title': 'Sin seriales disponibles',\n  'serial_panel.input_placeholder': 'Escanee o escriba el serial y presione Enter',\n  'serial_panel.input_label': 'Serial',\n  'serial_panel.validating': 'Validando serial',\n  'serial_panel.chip_empty': 'Aún no se han capturado seriales.',\n  'serial_panel.readonly_banner': 'Documento en estado no editable — modo solo lectura.',\n  'serial_panel.col_serial': 'Serial',\n  'serial_panel.col_lot': 'Lote',\n  'serial_panel.col_location': 'Ubicación',\n  'serial_panel.col_status': 'Estado',\n  'serial_panel.status_created': 'Creado',\n  'serial_panel.status_available': 'Disponible',\n  'serial_panel.status_active': 'Activo',\n  'serial_panel.status_committed': 'Comprometido',\n  'serial_panel.status_unavailable': 'No disponible',\n  'serial_panel.pagination': 'Mostrando {from}–{to} de {total}',\n  'serial_panel.remove_aria': 'Quitar serial',\n  'serial_panel.confirm_selection':\n    'El serial {serialCode} tiene movimientos. ¿Desea continuar?',\n  'serial_panel.unsupported':\n    'El manejo de seriales está configurado para este ítem, pero el adaptador no implementa el método requerido. Contacte al administrador.',\n  'serial_panel.section_title': 'Seriales',\n  'serial_panel.max_reached_one':\n    'Ya capturó {count} serial (la cantidad requerida). Quite uno antes de agregar otro.',\n  'serial_panel.max_reached_other':\n    'Ya capturó {count} seriales (la cantidad requerida). Quite uno antes de agregar otro.',\n};\n\nexport const SERIAL_PANEL_TRANSLATIONS_EN: Record<string, string> = {\n  'serial_panel.alert_required':\n    'This item requires serial capture. Enter one serial per unit of the quantity.',\n  'serial_panel.counter_label': 'Captured: {captured} / {required}',\n  'serial_panel.select_counter_label': 'Selected: {selected} / {required}',\n  'serial_panel.captured_section': 'Captured serials',\n  'serial_panel.selected_section': 'Serials selected for issue',\n  'serial_panel.add': TEXTO_COMUN_EN.add,\n  'serial_panel.duplicate_error': 'This serial was already captured in this line.',\n  'serial_panel.not_available_error': 'Serial not available in the source warehouse.',\n  'serial_panel.overcount_error_one':\n    'You already selected {count} serial — unselect one before selecting another.',\n  'serial_panel.overcount_error_other':\n    'You already selected {count} serials — unselect one before selecting another.',\n  'serial_panel.count_mismatch':\n    'The number of serials ({captured}) does not match the item quantity ({required}).',\n  'serial_panel.save_tooltip_one': 'Capture {count} serial before saving.',\n  'serial_panel.save_tooltip_other': 'Capture {count} serials before saving.',\n  'serial_panel.search_placeholder': 'Search by serial code...',\n  'serial_panel.empty_state': 'No serials available for this item and warehouse.',\n  'serial_panel.empty_title': 'No serials available',\n  'serial_panel.input_placeholder': 'Scan or type the serial and press Enter',\n  'serial_panel.input_label': 'Serial',\n  'serial_panel.validating': 'Validating serial',\n  'serial_panel.chip_empty': 'No serials captured yet.',\n  'serial_panel.readonly_banner': 'Document is not editable — read-only mode.',\n  'serial_panel.col_serial': 'Serial',\n  'serial_panel.col_lot': 'Lot',\n  'serial_panel.col_location': 'Location',\n  'serial_panel.col_status': 'Status',\n  'serial_panel.status_created': 'Created',\n  'serial_panel.status_available': 'Available',\n  'serial_panel.status_active': 'Active',\n  'serial_panel.status_committed': 'Committed',\n  'serial_panel.status_unavailable': 'Unavailable',\n  'serial_panel.pagination': 'Showing {from}–{to} of {total}',\n  'serial_panel.remove_aria': 'Remove serial',\n  'serial_panel.confirm_selection':\n    'Serial {serialCode} has movements. Do you want to continue?',\n  'serial_panel.unsupported':\n    'Serial handling is configured for this item, but the adapter does not implement the required method. Contact your administrator.',\n  'serial_panel.section_title': 'Serials',\n  'serial_panel.max_reached_one':\n    'You already captured {count} serial (the required quantity). Remove one before adding another.',\n  'serial_panel.max_reached_other':\n    'You already captured {count} serials (the required quantity). Remove one before adding another.',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const SERIAL_PANEL_TRANSLATIONS = {\n  es: SERIAL_PANEL_TRANSLATIONS_ES,\n  en: SERIAL_PANEL_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción con interpolación `{var}`. */\nexport type SerialPanelT = TranslateFn;\n\n/**\n * Hook de traducción del SerialPanel. Usa `useTranslation` del kit; si la clave\n * no está registrada en el host, cae al diccionario local del idioma activo.\n */\nexport const useSerialPanelTranslation = createTranslationHook(SERIAL_PANEL_TRANSLATIONS);\n","import { useRef, useState } from 'react';\nimport { clsx } from 'clsx';\nimport {\n  PlusIcon,\n  XMarkIcon,\n  CheckIcon,\n  ExclamationCircleIcon,\n  InformationCircleIcon,\n  LockClosedIcon,\n} from '@heroicons/react/24/outline';\n\nimport { Loading } from '../components/loading';\nimport { useSerialPanelTranslation } from './i18n';\n\nexport interface SerialCapturePanelProps {\n  /** Códigos de serial ya capturados (orden de captura). */\n  serials: string[];\n  /** Cantidad requerida (M). El conteo objetivo. */\n  required: number;\n  /** Modo solo lectura (documento fuera de DRAFT). */\n  readOnly?: boolean;\n  /**\n   * Error externo a mostrar inline (p.ej. resultado de `adapter.validateSerial`).\n   * El chequeo de duplicado es local y tiene prioridad visual.\n   */\n  externalError?: string | null;\n  /**\n   * Hay un `adapter.validateSerial` en vuelo para el último código leído.\n   * Mientras dure, el panel lo indica y no acepta otro: el código no entra en\n   * la lista hasta que el backend responde, así que sin este bloqueo un\n   * escáner rápido encola lecturas sobre una validación sin resolver.\n   */\n  validating?: boolean;\n  /** Notifica la nueva lista de seriales tras agregar/eliminar. */\n  onChange: (next: string[]) => void;\n  className?: string;\n}\n\nfunction counterClasses(n: number, required: number): string {\n  if (n > required)\n    return 'bg-red-50 text-red-800 border-red-300 dark:bg-red-950 dark:text-red-300 dark:border-red-800';\n  if (n === required)\n    return 'bg-green-50 text-green-800 border-green-300 dark:bg-green-950 dark:text-green-300 dark:border-green-800';\n  return 'bg-amber-50 text-amber-800 border-amber-300 dark:bg-amber-950 dark:text-amber-300 dark:border-amber-800';\n}\n\n/**\n * Panel de CAPTURA de seriales (documentos de entrada, `NatureStock = Add`).\n *\n * El operador ingresa seriales uno a uno por teclado o escáner HID (Enter). Hace\n * verificación local de duplicado (case-insensitive) antes de aceptar; la\n * validación de disponibilidad contra el backend se inyecta vía `externalError`.\n * Componente presentacional y controlado: el estado vive en el contenedor.\n */\nexport function SerialCapturePanel({\n  serials,\n  required,\n  readOnly = false,\n  externalError,\n  validating = false,\n  onChange,\n  className,\n}: SerialCapturePanelProps) {\n  const { t } = useSerialPanelTranslation();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const [value, setValue] = useState('');\n  const [duplicate, setDuplicate] = useState(false);\n\n  const n = serials.length;\n  const remaining = Math.max(0, required - n);\n\n  const refocus = () => setTimeout(() => inputRef.current?.focus(), 10);\n\n  const add = () => {\n    if (validating) return;\n    const code = value.trim();\n    if (!code) return;\n    const isDup = serials.some((s) => s.toLowerCase() === code.toLowerCase());\n    if (isDup) {\n      setDuplicate(true);\n      refocus();\n      return;\n    }\n    setDuplicate(false);\n    onChange([...serials, code]);\n    setValue('');\n    refocus();\n  };\n\n  const remove = (idx: number) => {\n    const next = serials.slice();\n    next.splice(idx, 1);\n    onChange(next);\n  };\n\n  const inlineError = duplicate\n    ? t('serial_panel.duplicate_error')\n    : externalError || null;\n\n  return (\n    <div className={clsx('flex flex-col gap-4', className)}>\n      {/* Alert informativo (no dismissible) — oculto en read-only */}\n      {!readOnly && (\n        <div className=\"flex items-start gap-2.5 rounded-lg border border-blue-200 bg-blue-50 px-3.5 py-3 text-[13px] leading-relaxed text-blue-700 dark:border-blue-900 dark:bg-blue-950 dark:text-blue-300\">\n          <InformationCircleIcon className=\"mt-px h-4 w-4 shrink-0\" />\n          <span>{t('serial_panel.alert_required')}</span>\n        </div>\n      )}\n\n      {/* Banner read-only */}\n      {readOnly && (\n        <div className=\"flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-500 dark:border-slate-700 dark:bg-slate-800/60 dark:text-slate-400\">\n          <LockClosedIcon className=\"h-3.5 w-3.5\" />\n          {t('serial_panel.readonly_banner')}\n        </div>\n      )}\n\n      {/* Input de captura — oculto en read-only */}\n      {!readOnly && (\n        <div className=\"flex items-end gap-2\">\n          <div className=\"flex flex-1 flex-col gap-1\">\n            <label className=\"text-xs font-medium text-slate-600 dark:text-slate-300\">\n              {t('serial_panel.input_label')}\n            </label>\n            <input\n              ref={inputRef}\n              type=\"text\"\n              autoFocus\n              value={value}\n              disabled={validating}\n              placeholder={t('serial_panel.input_placeholder')}\n              onChange={(e) => {\n                setValue(e.target.value);\n                if (duplicate) setDuplicate(false);\n              }}\n              onKeyDown={(e) => {\n                if (e.key === 'Enter') {\n                  e.preventDefault();\n                  add();\n                }\n              }}\n              className={clsx(\n                'h-[38px] w-full rounded-lg border-[1.5px] px-3 text-sm text-slate-800 outline-none transition focus:ring-[3px] dark:bg-slate-900 dark:text-slate-100',\n                inlineError\n                  ? 'border-red-400 focus:border-red-500 focus:ring-red-500/15'\n                  : 'border-slate-300 focus:border-primary-500 focus:ring-primary-500/15 dark:border-slate-600',\n                validating && 'opacity-60',\n              )}\n            />\n          </div>\n          <button\n            type=\"button\"\n            onClick={add}\n            disabled={validating}\n            className={clsx(\n              'flex h-[38px] shrink-0 items-center gap-1.5 rounded-lg bg-primary-600 px-4 text-sm font-medium text-white transition hover:bg-primary-700',\n              'disabled:opacity-60 disabled:hover:bg-primary-600',\n            )}\n          >\n            {validating ? (\n              // El botón es `bg-primary-600`: sin `inheritColor` el spinner sería\n              // del mismo color que su fondo.\n              <Loading\n                size=\"sm\"\n                layout=\"inline\"\n                inheritColor\n                ariaLabel={t('serial_panel.validating')}\n              />\n            ) : (\n              <PlusIcon className=\"h-3.5 w-3.5 stroke-[2.5]\" />\n            )}\n            {t('serial_panel.add')}\n          </button>\n        </div>\n      )}\n\n      {/* Error inline (duplicado o validación externa) */}\n      {inlineError && (\n        <div className=\"flex items-start gap-2 rounded-lg border border-red-300 bg-red-50 px-3 py-2.5 text-[13px] text-red-600 dark:border-red-800 dark:bg-red-950 dark:text-red-300\">\n          <ExclamationCircleIcon className=\"mt-px h-[15px] w-[15px] shrink-0\" />\n          <span>{inlineError}</span>\n        </div>\n      )}\n\n      {/* Counter + chip list */}\n      <div>\n        <div className=\"mb-2 flex items-center justify-between\">\n          <span className=\"text-xs font-medium text-slate-600 dark:text-slate-300\">\n            {t('serial_panel.captured_section')}\n          </span>\n          <span\n            className={clsx(\n              'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[13px] font-semibold',\n              counterClasses(n, required),\n            )}\n          >\n            {t('serial_panel.counter_label', { captured: n, required })}\n          </span>\n        </div>\n\n        <div\n          className={clsx(\n            'flex min-h-[44px] flex-wrap gap-2 rounded-lg border-[1.5px] border-dashed border-slate-300 bg-slate-50 p-2.5 dark:border-slate-600 dark:bg-slate-800/40',\n            serials.length === 0 && 'items-center justify-center',\n          )}\n        >\n          {serials.length === 0 ? (\n            <span className=\"text-xs italic text-slate-400 dark:text-slate-500\">\n              {t('serial_panel.chip_empty')}\n            </span>\n          ) : (\n            serials.map((code, i) => (\n              <span\n                key={`${code}-${i}`}\n                className=\"inline-flex items-center gap-1.5 rounded-full border border-green-300 bg-green-50 px-2.5 py-1 text-xs font-medium text-green-800 dark:border-green-800 dark:bg-green-950 dark:text-green-300\"\n              >\n                <CheckIcon className=\"h-3 w-3 stroke-[2.5]\" />\n                {code}\n                {!readOnly && (\n                  <button\n                    type=\"button\"\n                    aria-label={t('serial_panel.remove_aria')}\n                    onClick={() => remove(i)}\n                    className=\"ml-0.5 rounded-full opacity-65 transition hover:opacity-100\"\n                  >\n                    <XMarkIcon className=\"h-3 w-3\" />\n                  </button>\n                )}\n              </span>\n            ))\n          )}\n        </div>\n      </div>\n\n      {/* Mensaje de conteo cuando aún falta (ayuda contextual) */}\n      {!readOnly && n !== required && (\n        <p className=\"text-xs text-slate-500 dark:text-slate-400\">\n          {n < required\n            ? t('serial_panel.save_tooltip', { count: remaining })\n            : t('serial_panel.count_mismatch', { captured: n, required })}\n        </p>\n      )}\n    </div>\n  );\n}\n","import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';\nimport { clsx } from 'clsx';\nimport {\n  XMarkIcon,\n  ArrowsPointingOutIcon,\n  ArrowsPointingInIcon,\n  EllipsisVerticalIcon,\n  ArrowPathIcon,\n} from '@heroicons/react/24/outline';\nimport { StateBadge } from './StateBadge';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { useMasterDocumentFormatters } from './formatters';\nimport type {\n  DocumentModalListConfig,\n  DocumentModalListButtonConfig,\n  DocumentModalListMenuItemConfig,\n  DocumentModalListColumnConfig,\n} from './template/MasterDocumentTemplate.types';\nimport type { StateBadgeConfig } from './MasterDocument.types';\n\n// ─── Types ─────────────────────────────────────────────────\n\nexport interface DocumentModalListProps {\n  open: boolean;\n  onClose: () => void;\n  config: DocumentModalListConfig;\n  /** UUID del documento desde el cual se abre el modal. */\n  documentId?: string;\n  /** UUID de la línea (solo para context: 'line'). */\n  lineId?: string;\n  /** Params adicionales del contexto del documento (ej: headerValues snapshot). */\n  contextParams?: Record<string, unknown>;\n  /**\n   * Función para realizar llamadas HTTP.\n   * Recibe method, path relativo al baseUrl y body opcional.\n   */\n  fetcher: (method: string, path: string, body?: unknown) => Promise<unknown>;\n  /** Formateador de moneda (inyectado por el adaptador). */\n  formatCurrency?: (value: number) => string;\n  /** Formateador de fecha (inyectado por el adaptador). */\n  formatDate?: (value: string) => string;\n}\n\n// ─── Helpers ───────────────────────────────────────────────\n\nfunction interpolatePath(\n  path: string,\n  vars: Record<string, string | undefined>,\n): string {\n  return path.replace(/\\{(\\w+)\\}/g, (_, key) => vars[key] ?? '');\n}\n\nfunction formatValue(\n  value: unknown,\n  format: string | undefined,\n  formatCurrency: ((v: number) => string) | undefined,\n  formatDate: ((v: string) => string) | undefined,\n  formatNumber: (v: number) => string,\n): string {\n  if (value == null) return '';\n  if (format === 'currency' && formatCurrency && typeof value === 'number') {\n    return formatCurrency(value);\n  }\n  if (format === 'date' && formatDate && typeof value === 'string') {\n    return formatDate(value);\n  }\n  if (format === 'number' && typeof value === 'number') {\n    return formatNumber(value);\n  }\n  return String(value);\n}\n\nfunction applyDisplayTemplate(template: string, row: Record<string, unknown>): string {\n  return template.replace(/\\{(\\w+)\\}/g, (_, key) => String(row[key] ?? ''));\n}\n\nfunction getCellValue(\n  row: Record<string, unknown>,\n  col: DocumentModalListColumnConfig,\n  formatCurrency: ((v: number) => string) | undefined,\n  formatDate: ((v: string) => string) | undefined,\n  formatNumber: (v: number) => string,\n): string {\n  if (col.displayTemplate) return applyDisplayTemplate(col.displayTemplate, row);\n  const raw = row[col.dataKey ?? col.key];\n  return formatValue(raw, col.format, formatCurrency, formatDate, formatNumber);\n}\n\n// ─── ConfirmDialog — dialog de confirmación inline ─────────\n\nexport interface ConfirmDialogProps {\n  message: string;\n  onConfirm: () => void;\n  onCancel: () => void;\n  /**\n   * Deshabilita el botón de confirmación.\n   * Útil cuando la confirmación depende de un campo obligatorio del contenido (children),\n   * por ejemplo un modal de anulación que exige seleccionar un \"motivo\".\n   * No afecta al botón de cancelar.\n   * @default false\n   */\n  confirmDisabled?: boolean;\n  /**\n   * Contenido opcional a renderizar entre el mensaje y los botones\n   * (por ejemplo el campo \"motivo\" del que depende `confirmDisabled`).\n   */\n  children?: ReactNode;\n}\n\nexport function ConfirmDialog({\n  message,\n  onConfirm,\n  onCancel,\n  confirmDisabled = false,\n  children,\n}: ConfirmDialogProps) {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div className=\"fixed inset-0 z-[400] flex items-center justify-center\">\n      <div\n        className=\"absolute inset-0 bg-black/40\"\n        aria-hidden=\"true\"\n        onClick={onCancel}\n      />\n      <div\n        className={clsx(\n          'relative z-10 w-[calc(100%-32px)] max-w-sm',\n          'bg-bg-primary dark:bg-dark-bg-primary',\n          'rounded-2xl shadow-xl dark:border dark:border-dark-border-primary',\n          'p-6 flex flex-col gap-4',\n        )}\n        role=\"alertdialog\"\n        aria-modal=\"true\"\n      >\n        <p className=\"text-sm text-content-primary dark:text-dark-content-primary\">{message}</p>\n        {children}\n        <div className=\"flex justify-end gap-3\">\n          <button\n            type=\"button\"\n            onClick={onCancel}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary text-content-secondary',\n              'hover:bg-background-secondary transition-colors',\n              'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n            )}\n          >\n            {t('master_document.chrome.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={onConfirm}\n            disabled={confirmDisabled}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'bg-red-600 text-white hover:bg-red-700 transition-colors',\n              'dark:bg-red-700 dark:hover:bg-red-600',\n              confirmDisabled && 'opacity-50 cursor-not-allowed hover:bg-red-600 dark:hover:bg-red-700',\n            )}\n          >\n            {t('master_document.chrome.confirm')}\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n// ─── RowContextMenu — menú de acciones por registro ────────\n\ninterface RowContextMenuProps {\n  items: DocumentModalListMenuItemConfig[];\n  onSelect: (item: DocumentModalListMenuItemConfig) => void;\n  onClose: () => void;\n  position: { x: number; y: number };\n}\n\nfunction RowContextMenu({ items, onSelect, onClose, position }: RowContextMenuProps) {\n  const ref = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    function handleClick(e: MouseEvent) {\n      if (ref.current && !ref.current.contains(e.target as Node)) onClose();\n    }\n    document.addEventListener('mousedown', handleClick);\n    return () => document.removeEventListener('mousedown', handleClick);\n  }, [onClose]);\n\n  // Adjust position to avoid going off-screen\n  const style: React.CSSProperties = {\n    position: 'fixed',\n    top: position.y,\n    left: position.x,\n    zIndex: 410,\n  };\n\n  return (\n    <div\n      ref={ref}\n      style={style}\n      className={clsx(\n        'min-w-[160px] rounded-xl shadow-lg',\n        'bg-bg-primary dark:bg-dark-bg-secondary',\n        'border border-border-primary dark:border-dark-border-primary',\n        'py-1',\n        'animate-[fadeIn_100ms_ease-out]',\n      )}\n      role=\"menu\"\n    >\n      {items.map((item) => (\n        <div key={item.key}>\n          {item.separator && (\n            <div className=\"my-1 border-t border-border-primary dark:border-dark-border-primary\" />\n          )}\n          <button\n            type=\"button\"\n            role=\"menuitem\"\n            onClick={() => onSelect(item)}\n            className={clsx(\n              'w-full flex items-center gap-2 px-3 py-2 text-sm text-left',\n              'transition-colors duration-100',\n              item.danger\n                ? 'text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20'\n                : 'text-content-primary dark:text-dark-content-primary hover:bg-background-secondary dark:hover:bg-dark-bg-primary',\n            )}\n          >\n            {item.label}\n          </button>\n        </div>\n      ))}\n    </div>\n  );\n}\n\n// ─── ListTable — vista de tabla ─────────────────────────────\n\ninterface ListTableProps {\n  rows: Record<string, unknown>[];\n  columns: DocumentModalListColumnConfig[];\n  contextMenu?: DocumentModalListMenuItemConfig[];\n  onContextMenuOpen: (row: Record<string, unknown>, position: { x: number; y: number }) => void;\n  formatCurrency?: (v: number) => string;\n  formatDate?: (v: string) => string;\n  emptyMessage?: string;\n}\n\nfunction ListTable({\n  rows,\n  columns,\n  contextMenu,\n  onContextMenuOpen,\n  formatCurrency,\n  formatDate,\n  emptyMessage,\n}: ListTableProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatNumber } = useMasterDocumentFormatters();\n  if (rows.length === 0) {\n    return (\n      <div className=\"flex items-center justify-center py-16\">\n        <p className=\"text-sm text-content-tertiary dark:text-dark-content-secondary\">\n          {emptyMessage ?? t('master_document.list.noRecords')}\n        </p>\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"overflow-x-auto\">\n      <table className=\"w-full text-sm border-collapse\">\n        <thead>\n          <tr className=\"border-b border-border-primary dark:border-dark-border-primary\">\n            {columns.map((col) => (\n              <th\n                key={col.key}\n                style={col.width ? { width: col.width } : undefined}\n                className={clsx(\n                  'px-3 py-2.5 text-xs font-semibold uppercase tracking-wide',\n                  'text-content-tertiary dark:text-dark-content-secondary',\n                  'whitespace-nowrap',\n                  col.align === 'right' && 'text-right',\n                  col.align === 'center' && 'text-center',\n                  (!col.align || col.align === 'left') && 'text-left',\n                )}\n              >\n                {col.header}\n              </th>\n            ))}\n            {contextMenu && contextMenu.length > 0 && (\n              <th className=\"w-10 px-2 py-2.5\" aria-label={t('master_document.list.rowActions')} />\n            )}\n          </tr>\n        </thead>\n        <tbody>\n          {rows.map((row, idx) => (\n            <tr\n              key={idx}\n              className={clsx(\n                'border-b border-border-primary dark:border-dark-border-primary',\n                'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                'transition-colors duration-100',\n              )}\n            >\n              {columns.map((col) => {\n                const rawValue = row[col.dataKey ?? col.key];\n                const badge = col.badgeMap?.[String(rawValue ?? '')];\n                const displayText = getCellValue(row, col, formatCurrency, formatDate, formatNumber);\n\n                return (\n                  <td\n                    key={col.key}\n                    className={clsx(\n                      'px-3 py-2.5',\n                      col.mono && 'tabular-nums text-xs',\n                      col.align === 'right' && 'text-right',\n                      col.align === 'center' && 'text-center',\n                      (!col.align || col.align === 'left') && 'text-left',\n                      'text-content-primary dark:text-dark-content-primary',\n                    )}\n                  >\n                    {badge ? (\n                      <StateBadge label={badge.label} bg={badge.bg} color={badge.color} />\n                    ) : (\n                      displayText\n                    )}\n                  </td>\n                );\n              })}\n              {contextMenu && contextMenu.length > 0 && (\n                <td className=\"px-2 py-2\">\n                  <button\n                    type=\"button\"\n                    aria-label={t('master_document.list.rowOptions')}\n                    onClick={(e) => {\n                      e.stopPropagation();\n                      const rect = e.currentTarget.getBoundingClientRect();\n                      onContextMenuOpen(row, { x: rect.left - 160, y: rect.bottom + 4 });\n                    }}\n                    className={clsx(\n                      'p-1 rounded-md',\n                      'text-content-tertiary dark:text-dark-content-secondary',\n                      'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                      'transition-colors duration-100',\n                    )}\n                  >\n                    <EllipsisVerticalIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n                  </button>\n                </td>\n              )}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n\n// ─── CardGrid — vista de cards ──────────────────────────────\n\ninterface CardGridProps {\n  rows: Record<string, unknown>[];\n  config: NonNullable<DocumentModalListConfig['card']>;\n  contextMenu?: DocumentModalListMenuItemConfig[];\n  onContextMenuOpen: (row: Record<string, unknown>, position: { x: number; y: number }) => void;\n  formatCurrency?: (v: number) => string;\n  formatDate?: (v: string) => string;\n  emptyMessage?: string;\n}\n\nfunction CardGrid({\n  rows,\n  config,\n  contextMenu,\n  onContextMenuOpen,\n  formatCurrency,\n  formatDate,\n  emptyMessage,\n}: CardGridProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatNumber } = useMasterDocumentFormatters();\n  if (rows.length === 0) {\n    return (\n      <div className=\"flex items-center justify-center py-16\">\n        <p className=\"text-sm text-content-tertiary dark:text-dark-content-secondary\">\n          {emptyMessage ?? t('master_document.list.noRecords')}\n        </p>\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 p-1\">\n      {rows.map((row, idx) => {\n        const title = String(row[config.titleField] ?? '');\n        const subtitle = config.subtitleField ? String(row[config.subtitleField] ?? '') : undefined;\n        const badgeRaw = config.badgeField ? String(row[config.badgeField] ?? '') : undefined;\n        const badge: StateBadgeConfig | undefined =\n          badgeRaw && config.badgeMap ? config.badgeMap[badgeRaw] : undefined;\n\n        return (\n          <div\n            key={idx}\n            className={clsx(\n              'relative rounded-xl p-4',\n              'bg-bg-primary dark:bg-dark-bg-secondary',\n              'border border-border-primary dark:border-dark-border-primary',\n              'hover:border-primary-custom-300 dark:hover:border-primary-custom-600',\n              'transition-colors duration-150',\n            )}\n          >\n            {/* Card header */}\n            <div className=\"flex items-start justify-between gap-2 mb-2\">\n              <div className=\"flex-1 min-w-0\">\n                <p className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary truncate\">\n                  {title}\n                </p>\n                {subtitle && (\n                  <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary mt-0.5 truncate\">\n                    {subtitle}\n                  </p>\n                )}\n              </div>\n              <div className=\"flex items-center gap-1 shrink-0\">\n                {badge && (\n                  <StateBadge label={badge.label} bg={badge.bg} color={badge.color} />\n                )}\n                {contextMenu && contextMenu.length > 0 && (\n                  <button\n                    type=\"button\"\n                    aria-label={t('master_document.list.rowOptions')}\n                    onClick={(e) => {\n                      e.stopPropagation();\n                      const rect = e.currentTarget.getBoundingClientRect();\n                      onContextMenuOpen(row, { x: rect.left - 160, y: rect.bottom + 4 });\n                    }}\n                    className={clsx(\n                      'p-1 rounded-md',\n                      'text-content-tertiary dark:text-dark-content-secondary',\n                      'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                      'transition-colors duration-100',\n                    )}\n                  >\n                    <EllipsisVerticalIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n                  </button>\n                )}\n              </div>\n            </div>\n\n            {/* Card fields */}\n            {config.fields && config.fields.length > 0 && (\n              <dl className=\"space-y-1 mt-3 pt-3 border-t border-border-primary dark:border-dark-border-primary\">\n                {config.fields.map((field) => {\n                  const raw = row[field.dataKey ?? field.key];\n                  const text = formatValue(raw, field.format, formatCurrency, formatDate, formatNumber);\n                  return (\n                    <div key={field.key} className=\"flex justify-between gap-2\">\n                      {field.label && (\n                        <dt className=\"text-xs text-content-tertiary dark:text-dark-content-secondary shrink-0\">\n                          {field.label}\n                        </dt>\n                      )}\n                      <dd\n                        className={clsx(\n                          'text-xs text-right',\n                          field.bold && 'font-semibold',\n                          field.accent\n                            ? 'text-primary-custom-600 dark:text-primary-custom-400'\n                            : 'text-content-primary dark:text-dark-content-primary',\n                        )}\n                      >\n                        {text}\n                      </dd>\n                    </div>\n                  );\n                })}\n              </dl>\n            )}\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\n// ─── DocumentModalList — componente principal ───────────────\n\n/**\n * Modal de lista interna del documento.\n * Muestra registros relacionados a un documento con toolbar configurable,\n * menú de contexto por registro y soporte para vista tabla o cards.\n *\n * Se define completamente a través del JSON template en `ActionRegistryEntry.modalList`.\n *\n * @example\n * ```tsx\n * <DocumentModalList\n *   open={open}\n *   onClose={() => setOpen(false)}\n *   config={template.actionRegistry['ver_entregas'].modalList}\n *   documentId={state.documentId}\n *   fetcher={adapter.genericFetch}\n * />\n * ```\n */\nexport function DocumentModalList({\n  open,\n  onClose,\n  config,\n  documentId,\n  lineId,\n  contextParams,\n  fetcher,\n  formatCurrency,\n  formatDate,\n}: DocumentModalListProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [maximized, setMaximized] = useState(config.maximized ?? false);\n  const [rows, setRows] = useState<Record<string, unknown>[]>([]);\n  const [loading, setLoading] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  const [page, setPage] = useState(1);\n  const [totalCount, setTotalCount] = useState(0);\n  const pageSize = config.pageSize ?? 20;\n\n  // Per-button loading state for toolbar\n  const [buttonLoading, setButtonLoading] = useState<Record<string, boolean>>({});\n\n  // Context menu state\n  const [menuRow, setMenuRow] = useState<Record<string, unknown> | null>(null);\n  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });\n\n  // Confirmation dialog state\n  const [confirm, setConfirm] = useState<{\n    message: string;\n    onConfirm: () => void;\n  } | null>(null);\n\n  // ── Context variable map for path interpolation ──\n  const contextVars = useCallback(\n    (extraVars?: Record<string, string>): Record<string, string | undefined> => ({\n      documentId: documentId,\n      lineId: lineId,\n      ...Object.fromEntries(\n        Object.entries(contextParams ?? {}).map(([k, v]) => [k, String(v ?? '')]),\n      ),\n      ...extraVars,\n    }),\n    [documentId, lineId, contextParams],\n  );\n\n  // ── Load list data ────────────────────────────────\n  const loadData = useCallback(\n    async (currentPage: number) => {\n      setLoading(true);\n      setError(null);\n      try {\n        const path = interpolatePath(\n          config.dataEndpoint.path,\n          contextVars(),\n        );\n        const body =\n          config.dataEndpoint.method !== 'GET'\n            ? {\n                page: currentPage,\n                pageSize,\n                ...config.dataEndpoint.params,\n              }\n            : undefined;\n\n        const result = await fetcher(config.dataEndpoint.method, path, body);\n        const data = result as { rows?: Record<string, unknown>[]; totalCount?: number } | Record<string, unknown>[];\n\n        if (Array.isArray(data)) {\n          setRows(data);\n          setTotalCount(data.length);\n        } else {\n          setRows(data.rows ?? []);\n          setTotalCount(data.totalCount ?? data.rows?.length ?? 0);\n        }\n      } catch (err) {\n        setError(err instanceof Error ? err.message : t('master_document.list.loadError'));\n      } finally {\n        setLoading(false);\n      }\n    },\n    [config.dataEndpoint, contextVars, fetcher, pageSize, t],\n  );\n\n  useEffect(() => {\n    if (open) {\n      setPage(1);\n      loadData(1);\n    }\n  }, [open]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  // Reset maximized when config changes\n  useEffect(() => {\n    if (open) setMaximized(config.maximized ?? false);\n  }, [open, config.maximized]);\n\n  // Esc to close\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape' && !confirm) onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose, confirm]);\n\n  if (!open) return null;\n\n  // ── Toolbar button handler ────────────────────────\n  async function handleToolbarButton(btn: DocumentModalListButtonConfig) {\n    if (btn.requiresConfirmation) {\n      setConfirm({\n        message: btn.confirmationMessage ?? t('master_document.list.confirmAction'),\n        onConfirm: () => {\n          setConfirm(null);\n          void executeToolbarButton(btn);\n        },\n      });\n      return;\n    }\n    await executeToolbarButton(btn);\n  }\n\n  async function executeToolbarButton(btn: DocumentModalListButtonConfig) {\n    setButtonLoading((prev) => ({ ...prev, [btn.key]: true }));\n    try {\n      const path = interpolatePath(btn.endpoint.path, contextVars());\n      await fetcher(btn.endpoint.method, path, btn.endpoint.params);\n      if (btn.reloadAfter) await loadData(page);\n    } catch {\n      // Errors shown inline; let consumer handle globally via adapter.onError\n    } finally {\n      setButtonLoading((prev) => ({ ...prev, [btn.key]: false }));\n    }\n  }\n\n  // ── Context menu item handler ─────────────────────\n  function handleContextMenuOpen(row: Record<string, unknown>, pos: { x: number; y: number }) {\n    setMenuRow(row);\n    setMenuPosition(pos);\n  }\n\n  function handleContextMenuClose() {\n    setMenuRow(null);\n  }\n\n  async function handleMenuItemSelect(item: DocumentModalListMenuItemConfig) {\n    setMenuRow(null);\n    if (!menuRow) return;\n\n    const recordIdField = config.recordIdField ?? 'id';\n    const recordId = String(menuRow[recordIdField] ?? '');\n\n    if (item.requiresConfirmation) {\n      setConfirm({\n        message: item.confirmationMessage ?? t('master_document.list.confirmAction'),\n        onConfirm: () => {\n          setConfirm(null);\n          void executeMenuAction(item, recordId);\n        },\n      });\n      return;\n    }\n    await executeMenuAction(item, recordId);\n  }\n\n  async function executeMenuAction(item: DocumentModalListMenuItemConfig, recordId: string) {\n    try {\n      const path = interpolatePath(item.endpoint.path, contextVars({ recordId }));\n      await fetcher(item.endpoint.method, path, item.endpoint.params);\n      if (item.reloadAfter) await loadData(page);\n    } catch {\n      // Errors handled globally\n    }\n  }\n\n  // ── Pagination ────────────────────────────────────\n  const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));\n\n  function handlePageChange(newPage: number) {\n    setPage(newPage);\n    void loadData(newPage);\n  }\n\n  // ── Sizes ─────────────────────────────────────────\n  const displayMode = config.displayMode ?? 'list';\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n        onClick={onClose}\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] flex flex-col',\n          'bg-bg-primary dark:bg-dark-bg-primary',\n          'shadow-xl',\n          'dark:border dark:border-dark-border-primary',\n          'animate-[fadeIn_150ms_ease-out]',\n          maximized\n            ? 'inset-2 rounded-2xl'\n            : [\n                'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n                'w-[calc(100%-32px)] max-w-[75vw]',\n                'max-h-[80vh] rounded-2xl',\n              ],\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"dml-modal-title\"\n      >\n        {/* ── Header ── */}\n        <div\n          className={clsx(\n            'flex items-center justify-between px-5 py-3.5 shrink-0',\n            'border-b border-border-primary dark:border-dark-border-primary',\n          )}\n        >\n          <h2\n            id=\"dml-modal-title\"\n            className=\"text-[15px] font-bold text-content-primary dark:text-dark-content-primary truncate\"\n          >\n            {config.title}\n          </h2>\n\n          <div className=\"flex items-center gap-1\">\n            {/* Reload */}\n            <button\n              type=\"button\"\n              onClick={() => void loadData(page)}\n              disabled={loading}\n              aria-label={t('master_document.list.reload')}\n              className={clsx(\n                'p-1.5 rounded-md',\n                'text-content-secondary dark:text-dark-content-secondary',\n                'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                'transition-colors duration-150',\n                'disabled:opacity-40',\n              )}\n            >\n              <ArrowPathIcon className={clsx('w-4 h-4', loading && 'animate-spin')} aria-hidden=\"true\" />\n            </button>\n\n            {/* Maximize toggle */}\n            <button\n              type=\"button\"\n              onClick={() => setMaximized((m) => !m)}\n              aria-label={maximized ? t('master_document.chrome.restoreSize') : t('master_document.chrome.maximize')}\n              className={clsx(\n                'p-1.5 rounded-md',\n                'text-content-secondary dark:text-dark-content-secondary',\n                'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                'transition-colors duration-150',\n              )}\n            >\n              {maximized ? (\n                <ArrowsPointingInIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n              ) : (\n                <ArrowsPointingOutIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n              )}\n            </button>\n\n            {/* Close */}\n            <button\n              type=\"button\"\n              onClick={onClose}\n              aria-label={t('master_document.chrome.close')}\n              className={clsx(\n                'p-1.5 rounded-md',\n                'text-content-secondary dark:text-dark-content-secondary',\n                'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                'transition-colors duration-150',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              )}\n            >\n              <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n            </button>\n          </div>\n        </div>\n\n        {/* ── Toolbar ── */}\n        {config.toolbar && config.toolbar.buttons.length > 0 && (\n          <div\n            className={clsx(\n              'flex items-center gap-2 px-4 py-2.5 shrink-0',\n              'border-b border-border-primary dark:border-dark-border-primary',\n              'bg-background-secondary/40 dark:bg-dark-bg-secondary/40',\n            )}\n          >\n            {config.toolbar.buttons.map((btn) => {\n              const isLoading = buttonLoading[btn.key] ?? false;\n              return (\n                <button\n                  key={btn.key}\n                  type=\"button\"\n                  onClick={() => void handleToolbarButton(btn)}\n                  disabled={isLoading}\n                  className={clsx(\n                    'inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-md text-sm font-semibold',\n                    'transition-colors duration-150',\n                    'disabled:opacity-50 disabled:pointer-events-none',\n                    btn.variant === 'primary' && [\n                      'bg-primary-inverse-background text-white',\n                      'hover:bg-primary-custom-700',\n                      'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n                    ],\n                    btn.variant === 'danger' && [\n                      'bg-red-600 text-white hover:bg-red-700',\n                      'dark:bg-red-700 dark:hover:bg-red-600',\n                    ],\n                    (!btn.variant || btn.variant === 'secondary') && [\n                      'border border-border-primary text-content-secondary',\n                      'hover:bg-background-secondary',\n                      'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n                    ],\n                    btn.variant === 'ghost' && [\n                      'text-content-secondary hover:bg-background-secondary',\n                      'dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n                    ],\n                  )}\n                >\n                  {isLoading && (\n                    <span className=\"w-3.5 h-3.5 border-2 border-current border-t-transparent rounded-full animate-spin\" aria-hidden=\"true\" />\n                  )}\n                  {btn.label}\n                </button>\n              );\n            })}\n          </div>\n        )}\n\n        {/* ── Body ── */}\n        <div className=\"flex-1 overflow-y-auto min-h-0 px-4 py-3\">\n          {loading && rows.length === 0 ? (\n            <div className=\"flex items-center justify-center py-16\">\n              <div className=\"w-6 h-6 border-2 border-primary-custom-400 border-t-transparent rounded-full animate-spin\" />\n            </div>\n          ) : error ? (\n            <div className=\"flex flex-col items-center justify-center py-16 gap-3\">\n              <p className=\"text-sm text-red-600 dark:text-red-400\">{error}</p>\n              <button\n                type=\"button\"\n                onClick={() => void loadData(page)}\n                className={clsx(\n                  'px-4 py-2 rounded-md text-sm font-semibold',\n                  'border border-border-primary text-content-secondary',\n                  'hover:bg-background-secondary transition-colors',\n                  'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n                )}\n              >\n                {t('master_document.chrome.retry')}\n              </button>\n            </div>\n          ) : displayMode === 'card' && config.card ? (\n            <CardGrid\n              rows={rows}\n              config={config.card}\n              contextMenu={config.contextMenu}\n              onContextMenuOpen={handleContextMenuOpen}\n              formatCurrency={formatCurrency}\n              formatDate={formatDate}\n              emptyMessage={config.emptyMessage}\n            />\n          ) : (\n            <ListTable\n              rows={rows}\n              columns={config.columns ?? []}\n              contextMenu={config.contextMenu}\n              onContextMenuOpen={handleContextMenuOpen}\n              formatCurrency={formatCurrency}\n              formatDate={formatDate}\n              emptyMessage={config.emptyMessage}\n            />\n          )}\n        </div>\n\n        {/* ── Footer: pagination ── */}\n        {totalPages > 1 && (\n          <div\n            className={clsx(\n              'flex items-center justify-between px-4 py-2.5 shrink-0',\n              'border-t border-border-primary dark:border-dark-border-primary',\n            )}\n          >\n            <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary\">\n              {t('master_document.list.recordCount', { count: totalCount })}\n            </span>\n            <div className=\"flex items-center gap-1\">\n              <button\n                type=\"button\"\n                onClick={() => handlePageChange(page - 1)}\n                disabled={page === 1 || loading}\n                className={clsx(\n                  'px-2.5 py-1 rounded-md text-xs font-semibold',\n                  'border border-border-primary text-content-secondary',\n                  'hover:bg-background-secondary transition-colors',\n                  'disabled:opacity-40 disabled:pointer-events-none',\n                  'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n                )}\n              >\n                {t('master_document.list.previousShort')}\n              </button>\n              <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary px-2\">\n                {page} / {totalPages}\n              </span>\n              <button\n                type=\"button\"\n                onClick={() => handlePageChange(page + 1)}\n                disabled={page === totalPages || loading}\n                className={clsx(\n                  'px-2.5 py-1 rounded-md text-xs font-semibold',\n                  'border border-border-primary text-content-secondary',\n                  'hover:bg-background-secondary transition-colors',\n                  'disabled:opacity-40 disabled:pointer-events-none',\n                  'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n                )}\n              >\n                {t('master_document.list.nextShort')}\n              </button>\n            </div>\n          </div>\n        )}\n      </div>\n\n      {/* ── Context menu ── */}\n      {menuRow && config.contextMenu && config.contextMenu.length > 0 && (\n        <RowContextMenu\n          items={config.contextMenu}\n          position={menuPosition}\n          onSelect={(item) => void handleMenuItemSelect(item)}\n          onClose={handleContextMenuClose}\n        />\n      )}\n\n      {/* ── Confirmation dialog ── */}\n      {confirm && (\n        <ConfirmDialog\n          message={confirm.message}\n          onConfirm={confirm.onConfirm}\n          onCancel={() => setConfirm(null)}\n        />\n      )}\n    </>\n  );\n}\n","import { useMemo, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { clsx } from 'clsx';\nimport {\n  MagnifyingGlassIcon,\n  CheckIcon,\n  XMarkIcon,\n  ChevronLeftIcon,\n  ChevronRightIcon,\n  ExclamationCircleIcon,\n  LockClosedIcon,\n  ArchiveBoxIcon,\n} from '@heroicons/react/24/outline';\n\nimport type { SerialRow, SerialStatus } from '../adapter/MasterDocumentAdapter.types';\nimport { ConfirmDialog } from '../DocumentModalList';\nimport { useSerialPanelTranslation } from './i18n';\n\n/**\n * Mapa de estado de serial -> clave i18n y clases de color del badge.\n * El fallback (estado no mapeado) es `Available` para no regresionar.\n */\nconst STATUS_BADGE: Record<SerialStatus, { i18nKey: string; className: string }> = {\n  Created: {\n    i18nKey: 'serial_panel.status_created',\n    className: 'bg-slate-50 text-slate-600 dark:bg-slate-900 dark:text-slate-400',\n  },\n  Available: {\n    i18nKey: 'serial_panel.status_available',\n    className: 'bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300',\n  },\n  Active: {\n    i18nKey: 'serial_panel.status_active',\n    className: 'bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300',\n  },\n  Committed: {\n    i18nKey: 'serial_panel.status_committed',\n    className: 'bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300',\n  },\n  Unavailable: {\n    i18nKey: 'serial_panel.status_unavailable',\n    className: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300',\n  },\n};\n\n/** Clave i18n del mensaje de confirmación cuando el consumidor no declara otra. */\nconst DEFAULT_CONFIRM_MESSAGE_KEY = 'serial_panel.confirm_selection';\n\nexport interface SerialSelectPanelProps {\n  /**\n   * Seriales disponibles para seleccionar.\n   *\n   * - Modo cliente (default): se provee el conjunto completo y el panel filtra y\n   *   pagina en cliente (suficiente para demo y datasets chicos / stories).\n   * - Modo servidor (cuando se provee `onQueryChange` u `onPageChange`): `rows`\n   *   es ya la PÁGINA actual devuelta por `adapter.fetchAvailableSerials`; el\n   *   panel no filtra ni rebana, solo renderiza y delega búsqueda/paginación.\n   */\n  rows: SerialRow[];\n  /** IDs de seriales seleccionados (controlado). */\n  value: string[];\n  /** Cantidad requerida (M). */\n  required: number;\n  /** Modo solo lectura (documento fuera de DRAFT). */\n  readOnly?: boolean;\n  /** Tamaño de página. Default 8. */\n  pageSize?: number;\n  onChange: (next: string[]) => void;\n  className?: string;\n\n  // ── Modo servidor (opcional) ───────────────────────────────\n  // Si se provee `onQueryChange` u `onPageChange`, el panel entra en modo\n  // controlado/servidor: usa estos valores en lugar de su estado interno y no\n  // hace filtrado ni rebanado en cliente.\n  /** Texto de búsqueda controlado (modo servidor). */\n  query?: string;\n  /** Notifica el cambio de búsqueda (activa el modo servidor). */\n  onQueryChange?: (query: string) => void;\n  /** Página actual (1-based) controlada (modo servidor). */\n  page?: number;\n  /** Notifica el cambio de página (activa el modo servidor). */\n  onPageChange?: (page: number) => void;\n  /** Total de registros del lado servidor, para calcular la paginación. */\n  total?: number;\n  /** Indicador de carga (modo servidor): se muestra mientras llega la página. */\n  loading?: boolean;\n\n  // ── Confirmación al marcar (opcional) ──────────────────────\n  // Las inyecta `useSerialPanel` desde `serialSupport` del template.\n  /**\n   * Estados que exigen confirmación Sí/No al MARCAR una fila. Ausente o vacío ⇒\n   * comportamiento idéntico al actual (nunca se confirma). DESmarcar nunca\n   * confirma, y el tope de sobre-selección se evalúa antes que la confirmación.\n   */\n  confirmOnStatuses?: SerialStatus[];\n  /**\n   * Clave i18n del mensaje de la confirmación. Recibe `{serialCode}`.\n   * Default: `serial_panel.confirm_selection`.\n   */\n  confirmMessageKey?: string;\n}\n\nfunction counterClasses(n: number, required: number): string {\n  if (n > required)\n    return 'bg-red-50 text-red-800 border-red-300 dark:bg-red-950 dark:text-red-300 dark:border-red-800';\n  if (n === required)\n    return 'bg-green-50 text-green-800 border-green-300 dark:bg-green-950 dark:text-green-300 dark:border-green-800';\n  return 'bg-amber-50 text-amber-800 border-amber-300 dark:bg-amber-950 dark:text-amber-300 dark:border-amber-800';\n}\n\n/**\n * Panel de SELECCIÓN de seriales (documentos de salida, `NatureStock = Subtract`).\n *\n * Tabla multi-select sobre seriales en estado `Available`, con búsqueda y\n * paginación. Bloquea la over-selección (no permite superar `required`) y muestra\n * un toast. Componente presentacional/controlado: la selección vive en el\n * contenedor; búsqueda y paginación son estado local de presentación.\n */\nexport function SerialSelectPanel({\n  rows,\n  value,\n  required,\n  readOnly = false,\n  pageSize = 8,\n  onChange,\n  className,\n  query: queryProp,\n  onQueryChange,\n  page: pageProp,\n  onPageChange,\n  total,\n  loading = false,\n  confirmOnStatuses,\n  confirmMessageKey,\n}: SerialSelectPanelProps) {\n  const { t } = useSerialPanelTranslation();\n  // Modo servidor: la búsqueda/paginación se delega al contenedor.\n  const serverMode = onQueryChange !== undefined || onPageChange !== undefined;\n\n  const [queryLocal, setQueryLocal] = useState('');\n  const [pageLocal, setPageLocal] = useState(1);\n  const [overAttempted, setOverAttempted] = useState(false);\n  /**\n   * Fila cuya selección espera confirmación. `null` ⇒ sin diálogo abierto.\n   * Se guarda la fila entera, no el id: el mensaje necesita el `serialCode` y\n   * `rows` puede haber cambiado (refetch del contenedor) para cuando se responda.\n   */\n  const [pendingRow, setPendingRow] = useState<SerialRow | null>(null);\n\n  const query = serverMode ? queryProp ?? '' : queryLocal;\n  const setQuery = (q: string) => {\n    if (serverMode) onQueryChange?.(q);\n    else setQueryLocal(q);\n  };\n\n  const selected = useMemo(() => new Set(value), [value]);\n\n  const filtered = useMemo(() => {\n    // En modo servidor `rows` ya viene filtrado/paginado por el adapter.\n    if (serverMode) return rows;\n    const q = query.trim().toLowerCase();\n    return q ? rows.filter((r) => r.serialCode.toLowerCase().includes(q)) : rows;\n  }, [rows, query, serverMode]);\n\n  // Total real: en servidor lo provee el contenedor; en cliente es el set filtrado.\n  const totalCount = serverMode ? total ?? rows.length : filtered.length;\n  const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));\n  const rawPage = serverMode ? pageProp ?? 1 : pageLocal;\n  const currentPage = Math.min(rawPage, totalPages);\n  const start = (currentPage - 1) * pageSize;\n  // En modo servidor `rows` ya es la página → no rebanar.\n  const pageItems = serverMode ? filtered : filtered.slice(start, start + pageSize);\n  const goToPage = (p: number) => {\n    const clamped = Math.max(1, Math.min(totalPages, p));\n    if (serverMode) onPageChange?.(clamped);\n    else setPageLocal(clamped);\n  };\n\n  const n = value.length;\n\n  /** Agrega el serial a la selección. Única ruta de alta, con o sin confirmación. */\n  const commitSelection = (id: string) => {\n    setOverAttempted(false);\n    onChange([...value, id]);\n  };\n\n  /**\n   * Fila que exige confirmación al marcarse, o `null`. Una lista ausente o vacía,\n   * un estado fuera de ella o un id que no está en `rows` ⇒ `null`, y entonces el\n   * camino es bit a bit el de antes de existir `confirmOnStatuses`.\n   */\n  const rowToConfirm = (id: string): SerialRow | null => {\n    if (!confirmOnStatuses || confirmOnStatuses.length === 0) return null;\n    const row = rows.find((r) => r.serialId === id);\n    return row && confirmOnStatuses.includes(row.status) ? row : null;\n  };\n\n  const toggle = (id: string) => {\n    if (readOnly) return;\n    if (selected.has(id)) {\n      setOverAttempted(false);\n      onChange(value.filter((x) => x !== id));\n      return;\n    }\n    if (n >= required) {\n      // ANTES de confirmar a propósito: no se pregunta por un serial que de\n      // todos modos sería rechazado por exceder la cantidad requerida.\n      setOverAttempted(true);\n      return;\n    }\n    const rowNeedingConfirm = rowToConfirm(id);\n    if (rowNeedingConfirm) {\n      setPendingRow(rowNeedingConfirm);\n      return;\n    }\n    commitSelection(id);\n  };\n\n  /**\n   * Respuesta afirmativa del diálogo. Re-evalúa los guards del `toggle`: entre\n   * abrir el diálogo y responder, el contenedor pudo cambiar `readOnly`, `value`\n   * o `required` (una regla de servidor sobre la cantidad de la línea, p.ej.),\n   * y la confirmación no puede saltarse el tope ni escribir en solo lectura.\n   *\n   * El serial también pudo dejar de estar en `rows`: si el ítem de la línea\n   * cambió, `useSerialPanel` limpia los seriales y recarga el inventario, y\n   * agregar el pendiente escribiría un id del inventario anterior.\n   */\n  const confirmPending = () => {\n    if (pendingRow === null) return;\n    const id = pendingRow.serialId;\n    setPendingRow(null);\n    if (readOnly || selected.has(id)) return;\n    if (!rows.some((r) => r.serialId === id)) return;\n    if (n >= required) {\n      setOverAttempted(true);\n      return;\n    }\n    commitSelection(id);\n  };\n\n  const isEmpty = filtered.length === 0;\n\n  return (\n    <div className={clsx('flex flex-col gap-4', className)}>\n      {readOnly && (\n        <div className=\"flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-500 dark:border-slate-700 dark:bg-slate-800/60 dark:text-slate-400\">\n          <LockClosedIcon className=\"h-3.5 w-3.5\" />\n          {t('serial_panel.readonly_banner')}\n        </div>\n      )}\n\n      {/* Header: búsqueda + contador */}\n      <div className=\"flex items-center justify-between gap-3\">\n        <div className=\"relative flex-1\">\n          <MagnifyingGlassIcon className=\"pointer-events-none absolute left-2.5 top-1/2 h-[15px] w-[15px] -translate-y-1/2 text-slate-400\" />\n          <input\n            type=\"text\"\n            value={query}\n            disabled={readOnly}\n            placeholder={t('serial_panel.search_placeholder')}\n            onChange={(e) => {\n              setQuery(e.target.value);\n              goToPage(1);\n            }}\n            className=\"h-9 w-full rounded-lg border-[1.5px] border-slate-300 pl-9 pr-3 text-[13px] outline-none transition focus:border-primary-500 focus:ring-[3px] focus:ring-primary-500/15 disabled:bg-slate-50 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-100 dark:disabled:bg-slate-800\"\n          />\n        </div>\n        <span\n          className={clsx(\n            'inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border px-3 py-1.5 text-[13px] font-semibold',\n            counterClasses(n, required),\n          )}\n        >\n          <CheckIcon className=\"h-3 w-3 stroke-[2.5]\" />\n          {t('serial_panel.select_counter_label', { selected: n, required })}\n        </span>\n      </div>\n\n      {/* Toast over-selección */}\n      {overAttempted && (\n        <div className=\"flex items-center gap-2 rounded-lg border border-red-300 bg-red-50 px-3.5 py-2.5 text-[13px] text-red-600 dark:border-red-800 dark:bg-red-950 dark:text-red-300\">\n          <ExclamationCircleIcon className=\"h-[15px] w-[15px] shrink-0\" />\n          {/* `required` viaja ADEMÁS de `count`: el factory interpola solo las variables que\n              recibe, y un catálogo de host que declare el texto con `{required}` (los hubo, y\n              los hay en ambientes cuyo /langs va por detrás) dejaba el token crudo en pantalla.\n              Pasar las dos hace el mensaje correcto con CUALQUIER catálogo. */}\n          <span>{t('serial_panel.overcount_error', { count: required, required })}</span>\n        </div>\n      )}\n\n      {/* Tabla / estado vacío */}\n      <div className=\"relative overflow-hidden rounded-lg border-[1.5px] border-slate-200 dark:border-slate-700\">\n        {loading && (\n          <div className=\"absolute inset-0 z-10 flex items-center justify-center bg-white/60 dark:bg-slate-900/60\">\n            <svg className=\"h-5 w-5 animate-spin text-primary-600\" viewBox=\"0 0 24 24\" fill=\"none\">\n              <circle className=\"opacity-25\" cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"3\" />\n              <path className=\"opacity-80\" fill=\"currentColor\" d=\"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z\" />\n            </svg>\n          </div>\n        )}\n        {isEmpty ? (\n          <div className=\"flex flex-col items-center justify-center gap-2.5 px-5 py-10 text-center\">\n            <div className=\"flex h-12 w-12 items-center justify-center rounded-full bg-slate-100 text-slate-400 dark:bg-slate-800 dark:text-slate-500\">\n              <ArchiveBoxIcon className=\"h-6 w-6\" />\n            </div>\n            <div className=\"text-sm font-semibold text-slate-700 dark:text-slate-200\">\n              {t('serial_panel.empty_title')}\n            </div>\n            <div className=\"text-[13px] text-slate-500 dark:text-slate-400\">\n              {t('serial_panel.empty_state')}\n            </div>\n          </div>\n        ) : (\n          <>\n            <table className=\"w-full border-collapse text-[13px]\">\n              <thead className=\"border-b-[1.5px] border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-800/60\">\n                <tr>\n                  <th className=\"w-[42px] px-3.5 py-2.5\" />\n                  <th className=\"px-3.5 py-2.5 text-left text-[11px] font-bold uppercase tracking-wide text-slate-500 dark:text-slate-400\">\n                    {t('serial_panel.col_serial')}\n                  </th>\n                  <th className=\"px-3.5 py-2.5 text-left text-[11px] font-bold uppercase tracking-wide text-slate-500 dark:text-slate-400\">\n                    {t('serial_panel.col_lot')}\n                  </th>\n                  <th className=\"px-3.5 py-2.5 text-left text-[11px] font-bold uppercase tracking-wide text-slate-500 dark:text-slate-400\">\n                    {t('serial_panel.col_location')}\n                  </th>\n                  <th className=\"px-3.5 py-2.5 text-left text-[11px] font-bold uppercase tracking-wide text-slate-500 dark:text-slate-400\">\n                    {t('serial_panel.col_status')}\n                  </th>\n                </tr>\n              </thead>\n              <tbody>\n                {pageItems.map((row) => {\n                  const isSel = selected.has(row.serialId);\n                  const badge = STATUS_BADGE[row.status] ?? STATUS_BADGE.Available;\n                  return (\n                    <tr\n                      key={row.serialId}\n                      onClick={() => toggle(row.serialId)}\n                      className={clsx(\n                        'border-b border-slate-100 transition last:border-b-0 dark:border-slate-800',\n                        !readOnly && 'cursor-pointer',\n                        isSel\n                          ? 'bg-primary-50 hover:bg-primary-100 dark:bg-primary-950/40 dark:hover:bg-primary-950/60'\n                          : 'hover:bg-slate-50 dark:hover:bg-slate-800/50',\n                      )}\n                    >\n                      <td className=\"px-3.5 py-2.5 text-center\">\n                        <span\n                          className={clsx(\n                            'inline-flex h-[17px] w-[17px] items-center justify-center rounded border-2 transition',\n                            isSel\n                              ? 'border-primary-600 bg-primary-600'\n                              : 'border-slate-400 bg-white dark:bg-slate-900',\n                          )}\n                        >\n                          {isSel && <CheckIcon className=\"h-2.5 w-2.5 stroke-[3] text-white\" />}\n                        </span>\n                      </td>\n                      <td className=\"px-3.5 py-2.5\">\n                        <span className=\"font-mono font-semibold text-slate-800 dark:text-slate-100\">\n                          {row.serialCode}\n                        </span>\n                      </td>\n                      <td className=\"px-3.5 py-2.5 text-slate-600 dark:text-slate-300\">\n                        {row.lotCode ?? '—'}\n                      </td>\n                      <td className=\"px-3.5 py-2.5 text-slate-600 dark:text-slate-300\">\n                        {row.locationCode ?? '—'}\n                      </td>\n                      <td className=\"px-3.5 py-2.5\">\n                        <span\n                          className={clsx(\n                            'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold',\n                            badge.className,\n                          )}\n                        >\n                          <span className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n                          {t(badge.i18nKey)}\n                        </span>\n                      </td>\n                    </tr>\n                  );\n                })}\n              </tbody>\n            </table>\n\n            {totalCount > pageSize && (\n              <div className=\"flex items-center justify-between border-t border-slate-200 bg-slate-50 px-3.5 py-2.5 dark:border-slate-700 dark:bg-slate-800/60\">\n                <span className=\"text-xs text-slate-500 dark:text-slate-400\">\n                  {t('serial_panel.pagination', {\n                    from: totalCount === 0 ? 0 : start + 1,\n                    to: Math.min(start + pageSize, totalCount),\n                    total: totalCount,\n                  })}\n                </span>\n                <div className=\"flex gap-1\">\n                  <button\n                    type=\"button\"\n                    disabled={currentPage === 1}\n                    onClick={() => goToPage(currentPage - 1)}\n                    className=\"flex h-[30px] w-[30px] items-center justify-center rounded-md border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-100 disabled:opacity-40 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:bg-slate-800\"\n                  >\n                    <ChevronLeftIcon className=\"h-3.5 w-3.5\" />\n                  </button>\n                  <button\n                    type=\"button\"\n                    disabled={currentPage === totalPages}\n                    onClick={() => goToPage(currentPage + 1)}\n                    className=\"flex h-[30px] w-[30px] items-center justify-center rounded-md border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-100 disabled:opacity-40 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:bg-slate-800\"\n                  >\n                    <ChevronRightIcon className=\"h-3.5 w-3.5\" />\n                  </button>\n                </div>\n              </div>\n            )}\n          </>\n        )}\n      </div>\n\n      {/* Resumen de seleccionados */}\n      {n > 0 && (\n        <div className=\"rounded-lg border-[1.5px] border-primary-200 bg-primary-50 px-3.5 py-3 dark:border-primary-900 dark:bg-primary-950/30\">\n          <div className=\"mb-2 text-xs font-semibold text-primary-700 dark:text-primary-300\">\n            {t('serial_panel.selected_section')}\n          </div>\n          <div className=\"flex flex-wrap gap-1.5\">\n            {value.map((id) => {\n              const row = rows.find((r) => r.serialId === id);\n              return (\n                <span\n                  key={id}\n                  className=\"inline-flex items-center gap-1 rounded-full border border-primary-300 bg-primary-100 px-2 py-0.5 font-mono text-[11px] font-semibold text-primary-700 dark:border-primary-800 dark:bg-primary-950 dark:text-primary-300\"\n                >\n                  {row ? row.serialCode : id}\n                  {!readOnly && (\n                    <button\n                      type=\"button\"\n                      aria-label={t('serial_panel.remove_aria')}\n                      onClick={(e) => {\n                        e.stopPropagation();\n                        toggle(id);\n                      }}\n                      className=\"rounded-full opacity-70 transition hover:opacity-100\"\n                    >\n                      <XMarkIcon className=\"h-2.5 w-2.5\" />\n                    </button>\n                  )}\n                </span>\n              );\n            })}\n          </div>\n        </div>\n      )}\n\n      {/*\n        Confirmación al marcar. Va en un portal a `document.body` porque el\n        `ConfirmDialog` es `position: fixed` y el modal de línea que contiene al\n        panel lleva `-translate-x-1/2` (una transform crea bloque contenedor para\n        los descendientes fijos) más `overflow-hidden`: sin portal, el diálogo\n        quedaría anclado y recortado dentro de la tarjeta del modal.\n        Sin `confirmOnStatuses` `pendingRow` nunca sale de `null` y aquí no se\n        renderiza nada: el DOM queda idéntico al de antes del cambio.\n      */}\n      {pendingRow !== null &&\n        createPortal(\n          <ConfirmDialog\n            message={t(confirmMessageKey ?? DEFAULT_CONFIRM_MESSAGE_KEY, {\n              serialCode: pendingRow.serialCode,\n            })}\n            onConfirm={confirmPending}\n            onCancel={() => setPendingRow(null)}\n          />,\n          document.body,\n        )}\n    </div>\n  );\n}\n","import { SerialCapturePanel } from './SerialCapturePanel';\nimport { SerialSelectPanel } from './SerialSelectPanel';\nimport type { SerialRow, SerialStatus } from '../adapter/MasterDocumentAdapter.types';\n\nexport interface SerialCaptureModeProps {\n  mode: 'capture';\n  /** Códigos de serial capturados. */\n  serials: string[];\n  required: number;\n  readOnly?: boolean;\n  /** Error externo (p.ej. `adapter.validateSerial`). */\n  externalError?: string | null;\n  /** Hay un `adapter.validateSerial` en vuelo para el último código leído. */\n  validating?: boolean;\n  onChange: (next: string[]) => void;\n  className?: string;\n}\n\nexport interface SerialSelectModeProps {\n  mode: 'select';\n  /** Seriales disponibles (paginados por el adapter en el kit final). */\n  rows: SerialRow[];\n  /** IDs seleccionados. */\n  value: string[];\n  required: number;\n  readOnly?: boolean;\n  pageSize?: number;\n  onChange: (next: string[]) => void;\n  className?: string;\n  // ── Modo servidor (cableado vía useSerialPanel) ────────────\n  /** Búsqueda controlada server-side. */\n  query?: string;\n  onQueryChange?: (query: string) => void;\n  /** Página actual (1-based) controlada server-side. */\n  page?: number;\n  onPageChange?: (page: number) => void;\n  /** Total de registros del lado servidor. */\n  total?: number;\n  /** Indicador de carga de la página. */\n  loading?: boolean;\n  // ── Confirmación al marcar (cableada vía useSerialPanel) ───\n  /**\n   * Estados que exigen confirmación Sí/No al MARCAR una fila. Ausente o vacío ⇒\n   * comportamiento idéntico al actual.\n   */\n  confirmOnStatuses?: SerialStatus[];\n  /** Clave i18n del mensaje de esa confirmación. Recibe `{serialCode}`. */\n  confirmMessageKey?: string;\n}\n\nexport type SerialPanelProps = SerialCaptureModeProps | SerialSelectModeProps;\n\n/**\n * Panel nativo de seriales del kit. Selecciona la UI según `mode`:\n * - `capture` → entrada por escáner/teclado ([[SerialCapturePanel]]).\n * - `select`  → selección desde inventario ([[SerialSelectPanel]]).\n *\n * Componente presentacional. La activación condicional (`_itemIsSerialized`),\n * la lectura de la cantidad requerida y el cableado del adapter los resuelve el\n * contenedor (`LineFormModal` + hook `useSerialPanel`, paso 2).\n */\nexport function SerialPanel(props: SerialPanelProps) {\n  if (props.mode === 'capture') {\n    return (\n      <SerialCapturePanel\n        serials={props.serials}\n        required={props.required}\n        readOnly={props.readOnly}\n        externalError={props.externalError}\n        validating={props.validating}\n        onChange={props.onChange}\n        className={props.className}\n      />\n    );\n  }\n  return (\n    <SerialSelectPanel\n      rows={props.rows}\n      value={props.value}\n      required={props.required}\n      readOnly={props.readOnly}\n      pageSize={props.pageSize}\n      onChange={props.onChange}\n      className={props.className}\n      query={props.query}\n      onQueryChange={props.onQueryChange}\n      page={props.page}\n      onPageChange={props.onPageChange}\n      total={props.total}\n      loading={props.loading}\n      confirmOnStatuses={props.confirmOnStatuses}\n      confirmMessageKey={props.confirmMessageKey}\n    />\n  );\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useWatch } from 'react-hook-form';\nimport type { Control, FieldValues, UseFormSetValue } from 'react-hook-form';\n\nimport type {\n  IMasterDocumentAdapter,\n  SerialRow,\n} from '../../adapter/MasterDocumentAdapter.types';\nimport type { SerialSupportConfig } from '../../template/MasterDocumentTemplate.types';\nimport type { SerialPanelProps } from '../SerialPanel';\nimport { useSerialPanelTranslation } from '../i18n';\n\n// ── Defaults de configuración ────────────────────────────────\nconst DEFAULT_TRIGGER_FIELD = '_itemIsSerialized';\nconst DEFAULT_QUANTITY_FIELD = 'quantity_base';\nconst DEFAULT_SERIAL_IDS_FIELD = 'serial_ids';\nconst DEFAULT_ITEM_FIELD = 'item_extension_id';\nconst DEFAULT_STORAGE_FIELD = 'storage_id';\nconst DEFAULT_LOT_FIELD = 'lot_id';\n\n/** Tamaño de página de la consulta server-side de seriales (modo `select`). */\nconst SELECT_PAGE_SIZE = 8;\n/** Debounce de la búsqueda/refetch server-side (ms). */\nconst FETCH_DEBOUNCE_MS = 250;\n\ntype ValidateSerialFn = NonNullable<IMasterDocumentAdapter['validateSerial']>;\ntype FetchAvailableSerialsFn = NonNullable<IMasterDocumentAdapter['fetchAvailableSerials']>;\n\nexport interface UseSerialPanelParams {\n  /** `layout.detail.serialSupport` del template. Si se omite, el panel queda inactivo. */\n  serialSupport?: SerialSupportConfig;\n  /** `control` del formulario de la línea (react-hook-form). */\n  control: Control<FieldValues>;\n  /** `setValue` del formulario de la línea (para gestionar el campo virtual `serial_ids`). */\n  setValue: UseFormSetValue<FieldValues>;\n  /**\n   * Solo lectura: el documento está fuera del estado editable. El contenedor\n   * resuelve el criterio (mismo que usa `LineFormModal` para `editableOn`).\n   */\n  readOnly?: boolean;\n  /**\n   * Transición open→true del modal: re-siembra el estado del panel desde\n   * `initialData` (precarga en edición) y resetea búsqueda/paginación.\n   */\n  open?: boolean;\n  /** Datos iniciales de la línea (para precargar `serial_ids` en edición). */\n  initialData?: Record<string, unknown>;\n  /** `adapter.validateSerial` — requerido en modo `capture`. */\n  validateSerial?: ValidateSerialFn;\n  /** `adapter.fetchAvailableSerials` — requerido en modo `select`. */\n  fetchAvailableSerials?: FetchAvailableSerialsFn;\n}\n\nexport interface UseSerialPanelResult {\n  /** `true` cuando el panel debe renderizarse (mode ≠ none y el ítem es serializado). */\n  isActive: boolean;\n  /**\n   * `true` cuando el gating de Guardar está satisfecho:\n   * `serial_ids.length === M` (o el panel está inactivo / no soportado).\n   */\n  isComplete: boolean;\n  /** Cantidad requerida `M` (en vivo desde `quantityField`). */\n  required: number;\n  /** Seriales actualmente registrados en `serial_ids`. */\n  count: number;\n  /** Clave del campo virtual donde viajan los IDs de seriales. */\n  serialIdsField: string;\n  /** `true` cuando el adapter no implementa el método requerido por el `mode`. */\n  unsupported: boolean;\n  /** Mensaje a mostrar cuando `unsupported` es `true`. */\n  unsupportedMessage: string | null;\n  /** Props listos para `<SerialPanel {...panelProps} />`. `null` si no aplica. */\n  panelProps: SerialPanelProps | null;\n}\n\nfunction toBool(value: unknown): boolean {\n  return value === true || value === 'true' || value === 1 || value === '1';\n}\n\nfunction toStringArray(value: unknown): string[] {\n  return Array.isArray(value) ? (value as unknown[]).map(String) : [];\n}\n\n/**\n * Hook contenedor del soporte nativo de seriales (FASE 2).\n *\n * Vive dentro de `LineFormModal`: lee `serialSupport`, observa el form de la\n * línea (trigger, cantidad, ítem, bodega, lote), gestiona el campo virtual\n * `serial_ids` y cablea el adapter (`validateSerial` para `capture`,\n * `fetchAvailableSerials` paginado server-side para `select`).\n *\n * Reglas:\n * - El panel solo se muestra cuando `triggerField` (default `_itemIsSerialized`)\n *   es truthy. Si no, no gatea Guardar (comportamiento idéntico al actual).\n * - La cantidad requerida `M` se lee en vivo de `quantityField`.\n * - Al cambiar la CANTIDAD se conservan los seriales (el badge revalida solo).\n * - Al cambiar el ÍTEM (`itemField`) se limpian los seriales.\n * - `readOnly` desactiva la edición fuera del estado editable.\n * - Degrada con un mensaje claro si el adapter no implementa el método del `mode`.\n *\n * @see SerialPanel — componente presentacional que recibe `panelProps`.\n */\nexport function useSerialPanel({\n  serialSupport,\n  control,\n  setValue,\n  readOnly = false,\n  open = true,\n  initialData,\n  validateSerial,\n  fetchAvailableSerials,\n}: UseSerialPanelParams): UseSerialPanelResult {\n  const { t } = useSerialPanelTranslation();\n\n  const mode = serialSupport?.mode ?? 'none';\n  const triggerField = serialSupport?.triggerField ?? DEFAULT_TRIGGER_FIELD;\n  const quantityField = serialSupport?.quantityField ?? DEFAULT_QUANTITY_FIELD;\n  const serialIdsField = serialSupport?.serialIdsField ?? DEFAULT_SERIAL_IDS_FIELD;\n  const itemField = serialSupport?.itemField ?? DEFAULT_ITEM_FIELD;\n  const storageField = serialSupport?.storageField ?? DEFAULT_STORAGE_FIELD;\n  const lotField = serialSupport?.lotField ?? DEFAULT_LOT_FIELD;\n  // Confirmación al marcar (modo `select`): viaja tal cual al panel, que es donde\n  // vive la decisión, junto al `toggle`. El hook no añade lógica.\n  const confirmOnStatuses = serialSupport?.confirmOnStatuses;\n  const confirmMessageKey = serialSupport?.confirmMessageKey;\n\n  // ── Observación en vivo del form ───────────────────────────\n  const triggerValue = useWatch({ control, name: triggerField });\n  const quantityValue = useWatch({ control, name: quantityField });\n  const itemValue = useWatch({ control, name: itemField });\n  const storageValue = useWatch({ control, name: storageField });\n  const lotValue = useWatch({ control, name: lotField });\n  const serialIdsValue = useWatch({ control, name: serialIdsField });\n\n  const isActive = mode !== 'none' && toBool(triggerValue);\n  const required = Math.max(0, Math.floor(Number(quantityValue) || 0));\n\n  const serialIds = useMemo(() => toStringArray(serialIdsValue), [serialIdsValue]);\n  const serialIdsRef = useRef<string[]>(serialIds);\n  useEffect(() => {\n    serialIdsRef.current = serialIds;\n  }, [serialIds]);\n\n  const itemExtensionId = itemValue == null ? '' : String(itemValue);\n  const storageId = storageValue == null || storageValue === '' ? undefined : String(storageValue);\n  const lotId = lotValue == null || lotValue === '' ? undefined : String(lotValue);\n\n  // ── Estado de presentación (capture) ───────────────────────\n  // Códigos legibles mostrados como chips, alineados índice a índice con serial_ids.\n  const [captureCodes, setCaptureCodes] = useState<string[]>([]);\n  const [captureError, setCaptureError] = useState<string | null>(null);\n\n  // ── Estado de presentación (select) ────────────────────────\n  const [selectRows, setSelectRows] = useState<SerialRow[]>([]);\n  const [selectTotal, setSelectTotal] = useState(0);\n  const [selectLoading, setSelectLoading] = useState(false);\n  // Hay un `validateSerial` en vuelo (P5 de LOADING-INTEGRATION.md). El código\n  // recién leído no entra en la lista hasta que el backend lo aprueba, así que\n  // sin esto el operario pulsa Enter y no ve absolutamente nada.\n  const [validating, setValidating] = useState(false);\n  const [selectQuery, setSelectQuery] = useState('');\n  const [selectPage, setSelectPage] = useState(1);\n  const selectGenRef = useRef(0);\n\n  const commitSerialIds = useCallback(\n    (next: string[]) => {\n      // Tope duro: el onChange del SerialSelectPanel nunca debe exceder `required`.\n      // (El panel ya bloquea la sobre-selección con un toast; esto es defensa en\n      // profundidad. No recortamos cuando required es 0/transitorio.)\n      const capped = required > 0 && next.length > required ? next.slice(0, required) : next;\n      serialIdsRef.current = capped;\n      setValue(serialIdsField, capped, { shouldDirty: true });\n    },\n    [setValue, serialIdsField, required],\n  );\n\n  // ── Reinicio en la transición open→true (precarga en edición) ──\n  const prevOpenRef = useRef(false);\n  const prevItemRef = useRef<unknown>(undefined);\n  useEffect(() => {\n    const justOpened = open && !prevOpenRef.current;\n    prevOpenRef.current = open;\n    if (!justOpened) return;\n\n    // Baseline del ítem desde initialData (no desde el useWatch, que aún está stale).\n    prevItemRef.current = initialData?.[itemField];\n\n    const seeded = toStringArray(initialData?.[serialIdsField]);\n    serialIdsRef.current = seeded;\n    // `reset()` del modal limpia serial_ids → re-inyectar sin marcar dirty.\n    setValue(serialIdsField, seeded, { shouldDirty: false });\n    // TODO(seriales): en EDICIÓN solo tenemos `serial_ids` (GUIDs), no el código\n    // legible, así que los chips de captura muestran el GUID. Para mostrar el\n    // código real el backend debe devolverlo en la precarga de la línea (p.ej.\n    // un campo `serial_codes` paralelo a `serial_ids`). Follow-up fuera de este PR.\n    setCaptureCodes(seeded);\n    setCaptureError(null);\n    setSelectQuery('');\n    setSelectPage(1);\n  }, [open, initialData, itemField, serialIdsField, setValue]);\n\n  // ── Limpieza al cambiar el ÍTEM ────────────────────────────\n  // Solo limpiamos ante un cambio REAL `valorA → valorB` con ambos definidos y\n  // distintos. Las transiciones desde/hacia vacío (undefined/null/'') se tratan\n  // como inicialización: cubren la carrera open↔reset en la que `useWatch` llega\n  // `undefined` antes de que aplique el `reset()` del modal, lo que de otro modo\n  // borraría los `serial_ids` recién precargados en edición.\n  useEffect(() => {\n    if (!open) return;\n    const prev = prevItemRef.current;\n    if (Object.is(prev, itemValue)) return;\n    const isEmpty = (v: unknown) => v === undefined || v === null || v === '';\n    if (isEmpty(prev) || isEmpty(itemValue)) {\n      // Inicialización (o limpieza del campo): adoptar baseline sin tocar seriales.\n      prevItemRef.current = itemValue;\n      return;\n    }\n    // Cambio real de ítem → limpiar seriales.\n    prevItemRef.current = itemValue;\n    commitSerialIds([]);\n    setCaptureCodes([]);\n    setCaptureError(null);\n    setSelectQuery('');\n    setSelectPage(1);\n  }, [itemValue, open, commitSerialIds]);\n\n  // ── Degradación elegante ───────────────────────────────────\n  const unsupported =\n    isActive &&\n    ((mode === 'capture' && !validateSerial) ||\n      (mode === 'select' && !fetchAvailableSerials));\n\n  const loggedUnsupportedRef = useRef(false);\n  useEffect(() => {\n    if (unsupported && !loggedUnsupportedRef.current) {\n      loggedUnsupportedRef.current = true;\n      const missing = mode === 'capture' ? 'validateSerial' : 'fetchAvailableSerials';\n      console.error(\n        `[MasterDocument] serialSupport.mode=\"${mode}\" requiere que el adapter implemente \"${missing}\". ` +\n          'El panel de seriales se deshabilita.',\n      );\n    }\n    if (!unsupported) loggedUnsupportedRef.current = false;\n  }, [unsupported, mode]);\n\n  // ── Fetch server-side (modo select) ────────────────────────\n  useEffect(() => {\n    if (!isActive || mode !== 'select' || !fetchAvailableSerials) return;\n    const handle = setTimeout(() => {\n      const gen = ++selectGenRef.current;\n      setSelectLoading(true);\n      fetchAvailableSerials({\n        itemExtensionId,\n        storageId,\n        lotId,\n        status: 'Available',\n        page: selectPage,\n        pageSize: SELECT_PAGE_SIZE,\n        q: selectQuery.trim() || undefined,\n      })\n        .then((res) => {\n          if (selectGenRef.current !== gen) return;\n          setSelectRows(res?.items ?? []);\n          setSelectTotal(res?.total ?? 0);\n        })\n        .catch(() => {\n          if (selectGenRef.current !== gen) return;\n          setSelectRows([]);\n          setSelectTotal(0);\n        })\n        .finally(() => {\n          if (selectGenRef.current === gen) setSelectLoading(false);\n        });\n    }, FETCH_DEBOUNCE_MS);\n    return () => clearTimeout(handle);\n  }, [\n    isActive,\n    mode,\n    fetchAvailableSerials,\n    itemExtensionId,\n    storageId,\n    lotId,\n    selectPage,\n    selectQuery,\n  ]);\n\n  // ── Captura: validar cada serial nuevo contra el adapter ───\n  const handleCaptureChange = useCallback(\n    async (nextCodes: string[]) => {\n      const currentCodes = captureCodes;\n\n      // Eliminación: códigos son únicos → localizar el índice removido.\n      if (nextCodes.length < currentCodes.length) {\n        const nextSet = new Set(nextCodes);\n        const removedIdx = currentCodes.findIndex((c) => !nextSet.has(c));\n        const nextIds = serialIdsRef.current.slice();\n        if (removedIdx >= 0) nextIds.splice(removedIdx, 1);\n        setCaptureCodes(nextCodes);\n        commitSerialIds(nextIds);\n        setCaptureError(null);\n        return;\n      }\n\n      // Adición: el código nuevo es el último (el panel lo agrega al final).\n      const added = nextCodes[nextCodes.length - 1];\n      if (!added || !validateSerial) return;\n      setCaptureError(null);\n      setValidating(true);\n      try {\n        const res = await validateSerial({\n          serialCode: added,\n          itemExtensionId,\n          storageId,\n          lotId,\n        });\n        if (res?.available) {\n          // Tope duro: ya alcanzamos la cantidad requerida → ignorar el sobrante.\n          if (required > 0 && serialIdsRef.current.length >= required) {\n            // `required` además de `count`, por lo mismo que en SerialSelectPanel: un catálogo\n            // de host que declare el texto con `{required}` dejaba el token crudo.\n            setCaptureError(t('serial_panel.max_reached', { count: required, required }));\n            return;\n          }\n          setCaptureCodes((prev) => [...prev, added]);\n          commitSerialIds([...serialIdsRef.current, res.serialId ?? added]);\n        } else {\n          setCaptureError(res?.reason || t('serial_panel.not_available_error'));\n        }\n      } catch {\n        setCaptureError(t('serial_panel.not_available_error'));\n      } finally {\n        // En `finally` y no tras el `await`: la rama del tope duro\n        // (`max_reached`) sale por un `return` temprano.\n        setValidating(false);\n      }\n    },\n    [captureCodes, validateSerial, itemExtensionId, storageId, lotId, commitSerialIds, required, t],\n  );\n\n  const handleSelectQueryChange = useCallback((q: string) => {\n    setSelectQuery(q);\n    setSelectPage(1);\n  }, []);\n\n  // ── Resultado ──────────────────────────────────────────────\n  const count = serialIds.length;\n  // `>=` (no `===`): tolera el tope. Una sobre-captura/sobre-selección (count >\n  // required) NUNCA debe dejar Guardar bloqueado para siempre.\n  const isComplete = !isActive || unsupported || count >= required;\n\n  const panelProps = useMemo<SerialPanelProps | null>(() => {\n    if (!isActive || unsupported) return null;\n    if (mode === 'capture') {\n      return {\n        mode: 'capture',\n        serials: captureCodes,\n        required,\n        readOnly,\n        externalError: captureError,\n        validating,\n        onChange: handleCaptureChange,\n      };\n    }\n    return {\n      mode: 'select',\n      rows: selectRows,\n      value: serialIds,\n      required,\n      readOnly,\n      pageSize: SELECT_PAGE_SIZE,\n      onChange: commitSerialIds,\n      query: selectQuery,\n      onQueryChange: handleSelectQueryChange,\n      page: selectPage,\n      onPageChange: setSelectPage,\n      total: selectTotal,\n      loading: selectLoading,\n      confirmOnStatuses,\n      confirmMessageKey,\n    };\n  }, [\n    isActive,\n    unsupported,\n    mode,\n    captureCodes,\n    required,\n    readOnly,\n    captureError,\n    validating,\n    handleCaptureChange,\n    selectRows,\n    serialIds,\n    commitSerialIds,\n    selectQuery,\n    handleSelectQueryChange,\n    selectPage,\n    selectTotal,\n    selectLoading,\n    confirmOnStatuses,\n    confirmMessageKey,\n  ]);\n\n  return {\n    isActive,\n    isComplete,\n    required,\n    count,\n    serialIdsField,\n    unsupported,\n    unsupportedMessage: unsupported ? t('serial_panel.unsupported') : null,\n    panelProps,\n  };\n}\n","import React, { useEffect, useCallback, useRef, useMemo, useState } from 'react';\nimport { useForm, useWatch } from 'react-hook-form';\nimport { clsx } from 'clsx';\nimport { FieldRenderer } from './FieldRenderer';\nimport { evaluateBlockingFields } from './fieldValidation';\nimport type {\n  LineFormModalProps,\n  ComputedRule,\n  LineModalSectionConfig,\n  LookupFieldConfig,\n  FieldErrorMap,\n} from './MasterDocument.types';\nimport type { ServerRuleConfig } from './template/MasterDocumentTemplate.types';\nimport { evaluateCondition, extractDependencyFields } from './fieldCondition';\nimport type { FieldCondition } from './fieldCondition';\nimport { buildDependentLookupProps, buildDependentsByParent } from './lookupFilters';\nimport type { DependentLookupProps } from './lookupFilters';\nimport { SerialPanel } from './SerialPanel';\nimport { useSerialPanel } from './SerialPanel/hooks';\nimport { useSerialPanelTranslation } from './SerialPanel/i18n';\nimport { ExclamationTriangleIcon } from '@heroicons/react/24/outline';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { FieldLoadingIndicator } from './components/loading';\n\n// ─── Icons ─────────────────────────────────────────────────\n\nfunction XIcon(props: React.SVGProps<SVGSVGElement>) {\n  return (\n    <svg viewBox=\"0 0 20 20\" fill=\"currentColor\" {...props}>\n      <path d=\"M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z\" />\n    </svg>\n  );\n}\n\n// ─── Computed Rules Runner ─────────────────────────────────\n\nfunction ComputedRulesRunner({\n  rules,\n  control,\n  setValue,\n}: {\n  rules: ComputedRule[];\n  control: ReturnType<typeof useForm>['control'];\n  setValue: ReturnType<typeof useForm>['setValue'];\n}) {\n  // Watch all fields that any rule depends on\n  const allWatchFields = [...new Set(rules.flatMap((r) => r.watch))];\n  const watchedValues = useWatch({ control, name: allWatchFields });\n\n  useEffect(() => {\n    const formSnapshot: Record<string, unknown> = {};\n    allWatchFields.forEach((field, idx) => {\n      formSnapshot[field] = watchedValues[idx];\n    });\n\n    rules.forEach((rule) => {\n      const result = rule.compute(formSnapshot);\n      setValue(rule.targetField, result, { shouldDirty: false });\n    });\n  }, [watchedValues, rules, setValue, allWatchFields]);\n\n  return null;\n}\n\n// ─── Form Values Watcher ───────────────────────────────────\n\nfunction FormValuesWatcher({\n  control,\n  onChange,\n}: {\n  control: ReturnType<typeof useForm>['control'];\n  onChange: (values: Record<string, unknown>) => void;\n}) {\n  const values = useWatch({ control });\n  useEffect(() => {\n    const t = setTimeout(() => onChange(values as Record<string, unknown>), 100);\n    return () => clearTimeout(t);\n  }, [values, onChange]);\n  return null;\n}\n\n/**\n * Recalcula los campos que bloquean, para que los mensajes y los badges se apaguen a\n * medida que el usuario los resuelve tras un intento fallido.\n *\n * Va en un hijo, como `FormValuesWatcher`: si el `useWatch` de todos los valores viviera\n * en el modal, el modal entero se re-renderizaría en cada pulsación. Y solo se monta\n * DESPUÉS del primer intento fallido, así que antes no observa nada.\n */\nfunction LineBlockingWatcher({\n  control,\n  calcular,\n  onChange,\n}: {\n  control: ReturnType<typeof useForm>['control'];\n  calcular: (values: Record<string, unknown>) => FieldErrorMap;\n  onChange: (errors: FieldErrorMap) => void;\n}) {\n  const values = useWatch({ control });\n  // La firma evita el bucle de render: `useWatch` devuelve un objeto nuevo en cada\n  // render, así que sin comparar el CONTENIDO cada recálculo dispararía otro estado.\n  const firmaPrevia = useRef<string | null>(null);\n  useEffect(() => {\n    const errores = calcular((values ?? {}) as Record<string, unknown>);\n    const firma = JSON.stringify(\n      Object.entries(errores).map(([k, v]) => [k, v.message]).sort(),\n    );\n    if (firma !== firmaPrevia.current) {\n      firmaPrevia.current = firma;\n      onChange(errores);\n    }\n  }, [values, calcular, onChange]);\n  return null;\n}\n\n// ─── Server Rules Runner ───────────────────────────────────\n\nfunction ServerRulesRunner({\n  rules,\n  control,\n  setValue,\n  onEvaluate,\n  setLoadingFields,\n}: {\n  rules: ServerRuleConfig[];\n  control: ReturnType<typeof useForm>['control'];\n  setValue: ReturnType<typeof useForm>['setValue'];\n  onEvaluate: (ruleId: string, formData: Record<string, unknown>) => Promise<Partial<Record<string, unknown>>>;\n  setLoadingFields: React.Dispatch<React.SetStateAction<Set<string>>>;\n}) {\n  const allTriggerFields = useMemo(\n    () => [...new Set(rules.flatMap((r) => r.triggerFields))],\n    [rules],\n  );\n  const watched = useWatch({ control, name: allTriggerFields as [string, ...string[]] });\n\n  const initialized = useRef(false);\n  const timers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());\n  const generations = useRef<Map<string, number>>(new Map());\n\n  useEffect(() => {\n    const isInit = !initialized.current;\n    initialized.current = true;\n\n    const snapshot: Record<string, unknown> = {};\n    allTriggerFields.forEach((k, i) => { snapshot[k] = watched[i]; });\n\n    rules.forEach((rule) => {\n      if (isInit && (rule.triggerOn ?? 'change') !== 'always') return;\n      if (rule.condition && !evaluateCondition(rule.condition as FieldCondition, snapshot)) return;\n\n      const existing = timers.current.get(rule.ruleId);\n      if (existing) clearTimeout(existing);\n\n      const delay = rule.debounceMs ?? 300;\n      const timer = setTimeout(async () => {\n        const gen = (generations.current.get(rule.ruleId) ?? 0) + 1;\n        generations.current.set(rule.ruleId, gen);\n\n        setLoadingFields((prev) => {\n          const next = new Set(prev);\n          rule.targetFields.forEach((f) => next.add(f));\n          return next;\n        });\n\n        try {\n          const result = await onEvaluate(rule.ruleId, snapshot);\n          if (generations.current.get(rule.ruleId) !== gen) return;\n          Object.entries(result).forEach(([key, value]) => {\n            setValue(key, value, { shouldDirty: false });\n          });\n        } catch {\n          // Leave fields unchanged on error\n        } finally {\n          if (generations.current.get(rule.ruleId) === gen) {\n            setLoadingFields((prev) => {\n              const next = new Set(prev);\n              rule.targetFields.forEach((f) => next.delete(f));\n              return next;\n            });\n          }\n        }\n\n        timers.current.delete(rule.ruleId);\n      }, delay);\n\n      timers.current.set(rule.ruleId, timer);\n    });\n  }, [watched]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  // Clear all pending timers on unmount\n  useEffect(() => {\n    return () => {\n      timers.current.forEach((t) => clearTimeout(t));\n    };\n  }, []);\n\n  return null;\n}\n\n// ─── LineFormModal ──────────────────────────────────────────\n\n/**\n * LineFormModal — modal deslizante para crear o editar una línea del documento.\n *\n * En escritorio se muestra como un diálogo centrado; en móvil se presenta\n * como una hoja inferior (bottom sheet). Gestiona el formulario internamente\n * con `react-hook-form` y ejecuta las reglas de cálculo automático mediante\n * `ComputedRulesRunner`.\n *\n * @see FieldRenderer — renderiza cada campo del formulario\n * @see ComputedRule — tipo para las reglas de campos calculados\n *\n * @example\n * ```tsx\n * <LineFormModal\n *   open={lineModal.open}\n *   onClose={() => setLineModal({ open: false, lineId: null })}\n *   onConfirm={(data) => handleLineSave(lineModal.lineId, data)}\n *   fields={lineFields}\n *   title=\"Nueva línea\"\n *   confirmLabel=\"Agregar línea\"\n * />\n * ```\n */\nexport function LineFormModal({\n  open,\n  onClose,\n  onConfirm,\n  onConfirmAndAddAnother,\n  fields,\n  initialData,\n  computedRules,\n  serverRules,\n  onEvaluateServerRule,\n  errors: externalErrors,\n  busy = false,\n  title,\n  confirmLabel,\n  cancelLabel,\n  readOnly = false,\n  docState,\n  columns = 2,\n  sections,\n  widgetSlot,\n  dynamicEntitiesSlot,\n  onFormValuesChange,\n  lookupConfigs,\n  fetcher,\n  headerValues,\n  serialSupport,\n  serialReadOnly,\n  validateSerial,\n  fetchAvailableSerials,\n  className,\n}: LineFormModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const resolvedConfirmLabel = confirmLabel ?? t('master_document.chrome.confirm');\n  const resolvedCancelLabel = cancelLabel ?? t('master_document.chrome.cancel');\n  const sortedFields = [...fields].sort((a, b) => a.order - b.order);\n  const modalRef = useRef<HTMLDivElement>(null);\n  const [activeTab, setActiveTab] = useState<string>('');\n  /**\n   * Campos que el guardián marcó en el último intento de guardar. Vacío ⇒ no hubo intento\n   * fallido (o ya se resolvió). Alimenta a la vez el mensaje de cada campo y el badge de\n   * su pestaña, así que las dos señales no pueden contradecirse.\n   */\n  const [erroresCliente, setErroresCliente] = useState<FieldErrorMap>({});\n  const huboIntentoFallido = Object.keys(erroresCliente).length > 0;\n  const [loadingFields, setLoadingFields] = useState<Set<string>>(new Set());\n\n  // Collect all field keys referenced in field AND section conditions\n  const conditionDeps = useMemo(() => {\n    const keys = new Set<string>();\n    sortedFields.forEach((f) => {\n      if (f.visibleWhen) extractDependencyFields(f.visibleWhen as FieldCondition).forEach((k) => keys.add(k));\n      if (f.hiddenWhen) extractDependencyFields(f.hiddenWhen as FieldCondition).forEach((k) => keys.add(k));\n    });\n    sections?.forEach((s) => {\n      if (s.visibleWhen) extractDependencyFields(s.visibleWhen as FieldCondition).forEach((k) => keys.add(k));\n      if (s.hiddenWhen) extractDependencyFields(s.hiddenWhen as FieldCondition).forEach((k) => keys.add(k));\n    });\n    return [...keys];\n  }, [sortedFields, sections]);\n\n  // Build default values from fields\n  const defaultValues: Record<string, unknown> = {};\n  fields.forEach((f) => {\n    defaultValues[f.key] = initialData?.[f.key] ?? f.defaultValue ?? '';\n  });\n\n  const { control, setValue, reset, handleSubmit } = useForm({\n    defaultValues,\n  });\n\n  // Watch only the fields referenced in conditions for reactive visibility\n  const watchedConditionValues = useWatch({ control, name: conditionDeps as [string, ...string[]] });\n\n  const conditionSnapshot = useMemo(() => {\n    const snap: Record<string, unknown> = {};\n    conditionDeps.forEach((key, i) => { snap[key] = watchedConditionValues[i]; });\n    return snap;\n  }, [conditionDeps, watchedConditionValues]);\n\n  // ── Cascading lookups (filterDependencies) ──────────────\n  const lineFieldKeys = useMemo(() => new Set(fields.map((f) => f.key)), [fields]);\n\n  // Padres (form-keys) que son campos de la LÍNEA y deben observarse en vivo.\n  // Los padres de CABECERA se resuelven contra `headerValues` (estables en el modal).\n  const lineParentKeys = useMemo(() => {\n    const keys = new Set<string>();\n    fields.forEach((f) => {\n      const fd = lookupConfigs?.[f.key]?.filterDependencies;\n      if (fd) Object.values(fd).forEach((k) => { if (lineFieldKeys.has(k)) keys.add(k); });\n    });\n    return [...keys];\n  }, [fields, lookupConfigs, lineFieldKeys]);\n\n  const watchedParents = useWatch({\n    control,\n    name: (lineParentKeys.length ? lineParentKeys : ['__no_cascade__']) as [string, ...string[]],\n  });\n\n  const lineParentSnapshot = useMemo(() => {\n    const snap: Record<string, unknown> = {};\n    lineParentKeys.forEach((k, i) => { snap[k] = watchedParents[i]; });\n    return snap;\n  }, [lineParentKeys, watchedParents]);\n\n  // Resuelve un form-key contra el merge { ...cabecera, ...línea } (línea precede).\n  const resolveCascadeValue = useCallback(\n    (formKey: string) => {\n      if (lineFieldKeys.has(formKey)) return lineParentSnapshot[formKey];\n      return headerValues?.[formKey];\n    },\n    [lineFieldKeys, lineParentSnapshot, headerValues],\n  );\n\n  // Mapa padre → dependientes (sólo dependientes que son campos de la línea).\n  const lineDependentsByParent = useMemo(\n    () => buildDependentsByParent(lookupConfigs, lineFieldKeys),\n    [lookupConfigs, lineFieldKeys],\n  );\n\n  // Cambia un campo de línea y limpia los searchers dependientes (sólo en cambios\n  // del usuario; la carga inicial usa reset() y no dispara esto).\n  const handleLineFieldChange = useCallback(\n    (key: string, value: unknown) => {\n      setValue(key, value, { shouldDirty: true });\n      const dependents = lineDependentsByParent[key];\n      if (dependents) {\n        dependents.forEach((depKey) => setValue(depKey, '', { shouldDirty: true }));\n      }\n    },\n    [setValue, lineDependentsByParent],\n  );\n\n  const visibleFields = useMemo(() => {\n    if (conditionDeps.length === 0) return sortedFields;\n    return sortedFields.filter((f) => {\n      if (f.visibleWhen && !evaluateCondition(f.visibleWhen as FieldCondition, conditionSnapshot)) return false;\n      if (f.hiddenWhen && evaluateCondition(f.hiddenWhen as FieldCondition, conditionSnapshot)) return false;\n      return true;\n    });\n  }, [sortedFields, conditionDeps.length, conditionSnapshot]);\n\n  // Sections visible after evaluating their own conditions\n  const visibleSections = useMemo<LineModalSectionConfig[]>(() => {\n    if (!sections) return [];\n    return sections.filter((s) => {\n      if (s.visibleWhen && !evaluateCondition(s.visibleWhen as FieldCondition, conditionSnapshot)) return false;\n      if (s.hiddenWhen && evaluateCondition(s.hiddenWhen as FieldCondition, conditionSnapshot)) return false;\n      return true;\n    });\n  }, [sections, conditionSnapshot]);\n\n  // Keys of all configured sections (to separate \"common\" fields that have no matching section)\n  const configuredSectionKeys = useMemo(\n    () => new Set(sections?.map((s) => s.key) ?? []),\n    [sections],\n  );\n\n  // Fields above the tabs: fields whose section key isn't configured (always visible in flat mode too)\n  const commonFields = useMemo(\n    () => (sections ? visibleFields.filter((f) => !configuredSectionKeys.has(f.section)) : []),\n    [sections, visibleFields, configuredSectionKeys],\n  );\n\n  // Fields for the active tab\n  const activeTabFields = useMemo(\n    () => (sections ? visibleFields.filter((f) => f.section === activeTab) : visibleFields),\n    [sections, visibleFields, activeTab],\n  );\n\n  // Keep activeTab pointing at a visible section; fall back to first if current becomes hidden\n  useEffect(() => {\n    if (!visibleSections.length) return;\n    if (!visibleSections.find((s) => s.key === activeTab)) {\n      setActiveTab(visibleSections[0].key);\n    }\n  }, [visibleSections, activeTab]);\n\n  // Reset form and active tab only when modal transitions closed → open.\n  // Using a ref to track previous open state prevents resets caused by\n  // unstable initialData references (e.g. inline object literals in JSX).\n  const prevOpenRef = useRef(false);\n  useEffect(() => {\n    const justOpened = open && !prevOpenRef.current;\n    prevOpenRef.current = open;\n    if (!justOpened) return;\n\n    const values: Record<string, unknown> = {};\n    fields.forEach((f) => {\n      values[f.key] = initialData?.[f.key] ?? f.defaultValue ?? '';\n    });\n    reset(values);\n    /*\n     * Limpiar lo que marcó el guardián. El modal NO se desmonta al cerrarse —el padre lo\n     * monta siempre y solo alterna `open`, y `if (!open) return null` deja el estado\n     * vivo—, así que sin esto una línea nueva se abriría con los campos en rojo y los\n     * badges del intento anterior.\n     */\n    setErroresCliente({});\n\n    // Reset active tab to first visible section given initial values\n    if (sections && sections.length > 0) {\n      const initialSnap: Record<string, unknown> = {};\n      fields.forEach((f) => { initialSnap[f.key] = initialData?.[f.key] ?? f.defaultValue ?? ''; });\n      const firstVisible = sections.find((s) => {\n        if (s.visibleWhen && !evaluateCondition(s.visibleWhen as FieldCondition, initialSnap)) return false;\n        if (s.hiddenWhen && evaluateCondition(s.hiddenWhen as FieldCondition, initialSnap)) return false;\n        return true;\n      });\n      setActiveTab(firstVisible?.key ?? sections[0].key);\n    }\n  }, [open, initialData, fields, reset, sections]);\n\n  // Focus primer campo editable al abrir\n  useEffect(() => {\n    if (!open) return;\n    const timer = setTimeout(() => {\n      const first = modalRef.current?.querySelector<HTMLElement>(\n        'input:not([disabled]):not([readonly]), textarea:not([disabled]):not([readonly])',\n      );\n      first?.focus();\n    }, 80); // espera el fade-in de 150ms para no cortar la animación\n    return () => clearTimeout(timer);\n  }, [open]);\n\n  // Close on Escape\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  // ── Soporte nativo de seriales (FASE 2) ──────────────────\n  // Llamado DESPUÉS del efecto de reset para que la re-inyección de `serial_ids`\n  // ocurra tras el `reset()` del modal (que solo repuebla las keys de campo).\n  const { t: serialT } = useSerialPanelTranslation();\n  const serial = useSerialPanel({\n    serialSupport,\n    control,\n    setValue,\n    readOnly: readOnly || (serialReadOnly ?? false),\n    open,\n    initialData,\n    validateSerial,\n    fetchAvailableSerials,\n  });\n  const serialBlocksSave = serial.isActive && !serial.isComplete;\n\n  // Computed target fields (readonly). En `useMemo` porque de su identidad dependen\n  // `camposQueBloquean` y, por él, el efecto del vigía: recrear el Set en cada render\n  // hacía que el efecto se re-ejecutara en cada pulsación de tecla.\n  const computedTargets = useMemo(\n    () => new Set(computedRules?.map((r) => r.targetField) ?? []),\n    [computedRules],\n  );\n\n  // Evalúa si un campo es editable según editableOn y el docState actual\n  const isFieldEditable = useCallback(\n    (field: LineFormModalProps['fields'][number]) => {\n      if (readOnly) return false; // modo \"Ver\": ningún campo es editable\n      if (!field.editableOn || field.editableOn.length === 0) return false;\n      if (field.editableOn.includes('*')) return true;\n      if (!docState) return true; // sin docState → no restringir\n      return field.editableOn.includes(docState);\n    },\n    [readOnly, docState],\n  );\n\n  /*\n   * ── Guardián de la línea (ADR-027 §C.3) ──────────────────────────────────────\n   *\n   * Hasta ahora `disabled={serialBlocksSave || busy}` era TODO el control: una línea con\n   * un obligatorio vacío se agregaba sin más, porque `validations` no lo leía nadie.\n   * Medido en dev el 2026-09-08 sobre una devolución de venta: con «Motivo del\n   * movimiento» sin elegir, «Agregar línea» estaba habilitado.\n   *\n   * Se bloquea al PULSAR, no deshabilitando el botón. Un botón muerto no dice qué falta\n   * —y en un formulario con pestañas el campo puede no estar a la vista—, y si el\n   * guardián se equivocara sería indiagnosticable. Al pulsar se marca cada campo, se\n   * pinta el badge de su pestaña y se salta a la primera con algo pendiente.\n   */\n  const camposQueBloquean = useMemo(\n    // Solo lo que el usuario puede resolver AHORA. Un campo oculto por condición, no\n    // editable por estado, sin el permiso de edición (que llega con `editableOn: []`) o\n    // calculado no puede bloquear a nadie: no habría forma de desbloquearlo.\n    () => visibleFields.filter((f) => isFieldEditable(f) && !computedTargets.has(f.key)),\n    [visibleFields, isFieldEditable, computedTargets],\n  );\n\n  const calcularBloqueo = useCallback(\n    (values: Record<string, unknown>) =>\n      evaluateBlockingFields(camposQueBloquean, values, {\n        requiredFallbackMessage: t('master_document.lines.fieldRequired'),\n      }),\n    [camposQueBloquean, t],\n  );\n\n  /** `true` si la línea NO puede guardarse; deja ya marcado el motivo. */\n  const bloqueaGuardado = useCallback(\n    (data: Record<string, unknown>) => {\n      const errores = calcularBloqueo(data);\n      const claves = Object.keys(errores);\n      if (claves.length === 0) {\n        setErroresCliente({});\n        return false;\n      }\n      setErroresCliente(errores);\n      // Llevar al usuario a la primera pestaña con algo pendiente es la mitad del valor\n      // de esta señal: el campo que falta puede estar en otra pestaña.\n      const primera = visibleSections.find((sec) =>\n        camposQueBloquean.some((f) => f.section === sec.key && claves.includes(f.key)),\n      );\n      if (primera && primera.key !== activeTab) setActiveTab(primera.key);\n      return true;\n    },\n    [calcularBloqueo, visibleSections, camposQueBloquean, activeTab],\n  );\n\n  const handleConfirm = useCallback(\n    (data: Record<string, unknown>) => {\n      if (bloqueaGuardado(data)) return;\n      onConfirm(data);\n    },\n    [onConfirm, bloqueaGuardado],\n  );\n\n  // Guarda la línea actual, limpia el form y deja el modal abierto para agregar otra.\n  // Awaita el resultado del parent: si retorna errores, no limpia el form (el banner los muestra).\n  const handleConfirmAndAddAnother = useCallback(\n    async (data: Record<string, unknown>) => {\n      if (bloqueaGuardado(data)) return;\n      const errors = (await onConfirmAndAddAnother!(data)) as FieldErrorMap | undefined;\n      if (!errors || Object.keys(errors).length === 0) {\n        const emptyValues: Record<string, unknown> = {};\n        fields.forEach((f) => { emptyValues[f.key] = f.defaultValue ?? ''; });\n        reset(emptyValues);\n      }\n    },\n    [onConfirmAndAddAnother, fields, reset, bloqueaGuardado],\n  );\n\n  // Form-level errors: keys in externalErrors that don't match any field key\n  const fieldKeys = useMemo(() => new Set(fields.map((f) => f.key)), [fields]);\n  const formLevelErrors = useMemo(\n    () =>\n      externalErrors\n        ? Object.entries(externalErrors)\n            .filter(([key]) => !fieldKeys.has(key))\n            .map(([, err]) => err)\n        : [],\n    [externalErrors, fieldKeys],\n  );\n\n\n  const gridClass = columns === 1 ? 'grid-cols-1' : 'grid-cols-1 sm:grid-cols-2';\n\n  if (!open) return null;\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        onClick={onClose}\n        aria-hidden=\"true\"\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          // Desktop: centered modal\n          'fixed z-[301] bg-bg-primary rounded-2xl overflow-hidden',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          // Desktop\n          'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-h-[85vh]',\n          widgetSlot ? 'max-w-[1000px]' : 'max-w-[700px]',\n          // Mobile: bottom sheet\n          'max-sm:top-auto max-sm:bottom-0 max-sm:left-0 max-sm:right-0 max-sm:translate-x-0 max-sm:translate-y-0',\n          'max-sm:w-full max-sm:max-w-none max-sm:rounded-b-none max-sm:max-h-[90vh]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          className,\n        )}\n        ref={modalRef}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={title}\n      >\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-b border-border-secondary dark:border-dark-border-primary\">\n          <h2 className=\"text-base font-bold text-content-primary dark:text-dark-content-primary\">\n            {title}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"p-1.5 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XIcon className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/* Body: form + optional widget sidebar */}\n        <div\n          className={clsx('flex', widgetSlot ? 'flex-row' : 'flex-col')}\n          style={{ maxHeight: 'calc(85vh - 130px)' }}\n        >\n          {/* Form body */}\n          {/* El cuerpo ya NO scrollea como un todo: la barra de pestañas vivía dentro\n              del scroller, así que en una pestaña larga —«Costo», con seis campos y\n              los paneles de serie— se iba hacia arriba con el contenido y el usuario\n              perdía de vista en cuál estaba y cómo cambiar. Aquí sólo se reparte el\n              alto; quien scrollea es la caja de campos de abajo. */}\n          <div className={clsx('flex flex-col overflow-hidden min-h-0 px-6 py-5', widgetSlot ? 'flex-1 min-w-0' : 'w-full flex-1')}>\n            {/* Computed rules runner */}\n            {computedRules && computedRules.length > 0 && (\n              <ComputedRulesRunner rules={computedRules} control={control} setValue={setValue} />\n            )}\n\n            {/* Server rules runner */}\n            {serverRules && serverRules.length > 0 && onEvaluateServerRule && (\n              <ServerRulesRunner\n                rules={serverRules}\n                control={control}\n                setValue={setValue}\n                onEvaluate={onEvaluateServerRule}\n                setLoadingFields={setLoadingFields}\n              />\n            )}\n\n            {/* Form values watcher — notifies parent when values change */}\n            {onFormValuesChange && (\n              <FormValuesWatcher control={control} onChange={onFormValuesChange} />\n            )}\n\n            {/* Form-level error banner — errors whose keys don't match any field */}\n            {formLevelErrors.length > 0 && (\n              <div\n                role=\"alert\"\n                className=\"mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 dark:border-red-800 dark:bg-red-950/20\"\n              >\n                {formLevelErrors.map((err, i) => (\n                  <p key={i} className=\"text-sm text-red-700 dark:text-red-400\">\n                    {err.message}\n                  </p>\n                ))}\n              </div>\n            )}\n\n            {/* Common fields — rendered above tabs (section key not listed in sections config) */}\n            {sections && commonFields.length > 0 && (\n              <div className={clsx('grid gap-4 mb-4', gridClass)}>\n                {commonFields.map((field) => {\n                  const isComputed = computedTargets.has(field.key);\n                  const isLoading = loadingFields.has(field.key);\n                  const editable = isFieldEditable(field) && !isComputed && !isLoading;\n                  const depProps = buildDependentLookupProps(lookupConfigs?.[field.key], resolveCascadeValue);\n                  return (\n                    <div key={field.key} className={clsx(field.span >= 2 && columns === 2 && 'sm:col-span-2')}>\n                      <FieldRendererControlled\n                        field={field}\n                        control={control}\n                        setValue={setValue}\n                        onValueChange={handleLineFieldChange}\n                        editable={editable}\n                        readOnly={isComputed}\n                        loading={isLoading}\n                        error={externalErrors?.[field.key] ?? erroresCliente[field.key]}\n                        isComputed={isComputed}\n                        lookupConfig={lookupConfigs?.[field.key]}\n                        fetcher={fetcher}\n                        dependentProps={depProps}\n                      />\n                    </div>\n                  );\n                })}\n              </div>\n            )}\n\n            {/* Solo tras un intento fallido: antes no observa nada. */}\n            {huboIntentoFallido && (\n              <LineBlockingWatcher\n                control={control}\n                calcular={calcularBloqueo}\n                onChange={setErroresCliente}\n              />\n            )}\n\n            {/*\n              Tab bar. El asterisco sale de la obligatoriedad declarada y se ve desde el\n              primer render; el badge cuenta los campos que están bloqueando y solo\n              aparece tras un intento fallido. Las dos marcas salen de la MISMA fuente que\n              el guardián, así que no puede haber una pestaña con número y sin asterisco\n              —la contradicción del §C.3b—. Las clases son las literales de `CanonTabsBar`\n              para que la marca se lea igual aquí que en las pestañas de la cabecera.\n            */}\n            {visibleSections.length > 0 && (\n              <div className=\"shrink-0 flex gap-1 pt-0.5 pb-3 mb-4 px-0.5 border-b border-border-secondary dark:border-dark-border-primary overflow-x-auto\">\n                {visibleSections.map((section) => (\n                  <button\n                    key={section.key}\n                    type=\"button\"\n                    onClick={() => setActiveTab(section.key)}\n                    className={clsx(\n                      'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium whitespace-nowrap transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-1',\n                      activeTab === section.key\n                        ? 'bg-primary-inverse-background text-primary-inverse-content dark:bg-dark-bg-inverse dark:text-dark-content-inverse'\n                        : 'text-content-secondary hover:bg-background-secondary hover:text-content-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary dark:hover:text-dark-content-primary',\n                    )}\n                  >\n                    {section.label}\n                    {/* La MISMA regla que las pestañas del encabezado (§C.3b): la marca\n                        sólo sale si dentro hay un obligatorio que el usuario pueda ver\n                        marcado. `FieldRenderer` pinta el asterisco únicamente en campos\n                        editables, así que en un modal de sólo lectura —o sobre un campo\n                        `readonly`/`display`— la pestaña anunciaba un obligatorio que su\n                        contenido no mostraba, y que además nadie podía rellenar. Medido\n                        en dev el 2026-09-09: el modal de línea de una devolución\n                        aprobada, sin un solo control editable, traía `*` en tres de sus\n                        cuatro pestañas. */}\n                    {!readOnly\n                      && visibleFields.some(\n                        (f) => f.section === section.key && f.required\n                          && f.control !== 'readonly' && f.control !== 'display',\n                      ) && <span className=\"text-[#dc2626]\">*</span>}\n                    {(() => {\n                      const faltan = camposQueBloquean.filter(\n                        (f) => f.section === section.key && erroresCliente[f.key] !== undefined,\n                      ).length;\n                      return faltan > 0 ? (\n                        <span className=\"inline-flex items-center justify-center min-w-4 h-4 px-1 bg-[#dc2626] text-white rounded-full text-[9px] font-bold\">\n                          {faltan}\n                        </span>\n                      ) : null;\n                    })()}\n                  </button>\n                ))}\n              </div>\n            )}\n\n            {/* Scroller del contenido de la pestaña. `min-h-0` es lo que permite que un\n                hijo de flex se encoja por debajo de su contenido; sin él el `flex-1`\n                crece hasta el alto natural del formulario y no scrollea nada.\n\n                El `-mx-2 px-2` es SIMÉTRICO a propósito. Un contenedor con\n                `overflow-y-auto` recorta también en el eje horizontal (CSS lo obliga:\n                con un `overflow` distinto de `visible` en un eje, el otro no puede\n                quedarse en `visible`), y el anillo de foco del canon sobresale ~4px del\n                input —`ring-2` más `ring-offset-2`—. Sin holgura a los dos lados, un\n                campo pegado al borde se enfoca y su recuadro azul aparece cortado a la\n                izquierda, a la derecha o en ambas. Antes sólo había `pr-2`, que tapaba\n                el lado derecho y dejaba el izquierdo a la vista. El margen negativo\n                repone el gutter, así que los campos no se mueven. */}\n            <div className=\"flex-1 min-h-0 overflow-y-auto scrollbar-thin -mx-2 px-2\">\n            <div className={clsx('grid gap-4', gridClass)}>\n              {activeTabFields.map((field) => {\n                const isComputed = computedTargets.has(field.key);\n                const isLoading = loadingFields.has(field.key);\n                const editable = isFieldEditable(field) && !isComputed && !isLoading;\n                const depProps = buildDependentLookupProps(lookupConfigs?.[field.key], resolveCascadeValue);\n\n                return (\n                  <div\n                    key={field.key}\n                    className={clsx(\n                      field.span >= 2 && columns === 2 && 'sm:col-span-2',\n                    )}\n                  >\n                    <FieldRendererControlled\n                      field={field}\n                      control={control}\n                      setValue={setValue}\n                      onValueChange={handleLineFieldChange}\n                      editable={editable}\n                      readOnly={isComputed}\n                      loading={isLoading}\n                      error={externalErrors?.[field.key] ?? erroresCliente[field.key]}\n                      isComputed={isComputed}\n                      lookupConfig={lookupConfigs?.[field.key]}\n                      fetcher={fetcher}\n                      dependentProps={depProps}\n                    />\n                  </div>\n                );\n              })}\n            </div>\n\n            {/* Soporte nativo de seriales — panel cableado (FASE 2) */}\n            {serial.isActive && serial.panelProps && (\n              <div className=\"mt-5 pt-5 border-t border-border-secondary dark:border-dark-border-primary\">\n                <h3 className=\"mb-3 text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n                  {serialT('serial_panel.section_title')}\n                </h3>\n                <SerialPanel {...serial.panelProps} />\n              </div>\n            )}\n\n            {/* Campos adicionales (EAV) de la línea. Al final del cuerpo del\n                formulario, después de los seriales: son campos de captura, así\n                que van en la columna que sí existe en móvil — no en el panel\n                lateral `widgetSlot`, que está oculto en pantallas pequeñas. */}\n            {dynamicEntitiesSlot && (\n              <div className=\"mt-5 border-t border-border-secondary pt-5 dark:border-dark-border-primary\">\n                {dynamicEntitiesSlot}\n              </div>\n            )}\n\n            {/* Degradación: serialSupport activo pero el adapter no implementa el método */}\n            {serial.unsupported && serial.unsupportedMessage && (\n              <div\n                role=\"alert\"\n                className=\"mt-5 flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 px-3.5 py-3 text-[13px] text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300\"\n              >\n                <ExclamationTriangleIcon className=\"mt-px h-4 w-4 shrink-0\" />\n                <span>{serial.unsupportedMessage}</span>\n              </div>\n            )}\n            </div>\n          </div>\n\n          {/* Widget sidebar */}\n          {widgetSlot && (\n            <div className=\"w-72 shrink-0 border-l border-border-secondary dark:border-dark-border-primary overflow-y-auto max-sm:hidden\">\n              {widgetSlot}\n            </div>\n          )}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-border-secondary dark:border-dark-border-primary\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              // Secundario del canon: LLEVA borde. Sin él era un texto suelto que no se\n              // leía como botón —el «Cancelar» de MasterCrud y los otros modales del\n              // propio kit (`ConflictModal`, `LineCloseModal`, `CrossingGenerateModal`)\n              // ya lo pintan con `border border-border-primary`.\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary dark:border-dark-border-primary',\n              'text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n            )}\n          >\n            {resolvedCancelLabel}\n          </button>\n\n          {/* Guardar y agregar otra — solo visible cuando se provee el callback */}\n          {!readOnly && onConfirmAndAddAnother && (\n            <button\n              type=\"button\"\n              onClick={handleSubmit(handleConfirmAndAddAnother)}\n              disabled={serialBlocksSave || busy}\n              title={serialBlocksSave ? serialT('serial_panel.save_tooltip', { count: Math.max(0, serial.required - serial.count) }) : undefined}\n              className={clsx(\n                'px-4 py-2 rounded-md text-sm font-semibold',\n                'border border-border-primary text-content-primary hover:bg-background-secondary transition-all duration-150',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n                'dark:border-dark-border-primary dark:text-dark-content-primary dark:hover:bg-dark-bg-secondary',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent',\n              )}\n            >\n              {t('master_document.lines.saveAndAddAnother')}\n            </button>\n          )}\n\n          {/* En modo solo-lectura (\"Ver\") se ocultan los botones de confirmación. */}\n          {!readOnly && (\n            <button\n              type=\"button\"\n              onClick={handleSubmit(handleConfirm)}\n              disabled={serialBlocksSave || busy}\n              title={serialBlocksSave ? serialT('serial_panel.save_tooltip', { count: Math.max(0, serial.required - serial.count) }) : undefined}\n              className={clsx(\n                'px-5 py-2 rounded-md text-sm font-semibold',\n                'bg-primary-inverse-background text-primary-inverse-content hover:bg-primary-700 transition-all duration-150',\n                'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n                'min-h-[36px]',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-primary-inverse-background',\n              )}\n            >\n              {resolvedConfirmLabel}\n            </button>\n          )}\n        </div>\n      </div>\n    </>\n  );\n}\n\n// ─── Controlled Field Wrapper ──────────────────────────────\n\nfunction FieldRendererControlled({\n  field,\n  control,\n  setValue,\n  onValueChange,\n  editable,\n  readOnly,\n  loading,\n  error,\n  isComputed,\n  lookupConfig,\n  fetcher,\n  dependentProps,\n}: {\n  field: LineFormModalProps['fields'][number];\n  control: ReturnType<typeof useForm>['control'];\n  setValue: ReturnType<typeof useForm>['setValue'];\n  onValueChange: (key: string, value: unknown) => void;\n  editable: boolean;\n  readOnly: boolean;\n  loading?: boolean;\n  error?: import('./MasterDocument.types').FieldError;\n  isComputed: boolean;\n  lookupConfig?: LookupFieldConfig;\n  fetcher?: unknown;\n  dependentProps?: DependentLookupProps;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const value = useWatch({ control, name: field.key });\n\n  const handleRecordSelect = useCallback(\n    (record: Record<string, unknown> | null) => {\n      if (!record || !lookupConfig?.bindFields) return;\n      for (const [targetField, sourceField] of Object.entries(lookupConfig.bindFields)) {\n        const bound = record[sourceField];\n        if (bound !== undefined) setValue(targetField, bound, { shouldDirty: true });\n      }\n    },\n    [lookupConfig, setValue],\n  );\n\n  return (\n    <div className=\"relative\">\n      <FieldRenderer\n        fieldDef={field}\n        value={value}\n        onChange={(v) => onValueChange(field.key, v)}\n        editable={editable}\n        readOnly={readOnly}\n        error={error}\n        lookupConfig={lookupConfig}\n        fetcher={fetcher}\n        onRecordSelect={handleRecordSelect}\n        getLookupFilters={dependentProps?.getFilters}\n        lookupDependencies={dependentProps?.dependencies}\n        disabled={dependentProps?.parentMissing}\n      />\n      {isComputed && (\n        <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary italic mt-0.5\">{t('master_document.lines.calculated')}</span>\n      )}\n      {loading && <FieldLoadingIndicator />}\n    </div>\n  );\n}\n","import { useEffect } from 'react';\nimport { clsx } from 'clsx';\nimport { XMarkIcon, ExclamationTriangleIcon } from '@heroicons/react/24/outline';\nimport type { ConflictModalProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/**\n * Modal de alerta de conflicto de edición concurrente.\n *\n * Se muestra cuando otro usuario ha guardado cambios en el mismo documento\n * mientras el usuario actual estaba editando. Ofrece dos acciones: recargar\n * el documento (perder cambios locales) o seguir editando (mantener cambios).\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - ConflictModalProps\n *\n * @example\n * ```tsx\n * <ConflictModal\n *   open={hasConflict}\n *   modifiedBy=\"Carlos Pérez\"\n *   modifiedAgo=\"hace 2 minutos\"\n *   onReload={() => reloadDocument()}\n *   onKeepEditing={() => dismissConflict()}\n * />\n * ```\n */\nexport function ConflictModal({\n  open,\n  modifiedBy,\n  modifiedAgo,\n  onReload,\n  onKeepEditing,\n  dismissable = true,\n  message,\n  className,\n}: ConflictModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      // En modo duro (no descartable) Escape NO cierra: la única salida es recargar.\n      if (e.key === 'Escape' && dismissable) onKeepEditing?.();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onKeepEditing, dismissable]);\n\n  if (!open) return null;\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[440px]',\n          'bg-bg-primary rounded-2xl px-6 py-5',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          className,\n        )}\n        role=\"alertdialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"conflict-title\"\n        aria-describedby=\"conflict-desc\"\n      >\n        {/* Close button — solo en modo descartable (blando). En el conflicto duro\n            del servidor (409) la única acción permitida es recargar. */}\n        {dismissable && (\n          <button\n            type=\"button\"\n            onClick={() => onKeepEditing?.()}\n            className=\"absolute top-4 right-4 p-1 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          </button>\n        )}\n\n        {/* Icon */}\n        <div className=\"flex items-center justify-center w-12 h-12 rounded-full bg-amber-50 mb-4 dark:bg-amber-700/15\">\n          <ExclamationTriangleIcon className=\"w-6 h-6 text-amber-700 dark:text-amber-400\" aria-hidden=\"true\" />\n        </div>\n\n        {/* Title */}\n        <h2\n          id=\"conflict-title\"\n          className=\"text-base font-bold text-content-primary dark:text-dark-content-primary mb-1\"\n        >\n          {t('master_document.document.conflictTitle')}\n        </h2>\n\n        {/* Subtitle */}\n        {modifiedBy && (\n          <p className=\"text-sm text-content-tertiary dark:text-dark-content-secondary mb-3\">\n            {t('master_document.document.conflictModifiedBy', {\n              user: modifiedBy,\n              when: modifiedAgo ?? t('master_document.document.conflictRecently'),\n            })}\n          </p>\n        )}\n\n        {/* Description */}\n        {dismissable ? (\n          <>\n            <p\n              id=\"conflict-desc\"\n              className=\"text-sm text-content-tertiary dark:text-dark-content-secondary mb-1\"\n            >\n              {t('master_document.document.conflictReloadWarning')}\n            </p>\n            <p className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary mb-5\">\n              {t('master_document.document.conflictWhatToDo')}\n            </p>\n          </>\n        ) : (\n          <p\n            id=\"conflict-desc\"\n            className=\"text-sm text-content-tertiary dark:text-dark-content-secondary mb-5\"\n          >\n            {message ?? t('master_document.document.conflictBody')}\n          </p>\n        )}\n\n        {/* Actions */}\n        <div className=\"flex items-center justify-end gap-3\">\n          {dismissable && (\n            <button\n              type=\"button\"\n              onClick={() => onKeepEditing?.()}\n              className={clsx(\n                'px-4 py-2 rounded-md text-sm font-semibold',\n                'border border-border-primary text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n              )}\n            >\n              {t('master_document.document.conflictKeepChanges')}\n            </button>\n          )}\n          <button\n            type=\"button\"\n            onClick={onReload}\n            className={clsx(\n              'px-5 py-2 rounded-md text-sm font-semibold',\n              'bg-primary-inverse-background text-white hover:bg-primary-700 transition-all duration-150',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            {t('master_document.document.conflictReload')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { clsx } from 'clsx';\nimport type { SkeletonDocumentProps, SkeletonListProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n// ─── Skeleton Block ────────────────────────────────────────\n\nfunction SkeletonBlock({ className }: { className?: string }) {\n  return (\n    <div\n      className={clsx(\n        'rounded-md bg-gradient-to-r from-background-secondary to-background-secondary',\n        'animate-pulse',\n        'dark:from-dark-bg-secondary dark:to-dark-bg-primary',\n        className,\n      )}\n    />\n  );\n}\n\n// ─── SkeletonDocument ──────────────────────────────────────\n\n/**\n * Esqueleto de carga para el documento maestro completo.\n *\n * Replica la estructura visual de ActionBar, ContextStrip, HeaderRenderer,\n * LinesSection y FactBox con bloques animados de gradiente para indicar\n * que el contenido está siendo cargado.\n *\n * @see MasterDocument.types - SkeletonDocumentProps\n */\nexport function SkeletonDocument({ className }: SkeletonDocumentProps) {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div\n      className={clsx('flex flex-col gap-4', className)}\n      aria-busy=\"true\"\n      aria-label={t('master_document.loading.document')}\n      role=\"status\"\n    >\n      {/* ActionBar skeleton */}\n      <div className=\"flex items-center justify-between h-[52px] px-4 bg-bg-primary rounded-t-xl dark:bg-dark-bg-primary\">\n        <div className=\"flex items-center gap-3\">\n          <SkeletonBlock className=\"w-20 h-5\" />\n          <div className=\"w-px h-5 bg-border-secondary dark:bg-dark-border-primary\" />\n          <SkeletonBlock className=\"w-28 h-5\" />\n          <SkeletonBlock className=\"w-16 h-5 rounded-full\" />\n        </div>\n        <div className=\"flex items-center gap-2\">\n          <SkeletonBlock className=\"w-20 h-8 rounded-md\" />\n          <SkeletonBlock className=\"w-20 h-8 rounded-md\" />\n          <SkeletonBlock className=\"w-24 h-8 rounded-md\" />\n        </div>\n      </div>\n\n      {/* ContextStrip skeleton */}\n      <div className=\"flex items-center h-12 px-4 bg-bg-primary gap-6 dark:bg-dark-bg-primary\">\n        {Array.from({ length: 5 }).map((_, i) => (\n          <div key={i} className=\"flex flex-col gap-1\">\n            <SkeletonBlock className=\"w-14 h-2.5\" />\n            <SkeletonBlock className=\"w-20 h-3.5\" />\n          </div>\n        ))}\n      </div>\n\n      <div className=\"flex gap-4\">\n        {/* Main content */}\n        <div className=\"flex-1 flex flex-col gap-4\">\n          {/* Header section 1 */}\n          <div className=\"bg-bg-primary rounded-2xl p-5 dark:bg-dark-bg-primary\">\n            <SkeletonBlock className=\"w-36 h-4 mb-4\" />\n            <div className=\"grid grid-cols-3 gap-4\">\n              {Array.from({ length: 6 }).map((_, i) => (\n                <div key={i} className=\"flex flex-col gap-1.5\">\n                  <SkeletonBlock className=\"w-16 h-2.5\" />\n                  <SkeletonBlock className=\"h-9 rounded-md\" />\n                </div>\n              ))}\n            </div>\n          </div>\n\n          {/* Header section 2 */}\n          <div className=\"bg-bg-primary rounded-2xl p-5 dark:bg-dark-bg-primary\">\n            <SkeletonBlock className=\"w-44 h-4 mb-4\" />\n            <div className=\"grid grid-cols-3 gap-4\">\n              {Array.from({ length: 3 }).map((_, i) => (\n                <div key={i} className=\"flex flex-col gap-1.5\">\n                  <SkeletonBlock className=\"w-16 h-2.5\" />\n                  <SkeletonBlock className=\"h-9 rounded-md\" />\n                </div>\n              ))}\n            </div>\n          </div>\n\n          {/* Lines section */}\n          <div className=\"bg-bg-primary rounded-2xl overflow-hidden dark:bg-dark-bg-primary\">\n            <div className=\"flex items-center justify-between px-4 py-3 bg-background-secondary dark:bg-dark-bg-secondary\">\n              <SkeletonBlock className=\"w-32 h-4\" />\n              <SkeletonBlock className=\"w-24 h-8 rounded-md\" />\n            </div>\n            <div className=\"flex bg-background-secondary px-3 py-2 gap-4 dark:bg-dark-bg-secondary\">\n              {Array.from({ length: 5 }).map((_, i) => (\n                <SkeletonBlock key={i} className=\"flex-1 h-3\" />\n              ))}\n            </div>\n            {Array.from({ length: 4 }).map((_, i) => (\n              <div key={i} className=\"flex px-3 py-3 gap-4 border-b border-border-secondary dark:border-dark-border-primary\">\n                {Array.from({ length: 5 }).map((_, j) => (\n                  <SkeletonBlock key={j} className=\"flex-1 h-4\" />\n                ))}\n              </div>\n            ))}\n          </div>\n        </div>\n\n        {/* FactBox */}\n        <div className=\"hidden xl:block w-[264px] shrink-0\">\n          <div className=\"bg-background-secondary rounded-2xl p-2 flex flex-col gap-2 dark:bg-dark-bg-secondary\">\n            <div className=\"bg-bg-primary rounded-xl p-3.5 dark:bg-dark-bg-primary\">\n              <SkeletonBlock className=\"w-full h-16 rounded-xl mb-3\" />\n              <div className=\"grid grid-cols-2 gap-2\">\n                {Array.from({ length: 4 }).map((_, i) => (\n                  <SkeletonBlock key={i} className=\"h-6\" />\n                ))}\n              </div>\n            </div>\n            <div className=\"bg-bg-primary rounded-xl p-3.5 dark:bg-dark-bg-primary\">\n              <SkeletonBlock className=\"w-24 h-3 mb-3\" />\n              {Array.from({ length: 3 }).map((_, i) => (\n                <SkeletonBlock key={i} className=\"h-3 mb-2\" />\n              ))}\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n// ─── SkeletonList ──────────────────────────────────────────\n\n/**\n * Esqueleto de carga para la vista de lista de documentos.\n *\n * Replica la estructura visual de DocumentList con bloques animados:\n * encabezado, pills de estado, columnas de tabla y filas de datos.\n *\n * @see MasterDocument.types - SkeletonListProps\n */\nexport function SkeletonList({ rows = 6, className }: SkeletonListProps) {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div\n      className={clsx(\n        'bg-bg-primary rounded-2xl overflow-hidden',\n        'shadow-sm',\n        'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n        className,\n      )}\n      aria-busy=\"true\"\n      aria-label={t('master_document.loading.list')}\n      role=\"status\"\n    >\n      {/* Header */}\n      <div className=\"px-5 pt-5 pb-4\">\n        <div className=\"flex items-start justify-between\">\n          <div>\n            <SkeletonBlock className=\"w-48 h-6 mb-2\" />\n            <SkeletonBlock className=\"w-32 h-3\" />\n          </div>\n          <div className=\"flex items-center gap-2\">\n            <SkeletonBlock className=\"w-24 h-8 rounded-md\" />\n            <SkeletonBlock className=\"w-20 h-8 rounded-md\" />\n          </div>\n        </div>\n      </div>\n\n      {/* Pills */}\n      <div className=\"flex items-center gap-2 px-5 pb-3\">\n        {Array.from({ length: 5 }).map((_, i) => (\n          <SkeletonBlock key={i} className=\"w-20 h-7 rounded-full\" />\n        ))}\n      </div>\n\n      {/* Table header */}\n      <div className=\"flex bg-background-secondary px-4 py-2 gap-4 dark:bg-dark-bg-secondary\">\n        {Array.from({ length: 5 }).map((_, i) => (\n          <SkeletonBlock key={i} className=\"flex-1 h-3\" />\n        ))}\n      </div>\n\n      {/* Rows */}\n      {Array.from({ length: rows }).map((_, i) => (\n        <div key={i} className=\"flex px-4 py-3.5 gap-4 border-b border-border-secondary dark:border-dark-border-primary last:border-0\">\n          {Array.from({ length: 5 }).map((_, j) => (\n            <SkeletonBlock key={j} className=\"flex-1 h-4\" />\n          ))}\n        </div>\n      ))}\n\n      {/* Pagination */}\n      <div className=\"flex items-center justify-between px-5 py-2.5 bg-background-secondary dark:bg-dark-bg-secondary\">\n        <SkeletonBlock className=\"w-32 h-3\" />\n        <div className=\"flex gap-1\">\n          {Array.from({ length: 3 }).map((_, i) => (\n            <SkeletonBlock key={i} className=\"w-7 h-7 rounded-md\" />\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n}\n","/**\n * Estilo canónico de las ACCIONES EN LÍNEA de `MasterDocument`.\n *\n * `MasterCrud` no usa texto subrayado para accionar: todo lo que hace algo es un botón con\n * su caja —borde, radio y fondo—, y el subrayado queda reservado a la navegación. En\n * `MasterDocument` había siete `<button>` pintados como enlaces (`hover:underline`), lo que\n * daba dos afordancias distintas para la misma cosa: «Actualizar», «Descruzar», «Cerrar»,\n * «Cancelar» y «Añadir documento origen» se leían como enlaces y no como acciones.\n *\n * Las medidas salen del canon medido en `/app/items` el 2026-09-04 —radio 6px, 12px/600, el\n * azul de marca #1355b7 sobre #eff8ff y el borde #93d1fd del hover— reducidas a la escala de\n * una micro-acción dentro de un panel (24px de alto en vez de los 36px del toolbar).\n *\n * Un solo sitio para el estilo: si viviera repetido en los siete ficheros, volvería a\n * divergir en el siguiente PR (ADR-027 §Apéndice C, «un solo dueño del estilo»).\n */\n\n/** Caja común: geometría, tipografía y estados. No lleva color. */\nconst BASE =\n  'inline-flex items-center gap-1 px-2 h-6 rounded-md border text-xs font-semibold ' +\n  'transition-colors cursor-pointer select-none ' +\n  'disabled:opacity-50 disabled:cursor-not-allowed ' +\n  'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-400';\n\n/** Acción secundaria: el azul de marca del canon. */\nexport const inlineActionButton = `${BASE} ` +\n  'border-[#93d1fd] bg-[#eff8ff] text-[#1355b7] hover:bg-[#dbeefe] hover:border-[#3c9bf6] ' +\n  'dark:border-primary-800 dark:bg-primary-900/20 dark:text-primary-300 dark:hover:bg-primary-900/40';\n\n/** Acción destructiva o de descarte (descruzar, cancelar una conversión). */\nexport const inlineActionButtonDanger = `${BASE} ` +\n  'border-[#fca5a5] bg-[#fee2e2] text-[#b91c1c] hover:bg-[#fecaca] hover:border-[#f87171] ' +\n  'dark:border-red-800 dark:bg-red-900/20 dark:text-red-400 dark:hover:bg-red-900/40';\n\n/** Acción neutra: cerrar un aviso, cancelar sin consecuencia. */\nexport const inlineActionButtonNeutral = `${BASE} ` +\n  'border-border-primary bg-white text-content-secondary hover:bg-background-secondary ' +\n  'dark:border-dark-border-primary dark:bg-dark-bg-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary';\n","import { useState, useRef, useEffect, useCallback } from 'react';\nimport { clsx } from 'clsx';\nimport type { CrossingSourceSelectorProps, CrossingSourceDocument } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { inlineActionButton, inlineActionButtonNeutral } from './inlineActions';\n\n// ─── Async search input ────────────────────────────────────\n\nfunction AsyncSearchInput({\n  onAdd,\n  onCancel,\n  searchDocuments,\n  alreadySelectedIds = [],\n}: {\n  onAdd: (doc: CrossingSourceDocument) => void;\n  onCancel: () => void;\n  searchDocuments: (query: string) => Promise<CrossingSourceDocument[]>;\n  alreadySelectedIds?: string[];\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const [query, setQuery] = useState('');\n  const [results, setResults] = useState<CrossingSourceDocument[]>([]);\n  const [loading, setLoading] = useState(false);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(() => {\n    inputRef.current?.focus();\n  }, []);\n\n  const search = useCallback(\n    (value: string) => {\n      if (debounceRef.current) clearTimeout(debounceRef.current);\n      if (!value.trim()) {\n        setResults([]);\n        return;\n      }\n      debounceRef.current = setTimeout(async () => {\n        setLoading(true);\n        try {\n          const data = await searchDocuments(value.trim());\n          setResults(data);\n        } finally {\n          setLoading(false);\n        }\n      }, 300);\n    },\n    [searchDocuments],\n  );\n\n  const handleSelect = (doc: CrossingSourceDocument) => {\n    onAdd(doc);\n    setQuery('');\n    setResults([]);\n    inputRef.current?.focus();\n  };\n\n  const visibleResults = results.filter((r) => !alreadySelectedIds.includes(r.id));\n\n  return (\n    <div className=\"relative mt-2\">\n      <div className=\"relative\">\n        <input\n          ref={inputRef}\n          type=\"text\"\n          value={query}\n          onChange={(e) => {\n            setQuery(e.target.value);\n            search(e.target.value);\n          }}\n          onKeyDown={(e) => e.key === 'Escape' && onCancel()}\n          placeholder={t('master_document.crossing.searchPlaceholder')}\n          className={clsx(\n            'w-full px-2 py-1 pr-7 rounded-md text-sm',\n            'border border-border-primary dark:border-dark-border-primary',\n            'bg-bg-primary dark:bg-dark-bg-primary',\n            'text-content-primary dark:text-dark-content-primary',\n            'placeholder:text-content-secondary dark:placeholder:text-dark-content-secondary',\n            'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 dark:focus:ring-dark-border-custom',\n          )}\n        />\n        {loading && (\n          <svg\n            xmlns=\"http://www.w3.org/2000/svg\"\n            viewBox=\"0 0 20 20\"\n            fill=\"currentColor\"\n            aria-hidden=\"true\"\n            className=\"absolute right-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 animate-spin text-content-secondary dark:text-dark-content-secondary\"\n          >\n            <path\n              fillRule=\"evenodd\"\n              d=\"M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.433a.75.75 0 0 0 0-1.5H3.989a.75.75 0 0 0-.75.75v4.242a.75.75 0 0 0 1.5 0v-2.43l.31.31a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm1.23-3.723a.75.75 0 0 0 .219-.53V2.929a.75.75 0 0 0-1.5 0V5.36l-.31-.31A7 7 0 0 0 3.239 8.188a.75.75 0 1 0 1.448.389A5.5 5.5 0 0 1 13.89 6.11l.311.31h-2.432a.75.75 0 0 0 0 1.5h4.243a.75.75 0 0 0 .53-.219Z\"\n              clipRule=\"evenodd\"\n            />\n          </svg>\n        )}\n      </div>\n\n      {visibleResults.length > 0 && (\n        <ul className={clsx(\n          'absolute left-0 right-0 top-full mt-1 z-50 py-1 max-h-48 overflow-auto',\n          'bg-bg-primary dark:bg-dark-bg-primary',\n          'rounded-xl border border-border-primary dark:border-dark-border-primary',\n          'shadow-[0_4px_16px_rgba(0,0,0,.12)] dark:shadow-[0_4px_16px_rgba(0,0,0,.4)]',\n        )}>\n          {visibleResults.map((doc) => (\n            <li key={doc.id}>\n              <button\n                type=\"button\"\n                onMouseDown={(e) => {\n                  e.preventDefault();\n                  handleSelect(doc);\n                }}\n                className={clsx(\n                  'w-full text-left px-3 py-2 transition-colors',\n                  'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                )}\n              >\n                <span className=\"block text-sm text-content-primary dark:text-dark-content-primary font-medium\">\n                  {doc.number}\n                </span>\n                <span className=\"block text-xs text-content-secondary dark:text-dark-content-secondary\">\n                  {doc.classLabel}\n                </span>\n              </button>\n            </li>\n          ))}\n        </ul>\n      )}\n\n      <button\n        type=\"button\"\n        onClick={onCancel}\n        className={clsx(inlineActionButtonNeutral, 'mt-1')}\n      >\n        {t('master_document.chrome.cancel')}\n      </button>\n    </div>\n  );\n}\n\n// ─── CrossingSourceSelector ────────────────────────────────\n\n/**\n * CrossingSourceSelector — muestra y gestiona los documentos fuente (padre)\n * asociados a un documento de cruce.\n *\n * En modo `locked` solo presenta los chips de solo lectura para contexto visual.\n * Cuando se provee `searchDocuments`, usa búsqueda async con debounce.\n */\nexport function CrossingSourceSelector({\n  selectedDocuments,\n  onAdd,\n  onRemove,\n  locked = false,\n  searchDocuments,\n  className,\n}: CrossingSourceSelectorProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [showInput, setShowInput] = useState(false);\n\n  return (\n    <div\n      className={clsx(\n        'bg-bg-primary dark:bg-dark-bg-primary',\n        'border border-border-primary dark:border-dark-border-primary',\n        'rounded-xl p-3',\n        className,\n      )}\n    >\n      <div className=\"flex items-center gap-1.5 mb-2\">\n        {locked && (\n          <svg\n            xmlns=\"http://www.w3.org/2000/svg\"\n            viewBox=\"0 0 16 16\"\n            fill=\"currentColor\"\n            aria-hidden=\"true\"\n            className=\"w-3 h-3 text-content-secondary dark:text-dark-content-secondary flex-shrink-0\"\n          >\n            <path\n              fillRule=\"evenodd\"\n              d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V7A1.5 1.5 0 0 0 3 8.5v4A1.5 1.5 0 0 0 4.5 14h7a1.5 1.5 0 0 0 1.5-1.5v-4A1.5 1.5 0 0 0 11 7V4.5A3.5 3.5 0 0 0 8 1Zm2 6V4.5a2 2 0 1 0-4 0V7h4Z\"\n              clipRule=\"evenodd\"\n            />\n          </svg>\n        )}\n        <span className=\"text-xs font-bold text-content-secondary dark:text-dark-content-secondary uppercase tracking-wide\">\n          {t('master_document.crossing.sourceDocuments')}\n        </span>\n      </div>\n\n      {selectedDocuments.length === 0 && !locked ? (\n        <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary mb-2\">\n          {t('master_document.crossing.selectSourceHint')}\n        </p>\n      ) : (\n        <div className=\"flex flex-wrap gap-1.5 mb-2\">\n          {selectedDocuments.map((doc) => (\n            <span\n              key={doc.id}\n              className={clsx(\n                'inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium',\n                'bg-primary-custom-100 text-primary-custom-700',\n                'dark:bg-dark-bg-custom dark:text-dark-content-custom',\n              )}\n            >\n              {doc.classLabel} · {doc.number}\n              {!locked && (\n                <button\n                  type=\"button\"\n                  onClick={() => onRemove(doc.id)}\n                  aria-label={`Quitar ${doc.classLabel} ${doc.number}`}\n                  className={clsx(\n                    'w-3 h-3 rounded-full flex items-center justify-center flex-shrink-0 transition-colors',\n                    'hover:bg-primary-custom-300 dark:hover:bg-dark-border-custom',\n                  )}\n                >\n                  <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 12 12\" fill=\"currentColor\" aria-hidden=\"true\" className=\"w-2 h-2\">\n                    <path d=\"M6.707 6l2.647-2.646a.5.5 0 1 0-.708-.708L6 5.293 3.354 2.646a.5.5 0 1 0-.708.708L5.293 6 2.646 8.646a.5.5 0 1 0 .708.708L6 6.707l2.646 2.647a.5.5 0 1 0 .708-.708L6.707 6Z\" />\n                  </svg>\n                </button>\n              )}\n            </span>\n          ))}\n        </div>\n      )}\n\n      {!locked && (\n        <>\n          {showInput ? (\n            searchDocuments ? (\n              <AsyncSearchInput\n                onAdd={onAdd}\n                onCancel={() => setShowInput(false)}\n                searchDocuments={searchDocuments}\n                alreadySelectedIds={selectedDocuments.map((d) => d.id)}\n              />\n            ) : (\n              // Fallback sin backend: Enter agrega documento mock\n              <input\n                type=\"text\"\n                autoFocus\n                placeholder={t('master_document.crossing.addPlaceholder')}\n                onKeyDown={(e) => {\n                  if (e.key === 'Escape') { setShowInput(false); return; }\n                  if (e.key === 'Enter') {\n                    const raw = (e.target as HTMLInputElement).value.trim();\n                    if (!raw) return;\n                    onAdd({ id: `mock-${Date.now()}`, number: raw, classLabel: t('master_document.crossing.pending.document') });\n                    setShowInput(false);\n                  }\n                }}\n                onBlur={() => setShowInput(false)}\n                className={clsx(\n                  'w-full mt-2 px-2 py-1 rounded-md text-sm',\n                  'border border-border-primary dark:border-dark-border-primary',\n                  'bg-bg-primary dark:bg-dark-bg-primary',\n                  'text-content-primary dark:text-dark-content-primary',\n                  'placeholder:text-content-secondary dark:placeholder:text-dark-content-secondary',\n                  'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 dark:focus:ring-dark-border-custom',\n                )}\n              />\n            )\n          ) : (\n            <button\n              type=\"button\"\n              onClick={() => setShowInput(true)}\n              className={inlineActionButton}\n            >\n              ＋ {t('master_document.crossing.addSourceDocument')}\n            </button>\n          )}\n        </>\n      )}\n    </div>\n  );\n}\n","import { useState, useEffect } from 'react';\nimport { clsx } from 'clsx';\nimport type { StaleDataBannerProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/**\n * StaleDataBanner — avisa que los estados de cumplimiento pueden estar desactualizados.\n *\n * Verifica cada 5 segundos si han pasado más de `staleThresholdSeconds` desde `fetchedAt`.\n * Renderiza null mientras los datos son recientes para evitar ruido visual.\n */\nexport function StaleDataBanner({\n  fetchedAt,\n  staleThresholdSeconds = 30,\n  onRefresh,\n  isRefreshing = false,\n  className,\n}: StaleDataBannerProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [isStale, setIsStale] = useState(() => {\n    return (Date.now() - new Date(fetchedAt).getTime()) / 1000 > staleThresholdSeconds;\n  });\n\n  useEffect(() => {\n    const check = () => {\n      const ageSeconds = (Date.now() - new Date(fetchedAt).getTime()) / 1000;\n      setIsStale(ageSeconds > staleThresholdSeconds);\n    };\n\n    check();\n    const id = setInterval(check, 5000);\n    return () => clearInterval(id);\n  }, [fetchedAt, staleThresholdSeconds]);\n\n  if (!isStale) return null;\n\n  return (\n    <div\n      role=\"alert\"\n      className={clsx(\n        'flex items-center justify-between gap-3 rounded-lg px-4 py-2.5',\n        'bg-amber-50 border border-amber-200',\n        'dark:bg-amber-950/20 dark:border-amber-800',\n        className,\n      )}\n    >\n      <div className=\"flex items-center gap-2 min-w-0\">\n        {/* Clock icon — inline para evitar dependencia adicional */}\n        <svg\n          xmlns=\"http://www.w3.org/2000/svg\"\n          viewBox=\"0 0 20 20\"\n          fill=\"currentColor\"\n          aria-hidden=\"true\"\n          className=\"w-4 h-4 flex-shrink-0 text-amber-600 dark:text-amber-400\"\n        >\n          <path\n            fillRule=\"evenodd\"\n            d=\"M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm.75-13a.75.75 0 0 0-1.5 0v5c0 .414.336.75.75.75h4a.75.75 0 0 0 0-1.5h-3.25V5Z\"\n            clipRule=\"evenodd\"\n          />\n        </svg>\n        <span className=\"text-sm text-amber-800 dark:text-amber-200 truncate\">\n          {t('master_document.staleData.note')}\n        </span>\n      </div>\n\n      <button\n        type=\"button\"\n        onClick={onRefresh}\n        disabled={isRefreshing}\n        className={clsx(\n          'flex items-center gap-1 text-xs font-semibold flex-shrink-0 transition-colors',\n          'text-amber-700 dark:text-amber-300',\n          'hover:text-amber-900 dark:hover:text-amber-100',\n          isRefreshing && 'opacity-60 cursor-not-allowed',\n        )}\n        aria-label={t('master_document.staleData.refresh')}\n      >\n        {isRefreshing ? (\n          <svg\n            xmlns=\"http://www.w3.org/2000/svg\"\n            viewBox=\"0 0 20 20\"\n            fill=\"currentColor\"\n            aria-hidden=\"true\"\n            className=\"w-3.5 h-3.5 animate-spin\"\n          >\n            <path\n              fillRule=\"evenodd\"\n              d=\"M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.433a.75.75 0 0 0 0-1.5H3.989a.75.75 0 0 0-.75.75v4.242a.75.75 0 0 0 1.5 0v-2.43l.31.31a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm1.23-3.723a.75.75 0 0 0 .219-.53V2.929a.75.75 0 0 0-1.5 0V5.36l-.31-.31A7 7 0 0 0 3.239 8.188a.75.75 0 1 0 1.448.389A5.5 5.5 0 0 1 13.89 6.11l.311.31h-2.432a.75.75 0 0 0 0 1.5h4.243a.75.75 0 0 0 .53-.219Z\"\n              clipRule=\"evenodd\"\n            />\n          </svg>\n        ) : (\n          <svg\n            xmlns=\"http://www.w3.org/2000/svg\"\n            viewBox=\"0 0 20 20\"\n            fill=\"currentColor\"\n            aria-hidden=\"true\"\n            className=\"w-3.5 h-3.5\"\n          >\n            <path\n              fillRule=\"evenodd\"\n              d=\"M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.433a.75.75 0 0 0 0-1.5H3.989a.75.75 0 0 0-.75.75v4.242a.75.75 0 0 0 1.5 0v-2.43l.31.31a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm1.23-3.723a.75.75 0 0 0 .219-.53V2.929a.75.75 0 0 0-1.5 0V5.36l-.31-.31A7 7 0 0 0 3.239 8.188a.75.75 0 1 0 1.448.389A5.5 5.5 0 0 1 13.89 6.11l.311.31h-2.432a.75.75 0 0 0 0 1.5h4.243a.75.75 0 0 0 .53-.219Z\"\n              clipRule=\"evenodd\"\n            />\n          </svg>\n        )}\n        {t('master_document.chrome.refresh')}\n      </button>\n    </div>\n  );\n}\n","import { useState, useRef, useEffect } from 'react';\nimport { clsx } from 'clsx';\nimport { ChevronDownIcon } from '@heroicons/react/24/outline';\nimport type { CrossingClassMenuProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/**\n * CrossingClassMenu — desplegable para seleccionar la clase de documento hijo\n * al generar un cruce desde el documento actual.\n */\nexport function CrossingClassMenu({\n  options,\n  onSelect,\n  disabled = false,\n  className,\n}: CrossingClassMenuProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [open, setOpen] = useState(false);\n  const containerRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    if (!open) return;\n\n    const handleClickOutside = (e: MouseEvent) => {\n      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {\n        setOpen(false);\n      }\n    };\n\n    document.addEventListener('mousedown', handleClickOutside);\n    return () => document.removeEventListener('mousedown', handleClickOutside);\n  }, [open]);\n\n  const handleSelect = (id: string) => {\n    setOpen(false);\n    onSelect(id);\n  };\n\n  return (\n    <div ref={containerRef} className={clsx('relative inline-block', className)}>\n      <button\n        type=\"button\"\n        disabled={disabled}\n        onClick={() => !disabled && setOpen((v) => !v)}\n        aria-haspopup=\"listbox\"\n        aria-expanded={open}\n        className={clsx(\n          'flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-colors',\n          'bg-primary-inverse-background text-primary-inverse-content hover:bg-primary-custom-700',\n          'dark:bg-dark-bg-inverse dark:text-dark-content-inverse',\n          disabled && 'opacity-50 cursor-not-allowed',\n        )}\n      >\n        {t('master_document.crossing.generateDocument')}\n        <ChevronDownIcon\n          className={clsx('w-3.5 h-3.5 transition-transform duration-150', open && 'rotate-180')}\n          aria-hidden=\"true\"\n        />\n      </button>\n\n      {open && (\n        <ul\n          role=\"listbox\"\n          className={clsx(\n            'absolute right-0 mt-1 z-50 min-w-[200px] py-1',\n            'bg-bg-primary dark:bg-dark-bg-primary',\n            'rounded-xl border border-border-primary dark:border-dark-border-primary',\n            'shadow-[0_4px_16px_rgba(0,0,0,.12)] dark:shadow-[0_4px_16px_rgba(0,0,0,.4)]',\n          )}\n        >\n          {options.map((option) => (\n            <li key={option.id} role=\"option\" aria-selected={false}>\n              <button\n                type=\"button\"\n                onClick={() => handleSelect(option.id)}\n                className={clsx(\n                  'w-full text-left px-3 py-2 text-sm transition-colors',\n                  'text-content-primary dark:text-dark-content-primary',\n                  'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                )}\n              >\n                <span className=\"block\">{option.label}</span>\n                {option.description && (\n                  <span className=\"block text-xs text-content-secondary dark:text-dark-content-secondary mt-0.5\">\n                    {option.description}\n                  </span>\n                )}\n              </button>\n            </li>\n          ))}\n        </ul>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport type { LineFulfillmentStatus, PendingLinesPanelProps } from './MasterDocument.types';\nimport { LineFulfillmentBadge } from './LineFulfillmentBadge';\nimport { Loading } from './components/loading';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/**\n * PendingLinesPanel — panel de selección de líneas pendientes de los documentos\n * ORIGEN para el cruce (FE-02 de FEAT-094).\n *\n * Por cada línea muestra item, documento, cantidades (ordenada/cumplida/pendiente)\n * y su badge de estado (renderiza el `lineStatus` autoritativo del backend, no lo\n * recalcula). Las líneas seleccionadas habilitan el campo \"Cantidad a cruzar\"\n * editable con validación inline. Las líneas terminales (`Fulfilled`/`Closed`)\n * aparecen en gris y deshabilitadas.\n */\n\nfunction isTerminalStatus(status: LineFulfillmentStatus): boolean {\n  return status === 'Fulfilled' || status === 'Closed';\n}\n\nconst HEADER_CLASS =\n  'px-3 py-2 text-xs font-bold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary';\nconst CELL_CLASS = 'px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary align-top';\n\nexport function PendingLinesPanel({\n  lines,\n  selectedLineIds,\n  quantities,\n  errors,\n  loading,\n  onLineSelect,\n  onTrySelectTerminalLine,\n  onQuantityChange,\n  formatNumber,\n  className,\n}: PendingLinesPanelProps) {\n  const { t } = useMasterDocumentTranslation();\n  const fmt = (value: number | undefined): string => {\n    if (value == null) return '—';\n    return formatNumber ? formatNumber(value) : String(value);\n  };\n\n  if (loading) {\n    return (\n      <Loading\n        size=\"md\"\n        label={t('master_document.createFromSource.loadingLines')}\n        className={className}\n      />\n    );\n  }\n\n  if (lines.length === 0) {\n    return (\n      <div\n        className={clsx(\n          'py-8 px-4 text-center text-sm text-content-secondary dark:text-dark-content-secondary',\n          'border border-dashed border-border-primary dark:border-dark-border-primary rounded-lg',\n          className,\n        )}\n      >\n        {t('master_document.crossing.noPendingLinesAll')}\n      </div>\n    );\n  }\n\n  return (\n    <div className={clsx('overflow-x-auto', className)}>\n      <table className=\"w-full border-collapse\">\n        <thead>\n          <tr className=\"border-b border-border-primary dark:border-dark-border-primary\">\n            <th className={clsx(HEADER_CLASS, 'w-11')} aria-label={t('master_document.crossing.selectRow')} />\n            <th className={clsx(HEADER_CLASS, 'text-left')}>{t('master_document.crossing.pending.item')}</th>\n            <th className={clsx(HEADER_CLASS, 'text-left')}>{t('master_document.crossing.pending.document')}</th>\n            <th className={clsx(HEADER_CLASS, 'text-right')}>{t('master_document.crossing.pending.pending')}</th>\n            <th className={clsx(HEADER_CLASS, 'text-left')}>{t('master_document.crossing.pending.state')}</th>\n            <th className={clsx(HEADER_CLASS, 'text-left')}>{t('master_document.crossing.pending.quantityToCross')}</th>\n          </tr>\n        </thead>\n        <tbody>\n          {lines.map((line) => {\n            const terminal = isTerminalStatus(line.lineStatus);\n            const isSelected = selectedLineIds.includes(line.lineId);\n            const error = errors?.[line.lineId];\n            const qty = quantities[line.lineId];\n\n            return (\n              <tr\n                key={line.lineId}\n                className={clsx(\n                  'border-b border-border-primary/60 dark:border-dark-border-primary/60',\n                  terminal && 'opacity-50',\n                )}\n              >\n                <td className={clsx(CELL_CLASS, 'text-center')}>\n                  <input\n                    type=\"checkbox\"\n                    checked={isSelected}\n                    disabled={terminal}\n                    onChange={(e) => {\n                      if (terminal) {\n                        onTrySelectTerminalLine?.(line.lineId);\n                        return;\n                      }\n                      onLineSelect(line.lineId, e.target.checked);\n                    }}\n                    className={clsx(\n                      'w-4 h-4 rounded border-border-primary accent-primary-custom-600',\n                      'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                      'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                      terminal && 'cursor-not-allowed',\n                    )}\n                    aria-label={t('master_document.crossing.pending.selectLineAria', {\n                      item: line.itemCode ?? line.lineId,\n                    })}\n                  />\n                </td>\n\n                <td className={CELL_CLASS}>\n                  <div className=\"font-medium\">{line.itemCode ?? '—'}</div>\n                  {line.itemDescription && (\n                    <div className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">\n                      {line.itemDescription}\n                    </div>\n                  )}\n                </td>\n\n                <td className={clsx(CELL_CLASS, 'whitespace-nowrap')}>\n                  {line.documentNumber ?? '—'}\n                </td>\n\n                <td className={clsx(CELL_CLASS, 'text-right whitespace-nowrap tabular-nums')}>\n                  {fmt(line.quantityPending)}\n                  {line.unitOfMeasure ? ` ${line.unitOfMeasure}` : ''}\n                </td>\n\n                <td className={CELL_CLASS}>\n                  <LineFulfillmentBadge status={line.lineStatus} />\n                </td>\n\n                <td className={CELL_CLASS}>\n                  <input\n                    type=\"number\"\n                    inputMode=\"decimal\"\n                    min={0}\n                    max={line.quantityPending}\n                    value={isSelected && qty != null ? qty : ''}\n                    disabled={terminal || !isSelected}\n                    onChange={(e) => {\n                      const raw = e.target.value;\n                      onQuantityChange(line.lineId, raw === '' ? NaN : Number(raw));\n                    }}\n                    placeholder={isSelected ? fmt(line.quantityPending) : ''}\n                    aria-label={t('master_document.crossing.pending.quantityAria', {\n                      item: line.itemCode ?? line.lineId,\n                    })}\n                    aria-invalid={error ? true : undefined}\n                    className={clsx(\n                      'w-28 px-2 py-1 rounded-md text-sm tabular-nums',\n                      'border bg-bg-primary dark:bg-dark-bg-primary',\n                      'text-content-primary dark:text-dark-content-primary',\n                      'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 dark:focus:ring-dark-border-custom',\n                      error\n                        ? 'border-red-500 dark:border-red-400'\n                        : 'border-border-primary dark:border-dark-border-primary',\n                      (terminal || !isSelected) && 'opacity-50 cursor-not-allowed',\n                    )}\n                  />\n                  {error && (\n                    <p className=\"mt-1 text-xs text-red-600 dark:text-red-400\">{error}</p>\n                  )}\n                </td>\n              </tr>\n            );\n          })}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport type { DocumentTraceabilityTreeProps, TraceabilityTreeNode } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\ninterface DisplayNode {\n  node: TraceabilityTreeNode;\n  depth: number;\n  isLastSibling: boolean;\n  connectorPath: boolean[];\n}\n\nfunction buildDisplayList(root: TraceabilityTreeNode): DisplayNode[] {\n  const result: DisplayNode[] = [];\n\n  function walkAncestors(node: TraceabilityTreeNode, depth: number, connectorPath: boolean[]): void {\n    for (const parent of node.parents) {\n      walkAncestors(parent, depth, connectorPath);\n    }\n    result.push({ node, depth, isLastSibling: true, connectorPath });\n  }\n\n  function walkDescendants(\n    nodes: TraceabilityTreeNode[],\n    depth: number,\n    connectorPath: boolean[],\n  ): void {\n    nodes.forEach((node, index) => {\n      const isLast = index === nodes.length - 1;\n      const path = [...connectorPath, !isLast];\n      result.push({ node, depth, isLastSibling: isLast, connectorPath: path });\n      if (node.children.length > 0) {\n        walkDescendants(node.children, depth + 1, path);\n      }\n    });\n  }\n\n  for (const parent of root.parents) {\n    walkAncestors(parent, 0, []);\n  }\n\n  result.push({ node: root, depth: root.parents.length > 0 ? 1 : 0, isLastSibling: true, connectorPath: [] });\n\n  if (root.children.length > 0) {\n    const rootDepth = root.parents.length > 0 ? 1 : 0;\n    walkDescendants(root.children, rootDepth + 1, []);\n  }\n\n  return result;\n}\n\nfunction SmallDocIcon({ className }: { className?: string }) {\n  return (\n    <svg\n      width=\"14\"\n      height=\"14\"\n      viewBox=\"0 0 14 14\"\n      fill=\"none\"\n      xmlns=\"http://www.w3.org/2000/svg\"\n      className={className}\n      aria-hidden=\"true\"\n    >\n      <path\n        d=\"M3 1.75C3 1.336 3.336 1 3.75 1H8.25L11 3.75V12.25C11 12.664 10.664 13 10.25 13H3.75C3.336 13 3 12.664 3 12.25V1.75Z\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.2\"\n        strokeLinejoin=\"round\"\n      />\n      <path\n        d=\"M8 1V4H11\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.2\"\n        strokeLinejoin=\"round\"\n      />\n      <path d=\"M5 7H9M5 9.5H8\" stroke=\"currentColor\" strokeWidth=\"1.2\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nfunction ExclamationIcon() {\n  return (\n    <svg\n      width=\"32\"\n      height=\"32\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      xmlns=\"http://www.w3.org/2000/svg\"\n      aria-hidden=\"true\"\n      className=\"text-red-400\"\n    >\n      <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path d=\"M12 7v5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n      <circle cx=\"12\" cy=\"16\" r=\"0.75\" fill=\"currentColor\" />\n    </svg>\n  );\n}\n\nfunction DocLinkIcon() {\n  return (\n    <svg\n      width=\"32\"\n      height=\"32\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      xmlns=\"http://www.w3.org/2000/svg\"\n      aria-hidden=\"true\"\n      className=\"text-content-tertiary dark:text-dark-content-tertiary\"\n    >\n      <path\n        d=\"M9 12h6M9 8h4M5 3h10l4 4v14a1 1 0 01-1 1H5a1 1 0 01-1-1V4a1 1 0 011-1z\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinejoin=\"round\"\n      />\n      <path\n        d=\"M13.5 17a2 2 0 104 0 2 2 0 00-4 0zM17.5 17h1.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n      />\n    </svg>\n  );\n}\n\nfunction LoadingSkeleton() {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div className=\"space-y-2 p-4\" aria-busy=\"true\" aria-label={t('master_document.crossing.traceabilityLoading')}>\n      <div className=\"flex items-center gap-2\">\n        <div className=\"animate-pulse w-full h-8 bg-background-secondary dark:bg-dark-bg-secondary rounded-lg\" />\n      </div>\n      <div className=\"flex items-center gap-2 pl-5\">\n        <div className=\"animate-pulse flex-1 h-8 bg-background-secondary dark:bg-dark-bg-secondary rounded-lg\" />\n      </div>\n      <div className=\"flex items-center gap-2 pl-10\">\n        <div className=\"animate-pulse flex-1 h-8 bg-background-secondary dark:bg-dark-bg-secondary rounded-lg\" style={{ width: 'calc(100% - 2.5rem)' }} />\n      </div>\n    </div>\n  );\n}\n\nfunction ErrorState({ error, onRetry }: { error: string; onRetry?: () => void }) {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div className=\"flex flex-col items-center justify-center gap-3 py-8 px-4\">\n      <ExclamationIcon />\n      <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary text-center\">\n        {error}\n      </p>\n      {onRetry && (\n        <button\n          type=\"button\"\n          onClick={onRetry}\n          className={clsx(\n            'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md',\n            'text-sm font-semibold',\n            'bg-primary-custom-600 text-white',\n            'hover:bg-primary-custom-500',\n            'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n            'dark:bg-dark-bg-inverse dark:text-dark-content-inverse',\n            'dark:hover:bg-dark-bg-inverse/90',\n            'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            'transition-colors duration-150',\n          )}\n        >\n          {t('master_document.chrome.retry')}\n        </button>\n      )}\n    </div>\n  );\n}\n\nfunction EmptyState() {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div className=\"flex flex-col items-center justify-center gap-3 py-8 px-4\">\n      <DocLinkIcon />\n      <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary text-center\">\n        {t('master_document.crossing.noRelations')}\n      </p>\n    </div>\n  );\n}\n\nfunction ConnectorBlock({\n  drawVertical,\n  drawElbow,\n}: {\n  drawVertical: boolean;\n  drawElbow: boolean;\n}) {\n  return (\n    <div className=\"w-5 h-10 flex-shrink-0 relative\">\n      {drawVertical && !drawElbow && (\n        <div className=\"absolute left-2 top-0 bottom-0 border-l-2 border-border-primary dark:border-dark-border-primary\" />\n      )}\n      {drawElbow && (\n        <>\n          <div className=\"absolute left-2 top-0 h-5 border-l-2 border-border-primary dark:border-dark-border-primary\" />\n          <div className=\"absolute left-2 top-5 w-2.5 border-b-2 border-border-primary dark:border-dark-border-primary\" />\n        </>\n      )}\n    </div>\n  );\n}\n\nfunction TreeNodeRow({\n  displayNode,\n  onNodeClick,\n}: {\n  displayNode: DisplayNode;\n  onNodeClick?: (nodeId: string) => void;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const { node, depth, connectorPath } = displayNode;\n\n  const pct =\n    node.quantityOrdered && node.quantityOrdered > 0\n      ? Math.min(100, ((node.quantityFulfilled ?? 0) / node.quantityOrdered) * 100)\n      : 0;\n\n  const isClickable = !!onNodeClick && !node.isCurrent;\n\n  return (\n    <div className=\"flex items-start gap-0\">\n      {Array.from({ length: depth }).map((_, level) => {\n        const isLastLevel = level === depth - 1;\n        if (isLastLevel) {\n          return (\n            <ConnectorBlock key={level} drawVertical={false} drawElbow={true} />\n          );\n        }\n        const shouldContinue = connectorPath[level] ?? false;\n        return (\n          <ConnectorBlock key={level} drawVertical={shouldContinue} drawElbow={false} />\n        );\n      })}\n\n      <div\n        role={isClickable ? 'button' : undefined}\n        tabIndex={isClickable ? 0 : undefined}\n        onClick={isClickable ? () => onNodeClick!(node.id) : undefined}\n        onKeyDown={\n          isClickable\n            ? (e) => {\n                if (e.key === 'Enter' || e.key === ' ') {\n                  e.preventDefault();\n                  onNodeClick!(node.id);\n                }\n              }\n            : undefined\n        }\n        aria-current={node.isCurrent ? 'true' : undefined}\n        className={clsx(\n          'flex-1 flex items-center gap-2 py-1.5 px-2 rounded-lg transition-colors min-w-0',\n          node.isCurrent && [\n            'bg-primary-custom-100 dark:bg-dark-bg-custom',\n            'ring-1 ring-primary-custom-300 dark:ring-dark-border-custom',\n          ],\n          isClickable && 'cursor-pointer hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n        )}\n      >\n        <SmallDocIcon className=\"flex-shrink-0 text-content-secondary dark:text-dark-content-secondary\" />\n\n        <span className=\"text-xs font-medium text-content-secondary dark:text-dark-content-secondary flex-shrink-0\">\n          {node.classLabel}\n        </span>\n\n        <span className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary flex-shrink-0\">\n          {node.number}\n        </span>\n\n        <span className=\"inline-flex items-center px-1.5 py-0.5 rounded-md text-xs font-medium bg-zinc-100 text-zinc-600 flex-shrink-0\">\n          {node.status}\n        </span>\n\n        {node.quantityOrdered !== undefined && node.quantityFulfilled !== undefined && (\n          <span className=\"flex items-center gap-1.5 flex-shrink-0\">\n            <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary tabular-nums\">\n              {node.quantityFulfilled} / {node.quantityOrdered}\n            </span>\n            <span className=\"w-16 h-1 rounded-full bg-border-primary dark:bg-dark-border-primary overflow-hidden flex-shrink-0\">\n              <span\n                className=\"block h-full bg-primary-custom-500 rounded-full\"\n                style={{ width: `${pct}%` }}\n              />\n            </span>\n          </span>\n        )}\n\n        {node.isCurrent && (\n          <span className=\"text-[10px] font-bold uppercase tracking-widest text-primary-custom-600 dark:text-dark-content-custom flex-shrink-0\">\n            {t('master_document.crossing.current')}\n          </span>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * DocumentTraceabilityTree — muestra el árbol de trazabilidad de un documento,\n * incluyendo ancestros (padres) y descendientes (hijos) conectados con líneas visuales.\n *\n * @see docs/colors.md — Tokens de color del sistema\n * @see docs/dark-mode-guide.md — Estrategia de dark mode\n *\n * @example\n * ```tsx\n * <DocumentTraceabilityTree\n *   tree={treeData}\n *   onNodeClick={(id) => navigate(`/documents/${id}`)}\n * />\n * ```\n */\nexport function DocumentTraceabilityTree({\n  tree,\n  onNodeClick,\n  loading = false,\n  error,\n  onRetry,\n  className,\n}: DocumentTraceabilityTreeProps) {\n  const { t } = useMasterDocumentTranslation();\n  const isEmpty =\n    !loading &&\n    !error &&\n    (tree === null || (tree.parents.length === 0 && tree.children.length === 0 && !tree.isCurrent));\n\n  return (\n    <div\n      className={clsx(\n        'bg-bg-primary rounded-xl overflow-hidden',\n        'shadow-[0_1px_3px_rgba(60,64,67,.15),0_1px_2px_rgba(60,64,67,.10)]',\n        'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n        className,\n      )}\n    >\n      <div className=\"flex items-center px-4 py-3 bg-background-secondary dark:bg-dark-bg-secondary\">\n        <h3 className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n          {t('master_document.document.traceability')}\n        </h3>\n      </div>\n\n      <div className=\"p-4\">\n        {loading && <LoadingSkeleton />}\n\n        {!loading && error && <ErrorState error={error} onRetry={onRetry} />}\n\n        {!loading && !error && isEmpty && <EmptyState />}\n\n        {!loading && !error && !isEmpty && tree !== null && (\n          <div className=\"space-y-0.5\">\n            {buildDisplayList(tree).map((dn) => (\n              <TreeNodeRow key={dn.node.id} displayNode={dn} onNodeClick={onNodeClick} />\n            ))}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n","import { useEffect, useState } from 'react';\nimport { clsx } from 'clsx';\nimport { ExclamationTriangleIcon, ArrowPathIcon, XMarkIcon } from '@heroicons/react/24/outline';\nimport type { LineCloseModalProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/**\n * LineCloseModal — confirma el cierre o reapertura de una línea de documento.\n *\n * En modo 'close' solicita una razón de cierre (textarea obligatorio).\n * En modo 'reopen' muestra solo un mensaje de confirmación.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - LineCloseModalProps\n *\n * @example\n * ```tsx\n * <LineCloseModal\n *   open={isOpen}\n *   mode=\"close\"\n *   lineDescription=\"Producto A — 100 unidades\"\n *   onClose={() => setOpen(false)}\n *   onConfirm={(reason) => closeLine(lineId, reason)}\n * />\n * ```\n */\nexport function LineCloseModal({\n  open,\n  onClose,\n  onConfirm,\n  mode,\n  lineDescription,\n  isLoading = false,\n  error,\n  className,\n}: LineCloseModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [closeReason, setCloseReason] = useState('');\n\n  useEffect(() => {\n    if (!open) {\n      setCloseReason('');\n    }\n  }, [open]);\n\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  if (!open) return null;\n\n  const isCloseMode = mode === 'close';\n  const confirmDisabled = isLoading || (isCloseMode && closeReason.trim() === '');\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[440px]',\n          'bg-bg-primary rounded-2xl px-6 py-5',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          className,\n        )}\n        role=\"alertdialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"line-close-modal-title\"\n        aria-describedby={isCloseMode ? 'line-close-modal-desc' : 'line-close-modal-reopen-desc'}\n      >\n        {/* Close button */}\n        <button\n          type=\"button\"\n          onClick={onClose}\n          className=\"absolute top-4 right-4 p-1 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n          aria-label={t('master_document.chrome.close')}\n        >\n          <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n        </button>\n\n        {/* Icon */}\n        <div\n          className={clsx(\n            'flex items-center justify-center w-12 h-12 rounded-full mb-4',\n            isCloseMode\n              ? 'bg-amber-50 dark:bg-amber-700/15'\n              : 'bg-primary-custom-100 dark:bg-primary-custom-900/20',\n          )}\n        >\n          {isCloseMode ? (\n            <ExclamationTriangleIcon\n              className=\"w-6 h-6 text-amber-700 dark:text-amber-400\"\n              aria-hidden=\"true\"\n            />\n          ) : (\n            <ArrowPathIcon\n              className=\"w-6 h-6 text-primary-custom-600 dark:text-primary-custom-400\"\n              aria-hidden=\"true\"\n            />\n          )}\n        </div>\n\n        {/* Title */}\n        <h2\n          id=\"line-close-modal-title\"\n          className=\"text-base font-bold text-content-primary dark:text-dark-content-primary mb-1\"\n        >\n          {isCloseMode ? t('master_document.lines.closeLine') : t('master_document.lines.reopenLine')}\n        </h2>\n\n        {/* Line description */}\n        {lineDescription && (\n          <p\n            id=\"line-close-modal-desc\"\n            className=\"text-sm text-content-tertiary dark:text-dark-content-secondary mb-4\"\n          >\n            {lineDescription}\n          </p>\n        )}\n\n        {/* Body */}\n        {isCloseMode ? (\n          <div className=\"mb-4\">\n            <label\n              htmlFor=\"close-reason\"\n              className=\"block text-sm font-semibold text-content-primary dark:text-dark-content-primary mb-1.5\"\n            >\n              {t('master_document.lines.closeReason')}{' '}\n              <span className=\"text-red-600 dark:text-red-400\" aria-hidden=\"true\">\n                *\n              </span>\n            </label>\n            <textarea\n              id=\"close-reason\"\n              rows={3}\n              value={closeReason}\n              onChange={(e) => setCloseReason(e.target.value)}\n              placeholder={t('master_document.lines.closeReasonPlaceholder')}\n              className={clsx(\n                'w-full resize-none rounded-lg px-3 py-2 text-sm',\n                'border border-border-primary bg-bg-primary text-content-primary',\n                'placeholder:text-content-tertiary',\n                'transition-colors duration-150',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                'dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary',\n                'dark:placeholder:text-dark-content-secondary',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              )}\n            />\n          </div>\n        ) : (\n          <p\n            id=\"line-close-modal-reopen-desc\"\n            className=\"text-sm text-content-tertiary dark:text-dark-content-secondary mb-4\"\n          >\n            {t('master_document.lines.reopenConfirm')}\n          </p>\n        )}\n\n        {/* Error banner */}\n        {error && (\n          <div\n            className={clsx(\n              'bg-red-50 border border-red-200 rounded-lg px-3 py-2',\n              'text-sm text-red-700 mb-3',\n              'dark:bg-red-950/20 dark:border-red-800 dark:text-red-300',\n            )}\n            role=\"alert\"\n          >\n            {error}\n          </div>\n        )}\n\n        {/* Actions */}\n        <div className=\"flex items-center justify-end gap-3\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            disabled={isLoading}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n              isLoading && 'opacity-50 cursor-not-allowed',\n            )}\n          >\n            {t('master_document.chrome.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={() => onConfirm(isCloseMode ? closeReason : undefined)}\n            disabled={confirmDisabled}\n            className={clsx(\n              'flex items-center gap-2 px-5 py-2 rounded-md text-sm font-semibold transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              isCloseMode\n                ? 'bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600'\n                : 'bg-primary-inverse-background text-white hover:bg-primary-custom-700 dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              confirmDisabled && 'opacity-50 cursor-not-allowed',\n            )}\n          >\n            {isLoading && (\n              <svg\n                xmlns=\"http://www.w3.org/2000/svg\"\n                viewBox=\"0 0 20 20\"\n                fill=\"currentColor\"\n                aria-hidden=\"true\"\n                className=\"w-4 h-4 animate-spin\"\n              >\n                <path\n                  fillRule=\"evenodd\"\n                  d=\"M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.433a.75.75 0 0 0 0-1.5H3.989a.75.75 0 0 0-.75.75v4.242a.75.75 0 0 0 1.5 0v-2.43l.31.31a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm1.23-3.723a.75.75 0 0 0 .219-.53V2.929a.75.75 0 0 0-1.5 0V5.36l-.31-.31A7 7 0 0 0 3.239 8.188a.75.75 0 1 0 1.448.389A5.5 5.5 0 0 1 13.89 6.11l.311.31h-2.432a.75.75 0 0 0 0 1.5h4.243a.75.75 0 0 0 .53-.219Z\"\n                  clipRule=\"evenodd\"\n                />\n              </svg>\n            )}\n            {isCloseMode ? t('master_document.lines.closeLine') : t('master_document.lines.reopenLine')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { useEffect, useState } from 'react';\nimport { clsx } from 'clsx';\nimport { XMarkIcon } from '@heroicons/react/24/outline';\nimport type { CrossingGenerateField } from './template/MasterDocumentTemplate.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\nexport interface CrossingGenerateModalProps {\n  open: boolean;\n  classLabel: string;\n  fields: CrossingGenerateField[];\n  onConfirm: (headerValues: Record<string, unknown>) => void;\n  onCancel: () => void;\n  isLoading?: boolean;\n  error?: string;\n}\n\nexport function CrossingGenerateModal({\n  open,\n  classLabel,\n  fields,\n  onConfirm,\n  onCancel,\n  isLoading = false,\n  error,\n}: CrossingGenerateModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [values, setValues] = useState<Record<string, string>>({});\n\n  useEffect(() => {\n    if (!open) {\n      setValues({});\n    }\n  }, [open]);\n\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onCancel();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onCancel]);\n\n  if (!open) return null;\n\n  const hasFields = fields.length > 0;\n\n  const confirmDisabled =\n    isLoading ||\n    fields.some((f) => f.required && !String(values[f.key] ?? '').trim());\n\n  function handleConfirm() {\n    const headerValues: Record<string, unknown> = {};\n    for (const f of fields) {\n      headerValues[f.key] = values[f.key] ?? '';\n    }\n    onConfirm(headerValues);\n  }\n\n  return (\n    <>\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n      />\n\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[440px]',\n          'bg-bg-primary rounded-2xl px-6 py-5',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"crossing-generate-modal-title\"\n      >\n        <button\n          type=\"button\"\n          onClick={onCancel}\n          className=\"absolute top-4 right-4 p-1 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n          aria-label={t('master_document.chrome.close')}\n        >\n          <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n        </button>\n\n        <h2\n          id=\"crossing-generate-modal-title\"\n          className=\"text-base font-bold text-content-primary dark:text-dark-content-primary mb-4 pr-6\"\n        >\n          {t('master_document.crossing.generateTitle', { class: classLabel })}\n        </h2>\n\n        {!hasFields && (\n          <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary mb-4\">\n            {t('master_document.crossing.generateQuestion', { class: classLabel })}\n          </p>\n        )}\n\n        {hasFields && (\n          <div className=\"flex flex-col gap-3 mb-4\">\n            {fields.map((field) => (\n              <div key={field.key}>\n                <label\n                  htmlFor={`cgm-field-${field.key}`}\n                  className=\"block text-sm font-semibold text-content-primary dark:text-dark-content-primary mb-1\"\n                >\n                  {field.label}\n                  {field.required && (\n                    <span className=\"ml-0.5 text-red-600 dark:text-red-400\" aria-hidden=\"true\">\n                      {' '}*\n                    </span>\n                  )}\n                </label>\n                <input\n                  id={`cgm-field-${field.key}`}\n                  type={field.type}\n                  required={field.required}\n                  value={values[field.key] ?? ''}\n                  onChange={(e) =>\n                    setValues((prev) => ({ ...prev, [field.key]: e.target.value }))\n                  }\n                  className={clsx(\n                    'w-full rounded-lg px-3 py-2 text-sm',\n                    'border border-border-primary bg-bg-primary text-content-primary',\n                    'placeholder:text-content-tertiary',\n                    'transition-colors duration-150',\n                    'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                    'dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary',\n                    'dark:placeholder:text-dark-content-secondary',\n                    'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                  )}\n                />\n              </div>\n            ))}\n          </div>\n        )}\n\n        {error && (\n          <div\n            className={clsx(\n              'bg-red-50 border border-red-200 rounded-lg px-3 py-2',\n              'text-sm text-red-700 mb-3',\n              'dark:bg-red-950/20 dark:border-red-800 dark:text-red-300',\n            )}\n            role=\"alert\"\n          >\n            {error}\n          </div>\n        )}\n\n        <div className=\"flex items-center justify-end gap-3\">\n          <button\n            type=\"button\"\n            onClick={onCancel}\n            disabled={isLoading}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n              isLoading && 'opacity-50 cursor-not-allowed',\n            )}\n          >\n            {t('master_document.chrome.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={handleConfirm}\n            disabled={confirmDisabled}\n            className={clsx(\n              'flex items-center gap-2 px-5 py-2 rounded-md text-sm font-semibold transition-all duration-150',\n              'bg-primary-inverse-background text-white hover:bg-primary-custom-700',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              confirmDisabled && 'opacity-50 cursor-not-allowed',\n            )}\n          >\n            {isLoading && (\n              <svg\n                xmlns=\"http://www.w3.org/2000/svg\"\n                viewBox=\"0 0 20 20\"\n                fill=\"currentColor\"\n                aria-hidden=\"true\"\n                className=\"w-4 h-4 animate-spin\"\n              >\n                <path\n                  fillRule=\"evenodd\"\n                  d=\"M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.433a.75.75 0 0 0 0-1.5H3.989a.75.75 0 0 0-.75.75v4.242a.75.75 0 0 0 1.5 0v-2.43l.31.31a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm1.23-3.723a.75.75 0 0 0 .219-.53V2.929a.75.75 0 0 0-1.5 0V5.36l-.31-.31A7 7 0 0 0 3.239 8.188a.75.75 0 1 0 1.448.389A5.5 5.5 0 0 1 13.89 6.11l.311.31h-2.432a.75.75 0 0 0 0 1.5h4.243a.75.75 0 0 0 .53-.219Z\"\n                  clipRule=\"evenodd\"\n                />\n              </svg>\n            )}\n            {t('master_document.chrome.confirm')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { useMasterDocumentTranslation } from './i18n';\nimport { CanonTabsBar } from './CanonTabsBar';\nimport type { LineTabsBarProps } from './MasterDocument.types';\n\n/**\n * Barra de pestañas del área de detalle.\n *\n * Delega TODO el aspecto y el teclado en {@link CanonTabsBar}, que es el único dueño del\n * estilo de pestañas de `MasterDocument`.\n *\n * **Cambio de aspecto deliberado (2026-09-04).** Hasta aquí esta barra pintaba chips\n * `rounded-md` con `bg-primary-custom-100`, heredados de la tira de dos botones que\n * `MasterDocument` traía quemada para el cruce, y `HeaderRenderer` pintaba un tercer diseño\n * con subrayado. Ninguno de los dos era el canon de MasterCrud (ADR-027 §C.2), así que un\n * usuario que pasaba de un maestro a un documento veía tres barras de pestañas distintas.\n * Ahora las dos salen del mismo componente.\n *\n * Lo que NO cambia: el contrato de `id`s de ARIA (`line-tab-{key}` para la pestaña y\n * `line-tabpanel-{key}` para el panel, que `LineTabsRegion` referencia con\n * `aria-labelledby`), la navegación por flechas ←/→ e Inicio/Fin, el `tabIndex` rotatorio y\n * el scroll horizontal. Esta barra sigue sin decidir nada: recibe las pestañas resueltas y\n * la activa, y avisa del cambio.\n *\n * @see CanonTabsBar — el canon §C.2, con el indicador deslizante\n * @see LineTabsRegion — monta el contenido de la pestaña activa\n */\nexport function LineTabsBar({ tabs, activeKey, onChange, className }: LineTabsBarProps) {\n  const { t } = useMasterDocumentTranslation();\n\n  return (\n    <CanonTabsBar\n      tabs={tabs.map((tab) => ({ key: tab.key, label: tab.label, icon: tab.icon }))}\n      activeKey={activeKey}\n      onChange={onChange}\n      ariaLabel={t('master_document.lines.tabsLabel')}\n      idPrefix=\"line-tab\"\n      testId=\"line-tabs\"\n      className={className}\n    />\n  );\n}\n","import type { ReactNode } from 'react';\nimport { clsx } from 'clsx';\n\nimport { LineTabsBar } from './LineTabsBar';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { LineTabConfig, LineTabHelpers } from './MasterDocument.types';\n\nexport interface LineTabsRegionProps {\n  /** Pestañas ya resueltas, en el orden en que se dibujan. */\n  tabs: LineTabConfig[];\n  /** Pestaña activa. Si la clave no existe, cae a la primera. */\n  activeKey: string;\n  onChange: (key: string) => void;\n  /**\n   * Contenido de la pestaña Tipo 1. Recibe `hideTitle` porque el título de la\n   * grilla solo estorba cuando hay una barra que ya nombra la pestaña.\n   */\n  renderLines: (opts: { hideTitle: boolean }) => ReactNode;\n  /**\n   * Ayudantes del nivel presentacional para los contenidos Tipo 2 / Tipo 3.\n   * Los aporta `MasterDocument`, que es quien tiene el estado del modal de línea.\n   */\n  helpers: LineTabHelpers;\n  className?: string;\n}\n\n/**\n * Región de detalle con pestañas: dibuja la barra y monta el contenido de la\n * pestaña activa.\n *\n * Dos decisiones que parecen detalles y no lo son:\n *\n * 1. **Una sola pestaña no dibuja barra.** Una pestaña sola no es navegación, y\n *    el documento se ve idéntico a como se veía sin la capacidad.\n * 2. **Al cambiar de pestaña el contenido se DESMONTA**, no se oculta con\n *    `display:none`. La grilla nativa virtualiza midiendo su contenedor de\n *    scroll (`useVirtualizer`): oculta por CSS mide cero y al volver pinta cero\n *    filas o alto cero. El precio es perder el scroll de la pestaña saliente; el\n *    host que quiera conservarlo cachea el estado en su renderer.\n *\n * Renderiza un fragmento —no un contenedor propio— para que la barra y el panel\n * sigan siendo hijos directos de la columna del documento y conserven su\n * separación. El panel sí es un contenedor con la misma separación interna,\n * porque la pestaña de líneas apila varios bloques (menú de clases, aviso de\n * datos obsoletos, grilla).\n *\n * @see LineTabsBar — la barra\n * @see MasterDocument — decide qué pestañas existen y compone la de líneas\n */\nexport function LineTabsRegion({\n  tabs,\n  activeKey,\n  onChange,\n  renderLines,\n  helpers,\n  className,\n}: LineTabsRegionProps) {\n  const { t } = useMasterDocumentTranslation();\n\n  if (tabs.length === 0) return null;\n\n  const showBar = tabs.length > 1;\n  const activeTab = tabs.find((tab) => tab.key === activeKey) ?? tabs[0];\n\n  const content =\n    activeTab.type === 'lines' ? (\n      renderLines({ hideTitle: showBar })\n    ) : activeTab.render ? (\n      activeTab.render(helpers)\n    ) : (\n      // El template declaró un `renderKey` que el host no registró. Se avisa en\n      // consola desde el contenedor smart, que es quien conoce el registro; aquí\n      // solo queda dejar la pestaña con un estado explícito en vez de vacía.\n      <div className=\"flex flex-col items-center justify-center py-12 text-center\">\n        <p className=\"text-sm font-medium text-content-secondary dark:text-dark-content-secondary\">\n          {t('master_document.lines.tabUnavailable')}\n        </p>\n      </div>\n    );\n\n  return (\n    <>\n      {showBar && <LineTabsBar tabs={tabs} activeKey={activeTab.key} onChange={onChange} />}\n      <div\n        role=\"tabpanel\"\n        id={`line-tabpanel-${activeTab.key}`}\n        aria-labelledby={showBar ? `line-tab-${activeTab.key}` : undefined}\n        className={clsx('flex flex-col gap-[10px] min-w-0', className)}\n      >\n        {content}\n      </div>\n    </>\n  );\n}\n","import { useState, useMemo, useCallback } from 'react';\nimport { clsx } from 'clsx';\n\nimport { ActionBar } from './ActionBar';\nimport { ContextStrip } from './ContextStrip';\nimport { HeaderRenderer } from './HeaderRenderer';\nimport { LinesSection } from './LinesSection';\nimport { FactBox, FactBoxInline } from './FactBox';\nimport { ContentLayout } from './ContentLayout';\nimport { LineFormModal } from './LineFormModal';\nimport { ConflictModal } from './ConflictModal';\nimport { SkeletonDocument } from './Skeletons';\nimport { CrossingSourceSelector } from './CrossingSourceSelector';\nimport { StaleDataBanner } from './StaleDataBanner';\nimport { CrossingClassMenu } from './CrossingClassMenu';\nimport { PendingLinesPanel } from './PendingLinesPanel';\nimport { DocumentTraceabilityTree } from './DocumentTraceabilityTree';\nimport { LineCloseModal } from './LineCloseModal';\nimport { CrossingGenerateModal } from './CrossingGenerateModal';\nimport { LineTabsRegion } from './LineTabsRegion';\n\nimport type {\n  MasterDocumentProps,\n  FieldDescriptor,\n  FieldErrorMap,\n  LineTabConfig,\n  LineTabHelpers,\n} from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { inlineActionButtonDanger, inlineActionButtonNeutral } from './inlineActions';\n\n// ─── Helpers ──────────────────────────────────────────────\n\n/**\n * Clave reservada de la pestaña de trazabilidad del cruce.\n *\n * La trazabilidad ya era una pestaña antes de que existieran las pestañas\n * declarativas, con su propio estado (`crossing.activeTab`) y su unión cerrada\n * `'lines' | 'traceability'` en un callback público. En vez de ensanchar ese tipo\n * —lo que rompería la compilación de cualquier host que implemente el handler—,\n * se la anexa a la barra como una pestaña sintética y esta clave hace de puente:\n * al seleccionarla se traduce a `crossing.onTabChange('traceability')`.\n */\nconst TRACEABILITY_TAB_KEY = '__traceability';\n\nfunction groupFieldsBySection(fields: FieldDescriptor[]): Record<string, FieldDescriptor[]> {\n  const map: Record<string, FieldDescriptor[]> = {};\n  for (const f of fields) {\n    (map[f.section] ??= []).push(f);\n  }\n  return map;\n}\n\n// ─── MasterDocument ───────────────────────────────────────\n\n/**\n * MasterDocument — componente de presentación que compone el documento maestro\n * completo: barra de acciones, tira de contexto, encabezado, líneas y FactBox.\n *\n * Es un componente puramente presentacional: recibe todos los datos y callbacks\n * como props y no contiene lógica de negocio. Para la versión con lógica\n * completa, usar `SmartMasterDocument` dentro de un `MasterDocumentProvider`.\n *\n * @see SmartMasterDocument — versión inteligente con template y adaptador\n * @see MasterDocumentProvider — proveedor de contexto para el modo smart\n *\n * @example\n * ```tsx\n * <MasterDocument\n *   documentId=\"FA-001\"\n *   docTypeBadge=\"Factura\"\n *   docState=\"draft\"\n *   mode=\"edit\"\n *   headerFields={fields}\n *   headerValues={values}\n *   lines={lines}\n *   lineColumns={columns}\n *   onHeaderFieldChange={handleChange}\n *   onLineSave={handleSave}\n *   onDeleteLine={handleDelete}\n * />\n * ```\n */\nexport function MasterDocument({\n  // Identity\n  documentId,\n  documentNumber,\n  docTypeBadge,\n  breadcrumbLabel,\n  documentTitle,\n  companyName,\n  onBreadcrumbClick,\n\n  // State\n  docState,\n  stateBadge,\n  transitions,\n  onTransition,\n\n  // Mode\n  mode,\n\n  // Actions\n  actions,\n\n  // Context strip\n  contextItems,\n  currencyPanel,\n\n  // Header\n  headerLayout,\n  headerFields,\n  headerValues,\n  headerErrors,\n  onHeaderFieldChange,\n  dynamicEntitiesSlot,\n\n  // Lookup/Searcher\n  lookupConfigs,\n  fetcher,\n  onRecordSelect,\n\n  // Lines\n  linesTitle,\n  lines,\n  lineColumns,\n  lineFields,\n  lineComputedRules,\n  lineServerRules,\n  onEvaluateServerRule,\n  lineWidgetSlot,\n  lineDynamicEntitiesSlot,\n  onLineFormValuesChange,\n  lineModalSections,\n  serialSupport,\n  serialReadOnly,\n  validateSerial,\n  fetchAvailableSerials,\n  lineAlerts,\n  canAddLine = true,\n  onAddLine,\n  onEditLine,\n  onViewLine,\n  onDeleteLine,\n  onDuplicateLine,\n  getLineActions,\n  lineEditable = true,\n  lineDeletable = true,\n  onLineSave,\n\n  // Line tabs\n  lineTabs,\n  activeLineTabKey,\n  onLineTabChange,\n\n  // FactBox\n  factBoxSections,\n\n  // Conflict\n  conflict,\n\n  // Forbidden / 403\n  forbidden,\n\n  // Crossing\n  crossing,\n\n  // Loading / Error\n  loading,\n\n  // In-flight: deshabilita el guardado de línea mientras hay una mutación en curso\n  busy,\n  busyLineId,\n\n  // Style\n  className,\n}: MasterDocumentProps) {\n  const { t } = useMasterDocumentTranslation();\n\n  // ── Internal state ────────────────────────────────────────\n  const [lineModal, setLineModal] = useState<{\n    open: boolean;\n    lineId: string | null;\n    initialData?: Record<string, unknown>;\n    readOnly?: boolean;\n  }>({ open: false, lineId: null });\n  const [lineErrors, setLineErrors] = useState<FieldErrorMap | undefined>();\n\n  // ── Derived data ──────────────────────────────────────────\n  const fieldsBySection = useMemo(\n    () => groupFieldsBySection(headerFields),\n    [headerFields],\n  );\n\n  // Derivado internamente para evaluar `lockedWhen.hasLines` de los campos.\n  const hasLines = lines.length > 0;\n\n  const resolvedLinesTitle = linesTitle ?? t('master_document.lines.title');\n\n  // ── Line modal handlers ───────────────────────────────────\n  const handleEditLine = useCallback(\n    (lineId: string) => {\n      // Cuando las líneas no son editables, no abrir el modal de edición.\n      if (!lineEditable) return;\n      const lineData = lines.find((l) => l.id === lineId);\n      setLineModal({\n        open: true,\n        lineId,\n        initialData: lineData ? { ...lineData } : undefined,\n      });\n      onEditLine(lineId);\n    },\n    [lineEditable, lines, onEditLine],\n  );\n\n  // Abre la línea en modo solo-lectura (\"Ver\"). Solo se cablea desde\n  // LinesSection cuando `lineEditable === false`.\n  const handleViewLine = useCallback(\n    (lineId: string) => {\n      const lineData = lines.find((l) => l.id === lineId);\n      setLineModal({\n        open: true,\n        lineId,\n        initialData: lineData ? { ...lineData } : undefined,\n        readOnly: true,\n      });\n      onViewLine?.(lineId);\n    },\n    [lines, onViewLine],\n  );\n\n  const handleAddLine = useCallback(() => {\n    setLineModal({ open: true, lineId: null, initialData: undefined });\n    onAddLine();\n  }, [onAddLine]);\n\n  const handleLineModalConfirm = useCallback(\n    async (data: Record<string, unknown>) => {\n      const errors = (await onLineSave?.(lineModal.lineId, data)) as FieldErrorMap | undefined;\n      if (errors && Object.keys(errors).length > 0) {\n        setLineErrors(errors);\n      } else {\n        setLineErrors(undefined);\n        setLineModal({ open: false, lineId: null });\n      }\n    },\n    [lineModal.lineId, onLineSave],\n  );\n\n  // Guarda la línea actual y deja el modal abierto para ingresar otra\n  const handleLineModalConfirmAndAddAnother = useCallback(\n    async (data: Record<string, unknown>): Promise<FieldErrorMap | undefined> => {\n      const errors = (await onLineSave?.(null, data)) as FieldErrorMap | undefined;\n      if (errors && Object.keys(errors).length > 0) {\n        setLineErrors(errors);\n        return errors;\n      }\n      setLineErrors(undefined);\n      // El modal permanece abierto con lineId: null → próxima línea nueva\n      setLineModal({ open: true, lineId: null, initialData: undefined });\n      return undefined;\n    },\n    [onLineSave],\n  );\n\n  const handleLineModalClose = useCallback(() => {\n    setLineErrors(undefined);\n    setLineModal({ open: false, lineId: null });\n  }, []);\n\n  // ── Detail tabs ───────────────────────────────────────────\n  // Ayudantes para los contenidos Tipo 2 / Tipo 3. El modal de línea es estado\n  // de ESTE componente: el contenedor smart arma el contexto del renderer pero no\n  // puede abrir un modal que no controla, así que la correa pasa por aquí.\n  //\n  // Abre siempre en SOLO LECTURA, y es coherente con el contrato: una pestaña\n  // Tipo 2 es de consulta, y las mutaciones van por sus acciones de fila.\n  const lineTabHelpers = useMemo<LineTabHelpers>(\n    () => ({\n      openLineDetail: (lineId: string) => {\n        const lineData = lines.find((l) => l.id === lineId);\n        if (!lineData) return;\n        setLineModal({ open: true, lineId, initialData: { ...lineData }, readOnly: true });\n        onViewLine?.(lineId);\n      },\n    }),\n    [lines, onViewLine],\n  );\n\n  // Contenido de la pestaña de líneas. Es una función y no un nodo porque solo\n  // debe evaluarse cuando esa pestaña está activa: al cambiar de pestaña el\n  // contenido se desmonta (ver LineTabsRegion).\n  const renderLinesContent = ({ hideTitle }: { hideTitle: boolean }) => (\n    <>\n      {/* CrossingClassMenu — right-aligned, shown when in selection mode */}\n      {crossing?.selectionMode && crossing.classMenuOptions.length > 0 && (\n        <div className=\"flex justify-end\">\n          <CrossingClassMenu\n            options={crossing.classMenuOptions}\n            onSelect={crossing.onSelectClass}\n            disabled={!crossing.canGenerate}\n          />\n        </div>\n      )}\n\n      {/* StaleDataBanner — rendered above LinesSection when data may be stale */}\n      {crossing?.pendingLinesFetchedAt && (\n        <StaleDataBanner\n          fetchedAt={crossing.pendingLinesFetchedAt}\n          onRefresh={crossing.onRefreshPendingLines}\n          isRefreshing={crossing.pendingLinesLoading}\n        />\n      )}\n\n      {crossing?.selectionMode ? (\n        /* FE-02: panel de líneas pendientes del origen con cantidad a cruzar */\n        <PendingLinesPanel\n          lines={crossing.pendingLines}\n          selectedLineIds={crossing.selectedLineIds}\n          quantities={crossing.quantitiesToCross}\n          errors={crossing.lineSelectionErrors}\n          loading={crossing.pendingLinesLoading}\n          onLineSelect={crossing.onLineSelect}\n          onTrySelectTerminalLine={crossing.onTrySelectTerminalLine}\n          onQuantityChange={crossing.onQuantityChange}\n          formatNumber={crossing.formatNumber}\n        />\n      ) : (\n        <LinesSection\n          title={resolvedLinesTitle}\n          lines={lines}\n          columns={lineColumns}\n          lineFields={lineFields}\n          alerts={lineAlerts}\n          canAddLine={canAddLine && mode !== 'view'}\n          onAddLine={handleAddLine}\n          onEditLine={handleEditLine}\n          onViewLine={handleViewLine}\n          onDeleteLine={onDeleteLine}\n          onDuplicateLine={onDuplicateLine}\n          getLineActions={getLineActions}\n          // Hallazgo A de la solicitud: esta línea era la única de las tres que NO\n          // cruzaba con el modo. `canAddLine` y `lineDeletable` (arriba y abajo) ya lo\n          // hacían, y el comentario de aquéllas enunciaba el criterio —«un documento\n          // en sólo lectura no cambia su contenido»— justo antes de aplicárselo sólo a\n          // eliminar. El resultado era un lápiz vivo, que disparaba `onEditLine`, en un\n          // documento que el propio kit daba por de consulta.\n          lineEditable={lineEditable && mode !== 'view'}\n          // AC-4: en modo `view` no se borra, igual que no se agrega. Es el mismo\n          // criterio que ya gobierna `canAddLine` justo arriba: un documento en sólo\n          // lectura no cambia su contenido, y ofrecer el botón sería prometer una\n          // escritura que la pantalla no admite.\n          lineDeletable={lineDeletable && mode !== 'view'}\n          lineStatuses={crossing?.lineStatuses}\n          onOpenLineCloseModal={crossing?.onOpenLineCloseModal}\n          lineActions={crossing?.lineActions}\n          busyLineId={busyLineId}\n          hideTitle={hideTitle}\n        />\n      )}\n    </>\n  );\n\n  // Pestañas efectivas = las declaradas + la de trazabilidad si hay cruce. Sin\n  // ninguna de las dos cosas la lista queda vacía y el detalle se pinta directo,\n  // sin barra ni panel: es el camino de siempre y no debe cambiar de DOM.\n  const detailTabs = useMemo<LineTabConfig[]>(() => {\n    const declared = lineTabs ?? [];\n    if (declared.length === 0 && !crossing) return [];\n\n    const result: LineTabConfig[] =\n      declared.length > 0\n        ? [...declared]\n        : // Con cruce pero sin pestañas declaradas, la de líneas es implícita:\n          // es la que ya existía en la tira quemada.\n          [{ key: 'lines', label: t('master_document.lines.tab'), type: 'lines' }];\n\n    if (crossing) {\n      // Alias local: el estrechamiento de un parámetro no sobrevive dentro del\n      // closure de `render`, y sin él TS lo trata como posiblemente indefinido.\n      const cx = crossing;\n      result.push({\n        key: TRACEABILITY_TAB_KEY,\n        label: cx.traceabilityLabel || t('master_document.document.traceability'),\n        type: 'render',\n        render: () => (\n          <DocumentTraceabilityTree\n            tree={cx.traceabilityTree}\n            onNodeClick={cx.onTraceabilityNodeClick}\n            loading={cx.traceabilityLoading}\n            error={cx.traceabilityError}\n            onRetry={cx.onRetryTraceability}\n          />\n        ),\n      });\n    }\n\n    return result;\n  }, [lineTabs, crossing, t]);\n\n  // Pestaña de contenido seleccionada, INDEPENDIENTE de la trazabilidad: así,\n  // al volver del árbol se restaura la que el usuario estaba viendo.\n  const [internalTabKey, setInternalTabKey] = useState<string | null>(null);\n  const firstContentTabKey =\n    detailTabs.find((tab) => tab.key !== TRACEABILITY_TAB_KEY)?.key ?? TRACEABILITY_TAB_KEY;\n  const contentTabKey = activeLineTabKey ?? internalTabKey ?? firstContentTabKey;\n  const activeDetailTabKey =\n    crossing?.activeTab === 'traceability' ? TRACEABILITY_TAB_KEY : contentTabKey;\n\n  const handleDetailTabChange = useCallback(\n    (key: string) => {\n      if (key === TRACEABILITY_TAB_KEY) {\n        crossing?.onTabChange('traceability');\n        return;\n      }\n      // Volver de la trazabilidad a cualquier pestaña de contenido devuelve el\n      // estado del cruce a 'lines': es lo que espera el resto de su máquina.\n      if (crossing?.activeTab === 'traceability') crossing.onTabChange('lines');\n      setInternalTabKey(key);\n      onLineTabChange?.(key);\n    },\n    [crossing, onLineTabChange],\n  );\n\n  // ── Loading state ─────────────────────────────────────────\n  if (loading) {\n    return <SkeletonDocument className={className} />;\n  }\n\n  // ── Render ────────────────────────────────────────────────\n  return (\n    <div className={clsx('w-full h-full flex flex-col', className)}>\n      {/* Cabecera del detalle, al canon de MasterCrud: apilada y SIN caja propia.\n          Ya no es `sticky`: la barra de 52px se quedaba pegada arriba porque era\n          la única referencia del documento, pero una cabecera de tres alturas\n          fijada roba un tercio del alto útil en portátiles. La identidad del\n          documento —tipo, número, centro de operación— sigue a la vista en la\n          franja que abre la tarjeta. */}\n      <div className=\"shrink-0\">\n        <ActionBar\n          breadcrumbLabel={breadcrumbLabel}\n          documentTitle={documentTitle}\n          companyName={companyName}\n          onBreadcrumbClick={onBreadcrumbClick}\n          documentId={documentId}\n          documentNumber={documentNumber}\n          stateBadge={stateBadge}\n          docTypeBadge={docTypeBadge}\n          transitions={transitions}\n          onTransition={onTransition}\n          actions={actions}\n        />\n      </div>\n\n      {/* Main content area with optional FactBox */}\n      <ContentLayout\n        factBox={\n          factBoxSections ? (\n            <FactBox sections={factBoxSections} />\n          ) : undefined\n        }\n      >\n        {/* Envoltorio + tarjeta del canon (ADR-027, detalle de MasterCrud): el aire\n            lo pone el envoltorio y la ÚNICA superficie es la tarjeta blanca con\n            `rounded-2xl`, borde y `shadow-sm`. Antes el contenido colgaba\n            directamente del panel gris, sin tarjeta y con un `px-5` que no\n            cuadraba con el `px-4 md:px-6` de la cabecera: por eso el título y\n            los campos no compartían eje vertical. */}\n        <div className=\"w-full px-4 md:px-6 pb-4 flex-1 min-h-0 flex flex-col\">\n        <div className=\"w-full bg-white dark:bg-dark-bg-primary rounded-2xl border border-border-primary dark:border-dark-border-primary overflow-hidden flex flex-col flex-1 min-h-0 shadow-sm\">\n        <ContextStrip items={contextItems} currencyPanel={currencyPanel} />\n        {/* Dentro de la tarjeta ya no hay tarjetas: encabezado, campos dinámicos\n            y detalle son SECCIONES de una sola superficie. Para que se distingan\n            sin volver a encajonarlas, cada bloque que abre una región nueva se\n            separa con una regla a TODO el ancho de la tarjeta —de ahí el\n            `-mx` que anula el gutter y lo repone—, y el aire entre bloques sube\n            a 20px. Es lo que deja legibles dos barras de pestañas en la misma\n            tarjeta: la regla dice dónde empieza cada región y el subrayado\n            deslizante de cada barra dice cuál es su pestaña activa. */}\n        {/* EL SCROLL VIVE AQUÍ, no en el panel de `ContentLayout`. Así la franja de\n            identidad del documento —tipo, número, centro de operación— y el borde\n            superior de la tarjeta se quedan quietos, y sólo se desplaza el contenido de\n            las pestañas. Con el scroll en el panel, al bajar se iba la ficha entera y el\n            usuario perdía de vista qué documento estaba mirando. */}\n        <div className=\"flex flex-col gap-5 px-4 md:px-6 pt-4 pb-8 flex-1 min-h-0 overflow-y-auto scrollbar-thin\">\n          {/* Forbidden / 403 banner */}\n          {forbidden && (\n            <div\n              role=\"alert\"\n              className=\"flex items-start justify-between gap-3 px-4 py-2.5 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800\"\n            >\n              <span className=\"text-sm text-red-700 dark:text-red-400\">{forbidden.message}</span>\n              {forbidden.onDismiss && (\n                <button\n                  type=\"button\"\n                  onClick={forbidden.onDismiss}\n                  aria-label={t('master_document.chrome.closeNotice')}\n                  className={clsx(inlineActionButtonDanger, 'shrink-0')}\n                >\n                  {t('master_document.chrome.close')}\n                </button>\n              )}\n            </div>\n          )}\n\n          {/* Header Renderer */}\n          <HeaderRenderer\n            mode={headerLayout.mode}\n            columns={headerLayout.columns}\n            sections={headerLayout.sections}\n            fieldsBySection={fieldsBySection}\n            values={headerValues}\n            errors={headerErrors}\n            onFieldChange={onHeaderFieldChange}\n            docState={docState}\n            mode_form={mode}\n            hasLines={hasLines}\n            lookupConfigs={lookupConfigs}\n            fetcher={fetcher}\n            onRecordSelect={onRecordSelect}\n          />\n\n          {/* Crossing source selector — rendered below header when crossing is active */}\n          {crossing?.sourceSelector && (\n            <CrossingSourceSelector\n              selectedDocuments={crossing.sourceSelector.selectedDocuments}\n              onAdd={crossing.sourceSelector.onAdd}\n              onRemove={crossing.sourceSelector.onRemove}\n              locked={crossing.sourceSelector.locked}\n              searchDocuments={crossing.sourceSelector.searchDocuments}\n            />\n          )}\n\n          {/* Generate error banner — shown when crossing generate fails */}\n          {crossing?.generateError && (\n            <div className=\"flex items-center justify-between gap-3 px-4 py-2.5 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800\">\n              <span className=\"text-sm text-red-700 dark:text-red-400\">{crossing.generateError}</span>\n              <button\n                type=\"button\"\n                onClick={crossing.onClearGenerateError}\n                className={clsx(inlineActionButtonDanger, 'shrink-0')}\n              >\n                {t('master_document.chrome.close')}\n              </button>\n            </div>\n          )}\n\n          {/* Page-level business rule errors (BR-11, BR-13, BR-15, BR-16) */}\n          {crossing?.pageErrors?.map((msg, idx) => (\n            <div\n              key={idx}\n              className=\"flex items-start justify-between gap-3 px-4 py-2.5 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700\"\n            >\n              <span className=\"text-sm text-amber-800 dark:text-amber-300\">{msg}</span>\n              {crossing.onDismissPageError && (\n                <button\n                  type=\"button\"\n                  onClick={() => crossing.onDismissPageError!(idx)}\n                  aria-label={t('master_document.chrome.closeNotice')}\n                  className={clsx(inlineActionButtonNeutral, 'shrink-0')}\n                >\n                  {t('master_document.chrome.close')}\n                </button>\n              )}\n            </div>\n          ))}\n\n          {/* Campos adicionales (EAV) del encabezado. Van después de los avisos\n              —que son transitorios y pertenecen al encabezado— y justo encima del\n              detalle, que es donde el usuario los busca: son datos del documento,\n              no de sus líneas. */}\n          {dynamicEntitiesSlot && (\n            <div className=\"-mx-4 px-4 pt-5 border-t border-border-secondary dark:border-dark-border-primary\">\n              {dynamicEntitiesSlot}\n            </div>\n          )}\n\n          {/* Área de detalle: sin pestañas declaradas y sin cruce, es la grilla y\n              nada más — mismo DOM que antes de existir esta capacidad. */}\n          {/* ⚠️ `-mx-4 px-4` con UN SOLO valor de escala y sin variante `md:`, a\n              propósito. Con `-mx-4 md:-mx-6 px-4 md:px-6` el margen y el padding NO se\n              cancelaban: medido en dev el 2026-09-09 a 1470px, el computado daba\n              `margin-left: -24px` (ganaba `md:-mx-6`) y `padding-left: 16px` (ganaba\n              `px-4` a `md:px-6`, por orden de cascada en el CSS del kit). Resultado: la\n              barra de pestañas de líneas quedaba 8px a la izquierda de la del\n              encabezado. Con un valor único siempre se anulan. */}\n          <div className=\"-mx-4 px-4 pt-5 border-t border-border-secondary dark:border-dark-border-primary flex flex-col gap-5\">\n          {detailTabs.length > 0 ? (\n            <LineTabsRegion\n              tabs={detailTabs}\n              activeKey={activeDetailTabKey}\n              onChange={handleDetailTabChange}\n              renderLines={renderLinesContent}\n              helpers={lineTabHelpers}\n            />\n          ) : (\n            renderLinesContent({ hideTitle: false })\n          )}\n\n          {/* Los widgets, por debajo de `xl`, como última sección del documento y\n              dentro de SU MISMO scroll. Aquí y no en `ContentLayout` porque aquello\n              es una fila flex: puesto ahí, el bloque saldría al lado del documento\n              en vez de debajo. Por encima de `xl` no pinta nada — manda el riel. */}\n          {factBoxSections && <FactBoxInline sections={factBoxSections} />}\n          </div>\n        </div>\n        </div>\n        </div>\n      </ContentLayout>\n\n      {/* Line Form Modal */}\n      {onLineSave && (\n        <LineFormModal\n          open={lineModal.open}\n          onClose={handleLineModalClose}\n          onConfirm={handleLineModalConfirm}\n          onConfirmAndAddAnother={lineModal.lineId === null ? handleLineModalConfirmAndAddAnother : undefined}\n          fields={lineFields}\n          initialData={lineModal.initialData}\n          docState={docState}\n          computedRules={lineComputedRules}\n          serverRules={lineServerRules}\n          onEvaluateServerRule={onEvaluateServerRule}\n          sections={lineModalSections}\n          widgetSlot={lineWidgetSlot}\n          dynamicEntitiesSlot={\n            // Solo con el modal abierto: cerrado, `LineFormModal` devuelve null y\n            // construir el bloque sería montar formularios que nadie ve.\n            lineModal.open && lineDynamicEntitiesSlot\n              ? lineDynamicEntitiesSlot({ lineId: lineModal.lineId })\n              : undefined\n          }\n          onFormValuesChange={onLineFormValuesChange}\n          lookupConfigs={lookupConfigs}\n          fetcher={fetcher}\n          headerValues={headerValues}\n          serialSupport={serialSupport}\n          serialReadOnly={serialReadOnly}\n          validateSerial={validateSerial}\n          fetchAvailableSerials={fetchAvailableSerials}\n          errors={lineErrors}\n          busy={busy}\n          readOnly={lineModal.readOnly}\n          title={lineModal.readOnly ? t('master_document.lines.viewLine') : lineModal.lineId ? t('master_document.lines.editLine') : t('master_document.lines.newLine')}\n          confirmLabel={lineModal.lineId ? t('master_document.lines.saveChanges') : t('master_document.lines.addLine')}\n          cancelLabel={lineModal.readOnly ? t('master_document.chrome.close') : undefined}\n          columns={2}\n        />\n      )}\n\n      {/* Conflict Modal */}\n      {conflict && (\n        <ConflictModal\n          open\n          modifiedBy={conflict.modifiedBy}\n          modifiedAgo={conflict.modifiedAgo}\n          onReload={conflict.onReload}\n          onKeepEditing={conflict.onKeepEditing}\n          dismissable={conflict.dismissable}\n          message={conflict.message}\n        />\n      )}\n\n      {/* Line Close Modal — always rendered, controlled by open prop */}\n      {crossing && (\n        <LineCloseModal\n          open={crossing.lineCloseModal.open}\n          onClose={crossing.onCloseLineCloseModal}\n          onConfirm={crossing.onConfirmLineClose}\n          mode={crossing.lineCloseModal.mode}\n          lineDescription={crossing.lineCloseModal.lineDescription}\n          isLoading={crossing.lineCloseModal.isLoading}\n          error={crossing.lineCloseModal.error}\n        />\n      )}\n\n      {/* Crossing Generate Modal — always rendered, controlled by open prop */}\n      {crossing && (\n        <CrossingGenerateModal\n          open={crossing.generateModal.open}\n          classLabel={crossing.generateModal.classLabel}\n          fields={crossing.generateHeaderFields ?? []}\n          onConfirm={crossing.onConfirmGenerate}\n          onCancel={crossing.onCancelGenerateModal}\n          isLoading={crossing.generateModal.isLoading}\n          error={crossing.generateModal.error}\n        />\n      )}\n    </div>\n  );\n}\n","import React, { useCallback, useMemo, useRef, useState } from 'react';\nimport clsx from 'clsx';\nimport { EntityContainer } from '../DynamicEntities/ui/DynamicFeatureOrchestrator';\nimport type { DynamicEntitiesRef } from '../DynamicEntities/ui/DynamicEntities';\nimport { Tabs } from '../Tabs';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { DocumentDynamicGrain } from './smart/useDocumentDynamicEntities';\n\nexport interface DocumentDynamicEntitiesProps {\n  /** Grano ya resuelto por `useDocumentDynamicEntities`. */\n  grain: DocumentDynamicGrain;\n  /**\n   * Id del registro dueño de los valores: el documento para el grano de\n   * encabezado, la línea para el de línea. Ausente en creación — el formulario se\n   * captura igual y los valores se persisten cuando el backend devuelve el id.\n   */\n  recordId?: string;\n  /** Título por defecto cuando el template no declaró `label`/`labelKey`. */\n  defaultTitleKey: string;\n  /** El documento no es editable: el bloque se pinta pero no se puede capturar. */\n  readOnly?: boolean;\n  /**\n   * Presentación. `card` (por defecto) envuelve el bloque en la misma tarjeta que\n   * usan las secciones del encabezado; `bare` lo entrega suelto, para un anfitrión\n   * que ya aporta su propio marco — hoy, el modal de línea.\n   */\n  variant?: 'card' | 'bare';\n  className?: string;\n}\n\n/**\n * Bloque de campos adicionales (EAV) de un grano del documento.\n *\n * Es el equivalente para `MasterDocument` de `MasterCrudDynamicEntities`, y\n * mantiene sus dos decisiones importantes:\n *\n * 1. **Los `EntityContainer` van sin su botón Guardar** (`hideSubmitButton`). El\n *    documento tiene UNA acción de guardar; un segundo botón dentro del formulario\n *    guardaría solo una parte y dejaría al usuario sin saber qué quedó grabado.\n *    Quien persiste es el ciclo del documento, vía los refs registrados.\n *\n * 2. **Las pestañas ocultan, no desmontan.** Un `EntityContainer` desmontado\n *    pierde sus valores y desregistra su ref, así que capturar en la pestaña A,\n *    pasar a la B y guardar perdería A sin decir nada. Se pintan todas y se oculta\n *    con `hidden` — a diferencia de las pestañas de detalle del documento, que sí\n *    desmontan porque su grilla necesita medir el contenedor de scroll.\n *\n * ## El título lo pone SIEMPRE este componente\n *\n * `hideSubmitButton` viaja acompañado de `hideTitle` en todos los casos. El título\n * propio de `DynamicEntities` es un `h2 text-xl`, un peso tipográfico que en un\n * documento no se corresponde con nada: las secciones del encabezado se rotulan\n * con `text-sm font-bold`. Dejarlo salir metía un segundo nivel de titulación —y,\n * antes de este arreglo, una segunda tarjeta— dentro de la que ya aporta el bloque.\n * El nombre de cada entidad se rotula aquí, y solo cuando hay más de una: con una\n * sola, repetir \"Datos adicionales\" bajo \"Campos adicionales\" es ruido.\n */\nexport const DocumentDynamicEntities: React.FC<DocumentDynamicEntitiesProps> = ({\n  grain,\n  recordId,\n  defaultTitleKey,\n  readOnly,\n  variant = 'card',\n  className,\n}) => {\n  const { t } = useMasterDocumentTranslation();\n\n  const inlineEntities = useMemo(\n    () => grain.entities.filter((fe) => fe.renderMode === 'inline'),\n    [grain.entities],\n  );\n  const tabEntities = useMemo(\n    () => grain.entities.filter((fe) => fe.renderMode === 'tab'),\n    [grain.entities],\n  );\n\n  const [activeTab, setActiveTab] = useState<string>(\n    () => tabEntities[0]?.dynamicEntity?.code ?? '',\n  );\n\n  // Una entidad puede aparecer o desaparecer si el administrador la reconfigura\n  // mientras el documento está abierto: sin esto la pestaña activa apuntaría a\n  // una entidad que ya no existe y el cuerpo quedaría en blanco.\n  const activeKey =\n    tabEntities.some((fe) => fe.dynamicEntity?.code === activeTab)\n      ? activeTab\n      : (tabEntities[0]?.dynamicEntity?.code ?? '');\n\n  const title =\n    grain.labelKey && t(grain.labelKey) !== grain.labelKey\n      ? t(grain.labelKey)\n      : (grain.label ?? t(defaultTitleKey));\n\n  // Con una sola entidad su nombre no aporta nada sobre el título del bloque.\n  const showEntityNames = grain.entities.length > 1;\n\n  // Un callback de ref ESTABLE por entidad. Una función inline se recrearía en\n  // cada render y React desengancharía (`null`) y volvería a enganchar el ref en\n  // cada uno: ruido puro, y una ventana en la que el registro queda vacío.\n  //\n  // El callback lee el grano por ref en vez de capturarlo: así es estable de\n  // verdad y sigue apuntando al grano vigente si el Feature se recarga.\n  const grainRef = useRef(grain);\n  grainRef.current = grain;\n\n  // Qué entidades tienen campos que pintar. Una entidad recién creada a la que todavía no le\n  // pusieron campos devuelve una definición válida con `fields: []`, y sin esto el bloque dibujaba\n  // una tarjeta con título y nada dentro — un estado alcanzable por cualquiera que cree la entidad\n  // antes que sus campos.\n  const [renderable, setRenderable] = useState<Record<string, boolean>>({});\n\n  const renderableCallbacks = useRef(new Map<string, (v: boolean) => void>());\n  const reportRenderable = useCallback((entityCode: string) => {\n    let cb = renderableCallbacks.current.get(entityCode);\n    if (!cb) {\n      cb = (v: boolean) =>\n        setRenderable((prev) => (prev[entityCode] === v ? prev : { ...prev, [entityCode]: v }));\n      renderableCallbacks.current.set(entityCode, cb);\n    }\n    return cb;\n  }, []);\n\n  const registerCallbacks = useRef(new Map<string, (ref: DynamicEntitiesRef | null) => void>());\n  const register = useCallback((entityCode: string) => {\n    let cb = registerCallbacks.current.get(entityCode);\n    if (!cb) {\n      cb = (ref: DynamicEntitiesRef | null) => grainRef.current.registerRef(entityCode, ref);\n      registerCallbacks.current.set(entityCode, cb);\n    }\n    return cb;\n  }, []);\n\n  // Se esconde solo cuando TODAS reportaron y ninguna tiene nada. Mientras falte alguna por\n  // reportar el bloque se queda: decir \"no hay nada\" antes de saberlo lo haría parpadear.\n  //\n  // Y se esconde con `hidden`, sin desmontar: los formularios tienen que seguir montados para\n  // poder reportar —desmontarlos los devolvería al estado «sin reportar» y el bloque volvería a\n  // aparecer, en bucle— y para conservar sus refs. Mismo criterio que las pestañas.\n  const allReported = grain.entities.every(\n    (fe) => renderable[fe.dynamicEntity!.code] !== undefined,\n  );\n  const nothingToShow = allReported && !Object.values(renderable).some(Boolean);\n\n  const entityName = (code: string, description?: string) => (\n    <h4\n      className={clsx(\n        'mb-3 text-xs font-semibold uppercase tracking-wide',\n        'text-content-secondary dark:text-dark-content-secondary',\n      )}\n    >\n      {description || code}\n    </h4>\n  );\n\n  const body = (\n    <div className={clsx('space-y-6', variant === 'card' && 'px-4 py-4')}>\n      {inlineEntities.map((fe) => (\n        <div key={fe.dynamicEntity!.code}>\n          {showEntityNames && entityName(fe.dynamicEntity!.code, fe.dynamicEntity!.description)}\n          <EntityContainer\n            ref={register(fe.dynamicEntity!.code)}\n            featureCode={grain.featureCode}\n            entityCode={fe.dynamicEntity!.code}\n            recordId={recordId}\n            hideSubmitButton\n            hideTitle\n            onRenderableChange={reportRenderable(fe.dynamicEntity!.code)}\n          />\n        </div>\n      ))}\n\n      {tabEntities.length > 0 && (\n        <div>\n          {/* Barra de pestañas siempre que haya entidades en ese modo, incluso una\n              sola: es lo que el administrador pidió al elegir \"Pestaña\", y es el\n              mismo criterio que sigue `MasterCrudDynamicEntities`. */}\n          <Tabs\n            items={tabEntities.map((fe) => ({\n              id: fe.dynamicEntity!.code,\n              label: fe.dynamicEntity!.description || fe.dynamicEntity!.code,\n            }))}\n            activeId={activeKey}\n            onChange={setActiveTab}\n            className=\"mb-4\"\n          />\n          {tabEntities.map((fe) => (\n            <div\n              key={fe.dynamicEntity!.code}\n              className={activeKey === fe.dynamicEntity!.code ? 'block' : 'hidden'}\n            >\n              <EntityContainer\n                ref={register(fe.dynamicEntity!.code)}\n                featureCode={grain.featureCode}\n                entityCode={fe.dynamicEntity!.code}\n                recordId={recordId}\n                hideSubmitButton\n                hideTitle\n              />\n            </div>\n          ))}\n        </div>\n      )}\n    </div>\n  );\n\n  if (variant === 'bare') {\n    return (\n      <section\n        className={clsx(\n          nothingToShow && 'hidden',\n          readOnly && 'pointer-events-none opacity-60',\n          className,\n        )}\n        aria-label={title}\n      >\n        <h3\n          className={clsx(\n            'mb-3 text-sm font-bold',\n            'text-content-primary dark:text-dark-content-primary',\n          )}\n        >\n          {title}\n        </h3>\n        {body}\n      </section>\n    );\n  }\n\n  return (\n    <section\n      // Exactamente la tarjeta de `HeaderRenderer`: sombra suave en claro, borde en\n      // oscuro. Copiar estos tokens y no inventar unos propios es lo que hace que el\n      // bloque se lea como una sección más del documento y no como un injerto.\n      className={clsx(\n        // Sin tarjeta propia: ya está dentro de la del detalle (ADR-027 §E.7).\n        'min-w-0',\n        nothingToShow && 'hidden',\n        readOnly && 'pointer-events-none opacity-60',\n        className,\n      )}\n      aria-label={title}\n    >\n      {/* Mismo rótulo que una sección del encabezado: `text-sm font-bold`, px-4 py-3. */}\n      <h3\n        className={clsx(\n          'px-4 py-3 text-sm font-bold',\n          'text-content-primary dark:text-dark-content-primary',\n        )}\n      >\n        {title}\n      </h3>\n      {body}\n    </section>\n  );\n};\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { FeatureService, type Feature, type FeatureEntity } from '../../DynamicEntities/admin/services/FeatureService';\nimport { useOptionalDynamicEntitiesContext } from '../../DynamicEntities/core/DynamicEntitiesProvider';\nimport { isDynamicEntitiesHttpError } from '../../DynamicEntities/core/api/DynamicEntitiesHttpError';\nimport type { DynamicEntitiesRef } from '../../DynamicEntities/ui/DynamicEntities';\nimport type {\n  DynamicEntitiesGrainConfig,\n  DynamicEntitiesTemplateConfig,\n} from '../template/MasterDocumentTemplate.types';\n\n/** Sufijo por defecto de cada grano. Espeja los que siembra el backend del host. */\nconst DEFAULT_SUFFIX = { header: 'HEADER', line: 'LINE' } as const;\n\nexport type DocumentDynamicGrainKey = keyof typeof DEFAULT_SUFFIX;\n\n/**\n * Un grano ya resuelto: el Feature existe, tiene entidades renderizables y sus\n * refs se pueden registrar y guardar.\n */\nexport interface DocumentDynamicGrain {\n  /** Código del Feature realmente consultado. */\n  featureCode: string;\n  /** Entidades a pintar, ya filtradas y ordenadas. */\n  entities: FeatureEntity[];\n  /** Título del bloque tal como lo declaró el template (crudo). */\n  label?: string;\n  /** Clave i18n del título declarada por el template. */\n  labelKey?: string;\n  /** Registra (o desregistra, con `null`) el ref imperativo de una entidad. */\n  registerRef: (entityCode: string, ref: DynamicEntitiesRef | null) => void;\n  /**\n   * Persiste los valores de TODAS las entidades registradas contra `recordId`.\n   * Nunca lanza: un fallo se reporta por el `onError` del provider y vuelve\n   * como `false`.\n   */\n  save: (recordId: string) => Promise<boolean>;\n  /** Olvida los refs registrados. Se llama al cerrar el modal de línea. */\n  clearRefs: () => void;\n}\n\nexport interface DocumentDynamicEntitiesHandle {\n  /** `true` solo si hay provider Y el template declaró al menos un grano. */\n  enabled: boolean;\n  header: DocumentDynamicGrain | null;\n  line: DocumentDynamicGrain | null;\n}\n\ninterface UseDocumentDynamicEntitiesParams {\n  config?: DynamicEntitiesTemplateConfig;\n  /** Clase del documento en curso — la del estado, no la del template. */\n  documentClass: string;\n}\n\n/** Normaliza `true | false | {…}` a la forma de objeto, o `null` si está apagado. */\nfunction normalizeGrain(\n  grain: boolean | DynamicEntitiesGrainConfig | undefined,\n): DynamicEntitiesGrainConfig | null {\n  if (!grain) return null;\n  return grain === true ? {} : grain;\n}\n\nfunction resolveFeatureCode(\n  grain: DynamicEntitiesGrainConfig,\n  key: DocumentDynamicGrainKey,\n  documentClass: string,\n): string | null {\n  if (grain.featureCode) return grain.featureCode;\n  if (!documentClass) return null;\n  return `${documentClass}_${grain.suffix ?? DEFAULT_SUFFIX[key]}`;\n}\n\n/**\n * Resuelve los campos adicionales (EAV) de un documento y orquesta su guardado.\n *\n * ## Por qué el Feature se consulta y no se asume\n *\n * El template solo dice *que* el documento admite campos adicionales; **cuáles**\n * son lo decide el administrador en la pantalla de Entidades Dinámicas, y puede\n * cambiar sin desplegar. Por eso se pide el Feature por código en runtime y se\n * pinta lo que traiga: un Feature sin entidades ⇒ ningún bloque, exactamente como\n * un documento que no declara la capacidad.\n *\n * ## Degradaciones deliberadas (ninguna rompe el documento)\n *\n * - **Sin `DynamicEntitiesProvider`** ⇒ `enabled: false` y todo inerte. Es la\n *   situación de cualquier host que aún no cableó la capacidad, y de todos los\n *   tests y stories que montan el documento suelto.\n * - **Feature inexistente (404)** ⇒ se trata como \"esta clase no tiene campos\n *   adicionales\". Es el caso normal de una clase cuyo grano el backend no siembra\n *   (el catálogo está acotado por los flags de la clase), no un error que merezca\n *   un toast al usuario.\n * - **Cualquier otro fallo** ⇒ se reporta por el `onError` del provider y el\n *   grano queda vacío. El documento sigue guardándose.\n *\n * ## Modales, fuera\n *\n * De los tres `renderMode` del paquete se pintan `inline` y `tab`. `modal` se\n * ignora a propósito: el documento ya tiene su propia capa de modales (línea,\n * acciones, cruce) y abrir otro nivel desde dentro del formulario de captura es\n * una trampa de foco, no una funcionalidad.\n */\nexport function useDocumentDynamicEntities({\n  config,\n  documentClass,\n}: UseDocumentDynamicEntitiesParams): DocumentDynamicEntitiesHandle {\n  const context = useOptionalDynamicEntitiesContext();\n  const baseUrl = context?.baseUrl;\n  const fetcher = context?.fetcher;\n  const onError = context?.onError;\n\n  const headerConfig = normalizeGrain(config?.header);\n  const lineConfig = normalizeGrain(config?.line);\n\n  const headerCode = headerConfig ? resolveFeatureCode(headerConfig, 'header', documentClass) : null;\n  const lineCode = lineConfig ? resolveFeatureCode(lineConfig, 'line', documentClass) : null;\n\n  const service = useMemo(\n    () => (baseUrl ? new FeatureService(baseUrl, fetcher) : null),\n    [baseUrl, fetcher],\n  );\n\n  const [features, setFeatures] = useState<Record<string, Feature | null>>({});\n\n  // Los códigos a resolver, como una clave estable: sin esto el efecto se\n  // re-dispara en cada render porque el array es nuevo cada vez.\n  const wantedCodes = [headerCode, lineCode].filter((c): c is string => !!c);\n  const wantedKey = wantedCodes.join('|');\n\n  useEffect(() => {\n    if (!service || wantedKey === '') return;\n\n    let alive = true;\n    const codes = wantedKey.split('|');\n\n    Promise.all(\n      codes.map(async (code) => {\n        try {\n          return [code, await service.getByCode(code)] as const;\n        } catch (err) {\n          // 404 = esta clase no tiene ese grano sembrado. Es información, no un\n          // fallo: se cachea como `null` para no volver a preguntar.\n          if (isDynamicEntitiesHttpError(err) && err.status === 404) {\n            return [code, null] as const;\n          }\n          onError?.(err as Error);\n          return [code, null] as const;\n        }\n      }),\n    ).then((entries) => {\n      if (!alive) return;\n      setFeatures((prev) => {\n        const next = { ...prev };\n        for (const [code, feature] of entries) next[code] = feature;\n        return next;\n      });\n    });\n\n    return () => {\n      alive = false;\n    };\n  }, [service, wantedKey, onError]);\n\n  // Un registro de refs por grano. Vive en un ref y no en estado: registrar un\n  // hijo no debe re-renderizar al padre, y el guardado los lee en el momento del\n  // submit, no en el del render.\n  const headerRefs = useRef<Record<string, DynamicEntitiesRef | null>>({});\n  const lineRefs = useRef<Record<string, DynamicEntitiesRef | null>>({});\n\n  const makeGrain = useCallback(\n    (\n      code: string | null,\n      grainConfig: DynamicEntitiesGrainConfig | null,\n      refs: React.MutableRefObject<Record<string, DynamicEntitiesRef | null>>,\n    ): DocumentDynamicGrain | null => {\n      if (!service || !code || !grainConfig) return null;\n      const feature = features[code];\n      if (!feature) return null;\n\n      const entities = (feature.featureEntities ?? [])\n        .filter((fe) => !!fe.dynamicEntity && fe.renderMode !== 'modal')\n        .sort((a, b) => a.order - b.order);\n\n      if (entities.length === 0) return null;\n\n      return {\n        featureCode: code,\n        entities,\n        label: grainConfig.label,\n        labelKey: grainConfig.labelKey,\n        registerRef: (entityCode, ref) => {\n          if (ref) refs.current[entityCode] = ref;\n          else delete refs.current[entityCode];\n        },\n        save: async (recordId: string) => {\n          const active = Object.values(refs.current).filter((r): r is DynamicEntitiesRef => !!r);\n          if (active.length === 0) return true;\n          // `DynamicEntities.save` ya captura sus propios fallos y devuelve\n          // false, así que aquí no hay nada que reventar; el `catch` es por si\n          // una versión futura decide lanzar.\n          const results = await Promise.all(\n            active.map(async (ref) => {\n              try {\n                return await ref.save(recordId);\n              } catch (err) {\n                onError?.(err as Error);\n                return false;\n              }\n            }),\n          );\n          return !results.includes(false);\n        },\n        clearRefs: () => {\n          refs.current = {};\n        },\n      };\n    },\n    [service, features, onError],\n  );\n\n  const header = useMemo(\n    () => makeGrain(headerCode, headerConfig, headerRefs),\n    // headerConfig es un objeto nuevo en cada render (normalizeGrain); sus campos\n    // son los que importan y son primitivos.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [makeGrain, headerCode, headerConfig?.label, headerConfig?.labelKey],\n  );\n\n  const line = useMemo(\n    () => makeGrain(lineCode, lineConfig, lineRefs),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [makeGrain, lineCode, lineConfig?.label, lineConfig?.labelKey],\n  );\n\n  return {\n    enabled: !!service && (!!header || !!line),\n    header,\n    line,\n  };\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentFormatters } from './formatters';\n\n// ─── Types ─────────────────────────────────────────────────\n\nexport interface CurrencyPanelProps {\n  /** Código de moneda, ej: \"USD\", \"EUR\", \"COP\" */\n  code: string;\n  /** Valor de la tasa de cambio */\n  rate?: string | number;\n  /** Etiqueta antes de la tasa. Default: \"TRM\" */\n  rateLabel?: string;\n  /** Handler para abrir modal de cambio de moneda */\n  onClick?: () => void;\n  className?: string;\n}\n\n// ─── CurrencyPanel ─────────────────────────────────────────\n\n/**\n * Indicador de moneda y tasa de cambio (TRM) para la franja de contexto.\n *\n * Muestra el código de moneda y, si se proporciona la tasa, la formatea\n * con 2 decimales siguiendo el idioma activo (`useMasterDocumentFormatters`).\n * Cuando se pasa `onClick` actúa como botón interactivo para abrir un\n * selector de moneda.\n *\n * @example\n * ```tsx\n * <CurrencyPanel code=\"USD\" rate={4185.5} rateLabel=\"TRM\" onClick={() => setOpen(true)} />\n * // → \"USD · TRM 4.185,50\"\n * ```\n */\nexport function CurrencyPanel({\n  code,\n  rate,\n  rateLabel = 'TRM',\n  onClick,\n  className,\n}: CurrencyPanelProps) {\n  const { formatRate } = useMasterDocumentFormatters();\n  if (!code) return null;\n\n  const formattedRate =\n    rate != null\n      ? typeof rate === 'number'\n        ? formatRate(rate)\n        : rate\n      : null;\n\n  const display = formattedRate ? `${code} · ${rateLabel} ${formattedRate}` : code;\n\n  const baseClass = clsx(\n    'inline-flex items-center gap-1.5',\n    'text-[12px] font-semibold',\n    'text-primary-600 dark:text-primary-400',\n    'border border-[#E0E0E0] dark:border-dark-border-primary',\n    'rounded-[7px] px-[10px] py-[4px]',\n    'bg-transparent',\n    onClick && [\n      'cursor-pointer',\n      'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n      'transition-colors duration-150',\n      'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n      'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n    ],\n    className,\n  );\n\n  const icon = (\n    <svg\n      width=\"12\"\n      height=\"12\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"2\"\n      strokeLinecap=\"round\"\n      aria-hidden=\"true\"\n    >\n      <circle cx=\"12\" cy=\"12\" r=\"10\" />\n      <polyline points=\"12 6 12 12 16 14\" />\n    </svg>\n  );\n\n  if (onClick) {\n    return (\n      <button type=\"button\" onClick={onClick} className={baseClass}>\n        {icon}\n        {display}\n      </button>\n    );\n  }\n\n  return (\n    <span className={baseClass}>\n      {icon}\n      {display}\n    </span>\n  );\n}\n","import { useEffect, useState } from 'react';\nimport { clsx } from 'clsx';\nimport { XMarkIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';\nimport type { CurrencyInfo } from './adapter/MasterDocumentAdapter.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n// ─── Props ─────────────────────────────────────────────────\n\nexport interface CurrencySelectorModalProps {\n  open: boolean;\n  /** Código de la moneda actualmente seleccionada */\n  currentCode: string;\n  /** Lista de monedas disponibles */\n  currencies: CurrencyInfo[];\n  /** true mientras se carga la lista del backend */\n  loading?: boolean;\n  /** Callback cuando el usuario confirma el cambio */\n  onSelect: (currency: CurrencyInfo) => void;\n  onClose: () => void;\n}\n\n// ─── CurrencySelectorModal ─────────────────────────────────\n\n/**\n * Modal para cambiar la moneda del documento.\n * Muestra la lista de monedas activas con buscador y selección.\n *\n * @example\n * ```tsx\n * <CurrencySelectorModal\n *   open={modalOpen}\n *   currentCode=\"COP\"\n *   currencies={currencies}\n *   onSelect={(c) => handleChangeCurrency(c.code)}\n *   onClose={() => setModalOpen(false)}\n * />\n * ```\n */\nexport function CurrencySelectorModal({\n  open,\n  currentCode,\n  currencies,\n  loading = false,\n  onSelect,\n  onClose,\n}: CurrencySelectorModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [search, setSearch] = useState('');\n  const [selected, setSelected] = useState(currentCode);\n\n  // Sync selected with currentCode when modal opens\n  useEffect(() => {\n    if (open) {\n      setSelected(currentCode);\n      setSearch('');\n    }\n  }, [open, currentCode]);\n\n  // Esc to close\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  if (!open) return null;\n\n  const filtered = currencies.filter(\n    (c) =>\n      c.code.toLowerCase().includes(search.toLowerCase()) ||\n      c.name.toLowerCase().includes(search.toLowerCase()),\n  );\n\n  function handleConfirm() {\n    const currency = currencies.find((c) => c.code === selected);\n    if (currency) onSelect(currency);\n  }\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n        onClick={onClose}\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[480px]',\n          'bg-bg-primary rounded-2xl',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          'flex flex-col',\n          'max-h-[90vh]',\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"currency-modal-title\"\n      >\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-5 pt-5 pb-3 shrink-0\">\n          <h2\n            id=\"currency-modal-title\"\n            className=\"text-[15px] font-bold text-content-primary dark:text-dark-content-primary\"\n          >\n            {t('master_document.currency.changeTitle')}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'p-1.5 rounded-md',\n              'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n              'text-content-secondary dark:text-dark-content-secondary',\n              'transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          </button>\n        </div>\n\n        {/* Search */}\n        <div className=\"px-5 pb-3 shrink-0\">\n          <div className=\"relative\">\n            <MagnifyingGlassIcon\n              className=\"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-content-tertiary dark:text-dark-content-secondary pointer-events-none\"\n              aria-hidden=\"true\"\n            />\n            <input\n              type=\"text\"\n              placeholder={t('master_document.currency.searchPlaceholder')}\n              value={search}\n              onChange={(e) => setSearch(e.target.value)}\n              className={clsx(\n                'w-full pl-9 pr-3 py-2 text-sm rounded-lg',\n                'border border-border-primary dark:border-dark-border-primary',\n                'bg-bg-primary dark:bg-dark-bg-secondary',\n                'text-content-primary dark:text-dark-content-primary',\n                'placeholder:text-content-tertiary dark:placeholder:text-dark-content-secondary',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-400',\n                'dark:focus:ring-dark-border-custom',\n              )}\n              autoFocus\n            />\n          </div>\n        </div>\n\n        {/* Currency list */}\n        <div className=\"flex-1 overflow-y-auto px-2 pb-2 min-h-0\">\n          {loading ? (\n            <div className=\"flex items-center justify-center py-10\">\n              <div className=\"w-6 h-6 border-2 border-primary-400 border-t-transparent rounded-full animate-spin\" />\n            </div>\n          ) : filtered.length === 0 ? (\n            <p className=\"text-center text-sm text-content-tertiary dark:text-dark-content-secondary py-8\">\n              {t('master_document.currency.notFound')}\n            </p>\n          ) : (\n            <ul role=\"listbox\" aria-label={t('master_document.currency.listAria')}>\n              {filtered.map((currency) => {\n                const isSelected = currency.code === selected;\n                return (\n                  <li key={currency.code} role=\"option\" aria-selected={isSelected}>\n                    <button\n                      type=\"button\"\n                      onClick={() => setSelected(currency.code)}\n                      className={clsx(\n                        'w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-left',\n                        'transition-colors duration-100',\n                        isSelected\n                          ? 'bg-primary-100 dark:bg-primary-600/15'\n                          : 'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                      )}\n                    >\n                      {/* Code badge */}\n                      <span\n                        className={clsx(\n                          'shrink-0 w-12 text-center text-[12px] font-bold rounded-md px-1.5 py-1',\n                          isSelected\n                            ? 'bg-primary-200 text-primary-700 dark:bg-primary-600/30 dark:text-primary-300'\n                            : 'bg-background-secondary text-content-secondary dark:bg-dark-bg-secondary dark:text-dark-content-secondary',\n                        )}\n                      >\n                        {currency.code}\n                      </span>\n\n                      {/* Name */}\n                      <span\n                        className={clsx(\n                          'flex-1 text-sm',\n                          isSelected\n                            ? 'font-semibold text-primary-700 dark:text-primary-300'\n                            : 'text-content-primary dark:text-dark-content-primary',\n                        )}\n                      >\n                        {currency.name}\n                      </span>\n\n                      {/* Base badge */}\n                      {currency.isBase && (\n                        <span className=\"text-[10px] font-semibold uppercase tracking-wide text-content-tertiary dark:text-dark-content-secondary border border-border-primary dark:border-dark-border-primary rounded px-1.5 py-0.5 shrink-0\">\n                          {t('master_document.currency.base')}\n                        </span>\n                      )}\n\n                      {/* Selected indicator */}\n                      {isSelected && (\n                        <span className=\"shrink-0 w-4 h-4 rounded-full bg-primary-600 dark:bg-primary-400 flex items-center justify-center\">\n                          <svg width=\"8\" height=\"8\" viewBox=\"0 0 8 8\" fill=\"none\" aria-hidden=\"true\">\n                            <path d=\"M1.5 4L3.5 6L6.5 2\" stroke=\"white\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                          </svg>\n                        </span>\n                      )}\n                    </button>\n                  </li>\n                );\n              })}\n            </ul>\n          )}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-5 py-4 border-t border-border-primary dark:border-dark-border-primary shrink-0\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary text-content-tertiary',\n              'hover:bg-background-secondary transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:border-dark-border-primary dark:text-dark-content-secondary',\n              'dark:hover:bg-dark-bg-secondary',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            {t('master_document.chrome.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={handleConfirm}\n            disabled={selected === currentCode}\n            className={clsx(\n              'px-5 py-2 rounded-md text-sm font-semibold',\n              'bg-primary-inverse-background text-white',\n              'hover:bg-primary-700 transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'disabled:opacity-40 disabled:pointer-events-none',\n            )}\n          >\n            {t('master_document.currency.changeTitle')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { useCallback, useEffect, useMemo, useState } from 'react';\nimport type { CreateFromSourceTemplateConfig } from '../template/MasterDocumentTemplate.types';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport type { TranslateFn } from '../i18nFactory';\nimport type {\n  AvailableSourceItem,\n  CreateFromSourceSource,\n  IMasterDocumentAdapter,\n  PendingSourceLine,\n} from '../adapter/MasterDocumentAdapter.types';\n\n/** Modo de invocación. `create` = caso A (nace el documento); `append` = caso B (DRAFT existente). */\nexport type CreateFromSourceMode = 'create' | 'append';\n\n/** Pasos del asistente. `origin` solo aplica en modo create con `allowFreeCapture`. */\nexport type CreateFromSourceStep = 'origin' | 'sources' | 'lines' | 'confirm';\n\n/** Elección del selector de origen (paso 0). */\nexport type OriginChoice = 'source' | 'free';\n\nexport interface UseCreateFromSourceOptions {\n  open: boolean;\n  mode: CreateFromSourceMode;\n  config: CreateFromSourceTemplateConfig;\n  adapter: IMasterDocumentAdapter;\n  /** Requerido en modo `append`. */\n  documentId?: string;\n  /** Centro de operación del contexto (header en caso A, del documento en caso B). */\n  operationCenterId?: string;\n  /**\n   * Tercero fijado del header (modo `append`): filtra los orígenes y llega\n   * read-only. En modo `create` es undefined (el usuario elige libremente).\n   */\n  lockedThirdPartyId?: string;\n  /** Permisos del usuario. `null` ⇒ sin gating (mostrar todo). */\n  userPermissions?: string[] | null;\n  onCreated?: (documentId: string) => void;\n  onAppended?: (addedLineIds: string[]) => void;\n  onFreeCapture?: (route: string) => void;\n}\n\n/**\n * Validación de \"Cantidad a cruzar\" del asistente. Recibe `t` porque es una\n * función pura; el override de `config.i18n` sigue teniendo prioridad.\n */\nfunction validateQuantity(\n  quantity: number,\n  pending: number,\n  uom: string | undefined,\n  i18n: CreateFromSourceTemplateConfig['i18n'],\n  t: TranslateFn,\n): string | undefined {\n  if (Number.isNaN(quantity)) {\n    return i18n?.quantityRequired ?? t('master_document.crossing.quantityRequired');\n  }\n  if (quantity <= 0) {\n    return i18n?.quantityPositive ?? t('master_document.crossing.quantityPositive');\n  }\n  if (quantity > pending) {\n    // El override conserva su contrato: `{uom}` sin espacio previo.\n    const tpl = i18n?.quantityExceedsPending;\n    if (tpl) {\n      return tpl.replaceAll('{pending}', String(pending)).replaceAll('{uom}', uom ?? '').trim();\n    }\n    return t('master_document.crossing.quantityExceedsPending', {\n      pending: String(pending),\n      uom: uom ? ` ${uom}` : '',\n    });\n  }\n  return undefined;\n}\n\n/** Lee una clave de compatibilidad de un origen (busca en el item y en `extra`). */\nfunction readCompatKey(item: AvailableSourceItem, key: string): unknown {\n  if (key in item) return (item as unknown as Record<string, unknown>)[key];\n  return item.extra?.[key];\n}\n\nexport interface UseCreateFromSourceResult {\n  step: CreateFromSourceStep;\n  originChoice: OriginChoice | null;\n\n  candidates: AvailableSourceItem[];\n  candidatesLoading: boolean;\n  candidatesError?: string;\n  selectedSourceIds: string[];\n  /** sourceId → motivo de incompatibilidad (deshabilitado). Vacío ⇒ compatible. */\n  incompatibleReasons: Record<string, string>;\n\n  pendingLines: PendingSourceLine[];\n  linesLoading: boolean;\n  linesError?: string;\n  selectedLineIds: string[];\n  quantities: Record<string, number>;\n  lineErrors: Record<string, string>;\n\n  defaults: Record<string, unknown>;\n  /** Valores de los campos de header (`createHeaderFields`) capturados en modo create. */\n  headerValues: Record<string, unknown>;\n\n  /** Opciones de catálogo cargadas por `defaultsStep.fields[].optionsEntity`. */\n  selectOptions: Record<string, Array<{ label: string; value: string }>>;\n\n  submitting: boolean;\n  submitError?: string;\n\n  canMultiSelect: boolean;\n  canFreeCapture: boolean;\n  canSeeFinancial: boolean;\n\n  /** True cuando la selección actual permite avanzar del paso vigente. */\n  canAdvance: boolean;\n  /** True cuando existe el paso de confirmación. */\n  hasConfirmStep: boolean;\n  /** True cuando existe el paso 0 (selector de origen). */\n  hasOriginStep: boolean;\n  /** True cuando hay un paso anterior al que volver desde el paso vigente. */\n  canGoBack: boolean;\n\n  setOriginChoice: (choice: OriginChoice) => void;\n  toggleSource: (sourceId: string) => void;\n  toggleLine: (lineId: string, selected: boolean) => void;\n  setQuantity: (lineId: string, quantity: number) => void;\n  setDefault: (key: string, value: unknown) => void;\n  setHeaderValue: (key: string, value: unknown) => void;\n\n  next: () => void;\n  back: () => void;\n  submit: () => void;\n}\n\n/**\n * useCreateFromSource — orquesta el asistente \"crear/continuar documento desde\n * origen(es)\". Estado plano (sin React Query) para no exigir un\n * `QueryClientProvider` alrededor del flujo core de MasterDocument, igual que\n * `useCrossing`. Los datos se obtienen vía los fetchers inyectados en el adapter.\n */\nexport function useCreateFromSource(opts: UseCreateFromSourceOptions): UseCreateFromSourceResult {\n  const {\n    open, mode, config, adapter, documentId, operationCenterId, lockedThirdPartyId,\n    userPermissions, onCreated, onAppended, onFreeCapture,\n  } = opts;\n\n  const { t } = useMasterDocumentTranslation();\n  const i18n = config.i18n;\n  const pendingField = config.lineSelection.pendingField ?? 'quantityPending';\n\n  const canMultiSelect = useMemo(() => {\n    const perm = config.multiSelect?.permission;\n    if (!config.multiSelect) return false;\n    if (!perm) return true;\n    return userPermissions == null || userPermissions.includes(perm);\n  }, [config.multiSelect, userPermissions]);\n\n  const canFreeCapture = useMemo(() => {\n    const perm = config.allowFreeCapture?.permission;\n    if (!perm) return false;\n    return userPermissions == null || userPermissions.includes(perm);\n  }, [config.allowFreeCapture, userPermissions]);\n\n  const canSeeFinancial = useMemo(() => {\n    const perm = config.lineSelection.financialPermission;\n    if (!perm) return true;\n    return userPermissions == null || userPermissions.includes(perm);\n  }, [config.lineSelection.financialPermission, userPermissions]);\n\n  const hasOriginStep = mode === 'create' && !!config.allowFreeCapture;\n  const hasConfirmStep = !!config.confirmationStep?.enabled;\n\n  // ── State ───────────────────────────────────────────────\n  const [step, setStep] = useState<CreateFromSourceStep>('sources');\n  const [originChoice, setOriginChoiceState] = useState<OriginChoice | null>(null);\n\n  const [candidates, setCandidates] = useState<AvailableSourceItem[]>([]);\n  const [candidatesLoading, setCandidatesLoading] = useState(false);\n  const [candidatesError, setCandidatesError] = useState<string | undefined>();\n  const [selectedSourceIds, setSelectedSourceIds] = useState<string[]>([]);\n\n  const [pendingLines, setPendingLines] = useState<PendingSourceLine[]>([]);\n  const [linesLoading, setLinesLoading] = useState(false);\n  const [linesError, setLinesError] = useState<string | undefined>();\n  const [selectedLineIds, setSelectedLineIds] = useState<string[]>([]);\n  const [quantities, setQuantities] = useState<Record<string, number>>({});\n  const [lineErrors, setLineErrors] = useState<Record<string, string>>({});\n\n  const [defaults, setDefaults] = useState<Record<string, unknown>>({});\n  const [headerValues, setHeaderValues] = useState<Record<string, unknown>>({});\n  const [selectOptions, setSelectOptions] = useState<Record<string, Array<{ label: string; value: string }>>>({});\n\n  const [submitting, setSubmitting] = useState(false);\n  const [submitError, setSubmitError] = useState<string | undefined>();\n\n  // ── Reset al abrir/cerrar ────────────────────────────────\n  useEffect(() => {\n    if (!open) return;\n    setStep(hasOriginStep ? 'origin' : 'sources');\n    setOriginChoiceState(null);\n    setSelectedSourceIds([]);\n    setPendingLines([]);\n    setLinesError(undefined);\n    setSelectedLineIds([]);\n    setQuantities({});\n    setLineErrors({});\n    setDefaults({});\n    setHeaderValues({});\n    setSubmitError(undefined);\n  }, [open, hasOriginStep]);\n\n  // ── Fetch candidatos al entrar al paso 'sources' ─────────\n  useEffect(() => {\n    if (!open || step !== 'sources' || !adapter.fetchAvailableSources) return;\n    let cancelled = false;\n    setCandidatesLoading(true);\n    setCandidatesError(undefined);\n    adapter\n      .fetchAvailableSources({\n        childClass: config.childClass,\n        thirdPartyId: lockedThirdPartyId,\n        operationCenterId,\n        states: config.eligibleSourceStates,\n      })\n      .then((items) => { if (!cancelled) setCandidates(items ?? []); })\n      .catch((err) => { if (!cancelled) setCandidatesError(err instanceof Error ? err.message : String(err)); })\n      .finally(() => { if (!cancelled) setCandidatesLoading(false); });\n    return () => { cancelled = true; };\n  }, [open, step, adapter, config.childClass, config.eligibleSourceStates, lockedThirdPartyId, operationCenterId]);\n\n  // ── Carga opciones de catálogo para defaultsStep ─────────\n  useEffect(() => {\n    if (!open || !config.defaultsStep || !adapter.getSelectOptions) return;\n    let cancelled = false;\n    const entities = config.defaultsStep.fields\n      .filter((f) => f.type === 'select' && f.optionsEntity)\n      .map((f) => f.optionsEntity!);\n    entities.forEach((entity) => {\n      adapter\n        .getSelectOptions!(entity, undefined, operationCenterId)\n        .then((opts) => { if (!cancelled) setSelectOptions((prev) => ({ ...prev, [entity]: opts })); })\n        .catch(() => {});\n    });\n    return () => { cancelled = true; };\n  }, [open, config.defaultsStep, adapter, operationCenterId]);\n\n  // ── Compatibilidad multi-origen ──────────────────────────\n  const incompatibleReasons = useMemo<Record<string, string>>(() => {\n    const keys = config.compatibilityKeys ?? [];\n    if (selectedSourceIds.length === 0 || keys.length === 0) return {};\n    const anchor = candidates.find((c) => c.documentId === selectedSourceIds[0]);\n    if (!anchor) return {};\n    const result: Record<string, string> = {};\n    for (const cand of candidates) {\n      if (cand.documentId === anchor.documentId) continue;\n      const diffs = keys.filter((k) => readCompatKey(cand, k) !== readCompatKey(anchor, k));\n      if (diffs.length > 0) {\n        const tpl =\n          i18n?.incompatibleReason ?? t('master_document.createFromSource.incompatibleReason');\n        result[cand.documentId] = tpl.replaceAll('{keys}', diffs.join(', '));\n      }\n    }\n    return result;\n  }, [candidates, selectedSourceIds, config.compatibilityKeys, i18n, t]);\n\n  // ── Handlers ─────────────────────────────────────────────\n  const setOriginChoice = useCallback((choice: OriginChoice) => {\n    setOriginChoiceState(choice);\n    if (choice === 'free') {\n      if (config.allowFreeCapture) onFreeCapture?.(config.allowFreeCapture.route);\n    } else {\n      setStep('sources');\n    }\n  }, [config.allowFreeCapture, onFreeCapture]);\n\n  const toggleSource = useCallback((sourceId: string) => {\n    if (incompatibleReasons[sourceId]) return;\n    setSelectedSourceIds((prev) => {\n      if (prev.includes(sourceId)) return prev.filter((x) => x !== sourceId);\n      // Sin multi-selección: reemplaza. Con multi: respeta maxSources.\n      if (!canMultiSelect) return [sourceId];\n      const max = config.multiSelect?.maxSources;\n      if (max != null && prev.length >= max) return prev;\n      return [...prev, sourceId];\n    });\n  }, [canMultiSelect, config.multiSelect, incompatibleReasons]);\n\n  const toggleLine = useCallback((lineId: string, selected: boolean) => {\n    setSelectedLineIds((prev) => (selected ? [...prev.filter((x) => x !== lineId), lineId] : prev.filter((x) => x !== lineId)));\n    if (selected) {\n      // Default de cantidad = pendiente.\n      const line = pendingLines.find((l) => l.lineId === lineId);\n      const pending = line ? Number((line as unknown as Record<string, unknown>)[pendingField] ?? line.quantityPending) : 0;\n      setQuantities((prev) => ({ ...prev, [lineId]: prev[lineId] ?? pending }));\n      setLineErrors((prev) => {\n        const next = { ...prev };\n        const err = validateQuantity(pending, pending, line?.unitOfMeasure, i18n, t);\n        if (err) next[lineId] = err; else delete next[lineId];\n        return next;\n      });\n    } else {\n      setLineErrors((prev) => { const next = { ...prev }; delete next[lineId]; return next; });\n    }\n  }, [pendingLines, pendingField, i18n, t]);\n\n  const setQuantity = useCallback((lineId: string, quantity: number) => {\n    setQuantities((prev) => ({ ...prev, [lineId]: quantity }));\n    const line = pendingLines.find((l) => l.lineId === lineId);\n    const pending = line ? Number((line as unknown as Record<string, unknown>)[pendingField] ?? line.quantityPending) : 0;\n    setLineErrors((prev) => {\n      const next = { ...prev };\n      const err = validateQuantity(quantity, pending, line?.unitOfMeasure, i18n, t);\n      if (err) next[lineId] = err; else delete next[lineId];\n      return next;\n    });\n  }, [pendingLines, pendingField, i18n, t]);\n\n  const setDefault = useCallback((key: string, value: unknown) => {\n    setDefaults((prev) => ({ ...prev, [key]: value }));\n  }, []);\n\n  const setHeaderValue = useCallback((key: string, value: unknown) => {\n    setHeaderValues((prev) => ({ ...prev, [key]: value }));\n  }, []);\n\n  // ── Fetch de líneas al pasar a 'lines' ───────────────────\n  const loadLines = useCallback(() => {\n    if (!adapter.fetchPendingLines || selectedSourceIds.length === 0) return;\n    let cancelled = false;\n    setLinesLoading(true);\n    setLinesError(undefined);\n    adapter\n      .fetchPendingLines({ childClass: config.childClass, sourceIds: selectedSourceIds })\n      .then((lines) => { if (!cancelled) setPendingLines(lines ?? []); })\n      .catch((err) => { if (!cancelled) setLinesError(err instanceof Error ? err.message : String(err)); })\n      .finally(() => { if (!cancelled) setLinesLoading(false); });\n    return () => { cancelled = true; };\n  }, [adapter, config.childClass, selectedSourceIds]);\n\n  // ── Navegación ───────────────────────────────────────────\n  const canAdvance = useMemo(() => {\n    if (step === 'origin') return originChoice === 'source';\n    if (step === 'sources') return selectedSourceIds.length > 0;\n    if (step === 'lines') {\n      return selectedLineIds.length > 0 && selectedLineIds.every((id) => !lineErrors[id] && quantities[id] > 0);\n    }\n    return true;\n  }, [step, originChoice, selectedSourceIds, selectedLineIds, lineErrors, quantities]);\n\n  const buildSources = useCallback((): CreateFromSourceSource[] => {\n    const byDoc = new Map<string, CreateFromSourceSource>();\n    for (const lineId of selectedLineIds) {\n      const line = pendingLines.find((l) => l.lineId === lineId);\n      if (!line) continue;\n      if (!byDoc.has(line.documentId)) byDoc.set(line.documentId, { documentId: line.documentId, lines: [] });\n      byDoc.get(line.documentId)!.lines.push({ sourceLineId: line.lineId, quantityToCross: quantities[lineId] });\n    }\n    return [...byDoc.values()];\n  }, [selectedLineIds, pendingLines, quantities]);\n\n  const submit = useCallback(async () => {\n    if (submitting) return;\n    setSubmitting(true);\n    setSubmitError(undefined);\n    try {\n      const sources = buildSources();\n      if (mode === 'create') {\n        if (!adapter.createFromSource) throw new Error('adapter.createFromSource no implementado');\n        const anchor = candidates.find((c) => c.documentId === selectedSourceIds[0]);\n        const result = await adapter.createFromSource({\n          childClass: config.childClass,\n          header: {\n            ...headerValues,                                     // campos createHeaderFields\n            operationCenterId,\n            // alias nombrados (retrocompatibilidad de contrato):\n            referenceNumber: (headerValues.referenceNumber as string) || undefined,\n            notes: (headerValues.notes as string) || undefined,\n            thirdPartyId: anchor?.thirdPartyId,\n          },\n          defaults: Object.keys(defaults).length ? defaults : undefined,\n          sources,\n        });\n        onCreated?.(result.documentId);\n      } else {\n        if (!adapter.appendFromSource || !documentId) throw new Error('adapter.appendFromSource/documentId no disponibles');\n        const result = await adapter.appendFromSource(documentId, {\n          defaults: Object.keys(defaults).length ? defaults : undefined,\n          sources,\n        });\n        onAppended?.(result.addedLineIds ?? []);\n      }\n    } catch (err) {\n      setSubmitError(err instanceof Error ? err.message : String(err));\n    } finally {\n      setSubmitting(false);\n    }\n  }, [\n    submitting, buildSources, mode, adapter, candidates, selectedSourceIds, config.childClass,\n    operationCenterId, headerValues, defaults, documentId, onCreated, onAppended,\n  ]);\n\n  const next = useCallback(() => {\n    if (!canAdvance) return;\n    if (step === 'origin') { setStep('sources'); return; }\n    if (step === 'sources') { setStep('lines'); loadLines(); return; }\n    if (step === 'lines') {\n      if (hasConfirmStep) setStep('confirm');\n      else void submit();\n      return;\n    }\n    if (step === 'confirm') { void submit(); }\n  }, [canAdvance, step, hasConfirmStep, loadLines, submit]);\n\n  const back = useCallback(() => {\n    if (step === 'confirm') { setStep('lines'); return; }\n    if (step === 'lines') { setStep('sources'); return; }\n    if (step === 'sources' && hasOriginStep) { setStep('origin'); setSelectedSourceIds([]); return; }\n  }, [step, hasOriginStep]);\n\n  return {\n    step, originChoice,\n    candidates, candidatesLoading, candidatesError, selectedSourceIds, incompatibleReasons,\n    pendingLines, linesLoading, linesError, selectedLineIds, quantities, lineErrors,\n    defaults, headerValues, selectOptions,\n    submitting, submitError,\n    canMultiSelect, canFreeCapture, canSeeFinancial,\n    canAdvance, hasConfirmStep, hasOriginStep,\n    canGoBack: step === 'confirm' || step === 'lines' || (step === 'sources' && hasOriginStep),\n    setOriginChoice, toggleSource, toggleLine, setQuantity, setDefault, setHeaderValue,\n    next, back, submit,\n  };\n}\n","import { clsx } from 'clsx';\nimport { XMarkIcon } from '@heroicons/react/24/outline';\nimport type { CreateFromSourceTemplateConfig, CreateFromSourceLineColumn, CreateFromSourceField } from './template/MasterDocumentTemplate.types';\nimport type { IMasterDocumentAdapter, PendingSourceLine } from './adapter/MasterDocumentAdapter.types';\nimport {\n  useCreateFromSource,\n  type CreateFromSourceMode,\n} from './smart/useCreateFromSource';\nimport { Loading } from './components/loading';\nimport { useMasterDocumentTranslation } from './i18n';\n\nexport interface CreateFromSourceModalProps {\n  open: boolean;\n  mode: CreateFromSourceMode;\n  config: CreateFromSourceTemplateConfig;\n  adapter: IMasterDocumentAdapter;\n  /** Requerido en modo `append`. */\n  documentId?: string;\n  operationCenterId?: string;\n  /** Tercero fijado del header (modo `append`); filtra orígenes y llega read-only. */\n  lockedThirdPartyId?: string;\n  userPermissions?: string[] | null;\n  formatCurrency?: (value: number) => string;\n  formatNumber?: (value: number) => string;\n  onClose: () => void;\n  onCreated?: (documentId: string) => void;\n  onAppended?: (addedLineIds: string[]) => void;\n  onFreeCapture?: (route: string) => void;\n}\n\nconst OVERLAY_CLASS = 'fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]';\nconst PANEL_CLASS = clsx(\n  'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n  'w-[calc(100%-32px)] max-w-[860px] max-h-[calc(100vh-64px)] flex flex-col',\n  'bg-bg-primary rounded-2xl',\n  'shadow-lg animate-[fadeIn_150ms_ease-out]',\n  'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n);\nconst HEADER_CELL = 'px-3 py-2 text-xs font-bold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary';\nconst CELL = 'px-3 py-2 text-sm text-content-primary dark:text-dark-content-primary align-top';\nconst LABEL_CLASS = 'block text-sm font-semibold text-content-primary dark:text-dark-content-primary mb-1';\nconst INPUT_CLASS = clsx(\n  'w-full rounded-lg px-3 py-2 text-sm',\n  'border border-border-primary bg-bg-primary text-content-primary',\n  'placeholder:text-content-tertiary transition-colors duration-150',\n  'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n  'dark:bg-dark-bg-primary dark:border-dark-border-primary dark:text-dark-content-primary',\n  'dark:placeholder:text-dark-content-secondary dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n);\n\nfunction readCell(line: PendingSourceLine, key: string): unknown {\n  if (key in line) return (line as unknown as Record<string, unknown>)[key];\n  return line.extra?.[key];\n}\n\nexport function CreateFromSourceModal(props: CreateFromSourceModalProps) {\n  const { open, config, formatCurrency, formatNumber, onClose } = props;\n  const { t } = useMasterDocumentTranslation();\n\n  const s = useCreateFromSource({\n    open: props.open,\n    mode: props.mode,\n    config: props.config,\n    adapter: props.adapter,\n    documentId: props.documentId,\n    operationCenterId: props.operationCenterId,\n    lockedThirdPartyId: props.lockedThirdPartyId,\n    userPermissions: props.userPermissions,\n    onCreated: props.onCreated,\n    onAppended: props.onAppended,\n    onFreeCapture: props.onFreeCapture,\n  });\n\n  if (!open) return null;\n\n  const i18n = config.i18n;\n  const fmtNum = (v: number | undefined): string => (v == null ? '—' : formatNumber ? formatNumber(v) : String(v));\n  const fmtCur = (v: number | undefined): string => (v == null ? '—' : formatCurrency ? formatCurrency(v) : String(v));\n\n  const visibleColumns = config.lineSelection.columns.filter((c) => !c.financial || s.canSeeFinancial);\n\n  const title = (() => {\n    switch (s.step) {\n      case 'origin': return i18n?.originSelectorTitle ?? t('master_document.createFromSource.originSelectorTitle');\n      case 'sources': return i18n?.step1Title ?? t('master_document.createFromSource.step1Title');\n      case 'lines': return i18n?.step2Title ?? t('master_document.createFromSource.step2Title');\n      case 'confirm': return i18n?.confirmTitle ?? t('master_document.chrome.confirm');\n    }\n  })();\n\n  function renderColumnCell(line: PendingSourceLine, col: CreateFromSourceLineColumn) {\n    const raw = readCell(line, col.key);\n    let text: string;\n    if (raw == null) text = '—';\n    else if (col.format === 'currency') text = fmtCur(Number(raw));\n    else if (col.format === 'number') text = fmtNum(Number(raw));\n    else text = String(raw);\n    return (\n      <td\n        key={col.key}\n        className={clsx(CELL, col.align === 'right' && 'text-right tabular-nums', col.align === 'center' && 'text-center', col.mono && 'font-mono')}\n      >\n        {text}\n      </td>\n    );\n  }\n\n  // Renderiza un campo de formulario config-driven (defaultsStep o createHeaderFields).\n  function renderField(field: CreateFromSourceField, value: unknown, onChange: (v: unknown) => void, idPrefix: string) {\n    const id = `${idPrefix}-${field.key}`;\n    const options = field.optionsEntity\n      ? (s.selectOptions[field.optionsEntity] ?? field.options ?? [])\n      : (field.options ?? []);\n    return (\n      <div key={field.key}>\n        <label htmlFor={id} className={LABEL_CLASS}>\n          {field.label}\n          {field.required && <span className=\"ml-0.5 text-red-600 dark:text-red-400\" aria-hidden=\"true\"> *</span>}\n        </label>\n        {field.type === 'select' ? (\n          <select id={id} value={String(value ?? '')} onChange={(e) => onChange(e.target.value)} className={INPUT_CLASS}>\n            <option value=\"\">{field.placeholder ?? '—'}</option>\n            {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}\n          </select>\n        ) : (\n          <input\n            id={id}\n            type={field.type}\n            value={String(value ?? '')}\n            placeholder={field.placeholder}\n            onChange={(e) => onChange(e.target.value)}\n            className={INPUT_CLASS}\n          />\n        )}\n      </div>\n    );\n  }\n\n  const headerFields = config.createHeaderFields ?? [];\n  const showFormBlock = !!config.defaultsStep || (props.mode === 'create' && headerFields.length > 0);\n\n  return (\n    <>\n      <div className={OVERLAY_CLASS} aria-hidden=\"true\" />\n      <div className={PANEL_CLASS} role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"cfs-modal-title\">\n        {/* Header */}\n        <div className=\"flex items-start justify-between px-6 pt-5 pb-3 border-b border-border-primary dark:border-dark-border-primary\">\n          <h2 id=\"cfs-modal-title\" className=\"text-base font-bold text-content-primary dark:text-dark-content-primary pr-6\">\n            {title}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"p-1 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 dark:hover:bg-dark-bg-secondary\"\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          </button>\n        </div>\n\n        {/* Body */}\n        <div className=\"flex-1 overflow-y-auto px-6 py-4\">\n          {/* Paso 0 — selector de origen */}\n          {s.step === 'origin' && (\n            <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-4\">\n              <button\n                type=\"button\"\n                onClick={() => s.setOriginChoice('source')}\n                className={clsx(\n                  'text-left rounded-xl border p-4 transition-all duration-150',\n                  'border-border-primary hover:border-primary-custom-400 hover:bg-background-secondary',\n                  'dark:border-dark-border-primary dark:hover:bg-dark-bg-secondary',\n                )}\n              >\n                <div className=\"font-semibold text-content-primary dark:text-dark-content-primary\">\n                  {i18n?.fromSourceOption ?? t('master_document.createFromSource.fromSourceOption')}\n                </div>\n              </button>\n              <button\n                type=\"button\"\n                disabled={!s.canFreeCapture}\n                onClick={() => s.setOriginChoice('free')}\n                className={clsx(\n                  'text-left rounded-xl border p-4 transition-all duration-150',\n                  'border-border-primary hover:border-primary-custom-400 hover:bg-background-secondary',\n                  'dark:border-dark-border-primary dark:hover:bg-dark-bg-secondary',\n                  !s.canFreeCapture && 'opacity-50 cursor-not-allowed',\n                )}\n              >\n                <div className=\"font-semibold text-content-primary dark:text-dark-content-primary\">\n                  {i18n?.freeCaptureOption ?? t('master_document.createFromSource.freeCaptureOption')}\n                </div>\n              </button>\n            </div>\n          )}\n\n          {/* Paso 1 — selección de orígenes */}\n          {s.step === 'sources' && (\n            <>\n              {s.candidatesLoading && (\n                <Loading\n                  size=\"md\"\n                  label={i18n?.loadingSources ?? t('master_document.createFromSource.loadingSources')}\n                />\n              )}\n              {!s.candidatesLoading && s.candidatesError && (\n                <div className=\"bg-red-50 border border-red-200 rounded-lg px-3 py-2 text-sm text-red-700 dark:bg-red-950/20 dark:border-red-800 dark:text-red-300\" role=\"alert\">\n                  {s.candidatesError}\n                </div>\n              )}\n              {!s.candidatesLoading && !s.candidatesError && s.candidates.length === 0 && (\n                <div className=\"py-8 px-4 text-center text-sm text-content-secondary dark:text-dark-content-secondary border border-dashed border-border-primary dark:border-dark-border-primary rounded-lg\">\n                  {i18n?.emptyState ?? t('master_document.createFromSource.emptyState')}\n                </div>\n              )}\n              {!s.candidatesLoading && s.candidates.length > 0 && (\n                <div className=\"overflow-x-auto\">\n                  <table className=\"w-full border-collapse\">\n                    <thead>\n                      <tr className=\"border-b border-border-primary dark:border-dark-border-primary\">\n                        <th className={clsx(HEADER_CELL, 'w-11')} aria-label={t('master_document.crossing.selectRow')} />\n                        <th className={clsx(HEADER_CELL, 'text-left')}>{i18n?.sourceColumns?.document ?? t('master_document.createFromSource.columns.document')}</th>\n                        <th className={clsx(HEADER_CELL, 'text-left')}>{i18n?.sourceColumns?.thirdParty ?? t('master_document.createFromSource.columns.thirdParty')}</th>\n                        <th className={clsx(HEADER_CELL, 'text-left')}>{i18n?.sourceColumns?.date ?? t('master_document.createFromSource.columns.date')}</th>\n                        <th className={clsx(HEADER_CELL, 'text-left')}>{i18n?.sourceColumns?.state ?? t('master_document.createFromSource.columns.state')}</th>\n                        <th className={clsx(HEADER_CELL, 'text-right')}>{i18n?.sourceColumns?.total ?? t('master_document.createFromSource.columns.total')}</th>\n                      </tr>\n                    </thead>\n                    <tbody>\n                      {s.candidates.map((c) => {\n                        const reason = s.incompatibleReasons[c.documentId];\n                        const disabled = !!reason;\n                        const selected = s.selectedSourceIds.includes(c.documentId);\n                        return (\n                          <tr\n                            key={c.documentId}\n                            className={clsx('border-b border-border-primary/60 dark:border-dark-border-primary/60', disabled && 'opacity-50')}\n                            title={reason}\n                          >\n                            <td className={clsx(CELL, 'text-center')}>\n                              <input\n                                type=\"checkbox\"\n                                checked={selected}\n                                disabled={disabled}\n                                onChange={() => s.toggleSource(c.documentId)}\n                                className={clsx('w-4 h-4 rounded border-border-primary accent-primary-custom-600', disabled && 'cursor-not-allowed')}\n                                aria-label={t('master_document.crossing.pending.selectDocumentAria', { document: c.documentNumber })}\n                              />\n                            </td>\n                            <td className={clsx(CELL, 'whitespace-nowrap font-medium')}>{c.documentNumber}</td>\n                            <td className={CELL}>{c.thirdPartyName ?? '—'}</td>\n                            <td className={clsx(CELL, 'whitespace-nowrap')}>{c.documentDate ?? '—'}</td>\n                            <td className={CELL}>{c.state ?? '—'}</td>\n                            <td className={clsx(CELL, 'text-right whitespace-nowrap tabular-nums')}>{fmtCur(c.netTotal)}</td>\n                          </tr>\n                        );\n                      })}\n                    </tbody>\n                  </table>\n                  {!s.canMultiSelect && (\n                    <p className=\"mt-2 text-xs text-content-secondary dark:text-dark-content-secondary\">\n                      {i18n?.singleSelectHint ?? t('master_document.createFromSource.singleSelectHint')}\n                    </p>\n                  )}\n                </div>\n              )}\n            </>\n          )}\n\n          {/* Paso 2 — líneas + datos por defecto */}\n          {s.step === 'lines' && (\n            <>\n              {s.linesLoading && (\n                <Loading\n                  size=\"md\"\n                  label={i18n?.loadingLines ?? t('master_document.createFromSource.loadingLines')}\n                />\n              )}\n              {!s.linesLoading && s.linesError && (\n                <div className=\"bg-red-50 border border-red-200 rounded-lg px-3 py-2 text-sm text-red-700 dark:bg-red-950/20 dark:border-red-800 dark:text-red-300 mb-3\" role=\"alert\">\n                  {s.linesError}\n                </div>\n              )}\n              {!s.linesLoading && !s.linesError && s.pendingLines.length === 0 && (\n                <div className=\"py-8 px-4 text-center text-sm text-content-secondary dark:text-dark-content-secondary border border-dashed border-border-primary dark:border-dark-border-primary rounded-lg\">\n                  {i18n?.emptyLines\n                    ?? t('master_document.createFromSource.emptyLines', {\n                      count: s.selectedSourceIds.length,\n                    })}\n                </div>\n              )}\n              {!s.linesLoading && s.pendingLines.length > 0 && (\n                <div className=\"overflow-x-auto\">\n                  <table className=\"w-full border-collapse\">\n                    <thead>\n                      <tr className=\"border-b border-border-primary dark:border-dark-border-primary\">\n                        <th className={clsx(HEADER_CELL, 'w-11')} aria-label={t('master_document.crossing.selectRow')} />\n                        {visibleColumns.map((col) => (\n                          <th key={col.key} className={clsx(HEADER_CELL, col.align === 'right' ? 'text-right' : col.align === 'center' ? 'text-center' : 'text-left')}>\n                            {col.header}\n                          </th>\n                        ))}\n                        <th className={clsx(HEADER_CELL, 'text-left')}>{i18n?.quantityColumn ?? t('master_document.createFromSource.quantityColumn')}</th>\n                      </tr>\n                    </thead>\n                    <tbody>\n                      {s.pendingLines.map((line) => {\n                        const selected = s.selectedLineIds.includes(line.lineId);\n                        const err = s.lineErrors[line.lineId];\n                        const qty = s.quantities[line.lineId];\n                        const pending = Number(readCell(line, config.lineSelection.pendingField ?? 'quantityPending') ?? line.quantityPending);\n                        return (\n                          <tr key={line.lineId} className=\"border-b border-border-primary/60 dark:border-dark-border-primary/60\">\n                            <td className={clsx(CELL, 'text-center')}>\n                              <input\n                                type=\"checkbox\"\n                                checked={selected}\n                                onChange={(e) => s.toggleLine(line.lineId, e.target.checked)}\n                                className=\"w-4 h-4 rounded border-border-primary accent-primary-custom-600\"\n                                aria-label={t('master_document.crossing.pending.selectLineAria', { item: line.itemCode ?? line.lineId })}\n                              />\n                            </td>\n                            {visibleColumns.map((col) => renderColumnCell(line, col))}\n                            <td className={CELL}>\n                              <input\n                                type=\"number\"\n                                inputMode=\"decimal\"\n                                min={0}\n                                max={pending}\n                                value={selected && qty != null ? qty : ''}\n                                disabled={!selected}\n                                onChange={(e) => s.setQuantity(line.lineId, e.target.value === '' ? NaN : Number(e.target.value))}\n                                placeholder={selected ? fmtNum(pending) : ''}\n                                aria-invalid={err ? true : undefined}\n                                className={clsx(\n                                  'w-28 px-2 py-1 rounded-md text-sm tabular-nums border bg-bg-primary dark:bg-dark-bg-primary',\n                                  'text-content-primary dark:text-dark-content-primary',\n                                  'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 dark:focus:ring-dark-border-custom',\n                                  err ? 'border-red-500 dark:border-red-400' : 'border-border-primary dark:border-dark-border-primary',\n                                  !selected && 'opacity-50 cursor-not-allowed',\n                                )}\n                              />\n                              {err && <p className=\"mt-1 text-xs text-red-600 dark:text-red-400\">{err}</p>}\n                            </td>\n                          </tr>\n                        );\n                      })}\n                    </tbody>\n                  </table>\n                </div>\n              )}\n\n              {/* Datos por defecto (por línea) + campos de header (create), config-driven */}\n              {showFormBlock && (\n                <div className=\"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3\">\n                  {config.defaultsStep?.fields.map((field) =>\n                    renderField(field, s.defaults[field.key], (v) => s.setDefault(field.key, v), 'cfs-def'),\n                  )}\n                  {props.mode === 'create' && headerFields.map((field) =>\n                    renderField(field, s.headerValues[field.key], (v) => s.setHeaderValue(field.key, v), 'cfs-hdr'),\n                  )}\n                </div>\n              )}\n            </>\n          )}\n\n          {/* Paso 3 — confirmación de efectos */}\n          {s.step === 'confirm' && (\n            <div className=\"flex flex-col gap-4\">\n              <p className=\"text-sm text-content-primary dark:text-dark-content-primary\">\n                {/* Dos contadores en una frase: cada sustantivo se pluraliza por\n                    separado y entra como {linesLabel}/{sourcesLabel}. {lines} y\n                    {sources} siguen siendo números, para no romper los overrides\n                    que el host ya tenga escritos. */}\n                {(i18n?.confirmSummary ?? t('master_document.createFromSource.confirmSummary'))\n                  .replaceAll('{lines}', String(s.selectedLineIds.length))\n                  .replaceAll('{sources}', String(s.selectedSourceIds.length))\n                  .replaceAll(\n                    '{linesLabel}',\n                    t('master_document.createFromSource.lineNoun', {\n                      count: s.selectedLineIds.length,\n                    }),\n                  )\n                  .replaceAll(\n                    '{sourcesLabel}',\n                    t('master_document.createFromSource.sourceNoun', {\n                      count: s.selectedSourceIds.length,\n                    }),\n                  )}\n              </p>\n              {(config.confirmationStep?.effects ?? []).length > 0 && (\n                <ul className=\"flex flex-col gap-2\">\n                  {config.confirmationStep!.effects!.map((eff) => (\n                    <li key={eff.key} className=\"text-sm text-content-secondary dark:text-dark-content-secondary flex flex-col\">\n                      <span className=\"font-medium text-content-primary dark:text-dark-content-primary\">{eff.label}</span>\n                      {eff.description && <span className=\"text-xs\">{eff.description}</span>}\n                    </li>\n                  ))}\n                </ul>\n              )}\n            </div>\n          )}\n\n          {s.submitError && (\n            <div className=\"mt-3 bg-red-50 border border-red-200 rounded-lg px-3 py-2 text-sm text-red-700 dark:bg-red-950/20 dark:border-red-800 dark:text-red-300\" role=\"alert\">\n              {s.submitError}\n            </div>\n          )}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-between gap-3 px-6 py-4 border-t border-border-primary dark:border-dark-border-primary\">\n          <div>\n            {s.canGoBack && (\n              <button\n                type=\"button\"\n                onClick={s.back}\n                disabled={s.submitting}\n                className=\"px-4 py-2 rounded-md text-sm font-semibold border border-border-primary text-content-tertiary hover:bg-background-secondary transition-all duration-150 dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary\"\n              >\n                {i18n?.backButton ?? t('master_document.chrome.back')}\n              </button>\n            )}\n          </div>\n          <div className=\"flex items-center gap-3\">\n            <button\n              type=\"button\"\n              onClick={onClose}\n              disabled={s.submitting}\n              className={clsx(\n                'px-4 py-2 rounded-md text-sm font-semibold border border-border-primary text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n                'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n                s.submitting && 'opacity-50 cursor-not-allowed',\n              )}\n            >\n              {i18n?.cancelButton ?? t('master_document.chrome.cancel')}\n            </button>\n            {s.step !== 'origin' && (\n              <button\n                type=\"button\"\n                onClick={s.next}\n                disabled={!s.canAdvance || s.submitting}\n                className={clsx(\n                  'flex items-center gap-2 px-5 py-2 rounded-md text-sm font-semibold transition-all duration-150',\n                  'bg-primary-inverse-background text-white hover:bg-primary-custom-700',\n                  'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n                  (!s.canAdvance || s.submitting) && 'opacity-50 cursor-not-allowed',\n                )}\n              >\n                {s.submitting && (\n                  <svg viewBox=\"0 0 20 20\" fill=\"currentColor\" aria-hidden=\"true\" className=\"w-4 h-4 animate-spin\">\n                    <path fillRule=\"evenodd\" d=\"M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.433a.75.75 0 0 0 0-1.5H3.989a.75.75 0 0 0-.75.75v4.242a.75.75 0 0 0 1.5 0v-2.43l.31.31a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm1.23-3.723a.75.75 0 0 0 .219-.53V2.929a.75.75 0 0 0-1.5 0V5.36l-.31-.31A7 7 0 0 0 3.239 8.188a.75.75 0 1 0 1.448.389A5.5 5.5 0 0 1 13.89 6.11l.311.31h-2.432a.75.75 0 0 0 0 1.5h4.243a.75.75 0 0 0 .53-.219Z\" clipRule=\"evenodd\" />\n                  </svg>\n                )}\n                {s.step === 'confirm' || (s.step === 'lines' && !s.hasConfirmStep)\n                  ? (i18n?.confirmButton ?? t('master_document.chrome.confirm'))\n                  : (i18n?.nextButton ?? t('master_document.chrome.next'))}\n              </button>\n            )}\n          </div>\n        </div>\n      </div>\n    </>\n  );\n}\n","import type { SearchRequest, SearchResponse } from '../../LookupField/services/api.types';\nimport type { DocumentHeaderData } from '../MasterDocument.types';\nimport type { MasterDocumentTemplate } from '../template/MasterDocumentTemplate.types';\nimport type { ApiService } from './ApiService.types';\nimport type {\n  IMasterDocumentAdapter,\n  DocumentState,\n  SaveResult,\n  SaveLineResult,\n  DeleteLineResult,\n  DeleteLineOptions,\n  TransitionValidationResult,\n  TransitionResult,\n  ActionResult,\n  ConflictInfo,\n  DocumentListRequest,\n  DocumentListResponse,\n  CurrencyInfo,\n  StatusHistoryEntry,\n} from './MasterDocumentAdapter.types';\nimport type { DocumentListCompany } from '../MasterDocument.types';\nimport { createCurrencyFormatter } from '../formatters';\n\n// ════════════════════════════════════════════════════════════\n// HTTP HELPERS\n// ════════════════════════════════════════════════════════════\n\nclass ApiError extends Error {\n  constructor(\n    message: string,\n    public readonly status: number,\n    public readonly body: unknown,\n  ) {\n    super(message);\n    this.name = 'ApiError';\n  }\n}\n\nasync function resolveHeaders(apiService: ApiService): Promise<Record<string, string>> {\n  const headers = await apiService.getHeaders();\n  return {\n    'Content-Type': 'application/json',\n    ...headers,\n  };\n}\n\nasync function request<T>(\n  apiService: ApiService,\n  method: string,\n  path: string,\n  body?: unknown,\n): Promise<T> {\n  const url = `${apiService.baseUrl}${path}`;\n  const headers = await resolveHeaders(apiService);\n\n  const res = await fetch(url, {\n    method,\n    headers,\n    body: body != null ? JSON.stringify(body) : undefined,\n  });\n\n  // 204 No Content\n  if (res.status === 204) return undefined as T;\n\n  const data = await res.json().catch(() => null);\n\n  if (!res.ok) {\n    // Let consumer handle error globally\n    if (apiService.onError?.(res.status, data)) {\n      throw new ApiError('Error manejado por onError', res.status, data);\n    }\n    const errorField = (data as Record<string, unknown>)?.error;\n    const msg =\n      typeof errorField === 'string'\n        ? errorField\n        : errorField && typeof errorField === 'object' && 'message' in errorField && typeof (errorField as { message: unknown }).message === 'string'\n          ? (errorField as { message: string }).message\n          : res.statusText;\n    throw new ApiError(msg, res.status, data);\n  }\n\n  return data as T;\n}\n\n// ════════════════════════════════════════════════════════════\n// FORMATTING HELPERS\n// ════════════════════════════════════════════════════════════\n\nfunction createFormatCurrency(locale: string, currency: string) {\n  // Regla única del kit: un monto entero se muestra con los decimales propios de\n  // la moneda y uno con decimales nunca los pierde (ver `createCurrencyFormatter`).\n  return createCurrencyFormatter(locale, currency);\n}\n\nfunction createFormatDate(locale: string) {\n  return (value: string) => {\n    const d = new Date(value);\n    if (Number.isNaN(d.getTime())) return value;\n    return d.toLocaleDateString(locale, { day: '2-digit', month: 'short', year: 'numeric' });\n  };\n}\n\nfunction createFormatNumber(locale: string) {\n  const fmt = new Intl.NumberFormat(locale);\n  return (value: number) => fmt.format(value);\n}\n\n// ════════════════════════════════════════════════════════════\n// FACTORY\n// ════════════════════════════════════════════════════════════\n\n/**\n * Crea un adapter por defecto que usa los endpoints estándar\n * definidos en contratos_masterdocument_api.md.\n *\n * @param apiService — Servicio HTTP con baseUrl y headers de autenticación\n * @param template — Template del tipo de documento (para extraer documentClass)\n *\n * @example\n * const adapter = createDefaultAdapter(\n *   {\n *     baseUrl: 'https://api.siesa.com/api/v1',\n *     getHeaders: () => ({\n *       'Authorization': `Bearer ${token}`,\n *       'X-Company-Id': companyId,\n *     }),\n *     locale: 'es-CO',\n *     currency: 'COP',\n *   },\n *   template,\n * );\n */\n/**\n * Crea un adapter por defecto que usa los endpoints estándar\n * definidos en contratos_masterdocument_api.md.\n *\n * Convención de rutas:\n * - Documento existente: `/documents/{id}` donde {id} es el UUID v7 (PK).\n *   No necesita documentClass porque el UUID es globalmente único.\n * - Operaciones de clase (template, creación, listado): `/documents/{documentClass}/...`\n *   Estas NO operan sobre un documento existente, necesitan la clase.\n *\n * @param apiService — Servicio HTTP con baseUrl y headers de autenticación\n * @param template — Template del tipo de documento (para extraer documentClass en operaciones de clase)\n */\nexport function createDefaultAdapter(\n  apiService: ApiService,\n  template: MasterDocumentTemplate,\n): IMasterDocumentAdapter {\n  const docClass = template.identity.documentClass;\n  const locale = apiService.locale ?? 'es-CO';\n  const currency = apiService.currency ?? 'COP';\n\n  // Rutas para operaciones sobre un documento existente (por UUID)\n  const docPath = (id: string) => `/documents/${id}`;\n\n  // Rutas para operaciones de clase (template, creación, listado)\n  const classPath = `/documents/${docClass}`;\n\n  return {\n    // ── Fetcher (LookupField / searchers) ──────────\n    fetcher: async <TRecord = Record<string, unknown>>(\n      entity: string,\n      req: SearchRequest,\n    ): Promise<SearchResponse<TRecord>> => {\n      return request<SearchResponse<TRecord>>(\n        apiService,\n        'POST',\n        `/entities/${entity}/search`,\n        req,\n      );\n    },\n\n    // ── CRUD Documento ─────────────────────────────\n    // Todas las operaciones sobre documento existente usan UUID (PK)\n    getDocument: (id: string): Promise<DocumentState> => {\n      return request<DocumentState>(apiService, 'GET', docPath(id));\n    },\n\n    saveHeader: (id: string, header: DocumentHeaderData): Promise<SaveResult> => {\n      return request<SaveResult>(apiService, 'PUT', `${docPath(id)}/header`, {\n        headerValues: header,\n      });\n    },\n\n    // El kit inyecta `_row_version` en `data` al editar una línea existente, por\n    // lo que el token de concurrencia viaja en el body sin cache del consumidor.\n    saveLine: (\n      id: string,\n      lineId: string | null,\n      data: Record<string, unknown>,\n    ): Promise<SaveLineResult> => {\n      const lid = lineId ?? '_new';\n      return request<SaveLineResult>(\n        apiService,\n        'PUT',\n        `${docPath(id)}/lines/${lid}`,\n        data,\n      );\n    },\n\n    // `options.rowVersion`/`headerRowVersion` los provee el kit desde el estado.\n    // Se envían como `_row_version` (línea) y `_rowVersion` (cabecera) en el body\n    // del DELETE para que el backend valide la concurrencia de ambos.\n    deleteLine: (id: string, lineId: string, options?: DeleteLineOptions): Promise<DeleteLineResult | void> => {\n      const body: Record<string, string> = {};\n      if (options?.rowVersion != null) body._row_version = options.rowVersion;\n      if (options?.headerRowVersion != null) body._rowVersion = options.headerRowVersion;\n      return request<DeleteLineResult | void>(\n        apiService,\n        'DELETE',\n        `${docPath(id)}/lines/${lineId}`,\n        Object.keys(body).length > 0 ? body : undefined,\n      );\n    },\n\n    // ── Transiciones de estado ─────────────────────\n    validateTransition: (\n      id: string,\n      to: string,\n    ): Promise<TransitionValidationResult> => {\n      return request<TransitionValidationResult>(\n        apiService,\n        'POST',\n        `${docPath(id)}/transitions/validate`,\n        { to },\n      );\n    },\n\n    // `serverVersion` viaja en el body como `_rowVersion` para que execute-process\n    // valide el `row_version` del header. Un desfase responde 409\n    // (`OPTIMISTIC_LOCK_VIOLATION`); `request` lo lanza y el reducer lo trata como\n    // conflicto duro. La respuesta incluye el nuevo `serverVersion` del documento.\n    executeTransition: (id: string, to: string, _docState: string, serverVersion?: string): Promise<TransitionResult> => {\n      return request<TransitionResult>(\n        apiService,\n        'POST',\n        `${docPath(id)}/transitions`,\n        serverVersion != null ? { to, _rowVersion: serverVersion } : { to },\n      );\n    },\n\n    // ── Acciones ───────────────────────────────────\n    executeAction: (\n      actionKey: string,\n      documentState: DocumentState,\n    ): Promise<ActionResult> => {\n      return request<ActionResult>(\n        apiService,\n        'POST',\n        `${docPath(documentState.documentId!)}/actions/${actionKey}`,\n      );\n    },\n\n    // ── FactBox data ───────────────────────────────\n    getFactBoxData: (\n      id: string,\n      sectionKey: string,\n    ): Promise<Record<string, unknown>> => {\n      return request<Record<string, unknown>>(\n        apiService,\n        'GET',\n        `${docPath(id)}/factbox/${sectionKey}`,\n      );\n    },\n\n    // ── Historial de transiciones (OP1) ───────────────\n    // GET /api/v1/documents/{id}/historial-estados\n    // El backend devuelve { entries: StatusHistoryEntry[] } ordenado DESC por changedAt.\n    // El adapter desempaqueta entries para que el componente reciba el array directamente.\n    getStatusHistory: async (id: string): Promise<StatusHistoryEntry[]> => {\n      const res = await request<{ entries: StatusHistoryEntry[] }>(\n        apiService,\n        'GET',\n        `${docPath(id)}/historial-estados`,\n      );\n      return res.entries ?? [];\n    },\n\n    // ── Lista de documentos (usa documentClass, no UUID) ──\n    //\n    // Este adapter es MONO-CLASE por diseño: la clase va en la ruta\n    // (`/documents/{documentClass}/list`) y sale del template, que solo declara\n    // una. Por eso `documentClasses` (el filtro multi-clase que envía\n    // `MasterDocumentPage` cuando la superficie sirve a varias) se descarta junto\n    // con `documentClass` en lugar de reenviarse: mandarlo en el body de un\n    // endpoint que ya está acotado a una clase sería un request contradictorio.\n    // Un visor compartido de varias clases necesita un adapter propio.\n    listDocuments: (req: DocumentListRequest): Promise<DocumentListResponse> => {\n      const { filters } = req;\n      // Extraer las claves reservadas de filters (no son campos de primer nivel)\n      const { documentClass: _dc, documentClasses: _dcs, operationCenterId: _co, ...cleanFilters } =\n        (filters ?? {}) as Record<string, unknown>;\n      return request<DocumentListResponse>(apiService, 'POST', `${classPath}/list`, {\n        page: req.page,\n        pageSize: req.pageSize,\n        companyId: req.companyId ?? null,\n        search: req.search ?? null,\n        stateFilter: req.stateFilter ?? null,\n        filters: Object.keys(cleanFilters).length > 0 ? cleanFilters : null,\n        orderBy: req.orderBy ?? null,\n      });\n    },\n\n    // ── Lista de compañías (GET /companies) ───────\n    listCompanies: async (): Promise<DocumentListCompany[]> => {\n      const res = await request<{ data: Record<string, unknown>[] }>(\n        apiService, 'POST', '/entities/companies/search',\n        { page: 1, pageSize: 100, fields: [] },\n      );\n      return (res.data ?? []).map((item) => ({\n        uuid: String(item.Id ?? item.id ?? ''),\n        code: String(item.code ?? item.Id ?? item.id ?? ''),\n        name: String(item.name ?? item.nombre ?? ''),\n      }));\n    },\n\n    // ── Detección de conflictos ────────────────────\n    checkConflict: (\n      id: string,\n      lastModified: string,\n    ): Promise<ConflictInfo | null> => {\n      return request<ConflictInfo | null>(\n        apiService,\n        'GET',\n        `${docPath(id)}/conflict?serverVersion=${encodeURIComponent(lastModified)}`,\n      );\n    },\n\n    // ── Aprobación ─────────────────────────────────\n    approve: (id: string): Promise<void> => {\n      return request<void>(apiService, 'POST', `${docPath(id)}/approve`);\n    },\n\n    reject: (id: string, reason?: string): Promise<void> => {\n      return request<void>(apiService, 'POST', `${docPath(id)}/reject`, { reason });\n    },\n\n    // ── Multimoneda ────────────────────────────────\n    listCurrencies: (onlyActive = true): Promise<CurrencyInfo[]> => {\n      const qs = onlyActive ? '?onlyActive=true' : '';\n      return request<CurrencyInfo[]>(apiService, 'GET', `/currencies${qs}`);\n    },\n\n    getExchangeRate: (\n      currencyCode: string,\n    ): Promise<{ rate: number; label: string }> => {\n      return request<{ rate: number; label: string }>(\n        apiService,\n        'GET',\n        `/currencies/${currencyCode}/rate`,\n      );\n    },\n\n    changeCurrency: (id: string, currencyCode: string): Promise<void> => {\n      return request<void>(\n        apiService,\n        'PUT',\n        `${docPath(id)}/currency`,\n        { currencyCode },\n      );\n    },\n\n    // ── Formateo (client-side) ─────────────────────\n    formatCurrency: createFormatCurrency(locale, currency),\n    formatDate: createFormatDate(locale),\n    formatNumber: createFormatNumber(locale),\n\n    // ── Fetcher genérico (DocumentModalList) ───────\n    genericFetch: (method: string, path: string, body?: unknown): Promise<unknown> => {\n      return request<unknown>(apiService, method, path, body);\n    },\n  };\n}\n","import type { ComponentType, SVGProps } from 'react';\nimport {\n  DocumentIcon,\n  SaveIcon,\n  CheckIcon,\n  PrintIcon,\n  DuplicateIcon,\n  XIcon,\n  PlusIcon,\n  PurchasesIcon,\n  SalesIcon,\n  InventoryIcon,\n} from '../icons';\n\nexport type IconComponent = ComponentType<SVGProps<SVGSVGElement>>;\n\nexport const DEFAULT_ICON_REGISTRY: Record<string, IconComponent> = {\n  document: DocumentIcon,\n  save: SaveIcon,\n  check: CheckIcon,\n  print: PrintIcon,\n  duplicate: DuplicateIcon,\n  x: XIcon,\n  close: XIcon,\n  plus: PlusIcon,\n  purchases: PurchasesIcon,\n  sales: SalesIcon,\n  inventory: InventoryIcon,\n};\n","import { useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react';\nimport { clsx } from 'clsx';\nimport type { PrintViewerProps } from './MasterDocumentPrinting.types';\nimport { useMasterDocumentTranslation, MASTER_DOCUMENT_TRANSLATIONS_ES } from '../i18n';\n\n// CSS scope-ado del visor: oculta el bloque gris del skeleton interno del\n// ReportViewer y centra un spinner + texto, para una espera limpia. Replica el\n// comportamiento del PrintIexModal de core.\nconst PRINT_VIEWER_CSS = `\n.sds-print-viewer { height: 100%; }\n.sds-print-viewer [data-testid=\"report-viewer-skeleton\"] { animation: none; gap: .875rem; }\n.sds-print-viewer [data-testid=\"report-viewer-skeleton\"] > div:first-child { display: none; }\n.sds-print-viewer [data-testid=\"report-viewer-skeleton\"]::before {\n  content: \"\"; width: 2.75rem; height: 2.75rem; border-radius: 9999px;\n  border: 3px solid rgb(226 232 240); border-top-color: #0e79fd;\n  animation: sds-print-spin .7s linear infinite;\n}\n.sds-print-viewer [data-testid=\"report-viewer-skeleton\"] p { font-size: .9375rem; font-weight: 500; color: rgb(71 85 105); margin: 0; }\n@keyframes sds-print-spin { to { transform: rotate(360deg); } }\n`;\n\n/**\n * Mensaje por defecto cuando la impresión no está configurada.\n *\n * Es API pública del kit (se re-exporta hasta `src/index.ts`), así que sigue siendo\n * una constante en español y no se puede resolver con un hook. Su valor se toma del\n * catálogo para no duplicar el literal; el render usa `t()` sobre la misma clave,\n * de modo que la UI sí respeta el idioma activo.\n *\n * @see MASTER_DOCUMENT_TRANSLATIONS_ES\n */\nexport const DEFAULT_NOT_CONFIGURED_MESSAGE =\n  MASTER_DOCUMENT_TRANSLATIONS_ES['master_document.document.printNotImplemented'];\n\nconst FOCUSABLE_SELECTOR = [\n  'a[href]',\n  'button:not([disabled])',\n  'textarea:not([disabled])',\n  'input:not([disabled])',\n  'select:not([disabled])',\n  '[tabindex]:not([tabindex=\"-1\"])',\n].join(',');\n\nexport interface MasterDocumentPrintModalProps {\n  isOpen: boolean;\n  title: string;\n  onClose: () => void;\n  /**\n   * `true` cuando el backend/visor está configurado (hay viewer + apiBaseUrl +\n   * reportCode resueltos). `false` ⇒ se muestra el estado \"no configurado\".\n   */\n  backendConfigured: boolean;\n  /** Mensaje del estado \"no configurado\". */\n  notConfiguredMessage?: string;\n  /** El host pasa el visor ya resuelto (componente o render-prop) más sus props. */\n  viewer?: ComponentType<PrintViewerProps>;\n  renderViewer?: (props: PrintViewerProps) => ReactNode;\n  viewerProps: PrintViewerProps;\n}\n\n/**\n * Marco del modal de vista previa de impresión, propiedad del kit. Replica el UX\n * del `PrintIexModal` de core (overlay, maximizar/restaurar, cerrar) y añade\n * accesibilidad que core no tenía: `role=\"dialog\"` + `aria-modal`, cierre con\n * `Esc`, focus trap y restauración de foco al disparador.\n *\n * El **contenido** (visor de reportes) lo aporta el host por inyección; el kit\n * nunca importa `@siesateams/format-designer`.\n */\nexport function MasterDocumentPrintModal({\n  isOpen,\n  title,\n  onClose,\n  backendConfigured,\n  notConfiguredMessage,\n  viewer: Viewer,\n  renderViewer,\n  viewerProps,\n}: MasterDocumentPrintModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [isMaximized, setIsMaximized] = useState(false);\n  const dialogRef = useRef<HTMLDivElement>(null);\n  const triggerRef = useRef<HTMLElement | null>(null);\n\n  // Reinicia el tamaño al cerrar para que la próxima apertura sea consistente.\n  useEffect(() => {\n    if (!isOpen) setIsMaximized(false);\n  }, [isOpen]);\n\n  // Esc + focus trap + restauración de foco.\n  useEffect(() => {\n    if (!isOpen) return;\n    triggerRef.current = document.activeElement as HTMLElement | null;\n    dialogRef.current?.focus();\n\n    function onKeyDown(e: KeyboardEvent) {\n      if (e.key === 'Escape') {\n        e.stopPropagation();\n        onClose();\n        return;\n      }\n      if (e.key !== 'Tab' || !dialogRef.current) return;\n      const focusables = Array.from(\n        dialogRef.current.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),\n      ).filter((el) => el.offsetParent !== null);\n      if (focusables.length === 0) {\n        e.preventDefault();\n        dialogRef.current.focus();\n        return;\n      }\n      const first = focusables[0];\n      const last = focusables[focusables.length - 1];\n      const active = document.activeElement;\n      if (e.shiftKey && (active === first || active === dialogRef.current)) {\n        e.preventDefault();\n        last.focus();\n      } else if (!e.shiftKey && active === last) {\n        e.preventDefault();\n        first.focus();\n      }\n    }\n\n    document.addEventListener('keydown', onKeyDown, true);\n    return () => {\n      document.removeEventListener('keydown', onKeyDown, true);\n      triggerRef.current?.focus?.();\n    };\n  }, [isOpen, onClose]);\n\n  if (!isOpen) return null;\n\n  const viewerContent: ReactNode = renderViewer\n    ? renderViewer(viewerProps)\n    : Viewer\n      ? <Viewer {...viewerProps} />\n      : null;\n\n  return (\n    <div\n      className=\"fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4\"\n      onClick={onClose}\n    >\n      <style>{PRINT_VIEWER_CSS}</style>\n      <div\n        ref={dialogRef}\n        tabIndex={-1}\n        className={clsx(\n          'flex flex-col overflow-hidden rounded-lg shadow-xl outline-none',\n          'bg-bg-primary dark:bg-dark-bg-primary',\n          isMaximized ? 'h-[98vh] w-[98vw] max-w-none' : 'h-[90vh] w-full max-w-4xl',\n        )}\n        onClick={(e) => e.stopPropagation()}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={title}\n      >\n        {/* Cabecera */}\n        <div className=\"flex items-center justify-between border-b border-border-secondary px-4 py-3 dark:border-dark-border-primary\">\n          <h2 className=\"text-lg font-semibold text-content-primary dark:text-dark-content-primary\">\n            {title}\n          </h2>\n          <div className=\"flex items-center gap-1\">\n            {backendConfigured && (\n              <button\n                type=\"button\"\n                className=\"rounded p-1 text-content-tertiary transition-colors hover:bg-background-secondary hover:text-content-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary dark:hover:text-dark-content-primary\"\n                onClick={() => setIsMaximized((m) => !m)}\n                aria-label={isMaximized ? t('master_document.chrome.restoreSize') : t('master_document.chrome.maximize')}\n                title={isMaximized ? t('master_document.chrome.restoreSize') : t('master_document.chrome.maximize')}\n              >\n                {isMaximized ? (\n                  <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n                    <path d=\"M9 9H5V5\" /><path d=\"M15 9h4V5\" /><path d=\"M9 15H5v4\" /><path d=\"M15 15h4v4\" />\n                  </svg>\n                ) : (\n                  <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n                    <path d=\"M15 3h6v6\" /><path d=\"M9 21H3v-6\" /><path d=\"M21 3l-7 7\" /><path d=\"M3 21l7-7\" />\n                  </svg>\n                )}\n              </button>\n            )}\n            <button\n              type=\"button\"\n              className=\"text-2xl leading-none text-content-tertiary transition-colors hover:text-content-primary dark:text-dark-content-secondary dark:hover:text-dark-content-primary\"\n              onClick={onClose}\n              aria-label={t('master_document.chrome.close')}\n            >\n              ×\n            </button>\n          </div>\n        </div>\n\n        {/* Cuerpo */}\n        {backendConfigured ? (\n          <div className=\"sds-print-viewer min-h-0 flex-1 overflow-auto bg-background-secondary dark:bg-dark-bg-secondary\">\n            {viewerContent}\n          </div>\n        ) : (\n          <div className=\"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 bg-background-secondary p-8 text-center dark:bg-dark-bg-secondary\">\n            <div className=\"flex h-12 w-12 items-center justify-center rounded-full bg-primary-100 text-primary-600 dark:bg-primary-900/30 dark:text-primary-400\">\n              <svg width=\"26\" height=\"26\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n                <path d=\"M6 9V2h12v7\" /><path d=\"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2\" /><path d=\"M6 14h12v8H6z\" />\n              </svg>\n            </div>\n            <p className=\"text-base font-medium text-content-primary dark:text-dark-content-primary\">\n              {notConfiguredMessage ?? t('master_document.document.printNotImplemented')}\n            </p>\n            {/* Subtítulo enlatado solo cuando se usa el mensaje por defecto;\n                un mensaje personalizado controla el texto completo. */}\n            {!notConfiguredMessage && (\n              <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary\">\n                {t('master_document.document.printAvailableSoon')}\n              </p>\n            )}\n            <button\n              type=\"button\"\n              className=\"mt-1 rounded-md bg-primary-inverse-background px-4 py-2 text-sm font-semibold text-primary-inverse-content transition-colors hover:bg-primary-700 dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90\"\n              onClick={onClose}\n            >\n              {t('master_document.chrome.understood')}\n            </button>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n","import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';\nimport { MasterDocumentPrintModal } from './MasterDocumentPrintModal';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport type {\n  MasterDocumentPrintApi,\n  MasterDocumentPrintConfig,\n  PrintContext,\n  PrintViewerProps,\n} from './MasterDocumentPrinting.types';\n\n// ════════════════════════════════════════════════════════════\n// CONTEXTO — null = impresión no configurada en el provider.\n// ════════════════════════════════════════════════════════════\n\nconst PrintApiContext = createContext<MasterDocumentPrintApi | null>(null);\n\n/**\n * Devuelve la API de impresión expuesta por el `MasterDocumentProvider`, o `null`\n * si no se pasó la prop `printing` (impresión no disponible → retrocompatibilidad).\n * Lo consumen `DocumentList` (vía `MasterDocumentPage`) y `SmartMasterDocument`.\n */\nexport function useMasterDocumentPrint(): MasterDocumentPrintApi | null {\n  return useContext(PrintApiContext);\n}\n\ninterface MasterDocumentPrintProviderProps {\n  printing?: MasterDocumentPrintConfig;\n  /** Etiqueta del documento (template.identity.label) para el título por defecto. */\n  documentLabel?: string;\n  children: ReactNode;\n}\n\n/**\n * Host de impresión: posee el estado `{ open, ctx }`, monta UN único\n * `MasterDocumentPrintModal`, resuelve la config (`reportCode`/`apiBaseUrl`/\n * `parameters`/…) a partir de `printing` + el `PrintContext`, y expone la API\n * imperativa por contexto. Cuando no se pasa `printing`, el contexto queda en\n * `null` y todo el subsistema de impresión queda inerte.\n */\nexport function MasterDocumentPrintProvider({\n  printing,\n  documentLabel,\n  children,\n}: MasterDocumentPrintProviderProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [state, setState] = useState<{ open: boolean; ctx: PrintContext | null }>({\n    open: false,\n    ctx: null,\n  });\n\n  // Regla (a): la acción se MUESTRA si está habilitada, el documento está\n  // guardado (tiene id) y `canPrint` no la restringe.\n  const isPrintAvailable = useCallback(\n    (ctx: PrintContext): boolean => {\n      if (!printing) return false;\n      if (printing.enabled === false) return false;\n      if (!ctx.documentId) return false;\n      return printing.canPrint?.(ctx) ?? true;\n    },\n    [printing],\n  );\n\n  const openPrint = useCallback(\n    (ctx: PrintContext) => {\n      if (!printing) return;\n      setState({ open: true, ctx });\n    },\n    [printing],\n  );\n\n  const close = useCallback(() => setState({ open: false, ctx: null }), []);\n\n  const api = useMemo<MasterDocumentPrintApi | null>(() => {\n    if (!printing) return null;\n    return {\n      openPrint,\n      isPrintAvailable,\n      label: printing.label ?? t('master_document.document.print'),\n      buttonVariant: printing.buttonVariant ?? 'ghost',\n    };\n  }, [printing, openPrint, isPrintAvailable, t]);\n\n  // Resuelve los datos del modal a partir de la config + el ctx activo.\n  const resolved = useMemo(() => {\n    if (!printing || !state.ctx) return null;\n    const ctx = state.ctx;\n    const reportId =\n      typeof printing.reportCode === 'function' ? printing.reportCode(ctx) : printing.reportCode;\n    const apiBaseUrl =\n      typeof printing.apiBaseUrl === 'function' ? printing.apiBaseUrl() : printing.apiBaseUrl;\n    const parameters = printing.buildParameters?.(ctx) ?? { id: ctx.documentId };\n\n    // Regla (b): backend configurado ⇒ hay visor + apiBaseUrl + reportCode.\n    const hasViewer = !!(printing.viewer || printing.renderViewer);\n    const backendConfigured = hasViewer && !!apiBaseUrl && !!reportId;\n\n    const defaultTitle = `Imprimir${documentLabel ? ` — ${documentLabel}` : ''}`;\n    const title = printing.title?.(ctx) ?? defaultTitle;\n\n    const viewerProps: PrintViewerProps = {\n      reportId: reportId ?? '',\n      parameters,\n      apiBaseUrl: apiBaseUrl ?? '',\n      tenantId: printing.tenantId,\n      authToken: printing.authToken,\n    };\n\n    return { title, backendConfigured, viewerProps };\n  }, [printing, state.ctx, documentLabel]);\n\n  return (\n    <PrintApiContext.Provider value={api}>\n      {children}\n      {printing && resolved && (\n        <MasterDocumentPrintModal\n          isOpen={state.open}\n          title={resolved.title}\n          onClose={close}\n          backendConfigured={resolved.backendConfigured}\n          notConfiguredMessage={printing.notConfiguredMessage}\n          viewer={printing.viewer}\n          renderViewer={printing.renderViewer}\n          viewerProps={resolved.viewerProps}\n        />\n      )}\n    </PrintApiContext.Provider>\n  );\n}\n","import { useEffect, useRef } from 'react';\nimport { clsx } from 'clsx';\nimport { AuditHistoryPanel } from '../../../audit';\nimport type { AuditHistoryProps } from '../../../audit/types/audit.types';\nimport { Button } from '../../Button/Button';\nimport { XIcon } from '../icons';\nimport { useMasterDocumentTranslation } from '../i18n';\n\nconst FOCUSABLE_SELECTOR = [\n  'a[href]',\n  'button:not([disabled])',\n  'textarea:not([disabled])',\n  'input:not([disabled])',\n  'select:not([disabled])',\n  '[tabindex]:not([tabindex=\"-1\"])',\n].join(',');\n\nexport interface MasterDocumentAuditModalProps {\n  isOpen: boolean;\n  title: string;\n  onClose: () => void;\n  /** ID de la entidad/documento cuyo historial se muestra. */\n  entityId: string;\n  /** Función de fetch del historial (del `auditHistory` del provider). */\n  fetchFn: AuditHistoryProps['fetchFn'];\n}\n\n/**\n * Marco del modal de historial de auditoría, propiedad del kit. Replica el chrome\n * y la accesibilidad del `MasterDocumentPrintModal` (overlay, cierre con Esc, focus\n * trap y restauración de foco) y monta en el cuerpo el `AuditHistoryPanel` compartido\n * de `src/audit`. No hay lógica de fetch aquí: la aporta el host vía `fetchFn`.\n */\nexport function MasterDocumentAuditModal({\n  isOpen,\n  title,\n  onClose,\n  entityId,\n  fetchFn,\n}: MasterDocumentAuditModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const dialogRef = useRef<HTMLDivElement>(null);\n  const triggerRef = useRef<HTMLElement | null>(null);\n\n  useEffect(() => {\n    if (!isOpen) return;\n    triggerRef.current = document.activeElement as HTMLElement | null;\n    dialogRef.current?.focus();\n\n    function onKeyDown(e: KeyboardEvent) {\n      if (e.key === 'Escape') {\n        e.stopPropagation();\n        onClose();\n        return;\n      }\n      if (e.key !== 'Tab' || !dialogRef.current) return;\n      const focusables = Array.from(\n        dialogRef.current.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),\n      ).filter((el) => el.offsetParent !== null);\n      if (focusables.length === 0) {\n        e.preventDefault();\n        dialogRef.current.focus();\n        return;\n      }\n      const first = focusables[0];\n      const last = focusables[focusables.length - 1];\n      const active = document.activeElement;\n      if (e.shiftKey && (active === first || active === dialogRef.current)) {\n        e.preventDefault();\n        last.focus();\n      } else if (!e.shiftKey && active === last) {\n        e.preventDefault();\n        first.focus();\n      }\n    }\n\n    document.addEventListener('keydown', onKeyDown, true);\n    return () => {\n      document.removeEventListener('keydown', onKeyDown, true);\n      triggerRef.current?.focus?.();\n    };\n  }, [isOpen, onClose]);\n\n  if (!isOpen) return null;\n\n  return (\n    <div\n      className=\"fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4\"\n      onClick={onClose}\n    >\n      <div\n        ref={dialogRef}\n        tabIndex={-1}\n        className={clsx(\n          'flex max-h-[90vh] w-full max-w-5xl flex-col overflow-hidden rounded-lg shadow-xl outline-none',\n          'bg-white dark:bg-dark-bg-primary',\n        )}\n        onClick={(e) => e.stopPropagation()}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={title}\n      >\n        {/* Cabecera — mismo estilo que el modal de creación/edición de MasterCrud\n            (título en color de marca + botón de cierre outline con icono). */}\n        <div className=\"flex flex-none items-center justify-between gap-4 px-5 pb-3 pt-5\">\n          <h2 className=\"truncate text-[16px] font-medium text-primary-600 dark:text-primary-500\">\n            {title}\n          </h2>\n          <Button\n            type=\"outline\"\n            size=\"xs\"\n            iconOnly\n            leftIcon={<XIcon className=\"h-4 w-4\" />}\n            onClick={onClose}\n            ariaLabel={t('master_document.chrome.close')}\n            className=\"flex !bg-white dark:!bg-dark-bg-primary\"\n          />\n        </div>\n\n        {/* Cuerpo — panel de historial compartido */}\n        <div className=\"min-h-0 flex-1 overflow-hidden\">\n          <AuditHistoryPanel fetchFn={fetchFn} entityId={entityId} />\n        </div>\n\n        {/* Footer — mismo botón de cierre y remate que el footer de MasterCrud. */}\n        <div className=\"relative z-[200] flex flex-none items-center justify-end gap-4 border-t border-border-primary/50 bg-white px-5 pb-5 pt-3 shadow-sm dark:border-dark-border-primary/30 dark:bg-dark-bg-primary\">\n          <Button\n            type=\"outline\"\n            size=\"l\"\n            onClick={onClose}\n            className=\"px-6 font-medium hover:bg-gray-50 dark:hover:bg-gray-800\"\n          >\n            {t('master_document.chrome.close')}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n","import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';\nimport { MasterDocumentAuditModal } from './MasterDocumentAuditModal';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport type { AuditHistoryProps } from '../../../audit/types/audit.types';\n\n/**\n * Contexto que dispara la apertura del historial de auditoría de un documento.\n * `source` distingue desde dónde se invoca (detalle vs. listado); `documentId`\n * es el id de la entidad cuyo historial se consulta.\n */\nexport interface AuditContext {\n  source: 'detail' | 'list';\n  documentId: string;\n}\n\n/**\n * API imperativa expuesta por el `MasterDocumentProvider` cuando se pasa la prop\n * `auditHistory`. La consumen `SmartMasterDocument` (barra del detalle) y, si se\n * desea, `DocumentList` (menú de fila) — igual patrón que la impresión nativa.\n */\nexport interface MasterDocumentAuditApi {\n  openAudit(ctx: AuditContext): void;\n  isAuditAvailable(ctx: AuditContext): boolean;\n  label: string;\n}\n\n// null = auditoría no configurada en el provider → subsistema inerte (retrocompat).\nconst AuditApiContext = createContext<MasterDocumentAuditApi | null>(null);\n\n/**\n * Devuelve la API de auditoría del `MasterDocumentProvider`, o `null` si no se pasó\n * la prop `auditHistory` (auditoría no disponible → retrocompatibilidad total).\n */\nexport function useMasterDocumentAudit(): MasterDocumentAuditApi | null {\n  return useContext(AuditApiContext);\n}\n\ninterface MasterDocumentAuditProviderProps {\n  /**\n   * Configuración de auditoría (opcional). Mismo contrato que consume MasterCrud.\n   * Cuando se provee y `enabled` es true, el detalle del documento muestra una\n   * acción ⏱ que abre el historial. Sin esta prop el subsistema queda inerte y el\n   * comportamiento es idéntico al actual → retrocompatibilidad total.\n   */\n  auditHistory?: AuditHistoryProps;\n  children: ReactNode;\n}\n\n/**\n * Host de auditoría: posee el estado `{ open, entityId }`, monta UN único\n * `MasterDocumentAuditModal` y expone la API imperativa por contexto. Cuando no se\n * pasa `auditHistory` (o `enabled` es false), el contexto queda en `null` y no se\n * renderiza ninguna acción ni modal.\n */\nexport function MasterDocumentAuditProvider({\n  auditHistory,\n  children,\n}: MasterDocumentAuditProviderProps) {\n  const { t } = useMasterDocumentTranslation();\n  const auditLabel = t('master_document.document.auditTitle');\n  const [state, setState] = useState<{ open: boolean; entityId: string | null }>({\n    open: false,\n    entityId: null,\n  });\n\n  // La acción se MUESTRA si está habilitada por permiso (enabled) y el documento\n  // está guardado (tiene id). Mismo criterio que la impresión.\n  const isAuditAvailable = useCallback(\n    (ctx: AuditContext): boolean => {\n      if (!auditHistory) return false;\n      if (!auditHistory.enabled) return false;\n      if (!ctx.documentId) return false;\n      return true;\n    },\n    [auditHistory],\n  );\n\n  const openAudit = useCallback(\n    (ctx: AuditContext) => {\n      if (!auditHistory || !ctx.documentId) return;\n      setState({ open: true, entityId: ctx.documentId });\n    },\n    [auditHistory],\n  );\n\n  const close = useCallback(() => setState({ open: false, entityId: null }), []);\n\n  const api = useMemo<MasterDocumentAuditApi | null>(() => {\n    if (!auditHistory) return null;\n    return { openAudit, isAuditAvailable, label: auditLabel };\n  }, [auditHistory, openAudit, isAuditAvailable, auditLabel]);\n\n  return (\n    <AuditApiContext.Provider value={api}>\n      {children}\n      {auditHistory && state.entityId && (\n        <MasterDocumentAuditModal\n          isOpen={state.open}\n          title={auditLabel}\n          onClose={close}\n          entityId={state.entityId}\n          fetchFn={auditHistory.fetchFn}\n        />\n      )}\n    </AuditApiContext.Provider>\n  );\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport type { IMasterDocumentAdapter, DocumentState } from '../adapter/MasterDocumentAdapter.types';\nimport type { ApiService } from '../adapter/ApiService.types';\nimport type { MasterDocumentTemplate } from '../template/MasterDocumentTemplate.types';\nimport { createDefaultAdapter } from '../adapter/createDefaultAdapter';\nimport { DEFAULT_ICON_REGISTRY, type IconComponent } from './iconRegistry';\nimport { LookupResolveCacheProvider } from '../LookupReadonlyValue';\nimport { MasterDocumentPrintProvider } from '../printing/MasterDocumentPrintProvider';\nimport type { MasterDocumentPrintConfig } from '../printing/MasterDocumentPrinting.types';\nimport { MasterDocumentAuditProvider } from '../audit/MasterDocumentAuditProvider';\nimport type { AuditHistoryProps } from '../../../audit/types/audit.types';\n\n// ════════════════════════════════════════════════════════════\n// FACTBOX WIDGETS — registro de widgets custom\n// ════════════════════════════════════════════════════════════\n\n/**\n * Contexto en vivo que recibe un widget FactBox custom (`type: 'custom'`)\n * cuando se registra como función. Permite acceder al estado del documento y\n * al adapter para cablear widgets que dependen de datos en runtime\n * (ej: AdvanceApplicationsPanel necesita documentId, docState, headerValues).\n */\nexport interface FactBoxWidgetRenderContext {\n  documentId: string;\n  docState: string;\n  mode: DocumentState['mode'];\n  headerValues: Record<string, unknown>;\n  /** Datos resueltos de la sección (según `dataSource`). */\n  data: Record<string, unknown>;\n  adapter: IMasterDocumentAdapter;\n  /**\n   * Resincroniza el documento contra el servidor (encabezado, líneas, totales,\n   * `row_version`). Invócalo DESPUÉS de persistir por tu cuenta: el kit solo\n   * mergea lo que guarda él, así que un widget que escribe contra su propio\n   * endpoint —cruzar una OC, aplicar un anticipo— deja la grilla de Líneas y el\n   * widget de Totales mostrando los valores previos hasta que alguien recarga la\n   * página.\n   *\n   * Es el mismo `reload` que devuelve {@link useMasterDocumentReload}: usa el\n   * hook si tu widget es un componente y prefieres no cablearlo por props.\n   */\n  reload: () => Promise<void>;\n  /**\n   * Sube tras cada mutación del kit. Úsalo como dependencia del fetch propio del\n   * widget para que su vista se reconsulte cuando el documento cambió por fuera\n   * de él —el caso típico es una grilla de cantidades pendientes que quedaría\n   * stale tras un cruce.\n   */\n  refreshToken: number;\n}\n\n/**\n * Valor registrable en `factBoxWidgets`. Puede ser un nodo estático o una\n * función que recibe el contexto en vivo del documento y retorna el nodo.\n */\nexport type FactBoxWidget = ReactNode | ((ctx: FactBoxWidgetRenderContext) => ReactNode);\n\n// ════════════════════════════════════════════════════════════\n// LINE TAB RENDERERS — pestañas de detalle Tipo 2 (FlexQuery) y Tipo 3 (Render)\n// ════════════════════════════════════════════════════════════\n\n/**\n * Renderer de una pestaña de detalle, referido por clave desde el template\n * (`layout.detail.tabs[].renderKey`).\n *\n * Mismo mecanismo que `factBoxWidgets` y por la misma razón: el componente es del\n * host —una consulta FlexQuery, un panel propio— y el template solo transporta su\n * clave. Así el kit no importa nada del host ni el host tiene que reconstruir el\n * estado del documento: lo recibe resuelto en el contexto.\n *\n * @see LineTabRenderContext - Lo que recibe el renderer\n * @see DetailTabTemplate - La declaración en el template\n */\nexport type LineTabRenderer = (\n  ctx: import('../MasterDocument.types').LineTabRenderContext,\n) => ReactNode;\n\n// ════════════════════════════════════════════════════════════\n// CONTEXTS\n// ════════════════════════════════════════════════════════════\n\nconst AdapterContext = createContext<IMasterDocumentAdapter | null>(null);\nconst TemplateContext = createContext<MasterDocumentTemplate | null>(null);\nconst IconContext = createContext<Record<string, IconComponent>>(DEFAULT_ICON_REGISTRY);\nconst FactBoxWidgetContext = createContext<Record<string, FactBoxWidget>>({});\nconst LineTabRendererContext = createContext<Record<string, LineTabRenderer>>({});\n// null = sistema de permisos no activo → mostrar y habilitar todo (fallback permisivo)\nconst PermissionsContext = createContext<string[] | null>(null);\n\n// ════════════════════════════════════════════════════════════\n// HOOKS\n// ════════════════════════════════════════════════════════════\n\nexport function useMasterDocumentAdapter(): IMasterDocumentAdapter {\n  const adapter = useContext(AdapterContext);\n  if (!adapter) {\n    throw new Error(\n      'useMasterDocumentAdapter debe usarse dentro de un <MasterDocumentProvider>',\n    );\n  }\n  return adapter;\n}\n\nexport function useMasterDocumentTemplate(): MasterDocumentTemplate {\n  const template = useContext(TemplateContext);\n  if (!template) {\n    throw new Error(\n      'useMasterDocumentTemplate debe usarse dentro de un <MasterDocumentProvider>',\n    );\n  }\n  return template;\n}\n\nexport function useIconRegistry(): Record<string, IconComponent> {\n  return useContext(IconContext);\n}\n\nexport function useFactBoxWidgets(): Record<string, FactBoxWidget> {\n  return useContext(FactBoxWidgetContext);\n}\n\n/**\n * Renderers de pestañas de detalle registrados por el host. Vacío = ninguno, y\n * entonces una pestaña Tipo 2 o Tipo 3 del template queda sin contenido: es un\n * error de cableado del consumidor, no del kit, y se avisa por consola.\n */\nexport function useLineTabRenderers(): Record<string, LineTabRenderer> {\n  return useContext(LineTabRendererContext);\n}\n\n/**\n * Retorna los permisos del usuario activo, o `null` si el sistema de permisos\n * no está configurado en el provider (fallback permisivo: todo visible y editable).\n */\nexport function useUserPermissions(): string[] | null {\n  return useContext(PermissionsContext);\n}\n\n// ════════════════════════════════════════════════════════════\n// PROVIDER PROPS — Dos modos de uso\n// ════════════════════════════════════════════════════════════\n\ninterface BaseProviderProps {\n  template: MasterDocumentTemplate;\n  icons?: Record<string, IconComponent>;\n  factBoxWidgets?: Record<string, FactBoxWidget>;\n  /**\n   * Renderers de las pestañas de detalle Tipo 2 (FlexQuery) y Tipo 3 (Render),\n   * indexados por la `renderKey` que declara `template.layout.detail.tabs`.\n   *\n   * Ausente ⇒ el documento solo puede tener pestañas de tipo `lines`, que es el\n   * comportamiento de siempre. El kit no trae ninguna consulta FlexQuery propia:\n   * ese componente vive en la app host y entra por aquí.\n   *\n   * @example\n   * ```tsx\n   * <MasterDocumentProvider\n   *   template={template}\n   *   adapter={adapter}\n   *   lineTabRenderers={{\n   *     flexQuery: (ctx) => (\n   *       <FlexQueryGrid\n   *         queryCode={ctx.flexQuery!.queryCode}\n   *         filters={ctx.filters}\n   *         refreshToken={ctx.refreshToken}\n   *         rowActions={ctx.rowActions}\n   *       />\n   *     ),\n   *   }}\n   * >\n   * ```\n   */\n  lineTabRenderers?: Record<string, LineTabRenderer>;\n  /**\n   * Permisos del usuario activo. Cada string es una clave de permiso\n   * (e.g. \"view.cedula\", \"edit.precio\").\n   *\n   * - Ausente / null → sistema de permisos no activo: todos los campos visibles y editables.\n   * - [] → sistema activo pero sin permisos: campos restringidos quedan ocultos/deshabilitados.\n   */\n  userPermissions?: string[] | null;\n  /**\n   * Configuración de impresión nativa (opcional). Cuando se provee, el kit\n   * muestra \"Imprimir\" en el menú de cada fila del listado y como botón en la\n   * cabecera del detalle, abriendo un modal de vista previa con el visor que el\n   * host inyecta. Sin esta prop, el comportamiento es idéntico al actual\n   * (sin impresión) → retrocompatibilidad total.\n   *\n   * @see MasterDocumentPrintConfig\n   */\n  printing?: MasterDocumentPrintConfig;\n  /**\n   * Configuración de historial de auditoría (opcional). Mismo contrato que MasterCrud.\n   * Cuando se provee y `enabled` es true, el detalle del documento muestra una acción\n   * ⏱ que abre el historial de cambios (campo por campo) del documento guardado. Sin\n   * esta prop, el comportamiento es idéntico al actual (sin auditoría) →\n   * retrocompatibilidad total. La evaluación del permiso es responsabilidad del\n   * consumidor, comunicada vía `enabled`.\n   *\n   * @see AuditHistoryProps\n   */\n  auditHistory?: AuditHistoryProps;\n  children: ReactNode;\n}\n\n/**\n * Modo manual: el consumidor provee su propio adapter.\n */\ninterface ManualAdapterProps extends BaseProviderProps {\n  endpointAuto?: false;\n  adapter: IMasterDocumentAdapter;\n  apiService?: never;\n}\n\n/**\n * Modo auto: usa los endpoints estándar del contrato.\n * El consumidor solo entrega un apiService con baseUrl y headers.\n */\ninterface AutoEndpointProps extends BaseProviderProps {\n  endpointAuto: true;\n  apiService: ApiService;\n  adapter?: never;\n}\n\nexport type MasterDocumentProviderProps = ManualAdapterProps | AutoEndpointProps;\n\n// ════════════════════════════════════════════════════════════\n// PROVIDER\n// ════════════════════════════════════════════════════════════\n\nexport function MasterDocumentProvider(props: MasterDocumentProviderProps) {\n  const {\n    template,\n    icons,\n    factBoxWidgets,\n    lineTabRenderers,\n    userPermissions = null,\n    printing,\n    auditHistory,\n    children,\n  } = props;\n\n  // Resolver el adapter según el modo\n  const adapter = useMemo<IMasterDocumentAdapter>(() => {\n    if (props.endpointAuto) {\n      return createDefaultAdapter(props.apiService, template);\n    }\n    return props.adapter;\n  }, [\n    props.endpointAuto,\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    props.endpointAuto ? props.apiService : props.adapter,\n    template,\n  ]);\n\n  const mergedIcons = useMemo(\n    () => (icons ? { ...DEFAULT_ICON_REGISTRY, ...icons } : DEFAULT_ICON_REGISTRY),\n    [icons],\n  );\n\n  const widgets = useMemo(\n    () => factBoxWidgets ?? {},\n    [factBoxWidgets],\n  );\n\n  const tabRenderers = useMemo(\n    () => lineTabRenderers ?? {},\n    [lineTabRenderers],\n  );\n\n  return (\n    <AdapterContext.Provider value={adapter}>\n      <TemplateContext.Provider value={template}>\n        <IconContext.Provider value={mergedIcons}>\n          <FactBoxWidgetContext.Provider value={widgets}>\n            <LineTabRendererContext.Provider value={tabRenderers}>\n              <PermissionsContext.Provider value={userPermissions}>\n                <LookupResolveCacheProvider>\n                  <MasterDocumentPrintProvider\n                    printing={printing}\n                    documentLabel={template.identity.label}\n                  >\n                    <MasterDocumentAuditProvider auditHistory={auditHistory}>\n                      {children}\n                    </MasterDocumentAuditProvider>\n                  </MasterDocumentPrintProvider>\n                </LookupResolveCacheProvider>\n              </PermissionsContext.Provider>\n            </LineTabRendererContext.Provider>\n          </FactBoxWidgetContext.Provider>\n        </IconContext.Provider>\n      </TemplateContext.Provider>\n    </AdapterContext.Provider>\n  );\n}\n","import { createContext, useContext, type ReactNode } from 'react';\n\n// ════════════════════════════════════════════════════════════\n// RESINCRONIZACIÓN DEL DOCUMENTO — salida pública para el host\n// ════════════════════════════════════════════════════════════\n//\n// El `documentState` (headerValues, `_lines`, contador de líneas, totales) vive\n// en el reducer de `SmartMasterDocument`, NO en `MasterDocumentProvider`: ese\n// provider solo publica adapter, template, iconos, widgets y permisos. Por eso\n// el kit mergea una línea nueva únicamente cuando la guarda ÉL —desde su propio\n// modal de línea, vía `adapter.saveLine`— y un componente del host que persista\n// por su cuenta (un widget del FactBox que cruza una OC, una pestaña de detalle\n// que anula una línea contra su propio endpoint) dejaba la pantalla mostrando\n// los valores previos hasta que el usuario recargaba con F5.\n//\n// El kit ya sabía resincronizarse: `refetchDocument` (LOAD_START →\n// `adapter.getDocument` → LOAD_SUCCESS → `refreshToken++`) es lo que corre tras\n// un conflicto 409, tras una acción de línea genérica y tras anexar líneas desde\n// un origen. Lo único que faltaba era publicarlo. Esto lo publica, sin abrir el\n// `dispatch` del reducer: el host puede pedir \"vuelve a leer el documento\", no\n// escribir estado a mano.\n\n/**\n * Resincronización del documento en pantalla, disponible para cualquier\n * componente montado dentro de `SmartMasterDocument`.\n *\n * @see useMasterDocumentReload - El caso de uso normal (solo `reload`).\n * @see FactBoxWidgetRenderContext - Los widgets custom lo reciben ya en su contexto.\n */\nexport interface MasterDocumentRefreshApi {\n  /**\n   * Vuelve a leer el documento del servidor y reemplaza el estado del kit con la\n   * respuesta: encabezado, líneas, totales, `docState` y `row_version`. Es la\n   * MISMA operación que dispara \"Recargar documento\" del modal de conflicto.\n   *\n   * Descarta la edición en vuelo del encabezado (lo escrito y no guardado), así\n   * que se invoca DESPUÉS de persistir, no antes. Resuelve cuando el estado ya\n   * se aplicó; si la lectura falla, el error se reporta por el mismo canal que\n   * la carga inicial (toast + log) y la promesa igual resuelve.\n   */\n  reload: () => Promise<void>;\n  /**\n   * Contador que sube tras cada mutación del kit (guardar, borrar o duplicar una\n   * línea, acción de fila, `reload`). Úsalo como dependencia del fetch propio del\n   * host —una React Query key, un `useEffect`— para refrescar SU listado cuando\n   * el documento cambió por fuera de él. Es el mismo valor que reciben las\n   * pestañas de detalle en `LineTabRenderContext.refreshToken`.\n   */\n  refreshToken: number;\n}\n\nconst RefreshContext = createContext<MasterDocumentRefreshApi | null>(null);\n\n/**\n * `reload` inerte para los dos casos en que no hay documento montado: el hook\n * llamado fuera de `SmartMasterDocument` y el valor por defecto del builder del\n * FactBox. Avisa por consola en vez de lanzar —un widget del host no debe tumbar\n * la pantalla por estar mal cableado— y es una constante de módulo para que su\n * identidad sirva como dependencia estable.\n */\nexport const INERT_REFRESH: MasterDocumentRefreshApi = {\n  reload: async () => {\n    console.warn(\n      '[MasterDocument] reload() fuera de <SmartMasterDocument>: no hay documento que recargar.',\n    );\n  },\n  refreshToken: 0,\n};\n\n/**\n * API completa de resincronización, o `null` fuera de un `SmartMasterDocument`\n * (mismo contrato nullable que `useMasterDocumentPrint`/`useMasterDocumentAudit`:\n * subsistema ausente ⇒ contexto en null, nunca excepción).\n *\n * Úsalo cuando necesites `refreshToken` además de `reload`; si solo vas a\n * recargar, `useMasterDocumentReload()` evita el chequeo de null.\n */\nexport function useMasterDocumentRefresh(): MasterDocumentRefreshApi | null {\n  return useContext(RefreshContext);\n}\n\n/**\n * Recarga el documento del `SmartMasterDocument` que envuelve al componente.\n *\n * Pensado para el host que persiste por su cuenta y necesita que la pantalla se\n * entere: widgets custom del FactBox, renderers de pestañas de detalle, paneles\n * propios montados en cualquier slot del kit.\n *\n * Siempre devuelve una función invocable: fuera del árbol de un documento es un\n * no-op que avisa por consola, para que el consumidor no tenga que ramificar.\n *\n * @example\n * ```tsx\n * function CrossingsWidget() {\n *   const reload = useMasterDocumentReload();\n *   const onAccept = async () => {\n *     await api.crossLines(...);   // persistencia propia del host\n *     await reload();              // el kit vuelve a leer líneas y totales\n *   };\n *   // ...\n * }\n * ```\n */\nexport function useMasterDocumentReload(): () => Promise<void> {\n  const api = useContext(RefreshContext);\n  return api?.reload ?? INERT_REFRESH.reload;\n}\n\ninterface MasterDocumentRefreshProviderProps {\n  value: MasterDocumentRefreshApi;\n  children: ReactNode;\n}\n\n/**\n * Publica la resincronización a todo el subárbol del documento. Lo monta\n * `SmartMasterDocument` —el único que tiene el reducer y por tanto lo único que\n * puede recargar de verdad— y por eso NO se exporta al consumidor: montarlo a\n * mano obligaría al host a fabricar un `reload`, que es justo lo que no puede.\n */\nexport function MasterDocumentRefreshProvider({\n  value,\n  children,\n}: MasterDocumentRefreshProviderProps) {\n  return <RefreshContext.Provider value={value}>{children}</RefreshContext.Provider>;\n}\n","import type {\n  ComputedExpression,\n  ConditionExpression,\n  ExpressionNode,\n  FieldRef,\n  NumberLiteral,\n  StringLiteral,\n} from './MasterDocumentTemplate.types';\n\n// ════════════════════════════════════════════════════════════\n// HELPERS\n// ════════════════════════════════════════════════════════════\n\nfunction isFieldRef(node: unknown): node is FieldRef {\n  return typeof node === 'object' && node !== null && 'field' in node && !('op' in node) && !('value' in node);\n}\n\nfunction isLiteral(node: unknown): node is NumberLiteral | StringLiteral {\n  return typeof node === 'object' && node !== null && 'value' in node && !('op' in node) && !('field' in node);\n}\n\nfunction toNumber(val: unknown): number {\n  if (typeof val === 'number') return val;\n  if (typeof val === 'string') {\n    const n = Number(val);\n    return Number.isNaN(n) ? 0 : n;\n  }\n  return 0;\n}\n\n// ════════════════════════════════════════════════════════════\n// RESOLVE NODE — Resuelve un nodo a su valor\n// ════════════════════════════════════════════════════════════\n\nfunction resolveNode(\n  node: ExpressionNode | StringLiteral,\n  data: Record<string, unknown>,\n  customEvaluator?: (ruleId: string, formData: Record<string, unknown>) => unknown,\n): unknown {\n  if (isFieldRef(node)) return data[node.field];\n  if (isLiteral(node)) return node.value;\n  return evaluateExpression(node as ComputedExpression, data, customEvaluator);\n}\n\n// ════════════════════════════════════════════════════════════\n// EVALUATE CONDITION\n// ════════════════════════════════════════════════════════════\n\nexport function evaluateCondition(\n  cond: ConditionExpression,\n  data: Record<string, unknown>,\n  customEvaluator?: (ruleId: string, formData: Record<string, unknown>) => unknown,\n): boolean {\n  switch (cond.op) {\n    case 'eq':\n      return resolveNode(cond.left, data, customEvaluator) === resolveNode(cond.right, data, customEvaluator);\n    case 'neq':\n      return resolveNode(cond.left, data, customEvaluator) !== resolveNode(cond.right, data, customEvaluator);\n    case 'gt':\n      return toNumber(resolveNode(cond.left, data, customEvaluator)) > toNumber(resolveNode(cond.right, data, customEvaluator));\n    case 'gte':\n      return toNumber(resolveNode(cond.left, data, customEvaluator)) >= toNumber(resolveNode(cond.right, data, customEvaluator));\n    case 'lt':\n      return toNumber(resolveNode(cond.left, data, customEvaluator)) < toNumber(resolveNode(cond.right, data, customEvaluator));\n    case 'lte':\n      return toNumber(resolveNode(cond.left, data, customEvaluator)) <= toNumber(resolveNode(cond.right, data, customEvaluator));\n    case 'and':\n      return cond.conditions.every((c) => evaluateCondition(c, data, customEvaluator));\n    case 'or':\n      return cond.conditions.some((c) => evaluateCondition(c, data, customEvaluator));\n    case 'not':\n      return !evaluateCondition(cond.condition, data, customEvaluator);\n  }\n}\n\n// ════════════════════════════════════════════════════════════\n// EVALUATE EXPRESSION — Motor principal\n// ════════════════════════════════════════════════════════════\n\nexport function evaluateExpression(\n  expr: ComputedExpression,\n  data: Record<string, unknown>,\n  customEvaluator?: (ruleId: string, formData: Record<string, unknown>) => unknown,\n): unknown {\n  switch (expr.op) {\n    case 'add':\n      return expr.args.reduce(\n        (sum, arg) => sum + toNumber(resolveNode(arg, data, customEvaluator)),\n        0,\n      );\n\n    case 'subtract': {\n      const [a, b] = expr.args;\n      return toNumber(resolveNode(a, data, customEvaluator)) - toNumber(resolveNode(b, data, customEvaluator));\n    }\n\n    case 'multiply':\n      return expr.args.reduce(\n        (product, arg) => product * toNumber(resolveNode(arg, data, customEvaluator)),\n        1,\n      );\n\n    case 'divide': {\n      const [num, den] = expr.args;\n      const d = toNumber(resolveNode(den, data, customEvaluator));\n      return d === 0 ? 0 : toNumber(resolveNode(num, data, customEvaluator)) / d;\n    }\n\n    case 'round': {\n      const [val, decimals] = expr.args;\n      const v = toNumber(resolveNode(val, data, customEvaluator));\n      const dec = decimals.value;\n      const factor = 10 ** dec;\n      return Math.round(v * factor) / factor;\n    }\n\n    case 'coalesce': {\n      for (const arg of expr.args) {\n        const v = resolveNode(arg, data, customEvaluator);\n        if (v != null && v !== '' && v !== 0) return v;\n      }\n      return 0;\n    }\n\n    case 'if': {\n      const passes = evaluateCondition(expr.condition, data, customEvaluator);\n      return resolveNode(passes ? expr.then : expr.else, data, customEvaluator);\n    }\n\n    case 'custom': {\n      if (customEvaluator) {\n        return customEvaluator(expr.ruleId, data);\n      }\n      return undefined;\n    }\n  }\n}\n\n// ════════════════════════════════════════════════════════════\n// EVALUATE NODE — Entry point público para nodos genéricos\n// ════════════════════════════════════════════════════════════\n\nexport function evaluateNode(\n  node: ExpressionNode,\n  data: Record<string, unknown>,\n  customEvaluator?: (ruleId: string, formData: Record<string, unknown>) => unknown,\n): unknown {\n  if (isFieldRef(node)) return data[node.field];\n  if (isLiteral(node)) return node.value;\n  return evaluateExpression(node as ComputedExpression, data, customEvaluator);\n}\n","/**\n * Detección centralizada del conflicto de concurrencia optimista (HTTP 409 /\n * `OPTIMISTIC_LOCK_VIOLATION`) para CUALQUIER mutación del documento\n * (saveHeader, saveLine, deleteLine, execute-process/transición).\n *\n * El backend responde 409 con un problem-details:\n *   - código `OPTIMISTIC_LOCK_VIOLATION`\n *   - `detail` traducido (`error.row_version_stale` / `document.header_concurrency_conflict`)\n *   - extensiones `row_version_expected` y `row_version_actual`.\n *\n * El adapter por defecto LANZA un error (con `.status` y `.body`) ante un\n * non-ok; otros adapters pueden lanzar con otra forma o devolver la clave\n * reservada `_conflict`. Este helper hace duck-typing sobre lo que se lanza para\n * reconocer el 409 sin acoplarse a la clase `ApiError` concreta.\n */\n\nexport const OPTIMISTIC_LOCK_CODE = 'OPTIMISTIC_LOCK_VIOLATION';\n\n/**\n * Código de conflicto de concurrencia de los endpoints a medida de Ventas\n * (contrato FD-10).\n */\nexport const ROW_VERSION_CONFLICT_CODE = 'ROW_VERSION_CONFLICT';\n\n/**\n * Códigos de negocio que SÍ representan un conflicto de concurrencia optimista.\n * Debe reflejar `isOptimisticConcurrencyError` de la app consumidora\n * (`apps/frontend/src/config/document-conflict.ts`).\n */\nexport const CONCURRENCY_CODES = [OPTIMISTIC_LOCK_CODE, ROW_VERSION_CONFLICT_CODE] as const;\n\nexport interface ConflictDetails {\n  /** Mensaje traducido (problem-details `detail`/`title`) o el del error. */\n  message?: string;\n  /** `row_version` que el cliente envió (extensión `row_version_expected`). */\n  expected?: string | number;\n  /** `row_version` real en el servidor (extensión `row_version_actual`). */\n  actual?: string | number;\n}\n\n/** Extrae un valor de cualquiera de las claves dadas en un objeto plano. */\nfunction pick(obj: unknown, keys: string[]): string | number | undefined {\n  if (!obj || typeof obj !== 'object') return undefined;\n  const rec = obj as Record<string, unknown>;\n  for (const k of keys) {\n    const v = rec[k];\n    if (typeof v === 'string' || typeof v === 'number') return v;\n  }\n  return undefined;\n}\n\n/**\n * Inspecciona un valor lanzado por una mutación y, si corresponde a un conflicto\n * de concurrencia optimista, devuelve los detalles para el modal y el log.\n * Devuelve `null` si NO es un conflicto.\n *\n * Es conflicto de concurrencia solo cuando el `code` de negocio es uno de\n * concurrencia conocido (`OPTIMISTIC_LOCK_VIOLATION` / `ROW_VERSION_CONFLICT`),\n * o cuando es un 409 SIN `code` de negocio. Cualquier 409 con `code` de negocio\n * (p.ej. `NegativeCostException`) NO es conflicto y devuelve `null` para que el\n * kit lo enrute a su manejo de error normal / banner.\n */\nexport function isConflictError(err: unknown): ConflictDetails | null {\n  if (!err || typeof err !== 'object') return null;\n  const e = err as Record<string, unknown>;\n\n  // status puede vivir en el error o en una respuesta anidada (axios-like).\n  const response = e.response as Record<string, unknown> | undefined;\n  const status = e.status ?? e.statusCode ?? response?.status;\n\n  // body: problem-details. Puede venir en `.body`, `.data` o `response.data`.\n  const body = (e.body ?? e.data ?? response?.data ?? e.problem) as\n    | Record<string, unknown>\n    | undefined;\n\n  const code = e.code ?? body?.code ?? body?.type;\n  const codeStr = typeof code === 'string' ? code : '';\n\n  // El backend del ERP Comercial responde 409 para CUALQUIER DomainException de\n  // negocio (NegativeCostException, reglas de secuencia/prefijo, duplicados,\n  // integridad, ...), no solo para concurrencia. Por eso un 409 crudo NO basta:\n  // es conflicto de concurrencia solo cuando trae un `code` de concurrencia\n  // conocido, o cuando es un 409 SIN `code` de negocio (p.ej. la\n  // DbUpdateConcurrencyException que se serializa sin `code`).\n  const isConcurrencyCode =\n    !!codeStr && CONCURRENCY_CODES.some((c) => codeStr === c || codeStr.includes(c));\n\n  const isConflict = isConcurrencyCode || (status === 409 && !codeStr);\n\n  if (!isConflict) return null;\n\n  // Las extensiones de problem-details pueden estar al tope del body o anidadas.\n  const extensions = (body?.extensions ?? body) as Record<string, unknown> | undefined;\n  const expected = pick(extensions, ['row_version_expected', 'rowVersionExpected']);\n  const actual = pick(extensions, ['row_version_actual', 'rowVersionActual']);\n\n  const detail = body?.detail ?? body?.title;\n  const message =\n    typeof detail === 'string'\n      ? detail\n      : typeof e.message === 'string'\n        ? e.message\n        : undefined;\n\n  return { message, expected, actual };\n}\n","import type { TranslateFn } from '../i18nFactory';\n\n/**\n * Traduce un error desconocido a un mensaje que se le pueda mostrar a un usuario.\n *\n * El kit hacía `toast.error('Error', { description: err.message })`, así que al\n * usuario le llegaba el texto técnico de JavaScript en crudo — \"Cannot read\n * properties of undefined\", \"Failed to fetch\" — que además nunca está traducido.\n *\n * Orden de precedencia:\n *\n *  1. **Texto del backend.** Si el error trae `detail` / `message` / `title` de un\n *     `ProblemDetails`, gana: el backend recibe `Accept-Language` y lo devuelve ya\n *     traducido, y es más específico que cualquier cosa que el kit pueda inferir.\n *  2. **Código HTTP.** Sin texto del backend, el status se mapea a una clave del\n *     catálogo (403, 404, 409, 422, 5xx).\n *  3. **Fallo de red.** `TypeError: Failed to fetch` y equivalentes.\n *  4. **Genérico.** Cualquier otra cosa: mensaje genérico, y el texto técnico se\n *     devuelve aparte en `technical` para diagnóstico, nunca para la UI.\n *\n * Es una función pura y recibe `t`, para poder usarse desde hooks y desde módulos\n * sin acceso al contexto de React.\n *\n * ⚠️ El paso 1 tiene que reconocer TODAS las formas en que un adapter lanza, no\n * solo la de axios. `leerTextoBackend` nacía mirando únicamente las bolsas\n * `response.data` / `data` / `problem`, y con eso se le escapaban dos formas que\n * el propio kit produce y consume:\n *\n *   · `ApiError` del adapter por defecto, que deja el problem-details en `.body`\n *     (ver `adapter/createDefaultAdapter.ts`);\n *   · el error **plano**, que trae `status` + `code` + `detail` en la raíz porque\n *     el host ya normalizó la respuesta en su interceptor HTTP.\n *\n * En ambos casos el `detail` del backend existía y no se mostraba: el usuario veía\n * el mensaje por status (\"Revisa los datos ingresados\") o el genérico, y la causa\n * real —\"Esta acción no está disponible para la clase de documento de esta\n * factura\"— solo aparecía en la consola del navegador. `isConflictError` ya hacía\n * el duck-typing completo sobre esas mismas formas; este módulo tenía que ser\n * simétrico con él, no un subconjunto.\n *\n * @see src/components/MasterDocument/smart/conflictError.ts - mismo duck-typing sobre las formas de lanzar\n * @see src/components/MasterDocument/smart/crossingFetch.ts - mismo criterio para los errores de cruce\n */\n\n/** Error ya listo para mostrar. */\nexport interface ClassifiedError {\n  /** Texto para el usuario. Siempre presente y siempre en el idioma activo. */\n  message: string;\n  /** Clave usada, o `undefined` si el texto lo puso el backend. */\n  messageKey?: string;\n  /** Texto técnico original. Para `console.error`, jamás para la UI. */\n  technical?: string;\n}\n\nconst CLAVE_POR_STATUS: Record<number, string> = {\n  400: 'master_document.error.validation',\n  401: 'master_document.error.unauthorized',\n  403: 'master_document.error.forbidden',\n  404: 'master_document.error.notFound',\n  409: 'master_document.error.conflict',\n  422: 'master_document.error.validation',\n};\n\n/** Extrae el status HTTP de las formas habituales (fetch, axios, ProblemDetails). */\nfunction leerStatus(e: Record<string, unknown>): number | undefined {\n  const candidatos = [\n    e.status,\n    e.statusCode,\n    (e.response as Record<string, unknown> | undefined)?.status,\n    (e.data as Record<string, unknown> | undefined)?.status,\n  ];\n  for (const c of candidatos) {\n    const n = typeof c === 'string' ? Number(c) : c;\n    if (typeof n === 'number' && Number.isFinite(n) && n >= 100) return n;\n  }\n  return undefined;\n}\n\n/**\n * ¿Es un texto que se le puede mostrar tal cual a un usuario?\n *\n * El `title` de un problem-details del ERP Comercial NO es una frase: es la CLAVE\n * i18n de la excepción (`error.capability_not_supported`). El `detail` es el texto\n * ya traducido. Como `title` sigue siendo el último recurso de la cadena, se\n * descartan las cadenas con forma de clave (segmentos en minúscula unidos por\n * puntos y sin espacios) para no pintarle una clave cruda al usuario.\n */\nfunction esTextoParaUsuario(valor: unknown): valor is string {\n  if (typeof valor !== 'string' || valor.trim() === '') return false;\n  return !/^[a-z0-9_]+(\\.[a-z0-9_]+)+$/.test(valor.trim());\n}\n\n/** Extrae el texto que el backend haya enviado, si lo hay. */\nfunction leerTextoBackend(e: Record<string, unknown>): string | undefined {\n  const bolsas = [\n    (e.response as Record<string, unknown> | undefined)?.data,\n    e.data,\n    // `ApiError` del adapter por defecto del kit: el problem-details va en `.body`.\n    e.body,\n    e.problem,\n    // Host que normaliza en su interceptor y conserva el error de axios original.\n    ((e.originalError as Record<string, unknown> | undefined)?.response as\n      | Record<string, unknown>\n      | undefined)?.data,\n  ].filter((b) => b != null && typeof b === 'object') as Array<Record<string, unknown>>;\n\n  for (const bolsa of bolsas) {\n    const texto = bolsa.detail ?? bolsa.message ?? bolsa.title;\n    if (esTextoParaUsuario(texto)) return texto;\n  }\n\n  // Forma PLANA: el host ya aplanó el problem-details sobre el error mismo. Se leen\n  // solo los campos que son exclusivos de un problem-details (`detail` / `title`);\n  // `message` queda fuera a propósito, porque en un `Error` corriente es el texto\n  // técnico de JavaScript y ése nunca se le muestra al usuario.\n  const plano = e.detail ?? e.title;\n  return esTextoParaUsuario(plano) ? plano : undefined;\n}\n\n/** Heurística de fallo de red: `fetch` lanza `TypeError` sin status. */\nfunction esFalloDeRed(e: Record<string, unknown>, status: number | undefined): boolean {\n  if (status !== undefined) return false;\n  const nombre = typeof e.name === 'string' ? e.name : '';\n  const mensaje = typeof e.message === 'string' ? e.message.toLowerCase() : '';\n  return (\n    nombre === 'TypeError'\n    && (mensaje.includes('fetch') || mensaje.includes('network') || mensaje.includes('load failed'))\n  );\n}\n\n/**\n * Clasifica un error para mostrarlo al usuario.\n *\n * @example\n * ```ts\n * const { message, technical } = classifyError(err, t);\n * if (technical) console.error('[MasterDocument]', technical);\n * toast.error(t('master_document.chrome.error'), { description: message });\n * ```\n */\nexport function classifyError(err: unknown, t: TranslateFn): ClassifiedError {\n  const generico = (technical?: string): ClassifiedError => ({\n    message: t('master_document.error.unexpected'),\n    messageKey: 'master_document.error.unexpected',\n    technical,\n  });\n\n  if (err == null) return generico();\n\n  if (typeof err === 'string') {\n    // Una cadena suelta suele ser un mensaje ya pensado para el usuario.\n    return err.trim() === '' ? generico() : { message: err };\n  }\n\n  if (typeof err !== 'object') return generico(String(err));\n\n  const e = err as Record<string, unknown>;\n  const technical = typeof e.message === 'string' ? e.message : undefined;\n\n  const backend = leerTextoBackend(e);\n  if (backend) return { message: backend, technical };\n\n  const status = leerStatus(e);\n  if (status !== undefined) {\n    const clave =\n      CLAVE_POR_STATUS[status] ?? (status >= 500 ? 'master_document.error.serverUnavailable' : undefined);\n    if (clave) return { message: t(clave), messageKey: clave, technical };\n  }\n\n  if (esFalloDeRed(e, status)) {\n    return {\n      message: t('master_document.error.network'),\n      messageKey: 'master_document.error.network',\n      technical,\n    };\n  }\n\n  return generico(technical);\n}\n","import { useReducer, useCallback, useEffect, useRef } from 'react';\nimport type { DocumentState, IMasterDocumentAdapter, DeleteLineResult } from '../adapter/MasterDocumentAdapter.types';\nimport type { MasterDocumentTemplate, TotalsAggregation } from '../template/MasterDocumentTemplate.types';\nimport type { DocumentLineData, DocumentHeaderData, FieldErrorMap } from '../MasterDocument.types';\nimport { evaluateExpression } from '../template/expressionEvaluator';\nimport { isConflictError, type ConflictDetails } from './conflictError';\nimport { toast } from '../../Toast';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport { classifyError } from './userFacingError';\n\n// ════════════════════════════════════════════════════════════\n// LINE TOTALS ENGINE — propaga agregados de líneas → headerValues\n// ════════════════════════════════════════════════════════════\n\n// ════════════════════════════════════════════════════════════\n// RESERVED ERROR KEYS — _conflict / _forbidden\n// ════════════════════════════════════════════════════════════\n\nconst CONFLICT_KEY = '_conflict';\nconst FORBIDDEN_KEY = '_forbidden';\n\n// ════════════════════════════════════════════════════════════\n// RESERVED VERSION KEYS — retención del token de concurrencia optimista\n// ════════════════════════════════════════════════════════════\n\n/** Clave por defecto del rowVersion de cada línea (vive en `DocumentLineData`). */\nconst DEFAULT_LINE_VERSION_KEY = '_row_version';\n/** Clave por defecto del rowVersion de la cabecera (vive en `headerValues`). */\nconst DEFAULT_HEADER_VERSION_KEY = '_rowVersion';\n\n/**\n * Mergea el token de versión de la línea (`versionKey`) leído del ESTADO del\n * documento en el `data` que se enviará al adapter, para que el round-trip de\n * concurrencia optimista no dependa de que el modal recolecte los campos\n * internos `_`-prefijados.\n *\n * Reglas:\n * - Línea nueva (`lineId === null`) → sin versión previa: no inyecta nada.\n * - El formulario tiene prioridad: si `data` ya trae la clave, se respeta.\n * - Si la línea del estado no tiene versión, se devuelve `data` intacto.\n */\nfunction mergeLineVersion(\n  data: Record<string, unknown>,\n  lineId: string | null,\n  lines: DocumentLineData[],\n  versionKey: string,\n): Record<string, unknown> {\n  if (!lineId) return data;\n  if (data[versionKey] != null) return data;\n  const current = lines.find((l) => l.id === lineId);\n  const version = current?.[versionKey];\n  if (version == null) return data;\n  return { ...data, [versionKey]: version };\n}\n\n/**\n * Garantiza que la versión de cabecera (`versionKey`) viaje en `headerValues`.\n * `headerValues` ya transporta su propio `_rowVersion`; cuando no lo trae pero el\n * estado tiene `serverVersion`, se inyecta como respaldo. El valor existente en\n * `headerValues` siempre tiene prioridad.\n */\nfunction mergeHeaderVersion(\n  header: DocumentHeaderData,\n  serverVersion: string | undefined,\n  versionKey: string,\n): DocumentHeaderData {\n  if (header[versionKey] != null) return header;\n  if (serverVersion == null) return header;\n  return { ...header, [versionKey]: serverVersion };\n}\n\n/**\n * Inyecta el token de versión de la CABECERA (`headerVersionKey`) en el payload\n * de una mutación de LÍNEA, para que el backend valide la concurrencia del header\n * al guardar/agregar una línea (no solo al editar la cabecera). Aplica a líneas\n * nuevas y existentes.\n *\n * El valor se toma de `headerValues[headerVersionKey]` y, como respaldo, de\n * `serverVersion`. Degrada con gracia: si no hay versión de cabecera o el payload\n * ya la trae, se devuelve intacto (compatibilidad con backends que aún no la\n * validan en línea).\n */\nfunction withHeaderVersion(\n  data: Record<string, unknown>,\n  headerValues: DocumentHeaderData,\n  serverVersion: string | undefined,\n  headerVersionKey: string,\n): Record<string, unknown> {\n  if (data[headerVersionKey] != null) return data;\n  const version = headerValues[headerVersionKey] ?? serverVersion;\n  if (version == null) return data;\n  return { ...data, [headerVersionKey]: version };\n}\n\ninterface PartitionedErrors {\n  conflict: { message?: string } | null;\n  forbidden: { message: string } | null;\n  /** Errores de campo restantes (sin las claves reservadas). */\n  fieldErrors: FieldErrorMap;\n}\n\n/**\n * Separa las claves reservadas `_conflict` y `_forbidden` del resto de errores de\n * campo. Permite que un `SaveResult` 409/403 dispare el flujo de conflicto / banner\n * en lugar de renderizarse como un error de campo genérico.\n */\nexport function partitionReservedErrors(errors: FieldErrorMap): PartitionedErrors {\n  const { [CONFLICT_KEY]: conflictErr, [FORBIDDEN_KEY]: forbiddenErr, ...fieldErrors } = errors;\n  return {\n    conflict: conflictErr ? { message: conflictErr.message } : null,\n    forbidden: forbiddenErr ? { message: forbiddenErr.message } : null,\n    fieldErrors,\n  };\n}\n\nfunction applyLineTotals(\n  rules: Record<string, TotalsAggregation>,\n  lines: DocumentLineData[],\n): Record<string, number> {\n  const result: Record<string, number> = {};\n  for (const [key, agg] of Object.entries(rules)) {\n    switch (agg.op) {\n      case 'sum':\n        result[key] = lines.reduce((acc, l) => acc + (Number(l[agg.field]) || 0), 0);\n        break;\n      case 'sumProduct':\n        result[key] = lines.reduce((acc, l) => {\n          const product = agg.fields.reduce((p, f) => p * (Number(l[f]) || 0), 1);\n          return acc + product;\n        }, 0);\n        break;\n      case 'sumDiscount':\n        result[key] = lines.reduce((acc, l) => {\n          const qty = Number(l[agg.qtyField]) || 0;\n          const price = Number(l[agg.priceField]) || 0;\n          const discount = Number(l[agg.discountField]) || 0;\n          return acc + qty * price * (1 - discount / 100);\n        }, 0);\n        break;\n      case 'diff':\n        result[key] = (result[agg.a] ?? 0) - (result[agg.b] ?? 0);\n        break;\n      case 'add':\n        result[key] = agg.fields.reduce((acc, f) => acc + (result[f] ?? 0), 0);\n        break;\n      case 'ref':\n        result[key] = (result[agg.field] ?? 0) * (agg.multiplier ?? 1);\n        break;\n    }\n  }\n  return result;\n}\n\n// ════════════════════════════════════════════════════════════\n// ACTIONS\n// ════════════════════════════════════════════════════════════\n\ntype Action =\n  | { type: 'LOAD_START' }\n  | { type: 'LOAD_SUCCESS'; payload: DocumentState }\n  | { type: 'LOAD_ERROR'; payload: string }\n  | { type: 'SET_HEADER_FIELD'; key: string; value: unknown }\n  | { type: 'SET_HEADER_ERRORS'; errors: FieldErrorMap }\n  | { type: 'SET_LINES'; lines: DocumentLineData[] }\n  | { type: 'ADD_LINE'; line: DocumentLineData }\n  | { type: 'UPDATE_LINE'; lineId: string; data: Record<string, unknown> }\n  | { type: 'DELETE_LINE'; lineId: string }\n  | { type: 'DUPLICATE_LINE'; lineId: string; newLine: DocumentLineData }\n  | { type: 'SET_DOC_STATE'; docState: string }\n  | { type: 'SET_SAVING'; saving: boolean }\n  | { type: 'SET_ERROR'; error?: string }\n  | { type: 'SET_FACTBOX_DATA'; sectionKey: string; data: Record<string, unknown> }\n  | { type: 'SET_SERVER_VERSION'; version: string }\n  | { type: 'SET_CONFLICT'; conflict: NonNullable<DocumentState['conflict']> }\n  | { type: 'CLEAR_CONFLICT' }\n  | { type: 'SET_FORBIDDEN'; forbidden: NonNullable<DocumentState['forbidden']> }\n  | { type: 'CLEAR_FORBIDDEN' }\n  | { type: 'MERGE_STATE'; payload: Partial<DocumentState> };\n\n// ════════════════════════════════════════════════════════════\n// INITIAL STATE\n// ════════════════════════════════════════════════════════════\n\nfunction createInitialState(template: MasterDocumentTemplate): DocumentState {\n  return {\n    documentId: undefined,\n    mode: 'create',\n    docState: template.stateMachine.initial,\n    headerValues: {},\n    lines: [],\n    headerErrors: {},\n    lineErrors: {},\n    loading: false,\n    saving: false,\n    error: undefined,\n    serverVersion: undefined,\n    factBoxData: {},\n    conflict: null,\n    forbidden: null,\n  };\n}\n\n// ════════════════════════════════════════════════════════════\n// REDUCER\n// ════════════════════════════════════════════════════════════\n\nfunction reducer(state: DocumentState, action: Action): DocumentState {\n  switch (action.type) {\n    case 'LOAD_START':\n      return { ...state, loading: true, error: undefined };\n    case 'LOAD_SUCCESS':\n      return { ...action.payload, loading: false, saving: false };\n    case 'LOAD_ERROR':\n      return { ...state, loading: false, error: action.payload };\n    case 'SET_HEADER_FIELD':\n      return {\n        ...state,\n        headerValues: { ...state.headerValues, [action.key]: action.value },\n      };\n    case 'SET_HEADER_ERRORS':\n      return { ...state, headerErrors: action.errors };\n    case 'SET_LINES':\n      return { ...state, lines: action.lines };\n    case 'ADD_LINE':\n      return { ...state, lines: [...state.lines, action.line] };\n    case 'UPDATE_LINE':\n      return {\n        ...state,\n        lines: state.lines.map((l) =>\n          l.id === action.lineId ? { ...l, ...action.data } : l,\n        ),\n      };\n    case 'DELETE_LINE':\n      return {\n        ...state,\n        lines: state.lines.filter((l) => l.id !== action.lineId),\n      };\n    case 'DUPLICATE_LINE': {\n      const idx = state.lines.findIndex((l) => l.id === action.lineId);\n      if (idx === -1) return state;\n      const next = [...state.lines];\n      next.splice(idx + 1, 0, action.newLine);\n      return { ...state, lines: next };\n    }\n    case 'SET_DOC_STATE':\n      return { ...state, docState: action.docState };\n    case 'SET_SAVING':\n      return { ...state, saving: action.saving };\n    case 'SET_ERROR':\n      return { ...state, error: action.error };\n    case 'SET_FACTBOX_DATA':\n      return {\n        ...state,\n        factBoxData: { ...state.factBoxData, [action.sectionKey]: action.data },\n      };\n    case 'SET_SERVER_VERSION':\n      return { ...state, serverVersion: action.version };\n    case 'SET_CONFLICT':\n      return { ...state, conflict: action.conflict };\n    case 'CLEAR_CONFLICT':\n      return { ...state, conflict: null };\n    case 'SET_FORBIDDEN':\n      return { ...state, forbidden: action.forbidden };\n    case 'CLEAR_FORBIDDEN':\n      return { ...state, forbidden: null };\n    case 'MERGE_STATE':\n      return { ...state, ...action.payload };\n    default:\n      return state;\n  }\n}\n\n// ════════════════════════════════════════════════════════════\n// HOOK\n// ════════════════════════════════════════════════════════════\n\n/**\n * Trabajo que debe ocurrir DESPUÉS de que el backend confirmó una escritura y\n * devolvió su id, dentro de la misma interacción del usuario.\n *\n * Existe para los datos que no viajan en el payload del documento y necesitan un\n * id que solo existe una vez persistido — hoy, los valores de las entidades\n * dinámicas (EAV). Es deliberadamente un *callback* y no una llamada directa: el\n * reducer no sabe nada de entidades dinámicas ni debe saberlo, y quien conoce los\n * formularios montados es la capa que renderiza.\n *\n * Contrato: **no deben lanzar y no deben fallar la operación**. Para cuando se\n * invocan, el documento o la línea ya están guardados; revertir no es una opción y\n * propagar el error solo lograría que el usuario crea que perdió todo.\n */\nexport interface MasterDocumentPersistenceHooks {\n  /** El encabezado quedó persistido con este id (recién creado o existente). */\n  onHeaderPersisted?: (documentId: string) => Promise<void> | void;\n  /** La línea quedó persistida con este id (recién creada o existente). */\n  onLinePersisted?: (lineId: string) => Promise<void> | void;\n}\n\nexport function useMasterDocumentReducer(\n  template: MasterDocumentTemplate,\n  adapter: IMasterDocumentAdapter,\n  documentId?: string,\n  initialState?: DocumentState,\n  onSaved?: () => void,\n  viewOnly?: boolean,\n  onNavigateToList?: () => void,\n  persistenceHooks?: MasterDocumentPersistenceHooks,\n) {\n  const { t } = useMasterDocumentTranslation();\n\n  // Los hooks de post-persistencia se leen por REF y no por dependencia: el host\n  // los reconstruye en cada render, y meterlos en las dependencias de\n  // `handleSaveHeader`/`handleLineSave` invalidaría esos callbacks continuamente\n  // sin ninguna ganancia — se invocan siempre desde un evento del usuario, cuando\n  // el ref ya está al día.\n  const persistenceHooksRef = useRef(persistenceHooks);\n  persistenceHooksRef.current = persistenceHooks;\n\n  // Merge con defaults para garantizar que lines/headerErrors/lineErrors nunca sean undefined\n  const [state, dispatch] = useReducer(\n    reducer,\n    initialState\n      ? { ...createInitialState(template), ...initialState }\n      : createInitialState(template),\n  );\n\n  // Claves reservadas de versión (concurrencia optimista). Configurables vía\n  // template.versionKeys; por defecto `_row_version` (línea) / `_rowVersion` (cabecera).\n  const lineVersionKey = template.versionKeys?.line ?? DEFAULT_LINE_VERSION_KEY;\n  const headerVersionKey = template.versionKeys?.header ?? DEFAULT_HEADER_VERSION_KEY;\n\n  // ── Conflicto DURO (409 / OPTIMISTIC_LOCK_VIOLATION) ──\n  // Fuente de verdad única: el 409 del servidor en cualquier mutación. Descarta\n  // la edición en vuelo y muestra el modal NO descartable (la única acción es\n  // recargar). `expected`/`actual` se registran para diagnóstico.\n  const raiseConflict = useCallback((details: ConflictDetails) => {\n    if (details.expected != null || details.actual != null) {\n      console.warn(\n        '[MasterDocument] Conflicto de concurrencia optimista (row_version)',\n        { expected: details.expected, actual: details.actual },\n      );\n    }\n    dispatch({\n      type: 'SET_CONFLICT',\n      conflict: {\n        hard: true,\n        message: details.message,\n        expected: details.expected,\n        actual: details.actual,\n      },\n    });\n  }, []);\n\n  /**\n   * Manejo unificado del error lanzado por una mutación: si es un 409 de\n   * concurrencia, dispara el conflicto duro y devuelve `true`; en caso contrario\n   * registra el error genérico y devuelve `false`.\n   */\n  const handleMutationError = useCallback(\n    (err: unknown): boolean => {\n      const conflict = isConflictError(err);\n      if (conflict) {\n        raiseConflict(conflict);\n        return true;\n      }\n      // El texto tecnico de JS no llega al usuario: `state.error` alimenta un\n      // toast, asi que se guarda el mensaje clasificado y el crudo va al log.\n      const { message, technical } = classifyError(err, t);\n      if (technical) console.error('[MasterDocument]', technical);\n      dispatch({ type: 'SET_ERROR', error: message });\n      return false;\n    },\n    [raiseConflict, t],\n  );\n\n  // ── Sync lineTotals → headerValues cuando cambian las líneas ──\n  const linesRef = useRef(state.lines);\n  useEffect(() => {\n    const rules = template.lineTotals;\n    if (!rules || Object.keys(rules).length === 0) return;\n    // Solo disparar si realmente cambiaron las líneas (misma ref = no cambió)\n    if (state.lines === linesRef.current) return;\n    linesRef.current = state.lines;\n    const totals = applyLineTotals(rules, state.lines);\n    for (const [key, value] of Object.entries(totals)) {\n      dispatch({ type: 'SET_HEADER_FIELD', key, value });\n    }\n  }); // sin deps: corre en cada render, pero la guarda de ref evita loops\n\n  // ── Load document on mount ────────────────────────\n  useEffect(() => {\n    if (!documentId) return;\n\n    let cancelled = false;\n    dispatch({ type: 'LOAD_START' });\n\n    adapter.getDocument(documentId).then(\n      (doc) => {\n        if (!cancelled) dispatch({\n          type: 'LOAD_SUCCESS',\n          payload: viewOnly ? { ...doc, mode: 'view' } : doc,\n        });\n      },\n      (err) => {\n        // `LOAD_ERROR` alimenta el MISMO `state.error` —y por tanto el mismo toast— que las\n        // mutaciones, así que se clasifica igual que ellas. Era el último sitio que quedaba en\n        // el camino crudo: el usuario veía texto saneado al guardar y el mensaje técnico de JS\n        // (\"Cannot read properties of undefined\") al cargar, dentro del mismo componente.\n        //\n        // `t` se queda FUERA del array de dependencias a propósito: cambia con el idioma activo\n        // y añadirlo volvería a pedir el documento cada vez que el usuario cambia de idioma. El\n        // precio es que un mensaje de error ya emitido conserva el idioma en que se emitió.\n        if (cancelled) return;\n        const { message, technical } = classifyError(err, t);\n        if (technical) console.error('[MasterDocument] carga del documento falló:', technical);\n        dispatch({ type: 'LOAD_ERROR', payload: message });\n      },\n    );\n\n    return () => { cancelled = true; };\n  }, [documentId, adapter]);\n\n  // ── Header field change with computed rules ───────\n  const handleHeaderFieldChange = useCallback(\n    (key: string, value: unknown) => {\n      dispatch({ type: 'SET_HEADER_FIELD', key, value });\n\n      // Evaluate computed rules that watch this field\n      const newValues = { ...state.headerValues, [key]: value };\n      for (const rule of template.computedRules) {\n        if (rule.watch.includes(key)) {\n          const computed = evaluateExpression(\n            rule.expression,\n            newValues,\n            adapter.evaluateCustomRule?.bind(adapter),\n          );\n          dispatch({ type: 'SET_HEADER_FIELD', key: rule.targetField, value: computed });\n          newValues[rule.targetField] = computed;\n        }\n      }\n    },\n    [state.headerValues, template.computedRules, adapter],\n  );\n\n  // ── Save header ───────────────────────────────────\n  const handleSaveHeader = useCallback(async () => {\n    dispatch({ type: 'SET_SAVING', saving: true });\n    try {\n      let docId = state.documentId;\n\n      // Primer guardado: crear el registro en BD antes de guardar el header\n      if (!docId && adapter.createDocument) {\n        const { documentId: newId } = await adapter.createDocument(\n          // La clase del ESTADO manda sobre la del template: una superficie que\n          // sirve a varias clases la resuelve en el wizard, y el template solo\n          // puede declarar una. Sin ella (todos los documentos de una sola clase)\n          // se usa la del template, como siempre.\n          state.documentClass ?? template.identity.documentClass,\n          String(state.headerValues._companyId ?? ''),\n          String(state.headerValues._coId ?? ''),\n          String(state.headerValues._typeId ?? ''),\n        );\n        docId = newId;\n        dispatch({ type: 'MERGE_STATE', payload: { documentId: newId, mode: 'edit' } });\n      }\n\n      if (!docId) return;\n\n      const headerPayload = mergeHeaderVersion(state.headerValues, state.serverVersion, headerVersionKey);\n      const result = await adapter.saveHeader(docId, headerPayload);\n      if (result.errors) {\n        const { conflict, forbidden, fieldErrors } = partitionReservedErrors(result.errors);\n        if (conflict) raiseConflict(conflict);\n        if (forbidden) dispatch({ type: 'SET_FORBIDDEN', forbidden });\n        dispatch({ type: 'SET_HEADER_ERRORS', errors: fieldErrors });\n      }\n      if (result.serverVersion) {\n        dispatch({ type: 'SET_SERVER_VERSION', version: result.serverVersion });\n      }\n      // Segunda fase: lo que cuelga del documento y necesitaba su id. Solo si el\n      // backend aceptó el encabezado — colgarle valores adicionales a un header\n      // rechazado dejaría datos huérfanos de una edición que el usuario todavía\n      // tiene que corregir.\n      if (!result.errors) {\n        await persistenceHooksRef.current?.onHeaderPersisted?.(docId);\n      }\n    } catch (err) {\n      handleMutationError(err);\n    } finally {\n      dispatch({ type: 'SET_SAVING', saving: false });\n    }\n  }, [state.documentId, state.documentClass, state.headerValues, state.serverVersion, headerVersionKey, adapter, template.identity.documentClass, raiseConflict, handleMutationError]);\n\n  // ── Auto-save line totals → header ───────────────\n  // Calcula los totales de las líneas proporcionadas y los persiste en el\n  // header del backend inmediatamente, sin esperar a que el usuario guarde.\n  // docIdOverride: usado cuando el documentId acaba de ser obtenido en el mismo\n  // render cycle (ej: primera línea que crea el documento) y aún no está en state.\n  const autoSaveLineTotals = useCallback(\n    async (updatedLines: DocumentLineData[], docIdOverride?: string) => {\n      const docId = docIdOverride ?? state.documentId;\n      const rules = template.lineTotals;\n      if (!rules || !docId || Object.keys(rules).length === 0) return;\n      const totals = applyLineTotals(rules, updatedLines);\n      // Incluir _autoSaveServerVersion para que el adapter pueda refrescar su versión\n      const updatedHeaderValues = {\n        ...state.headerValues,\n        ...totals,\n        _autoSaveServerVersion: state.serverVersion,\n      };\n      try {\n        const result = await adapter.saveHeader(docId, updatedHeaderValues);\n        if (result.errors) {\n          const { conflict, forbidden } = partitionReservedErrors(result.errors);\n          if (conflict) raiseConflict(conflict);\n          if (forbidden) dispatch({ type: 'SET_FORBIDDEN', forbidden });\n        }\n        if (result.serverVersion) {\n          dispatch({ type: 'SET_SERVER_VERSION', version: result.serverVersion });\n        }\n      } catch (err) {\n        // Un 409 aquí (recálculo de totales en cabecera) es el mismo conflicto duro.\n        const conflict = isConflictError(err);\n        if (conflict) raiseConflict(conflict);\n        else {\n          dispatch({\n            type: 'SET_ERROR',\n            error: t('master_document.error.autoSaveTotals', {\n              detail: classifyError(err, t).message,\n            }),\n          });\n        }\n      }\n    },\n    [template.lineTotals, state.documentId, state.headerValues, state.serverVersion, adapter, raiseConflict, t],\n  );\n\n  // ── Save line ─────────────────────────────────────\n  const handleLineSave = useCallback(\n    async (lineId: string | null, data: Record<string, unknown>): Promise<FieldErrorMap | undefined> => {\n      // Separa las claves reservadas de un SaveLineResult.errors: `_conflict` (409)\n      // dispara el conflicto duro y cierra el modal (return undefined); `_forbidden`\n      // muestra el banner 403; el resto vuelve al modal como errores de campo.\n      const partitionLineResult = (errors: FieldErrorMap): FieldErrorMap | undefined => {\n        const { conflict, forbidden, fieldErrors } = partitionReservedErrors(errors);\n        if (conflict) { raiseConflict(conflict); return undefined; }\n        if (forbidden) dispatch({ type: 'SET_FORBIDDEN', forbidden });\n        return Object.keys(fieldErrors).length > 0 ? fieldErrors : undefined;\n      };\n      dispatch({ type: 'SET_SAVING', saving: true });\n      try {\n        if (state.documentId) {\n          // ── Documento ya guardado: persistir línea en backend ──\n          // Reinyecta el _row_version de la línea (leído del estado) cuando se edita\n          // una línea existente; las líneas nuevas (lineId === null) no llevan versión.\n          // Además inyecta el row_version de la CABECERA en TODA mutación de línea\n          // para que el backend valide la concurrencia del header al guardar la línea.\n          const payload = withHeaderVersion(\n            mergeLineVersion(data, lineId, state.lines, lineVersionKey),\n            state.headerValues,\n            state.serverVersion,\n            headerVersionKey,\n          );\n          const result = await adapter.saveLine(state.documentId, lineId, payload);\n          if (result.success) {\n            // Merge: payload enviado (incl. _row_version) + lineData del backend (autoritativo,\n            // refresca _row_version con la versión más reciente para la próxima edición).\n            const merged = { ...payload, ...(result.lineData ?? {}) };\n            if (lineId) {\n              const updatedLines = state.lines.map((l) =>\n                l.id === lineId ? { ...l, ...merged } : l,\n              );\n              dispatch({ type: 'UPDATE_LINE', lineId, data: merged });\n              // Antes de los totales: el modal sigue montado mientras esto corre\n              // —se cierra cuando `handleLineSave` resuelve—, y es de ahí de donde\n              // salen los valores adicionales de la línea.\n              await persistenceHooksRef.current?.onLinePersisted?.(lineId);\n              await autoSaveLineTotals(updatedLines);\n            } else {\n              const newLine: DocumentLineData = {\n                id: result.lineId,\n                line_number: state.lines.length + 1,\n                ...merged,\n              } as DocumentLineData;\n              dispatch({ type: 'ADD_LINE', line: newLine });\n              if (result.lineId) {\n                await persistenceHooksRef.current?.onLinePersisted?.(result.lineId);\n              }\n              await autoSaveLineTotals([...state.lines, newLine]);\n            }\n            // Sincronizar la versión/cabecera recalculadas por el backend tras el POST\n            // /lines. Sin esto la versión local se queda atrás y el poll de conflicto\n            // dispara un falso \"alguien más editó\". Se aplica DESPUÉS de UPDATE_LINE/\n            // ADD_LINE; SET_SERVER_VERSION y MERGE_STATE(headerValues) no tocan `lines`.\n            if (result.serverVersion) {\n              dispatch({ type: 'SET_SERVER_VERSION', version: result.serverVersion });\n            }\n            if (result.headerValues) {\n              dispatch({\n                type: 'MERGE_STATE',\n                payload: { headerValues: { ...state.headerValues, ...result.headerValues } },\n              });\n            }\n          } else if (result.errors) {\n            return partitionLineResult(result.errors);\n          }\n        } else if (lineId) {\n          // ── Sin documento, editando línea local: actualizar en estado ──\n          dispatch({ type: 'UPDATE_LINE', lineId, data });\n        } else {\n          // ── Sin documento, PRIMERA línea: intentar crear documento + línea juntos ──\n          // El adapter recibe headerValues para poder crear el documento en el mismo request.\n          // (En doc nuevo aún no hay row_version de cabecera, así que withHeaderVersion es no-op.)\n          const result = await adapter.saveLine(\n            null,\n            null,\n            withHeaderVersion(data, state.headerValues, state.serverVersion, headerVersionKey),\n            state.headerValues,\n          );\n          if (result.success) {\n            const merged = { ...data, ...(result.lineData ?? {}) };\n\n            if (result.documentId) {\n              // Backend creó el documento y la primera línea en una sola operación.\n              // Actualizar el estado con el nuevo documentId, modo 'edit' y los campos\n              // calculados por el backend (consecutivo, fecha, vencimiento, etc.).\n              dispatch({\n                type: 'MERGE_STATE',\n                payload: {\n                  documentId: result.documentId,\n                  mode: 'edit' as const,\n                  ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}),\n                  // Merge: primero los valores actuales del usuario, luego los del backend.\n                  // Así se respetan los campos ingresados y se agregan los calculados.\n                  ...(result.headerValues\n                    ? { headerValues: { ...state.headerValues, ...result.headerValues } }\n                    : {}),\n                },\n              });\n              const newLine: DocumentLineData = {\n                id: result.lineId,\n                line_number: state.lines.length + 1,\n                ...merged,\n              } as DocumentLineData;\n              dispatch({ type: 'ADD_LINE', line: newLine });\n              // Documento y primera línea nacieron en la misma operación: los dos\n              // ids existen recién ahora, así que las dos segundas fases se\n              // disparan aquí. El encabezado va primero por orden de dependencia.\n              await persistenceHooksRef.current?.onHeaderPersisted?.(result.documentId);\n              if (result.lineId) {\n                await persistenceHooksRef.current?.onLinePersisted?.(result.lineId);\n              }\n              // Pasar docIdOverride porque state.documentId aún no refleja el nuevo ID\n              await autoSaveLineTotals([...state.lines, newLine], result.documentId);\n            } else {\n              // Adapter no soporta creación combinada (ej: mock básico sin documentId).\n              // Agregar línea localmente con ID temporal; se persistirá al guardar cabecera.\n              dispatch({\n                type: 'ADD_LINE',\n                line: {\n                  id: `local-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n                  line_number: state.lines.length + 1,\n                  ...merged,\n                } as DocumentLineData,\n              });\n            }\n          } else if (result.errors) {\n            return partitionLineResult(result.errors);\n          }\n        }\n      } catch (err) {\n        handleMutationError(err);\n      } finally {\n        dispatch({ type: 'SET_SAVING', saving: false });\n      }\n      return undefined;\n    },\n    [state.documentId, state.lines, state.headerValues, state.serverVersion, lineVersionKey, headerVersionKey, adapter, autoSaveLineTotals, raiseConflict, handleMutationError],\n  );\n\n  // ── Delete line ───────────────────────────────────\n  // LA CONFIRMACIÓN NO VIVE AQUÍ. Antes esta función abría un `window.confirm` nativo: un cuadro del\n  // navegador, ajeno al estilo del kit, que además bloquea el hilo y obliga a parchear `window` para\n  // poder probar el borrado. La confirmación se movió a la capa que renderiza\n  // (`SmartMasterDocument`), que usa el `ConfirmDialog` del kit — el mismo patrón que `DocumentList`\n  // ya había adoptado para las acciones de fila con `requiresConfirmation`.\n  //\n  // CONSECUENCIA DELIBERADA para quien use este hook directamente: `handleDeleteLine` ya no pregunta,\n  // BORRA. Quien lo invoque fuera de `SmartMasterDocument` debe confirmar antes.\n  const handleDeleteLine = useCallback(\n    async (lineId: string) => {\n      dispatch({ type: 'SET_SAVING', saving: true });\n      try {\n        let deleteResult: DeleteLineResult | void = undefined;\n        if (state.documentId) {\n          // Expone al adapter el rowVersion de la línea Y el de la cabecera (leídos\n          // del estado), para los backends que validan concurrencia en el DELETE.\n          // Aditivo y opcional. Si el DELETE responde 409, el throw salta a la\n          // captura y la línea NO se elimina del estado (DELETE_LINE va después).\n          const current = state.lines.find((l) => l.id === lineId);\n          const rowVersion = current?.[lineVersionKey];\n          const headerRowVersion = state.headerValues[headerVersionKey] ?? state.serverVersion;\n          const options: { rowVersion?: string; headerRowVersion?: string } = {};\n          if (rowVersion != null) options.rowVersion = String(rowVersion);\n          if (headerRowVersion != null) options.headerRowVersion = String(headerRowVersion);\n          deleteResult = await adapter.deleteLine(\n            state.documentId,\n            lineId,\n            Object.keys(options).length > 0 ? options : undefined,\n          );\n        }\n        dispatch({ type: 'DELETE_LINE', lineId });\n\n        // Si el backend devuelve headerValues recalculados, aplicarlos directamente.\n        // Esto reemplaza la estrategia de autoSaveLineTotals (que el backend ignora).\n        const backendHeaderValues = (deleteResult as DeleteLineResult | undefined)?.headerValues;\n        if (backendHeaderValues && Object.keys(backendHeaderValues).length > 0) {\n          dispatch({\n            type: 'MERGE_STATE',\n            payload: { headerValues: { ...state.headerValues, ...backendHeaderValues } },\n          });\n        } else {\n          // Sin headerValues del backend → calcular localmente y persistir\n          const updatedLines = state.lines.filter((l) => l.id !== lineId);\n          await autoSaveLineTotals(updatedLines);\n        }\n\n        // Actualizar serverVersion si el backend la retornó\n        const newVersion = (deleteResult as DeleteLineResult | undefined)?.serverVersion;\n        if (newVersion) {\n          dispatch({ type: 'SET_SERVER_VERSION', version: newVersion });\n        }\n      } catch (err) {\n        handleMutationError(err);\n      } finally {\n        dispatch({ type: 'SET_SAVING', saving: false });\n      }\n    },\n    [state.documentId, state.lines, state.headerValues, state.serverVersion, lineVersionKey, headerVersionKey, adapter, autoSaveLineTotals, handleMutationError],\n  );\n\n  // ── Duplicate line ────────────────────────────────\n  const handleDuplicateLine = useCallback(\n    async (lineId: string) => {\n      const original = state.lines.find((l) => l.id === lineId);\n      if (!original) return;\n      dispatch({ type: 'SET_SAVING', saving: true });\n      try {\n        // Construir copia sin id/line_number — el backend asignará nuevos valores.\n        // Se descarta también el _row_version del original: la copia es una línea\n        // NUEVA y no debe heredar el token de versión de su origen. Sí viaja el\n        // row_version de la CABECERA para validar concurrencia del header.\n        const { id: _id, line_number: _ln, ...rest } = original;\n        const baseData = { ...rest };\n        delete (baseData as Record<string, unknown>)[lineVersionKey];\n        const lineData = withHeaderVersion(baseData, state.headerValues, state.serverVersion, headerVersionKey);\n        if (state.documentId && adapter.saveLine) {\n          const result = await adapter.saveLine(state.documentId, null, lineData);\n          if (result.success) {\n            const newLine: DocumentLineData = {\n              id: result.lineId,\n              line_number: state.lines.length + 1,\n              ...lineData,\n              ...(result.lineData ?? {}),\n            };\n            dispatch({ type: 'DUPLICATE_LINE', lineId, newLine });\n            await autoSaveLineTotals([...state.lines, newLine]);\n            // Sincronizar la versión/cabecera recalculadas por el backend tras el POST\n            // /lines. Sin esto la versión local se queda atrás y el poll de conflicto\n            // dispara un falso \"alguien más editó\" (mismo arreglo que en handleLineSave).\n            if (result.serverVersion) {\n              dispatch({ type: 'SET_SERVER_VERSION', version: result.serverVersion });\n            }\n            if (result.headerValues) {\n              dispatch({\n                type: 'MERGE_STATE',\n                payload: { headerValues: { ...state.headerValues, ...result.headerValues } },\n              });\n            }\n          }\n        } else {\n          // Sin backend: duplicar localmente con id temporal\n          const newLine: DocumentLineData = {\n            ...original,\n            id: `local-${Date.now()}`,\n            line_number: state.lines.length + 1,\n          };\n          dispatch({ type: 'DUPLICATE_LINE', lineId, newLine });\n        }\n      } catch (err) {\n        handleMutationError(err);\n      } finally {\n        dispatch({ type: 'SET_SAVING', saving: false });\n      }\n    },\n    [state.documentId, state.lines, state.headerValues, state.serverVersion, lineVersionKey, headerVersionKey, adapter, autoSaveLineTotals, handleMutationError],\n  );\n\n  // ── Transition ────────────────────────────────────\n  const handleTransition = useCallback(\n    async (to: string) => {\n      if (!state.documentId) return;\n\n      // Validate if guard exists\n      const transition = (template.stateMachine.transitions ?? []).find(\n        (t) => t.to === to && t.from.includes(state.docState),\n      );\n\n      // Gating in-flight (Caso B): mientras corre la transición, la barra de\n      // acciones queda deshabilitada para reducir la ventana de doble disparo\n      // (aprobar vs anular concurrentes).\n      dispatch({ type: 'SET_SAVING', saving: true });\n      try {\n        if (transition?.hasGuard && adapter.validateTransition) {\n          const validation = await adapter.validateTransition(state.documentId, to);\n          if (!validation.allowed) {\n            dispatch({ type: 'SET_ERROR', error: validation.errors?.join(', ') });\n            return;\n          }\n        }\n\n        // execute-process envía el row_version del header; un desfase responde 409\n        // (lanzado) y se trata como conflicto duro. La respuesta trae el nuevo\n        // serverVersion, que resincronizamos para la próxima mutación.\n        const result = await adapter.executeTransition(state.documentId, to, state.docState, state.serverVersion);\n        if (result.success) {\n          dispatch({ type: 'SET_DOC_STATE', docState: result.newState });\n          if (result.serverVersion) {\n            dispatch({ type: 'SET_SERVER_VERSION', version: result.serverVersion });\n          }\n        } else {\n          dispatch({ type: 'SET_ERROR', error: result.errors?.join(', ') });\n        }\n      } catch (err) {\n        handleMutationError(err);\n      } finally {\n        dispatch({ type: 'SET_SAVING', saving: false });\n      }\n    },\n    [state.documentId, state.docState, state.serverVersion, template.stateMachine.transitions, adapter, handleMutationError],\n  );\n\n  // ── Execute action ────────────────────────────────\n  const handleAction = useCallback(\n    async (actionKey: string) => {\n      // Gating in-flight (Caso B): deshabilita la barra de acciones mientras la\n      // acción (aprobar/anular/guardar) está en curso.\n      dispatch({ type: 'SET_SAVING', saving: true });\n      try {\n        const result = await adapter.executeAction(actionKey, state);\n        if (!result.success && result.message) {\n          dispatch({ type: 'SET_ERROR', error: result.message });\n          return;\n        }\n\n        // El documento fue eliminado (delete / cancel que borra): navegar de vuelta\n        // al listado en lugar de mezclar estado sobre un documento inexistente.\n        if (result.success && result.navigateToList) {\n          if (result.message) toast.success(result.message);\n          onNavigateToList?.();\n          return;\n        }\n\n        if (result.updatedData) {\n          dispatch({ type: 'MERGE_STATE', payload: result.updatedData });\n        }\n\n        // Tras crear el documento, persistir líneas locales (IDs temporales)\n        if (actionKey === 'save' && result.success) {\n          const newDocId = result.updatedData?.documentId ?? state.documentId;\n          if (newDocId) {\n            // Segunda fase del guardado. ESTE es el camino que recorre el botón\n            // \"Guardar\" de la barra de acciones: `handleSaveHeader` existe y hace lo\n            // propio, pero `SmartMasterDocument` no lo invoca — guarda por acción,\n            // vía `adapter.executeAction`. Enganchar solo allá dejaba los campos\n            // adicionales sin escribir en la aplicación real aunque las pruebas del\n            // reducer pasaran, porque llaman a `handleSaveHeader` directamente.\n            await persistenceHooksRef.current?.onHeaderPersisted?.(newDocId);\n\n            const localLines = state.lines.filter((l) => String(l.id).startsWith('local-'));\n            for (const line of localLines) {\n              try {\n                const { id: _id, line_number: _ln, ...lineData } = line;\n                const lineResult = await adapter.saveLine(newDocId, null, lineData);\n                if (lineResult.success) {\n                  dispatch({\n                    type: 'UPDATE_LINE',\n                    lineId: String(line.id),\n                    data: { id: lineResult.lineId, ...(lineResult.lineData ?? {}) },\n                  });\n                }\n              } catch { /* ignorar errores individuales de línea */ }\n            }\n          }\n          onSaved?.();\n        }\n      } catch (err) {\n        handleMutationError(err);\n      } finally {\n        dispatch({ type: 'SET_SAVING', saving: false });\n      }\n    },\n    [state, adapter, onSaved, onNavigateToList, handleMutationError],\n  );\n\n  // ── Approve / Reject ──────────────────────────────\n  const handleApprove = useCallback(async () => {\n    if (!state.documentId || !adapter.approve) return;\n    await adapter.approve(state.documentId);\n  }, [state.documentId, adapter]);\n\n  const handleReject = useCallback(async () => {\n    if (!state.documentId || !adapter.reject) return;\n    await adapter.reject(state.documentId);\n  }, [state.documentId, adapter]);\n\n  return {\n    state,\n    dispatch,\n    handleHeaderFieldChange,\n    handleSaveHeader,\n    handleLineSave,\n    handleDeleteLine,\n    handleDuplicateLine,\n    handleTransition,\n    handleAction,\n    handleApprove,\n    handleReject,\n  };\n}\n","import { useEffect } from 'react';\nimport type { Dispatch } from 'react';\nimport type { IMasterDocumentAdapter, DocumentState } from '../adapter/MasterDocumentAdapter.types';\nimport type { FactBoxSectionTemplate } from '../template/MasterDocumentTemplate.types';\n\nexport function useFactBoxData(\n  sections: FactBoxSectionTemplate[],\n  adapter: IMasterDocumentAdapter,\n  state: DocumentState,\n  dispatch: Dispatch<{ type: 'SET_FACTBOX_DATA'; sectionKey: string; data: Record<string, unknown> }>,\n) {\n  useEffect(() => {\n    if (!state.documentId) return;\n\n    const adapterSections = sections.filter((s) => s.dataSource === 'adapter');\n    if (adapterSections.length === 0) return;\n\n    let cancelled = false;\n\n    for (const section of adapterSections) {\n      // Skip if not visible in current state\n      if (section.visibleOn && !section.visibleOn.includes(state.docState) && !section.visibleOn.includes('*')) {\n        continue;\n      }\n\n      if (section.widget.type === 'statusHistory') {\n        // Historial de transiciones (OP1) — usa getStatusHistory en vez de getFactBoxData\n        if (!adapter.getStatusHistory) continue;\n        adapter.getStatusHistory(state.documentId!).then(\n          (entries) => {\n            if (!cancelled) {\n              dispatch({ type: 'SET_FACTBOX_DATA', sectionKey: section.key, data: { entries } });\n            }\n          },\n          () => { /* silently ignore errors */ },\n        );\n      } else {\n        // Resto de widgets — usa getFactBoxData genérico\n        if (!adapter.getFactBoxData) continue;\n        adapter.getFactBoxData(state.documentId!, section.key).then(\n          (data) => {\n            if (!cancelled) {\n              dispatch({ type: 'SET_FACTBOX_DATA', sectionKey: section.key, data });\n            }\n          },\n          () => { /* silently ignore factbox loading errors */ },\n        );\n      }\n    }\n\n    return () => { cancelled = true; };\n  }, [state.documentId, state.docState, sections, adapter, dispatch]);\n}\n","import { MASTER_DOCUMENT_TRANSLATIONS_ES } from '../i18n';\nimport type { TranslateFn } from '../i18nFactory';\nimport type { IMasterDocumentAdapter } from '../adapter/MasterDocumentAdapter.types';\n\n/**\n * Fetcher semántico para las llamadas del panel de cruce (Modelo B — FEAT-094).\n *\n * Enruta SIEMPRE por `adapter.genericFetch` cuando está disponible, de modo que\n * la app consumidora controle un único punto de salida HTTP: inyección de\n * autenticación (`Authorization`, `X-Company-Id`), `baseUrl` real y, si lo\n * necesita, remapeo de las rutas canónicas del kit a las del backend\n * (p. ej. `/api/v1/crossing/*` → `/api/v1/crossings/*`).\n *\n * Solo cae a `fetch` directo contra `baseUrl` cuando el adapter NO implementa\n * `genericFetch` (escenarios de Storybook/demo sin backend autenticado). En ese\n * camino los errores HTTP se normalizan a un `Error` con `errorCode`/`data` para\n * que la clasificación FE-08 (inline vs dialog) siga funcionando.\n */\nexport type CrossingFetch = <T = unknown>(method: string, path: string, body?: unknown) => Promise<T>;\n\n/**\n * Error normalizado de una operación de cruce. `errorCode` proviene del\n * `ProblemDetails` del backend (dependencia FE-08); `message` es texto de\n * usuario listo para mostrar (sin IDs internos ni stack traces).\n */\nexport interface CrossingError {\n  errorCode?: string;\n  message: string;\n  /**\n   * Clave i18n cuando el mensaje lo generó el kit y no el backend.\n   *\n   * `extractCrossingError` es una función pura consumida desde hooks, así que no\n   * puede llamar a `useMasterDocumentTranslation`. Cuando el error no traía texto\n   * propio del backend, propaga esta clave para que el hook llamante haga\n   * `messageKey ? t(messageKey) : message`. Cuando el backend SÍ mandó texto queda\n   * `undefined`: ese texto ya viene traducido (el kit envía `Accept-Language`) y\n   * tiene prioridad.\n   */\n  messageKey?: string;\n}\n\n/**\n * Códigos de error de cruce que el PRD (FE-08) clasifica como de LÍNEA y que por\n * tanto deben mostrarse inline junto a la fila afectada (no en dialog/banner).\n * El resto (p. ej. BR-13/BR-15) se trata a nivel documento/página.\n */\nconst LINE_LEVEL_ERROR_CODES = new Set(['BR-01', 'BR-11', 'BR-16', 'BR01', 'BR11', 'BR16']);\n\nexport function isLineLevelCrossingError(errorCode: string | undefined): boolean {\n  return errorCode ? LINE_LEVEL_ERROR_CODES.has(errorCode.toUpperCase()) : false;\n}\n\n/** Clave i18n del error genérico de cruce cuando el backend no manda texto propio. */\nconst FALLBACK_KEY = 'master_document.error.unexpected';\n/** Texto español del fallback, tomado del catálogo para no duplicar el literal. */\nconst FALLBACK_MESSAGE = MASTER_DOCUMENT_TRANSLATIONS_ES[FALLBACK_KEY];\n\n/**\n * Extrae `{ errorCode, message, messageKey }` de cualquier error lanzado por\n * `CrossingFetch`, cubriendo las formas más comunes: el propio `Error` con\n * `errorCode`/`data`, un `ProblemDetails` plano, o errores de cliente HTTP con\n * `response.data`.\n *\n * `messageKey` solo se rellena cuando el mensaje es el fallback del kit; si el\n * backend mandó texto, ese texto gana y `messageKey` queda `undefined`.\n */\nexport function extractCrossingError(err: unknown): CrossingError {\n  if (typeof err === 'string') {\n    return err ? { message: err } : { message: FALLBACK_MESSAGE, messageKey: FALLBACK_KEY };\n  }\n  if (err && typeof err === 'object') {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const e = err as Record<string, any>;\n    const data = e.response?.data ?? e.data ?? e.problem ?? e;\n    const errorCode = data?.errorCode ?? data?.error_code ?? e.errorCode;\n    const fromBackend = data?.detail ?? data?.message ?? data?.title ?? e.message;\n    return {\n      errorCode: errorCode != null ? String(errorCode) : undefined,\n      message: fromBackend != null ? String(fromBackend) : FALLBACK_MESSAGE,\n      messageKey: fromBackend != null ? undefined : FALLBACK_KEY,\n    };\n  }\n  return { message: FALLBACK_MESSAGE, messageKey: FALLBACK_KEY };\n}\n\n/**\n * Igual que `extractCrossingError`, pero ya traducido al idioma activo.\n *\n * Recibe `t` en vez de llamar al hook porque este módulo es puro; los hooks de\n * cruce (`useCrossing`, `useCrossDocuments`, `useBulkConversion`) obtienen `t` de\n * `useMasterDocumentTranslation` y lo pasan aquí.\n */\nexport function resolveCrossingError(err: unknown, t: TranslateFn): CrossingError {\n  const extracted = extractCrossingError(err);\n  return extracted.messageKey\n    ? { ...extracted, message: t(extracted.messageKey) }\n    : extracted;\n}\n\n/**\n * Construye el `CrossingFetch` para una sesión de MasterDocument.\n * Prefiere `adapter.genericFetch`; si no existe, usa `fetch` directo + `baseUrl`.\n */\nexport function createCrossingFetch(\n  adapter: IMasterDocumentAdapter,\n  baseUrl: string,\n): CrossingFetch {\n  const generic = adapter.genericFetch?.bind(adapter);\n  if (generic) {\n    return <T = unknown,>(method: string, path: string, body?: unknown): Promise<T> =>\n      generic(method, path, body) as Promise<T>;\n  }\n\n  return async <T = unknown,>(method: string, path: string, body?: unknown): Promise<T> => {\n    const res = await fetch(`${baseUrl}${path}`, {\n      method,\n      headers: body !== undefined ? { 'Content-Type': 'application/json' } : undefined,\n      body: body !== undefined ? JSON.stringify(body) : undefined,\n    });\n    if (!res.ok) {\n      throw await buildHttpError(res);\n    }\n    const text = await res.text();\n    return (text ? JSON.parse(text) : undefined) as T;\n  };\n}\n\nasync function buildHttpError(\n  res: Response,\n): Promise<Error & { errorCode?: string; data?: unknown }> {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  let data: any;\n  try {\n    data = await res.json();\n  } catch {\n    /* respuesta sin cuerpo JSON */\n  }\n  const message = data?.detail ?? data?.message ?? data?.title ?? `HTTP ${res.status}`;\n  const err = new Error(String(message)) as Error & { errorCode?: string; data?: unknown };\n  err.errorCode = data?.errorCode ?? data?.error_code;\n  err.data = data;\n  return err;\n}\n","import { useState, useEffect, useCallback } from 'react';\nimport type { CrossingMessagesConfig, CrossingTemplateConfig } from '../template/MasterDocumentTemplate.types';\nimport type {\n  CrossingClassOption,\n  CrossingSourceDocument,\n  LineFulfillmentStatus,\n  PendingLine,\n  TraceabilityTreeNode,\n} from '../MasterDocument.types';\nimport { isLineLevelCrossingError, resolveCrossingError } from './crossingFetch';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport type { CrossingFetch } from './crossingFetch';\nimport type { TranslateFn } from '../i18nFactory';\n\n/**\n * Mensajes de validación de \"Cantidad a cruzar\" (FE-02), sobreescribibles vía template.\n *\n * Recibe `t` en vez de llamar al hook porque es una función pura; el hook se lo\n * pasa. El override del template sigue teniendo prioridad sobre el catálogo.\n */\nfunction validateQuantity(\n  quantity: number,\n  pending: number,\n  t: TranslateFn,\n  uom?: string,\n  messages?: CrossingMessagesConfig,\n): string | undefined {\n  if (Number.isNaN(quantity)) {\n    return messages?.quantityRequired ?? t('master_document.crossing.quantityRequired');\n  }\n  if (quantity <= 0) {\n    return messages?.quantityPositive ?? t('master_document.crossing.quantityPositive');\n  }\n  if (quantity > pending) {\n    // El override del template conserva su contrato original: `{uom}` recibe la\n    // unidad sin espacio previo, porque la plantilla del host ya lo incluye.\n    if (messages?.quantityExceedsPending) {\n      return messages.quantityExceedsPending\n        .replaceAll('{pending}', String(pending))\n        .replaceAll('{uom}', uom ?? '')\n        .trim();\n    }\n    // La clave del catálogo sí espera el espacio dentro del propio valor, para\n    // que sin unidad no quede un hueco antes del paréntesis de cierre.\n    return t('master_document.crossing.quantityExceedsPending', {\n      pending: String(pending),\n      uom: uom ? ` ${uom}` : '',\n    });\n  }\n  return undefined;\n}\n\ninterface UseCrossingOptions {\n  config: CrossingTemplateConfig | undefined;\n  documentId: string | undefined;\n  docState: string;\n  hasLines: boolean;\n  /**\n   * Salida HTTP del panel de cruce. Enruta por `adapter.genericFetch` (auth,\n   * baseUrl, remapeo de rutas) — ver {@link createCrossingFetch}.\n   */\n  crossingFetch: CrossingFetch;\n  onDocumentGenerated?: (docId: string) => void;\n}\n\nexport interface CrossingState {\n  selectedSourceDocuments: CrossingSourceDocument[];\n  sourceSelectorLocked: boolean;\n\n  selectedLineIds: string[];\n  lineStatuses: Record<string, LineFulfillmentStatus>;\n  lineSelectionErrors: Record<string, string>;\n  pendingLines: PendingLine[];\n  quantitiesToCross: Record<string, number>;\n  canGenerate: boolean;\n  pendingLinesFetchedAt: string | null;\n  pendingLinesLoading: boolean;\n\n  crossingClassOptions: CrossingClassOption[];\n  crossingClassMenuOpen: boolean;\n\n  lineCloseModal: {\n    open: boolean;\n    lineId: string | null;\n    lineDescription: string;\n    mode: 'close' | 'reopen';\n    isLoading: boolean;\n    error: string | undefined;\n  };\n\n  generateModal: {\n    open: boolean;\n    classId: string;\n    classLabel: string;\n    isLoading: boolean;\n    error: string | undefined;\n  };\n\n  generateError: string | undefined;\n  pageErrors: string[];\n\n  activeTab: 'lines' | 'traceability';\n  traceabilityTree: TraceabilityTreeNode | null;\n  traceabilityLoading: boolean;\n  traceabilityError: string | undefined;\n}\n\nexport interface CrossingActions {\n  addSourceDocument: (doc: CrossingSourceDocument) => void;\n  removeSourceDocument: (docId: string) => void;\n  searchSourceDocuments: (query: string) => Promise<CrossingSourceDocument[]>;\n  toggleLineSelection: (lineId: string, selected: boolean) => void;\n  trySelectTerminalLine: (lineId: string) => void;\n  setQuantityToCross: (lineId: string, quantity: number) => void;\n  refreshPendingLines: () => void;\n  openCrossClassMenu: () => void;\n  closeCrossClassMenu: () => void;\n  selectClass: (classId: string) => void;\n  generateChild: (classId: string, headerValues?: Record<string, unknown>) => Promise<string | null>;\n  openLineCloseModal: (lineId: string, description: string, mode: 'close' | 'reopen') => void;\n  closeLineCloseModal: () => void;\n  confirmLineClose: (reason?: string) => Promise<void>;\n  openGenerateModal: (classId: string, classLabel: string) => void;\n  cancelGenerateModal: () => void;\n  confirmGenerate: (headerValues: Record<string, unknown>) => Promise<void>;\n  clearGenerateError: () => void;\n  addPageError: (message: string) => void;\n  dismissPageError: (index: number) => void;\n  setActiveTab: (tab: 'lines' | 'traceability') => void;\n  refreshTraceability: () => void;\n}\n\n// ─── mapNode helper ───────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction mapNode(raw: any): TraceabilityTreeNode {\n  return {\n    id: raw.id,\n    number: raw.number,\n    classLabel: raw.class_label,\n    status: raw.status,\n    quantityOrdered: raw.quantity_ordered,\n    quantityFulfilled: raw.quantity_fulfilled,\n    isCurrent: raw.is_current,\n    parents: (raw.parents ?? []).map(mapNode),\n    children: (raw.children ?? []).map(mapNode),\n  };\n}\n\n// ─── mapPendingLine helper ────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction mapPendingLine(raw: any, fallbackSourceId: string): PendingLine {\n  return {\n    lineId: String(raw.line_id ?? raw.id ?? raw.lineId),\n    sourceDocumentId: String(raw.source_document_id ?? raw.document_id ?? fallbackSourceId),\n    documentNumber: raw.document_number ?? raw.documentNumber,\n    itemCode: raw.item_code ?? raw.itemCode,\n    itemDescription: raw.item_description ?? raw.itemDescription,\n    quantityOrdered: raw.quantity_ordered ?? raw.quantityOrdered,\n    quantityFulfilled: raw.quantity_fulfilled ?? raw.quantityFulfilled,\n    quantityPending: Number(raw.quantity_pending ?? raw.quantityPending ?? 0),\n    unitOfMeasure: raw.unit_of_measure ?? raw.unitOfMeasure,\n    unitPrice: raw.unit_price ?? raw.unitPrice ?? null,\n    lineStatus: (raw.line_status ?? raw.lineStatus ?? 'Pending') as LineFulfillmentStatus,\n  };\n}\n\n// ─── Internal hook (always called unconditionally) ────────────\n\nfunction useCrossingInternal({\n  config,\n  documentId,\n  hasLines,\n  crossingFetch,\n  onDocumentGenerated,\n}: UseCrossingOptions): { state: CrossingState; actions: CrossingActions } {\n  // Traduce los errores que genera el kit; los que trae el backend pasan intactos.\n  const { t } = useMasterDocumentTranslation();\n  const [selectedSourceDocuments, setSelectedSourceDocuments] = useState<CrossingSourceDocument[]>([]);\n  const [selectedLineIds, setSelectedLineIds] = useState<string[]>([]);\n  const [lineStatuses, setLineStatuses] = useState<Record<string, LineFulfillmentStatus>>({});\n  const [lineSelectionErrors, setLineSelectionErrors] = useState<Record<string, string>>({});\n  const [pendingLines, setPendingLines] = useState<PendingLine[]>([]);\n  const [quantitiesToCross, setQuantitiesToCross] = useState<Record<string, number>>({});\n  const [pendingLinesFetchedAt, setPendingLinesFetchedAt] = useState<string | null>(null);\n  const [pendingLinesLoading, setPendingLinesLoading] = useState(false);\n  const [crossingClassOptions, setCrossingClassOptions] = useState<CrossingClassOption[]>([]);\n  const [crossingClassMenuOpen, setCrossingClassMenuOpen] = useState(false);\n  const [lineCloseModal, setLineCloseModal] = useState<CrossingState['lineCloseModal']>({\n    open: false,\n    lineId: null,\n    lineDescription: '',\n    mode: 'close',\n    isLoading: false,\n    error: undefined,\n  });\n  const [generateModal, setGenerateModal] = useState<CrossingState['generateModal']>({\n    open: false,\n    classId: '',\n    classLabel: '',\n    isLoading: false,\n    error: undefined,\n  });\n  const [generateError, setGenerateError] = useState<string | undefined>(undefined);\n  const [pageErrors, setPageErrors] = useState<string[]>([]);\n  const [activeTab, setActiveTab] = useState<'lines' | 'traceability'>('lines');\n  const [traceabilityTree, setTraceabilityTree] = useState<TraceabilityTreeNode | null>(null);\n  const [traceabilityLoading, setTraceabilityLoading] = useState(false);\n  const [traceabilityError, setTraceabilityError] = useState<string | undefined>(undefined);\n\n  // ── Fetch crossing rules on mount ─────────────────────────\n  useEffect(() => {\n    if (!config || !config.enabled) return;\n    let cancelled = false;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    crossingFetch<any>('GET', '/api/v1/crossing/rules')\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      .then((payload: any) => {\n        if (cancelled) return;\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        const rules: any[] = Array.isArray(payload) ? payload : (payload?.data ?? []);\n        setCrossingClassOptions(\n          rules.map((rule) => ({\n            id: rule.child_class_id,\n            label: rule.child_class_label,\n            description: rule.description,\n          })),\n        );\n      })\n      // Carga no crítica: si falla, el menú de clases queda vacío (sin bloquear).\n      .catch(() => { /* opciones de cruce no disponibles */ });\n    return () => { cancelled = true; };\n  }, [config, crossingFetch]);\n\n  // ── Fetch pending lines (agrega TODOS los documentos origen — FE-01) ──\n  const fetchPendingLines = useCallback(() => {\n    if (!config || !config.enabled) return;\n    if (selectedSourceDocuments.length === 0) {\n      setPendingLines([]);\n      setLineStatuses({});\n      return;\n    }\n    const childClassId = crossingClassOptions[0]?.id ?? '';\n    setPendingLinesLoading(true);\n\n    Promise.all(\n      selectedSourceDocuments.map((doc) =>\n        crossingFetch<unknown>(\n          'GET',\n          `/api/v1/crossing/pending-lines?source_document_id=${encodeURIComponent(doc.id)}&child_class_id=${encodeURIComponent(childClassId)}`,\n        )\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n          .then((payload: any) => {\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            const rows: any[] = Array.isArray(payload) ? payload : (payload?.lines ?? []);\n            return rows.map((row) => mapPendingLine(row, doc.id));\n          }),\n      ),\n    )\n      .then((perDoc) => {\n        const merged = perDoc.flat();\n        setPendingLines(merged);\n        const map: Record<string, LineFulfillmentStatus> = {};\n        for (const line of merged) map[line.lineId] = line.lineStatus;\n        setLineStatuses(map);\n        setPendingLinesFetchedAt(new Date().toISOString());\n      })\n      .catch((err) => {\n        const { message } = resolveCrossingError(err, t);\n        setPageErrors((prev) => (prev.includes(message) ? prev : [...prev, message]));\n      })\n      .finally(() => setPendingLinesLoading(false));\n  }, [config, selectedSourceDocuments, crossingClassOptions, crossingFetch, t]);\n\n  useEffect(() => {\n    if (!config || !config.enabled) return;\n    if (selectedSourceDocuments.length === 0) return;\n    fetchPendingLines();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [selectedSourceDocuments, config]);\n\n  // ── Fetch traceability tree ───────────────────────────────\n  const fetchTraceabilityTree = useCallback(() => {\n    if (!config || !config.enabled) return;\n    if (!documentId) return;\n    setTraceabilityLoading(true);\n    setTraceabilityError(undefined);\n    crossingFetch<unknown>(\n      'GET',\n      `/api/v1/crossing/document-tree?document_id=${encodeURIComponent(documentId)}`,\n    )\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      .then((payload: any) => {\n        const raw = payload?.root ?? payload;\n        setTraceabilityTree(mapNode(raw));\n      })\n      .catch((err) => {\n        setTraceabilityError(resolveCrossingError(err, t).message);\n      })\n      .finally(() => setTraceabilityLoading(false));\n  }, [config, documentId, crossingFetch, t]);\n\n  useEffect(() => {\n    if (!config || !config.enabled) return;\n    if (!documentId) return;\n    fetchTraceabilityTree();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [documentId, config]);\n\n  // ── Actions ───────────────────────────────────────────────\n\n  const addSourceDocument = useCallback((doc: CrossingSourceDocument) => {\n    setSelectedSourceDocuments((prev) => {\n      if (prev.some((d) => d.id === doc.id)) return prev;\n      return [...prev, doc];\n    });\n  }, []);\n\n  const removeSourceDocument = useCallback((docId: string) => {\n    setSelectedSourceDocuments((prev) => prev.filter((d) => d.id !== docId));\n  }, []);\n\n  const searchSourceDocuments = useCallback(\n    async (query: string): Promise<CrossingSourceDocument[]> => {\n      if (!config || !query.trim()) return [];\n      try {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        const payload: any = await crossingFetch<any>(\n          'GET',\n          `/api/v1/crossing/search-documents?q=${encodeURIComponent(query)}`,\n        );\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        const docs: any[] = Array.isArray(payload) ? payload : (payload?.data ?? []);\n        return docs.map((d) => ({\n          id: String(d.id),\n          number: String(d.number ?? d.document_number ?? ''),\n          classLabel: String(d.class_label ?? d.classLabel ?? ''),\n        }));\n      } catch {\n        // Búsqueda type-ahead: ante error devolvemos lista vacía (sin bloquear).\n        return [];\n      }\n    },\n    [config, crossingFetch],\n  );\n\n  const toggleLineSelection = useCallback(\n    (lineId: string, selected: boolean) => {\n      setSelectedLineIds((prev) =>\n        selected ? [...prev.filter((id) => id !== lineId), lineId] : prev.filter((id) => id !== lineId),\n      );\n      if (selected) {\n        // Al seleccionar, predefine la cantidad a cruzar = pendiente de la línea.\n        const pending = pendingLines.find((l) => l.lineId === lineId)?.quantityPending;\n        if (pending != null) {\n          setQuantitiesToCross((prev) => ({ ...prev, [lineId]: pending }));\n        }\n      } else {\n        // Al deseleccionar, limpia cantidad y error de esa línea.\n        setQuantitiesToCross((prev) => {\n          const next = { ...prev };\n          delete next[lineId];\n          return next;\n        });\n        setLineSelectionErrors((prev) => {\n          const next = { ...prev };\n          delete next[lineId];\n          return next;\n        });\n      }\n    },\n    [pendingLines],\n  );\n\n  const trySelectTerminalLine = useCallback(\n    (lineId: string) => {\n      setLineSelectionErrors((prev) => ({\n        ...prev,\n        [lineId]:\n          config?.messages?.terminalLineNotSelectable\n          ?? t('master_document.crossing.terminalLineMessage'),\n      }));\n    },\n    [config, t],\n  );\n\n  const setQuantityToCross = useCallback(\n    (lineId: string, quantity: number) => {\n      setQuantitiesToCross((prev) => ({ ...prev, [lineId]: quantity }));\n      const line = pendingLines.find((l) => l.lineId === lineId);\n      const message = validateQuantity(\n        quantity,\n        line?.quantityPending ?? 0,\n        t,\n        line?.unitOfMeasure,\n        config?.messages,\n      );\n      setLineSelectionErrors((prev) => {\n        const next = { ...prev };\n        if (message) next[lineId] = message;\n        else delete next[lineId];\n        return next;\n      });\n    },\n    [pendingLines, config, t],\n  );\n\n  const openCrossClassMenu = useCallback(() => setCrossingClassMenuOpen(true), []);\n  const closeCrossClassMenu = useCallback(() => setCrossingClassMenuOpen(false), []);\n  // Selecciona una clase hija del menú: cierra el menú y abre el modal de header\n  // obligatorio con la clase elegida (FE-06). El flujo de generación continúa en\n  // confirmGenerate.\n  const selectClass = useCallback((classId: string) => {\n    setCrossingClassMenuOpen(false);\n    setCrossingClassOptions((options) => {\n      const classLabel = options.find((o) => o.id === classId)?.label ?? classId;\n      setGenerateModal({ open: true, classId, classLabel, isLoading: false, error: undefined });\n      return options;\n    });\n    setGenerateError(undefined);\n  }, []);\n\n  // Lanza en error; usado internamente por confirmGenerate para exponer el\n  // mensaje del backend. La acción pública `generateChild` lo envuelve y\n  // devuelve null ante fallo para preservar su contrato histórico.\n  const generateChildInternal = useCallback(\n    async (classId: string, headerValues?: Record<string, unknown>): Promise<string> => {\n      const sourceDocId = selectedSourceDocuments[0]?.id;\n      if (!sourceDocId || selectedLineIds.length === 0) {\n        throw new Error(t('master_document.crossing.selectLineToGenerate'));\n      }\n      // selected_lines lleva la cantidad a cruzar por línea (FE-02). Espeja\n      // GenerateChildDocumentDto.SelectedLines del backend.\n      const selectedLines = selectedLineIds.map((lineId) => {\n        const line = pendingLines.find((l) => l.lineId === lineId);\n        return {\n          source_line_id: lineId,\n          source_document_id: line?.sourceDocumentId ?? sourceDocId,\n          quantity_to_cross: quantitiesToCross[lineId] ?? line?.quantityPending ?? 0,\n        };\n      });\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const payload: any = await crossingFetch<any>('POST', '/api/v1/crossing/generate', {\n        source_document_id: sourceDocId,\n        child_class_id: classId,\n        line_ids: selectedLineIds, // compat\n        selected_lines: selectedLines,\n        header_values: headerValues ?? {},\n      });\n      const docId = payload?.document_id ?? payload?.documentId ?? null;\n      if (!docId) {\n        throw new Error(t('master_document.crossing.noGeneratedDocument'));\n      }\n      return String(docId);\n    },\n    [selectedSourceDocuments, selectedLineIds, pendingLines, quantitiesToCross, crossingFetch, t],\n  );\n\n  const generateChild = useCallback(\n    async (classId: string, headerValues?: Record<string, unknown>): Promise<string | null> => {\n      try {\n        return await generateChildInternal(classId, headerValues);\n      } catch {\n        return null;\n      }\n    },\n    [generateChildInternal],\n  );\n\n  const openLineCloseModal = useCallback(\n    (lineId: string, description: string, mode: 'close' | 'reopen') => {\n      setLineCloseModal({ open: true, lineId, lineDescription: description, mode, isLoading: false, error: undefined });\n    },\n    [],\n  );\n\n  const closeLineCloseModal = useCallback(() => {\n    setLineCloseModal((prev) => ({ ...prev, open: false, lineId: null, error: undefined }));\n  }, []);\n\n  const openGenerateModal = useCallback((classId: string, classLabel: string) => {\n    setGenerateModal({ open: true, classId, classLabel, isLoading: false, error: undefined });\n    setGenerateError(undefined);\n  }, []);\n\n  const cancelGenerateModal = useCallback(() => {\n    setGenerateModal((prev) => ({ ...prev, open: false, error: undefined }));\n  }, []);\n\n  const confirmGenerate = useCallback(\n    async (headerValues: Record<string, unknown>) => {\n      setGenerateModal((prev) => ({ ...prev, isLoading: true, error: undefined }));\n      const classId = generateModal.classId;\n      try {\n        const docId = await generateChildInternal(classId, headerValues);\n        setGenerateModal({ open: false, classId: '', classLabel: '', isLoading: false, error: undefined });\n        onDocumentGenerated?.(docId);\n      } catch (err) {\n        setGenerateModal((prev) => ({\n          ...prev,\n          isLoading: false,\n          error: resolveCrossingError(err, t).message,\n        }));\n      }\n    },\n    [generateModal.classId, generateChildInternal, onDocumentGenerated, t],\n  );\n\n  const clearGenerateError = useCallback(() => {\n    setGenerateError(undefined);\n  }, []);\n\n  const addPageError = useCallback((message: string) => {\n    setPageErrors((prev) => [...prev, message]);\n  }, []);\n\n  const dismissPageError = useCallback((index: number) => {\n    setPageErrors((prev) => prev.filter((_, i) => i !== index));\n  }, []);\n\n  const confirmLineClose = useCallback(\n    async (reason?: string) => {\n      setLineCloseModal((prev) => ({ ...prev, isLoading: true, error: undefined }));\n      const lineId = lineCloseModal.lineId;\n      const mode = lineCloseModal.mode;\n      if (!lineId) return;\n      try {\n        if (mode === 'close') {\n          await crossingFetch('POST', `/api/v1/crossing/lines/${encodeURIComponent(lineId)}/close`, {\n            closeReason: reason,\n          });\n        } else {\n          await crossingFetch('POST', `/api/v1/crossing/lines/${encodeURIComponent(lineId)}/reopen`);\n        }\n        setLineStatuses((prev) => ({\n          ...prev,\n          [lineId]: mode === 'close' ? 'Closed' : 'Pending',\n        }));\n        setLineCloseModal({ open: false, lineId: null, lineDescription: '', mode: 'close', isLoading: false, error: undefined });\n        fetchPendingLines();\n      } catch (err) {\n        const { errorCode, message } = resolveCrossingError(err, t);\n        setLineCloseModal((prev) => ({ ...prev, isLoading: false, error: message }));\n        // FE-08: los errores de línea (BR-01/11/16) también se reflejan inline\n        // junto a la fila afectada.\n        if (isLineLevelCrossingError(errorCode)) {\n          setLineSelectionErrors((prev) => ({ ...prev, [lineId]: message }));\n        }\n      }\n    },\n    [lineCloseModal.lineId, lineCloseModal.mode, crossingFetch, fetchPendingLines, t],\n  );\n\n  const handleSetActiveTab = useCallback((tab: 'lines' | 'traceability') => {\n    setActiveTab(tab);\n  }, []);\n\n  // Habilita generar/cruzar solo si hay líneas seleccionadas, ninguna con error\n  // de validación, y todas con cantidad > 0 (FE-02).\n  const canGenerate =\n    selectedLineIds.length > 0 &&\n    selectedLineIds.every((id) => !lineSelectionErrors[id]) &&\n    selectedLineIds.every((id) => {\n      const q = quantitiesToCross[id];\n      return q != null && !Number.isNaN(q) && q > 0;\n    });\n\n  const state: CrossingState = {\n    selectedSourceDocuments,\n    sourceSelectorLocked: hasLines,\n    selectedLineIds,\n    lineStatuses,\n    lineSelectionErrors,\n    pendingLines,\n    quantitiesToCross,\n    canGenerate,\n    pendingLinesFetchedAt,\n    pendingLinesLoading,\n    crossingClassOptions,\n    crossingClassMenuOpen,\n    lineCloseModal,\n    generateModal,\n    generateError,\n    pageErrors,\n    activeTab,\n    traceabilityTree,\n    traceabilityLoading,\n    traceabilityError,\n  };\n\n  const actions: CrossingActions = {\n    addSourceDocument,\n    removeSourceDocument,\n    searchSourceDocuments,\n    toggleLineSelection,\n    trySelectTerminalLine,\n    setQuantityToCross,\n    refreshPendingLines: fetchPendingLines,\n    openCrossClassMenu,\n    closeCrossClassMenu,\n    selectClass,\n    generateChild,\n    openLineCloseModal,\n    closeLineCloseModal,\n    confirmLineClose,\n    openGenerateModal,\n    cancelGenerateModal,\n    confirmGenerate,\n    clearGenerateError,\n    addPageError,\n    dismissPageError,\n    setActiveTab: handleSetActiveTab,\n    refreshTraceability: fetchTraceabilityTree,\n  };\n\n  return { state, actions };\n}\n\n// ─── Public hook ──────────────────────────────────────────────\n\nexport function useCrossing(\n  options: UseCrossingOptions,\n): { state: CrossingState; actions: CrossingActions } | null {\n  const result = useCrossingInternal(options);\n  if (!options.config || !options.config.enabled) return null;\n  return result;\n}\n","import { clsx } from 'clsx';\nimport type { FactBoxTotalsProps } from './MasterDocument.types';\n\n/**\n * Widget de totales del documento para el panel FactBox.\n *\n * Renderiza un contenedor azul unificado con el total general, una grilla 2×2\n * de KPIs secundarios y un desglose detallado — todo dentro del mismo bloque.\n * Todos los valores monetarios son cadenas ya formateadas por el consumidor.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - FactBoxTotalsProps\n *\n * @example\n * ```tsx\n * <FactBoxTotals\n *   grandTotal={{ value: '$1.500.000', label: 'Total documento' }}\n *   kpis={[{ label: 'Subtotal', value: '$1.200.000' }]}\n *   breakdown={[{ label: 'IVA 19%', value: '$228.000' }]}\n * />\n * ```\n */\nexport function FactBoxTotals({\n  grandTotal,\n  kpis,\n  breakdown,\n  className,\n}: FactBoxTotalsProps) {\n  const hasSections = kpis.length > 0 || breakdown.length > 0;\n\n  return (\n    <div\n      className={clsx(\n        'bg-primary-custom-100 dark:bg-primary-custom-600/10 rounded-[10px] px-4 py-3.5',\n        className,\n      )}\n    >\n      {/* ── Grand Total ─────────────────────────────── */}\n      <div className=\"text-xl font-extrabold tabular-nums text-primary-custom-700 dark:text-primary-custom-400 leading-tight\">\n        {grandTotal.value}\n      </div>\n      <div className=\"text-xs font-semibold uppercase tracking-wide text-primary-custom-600 dark:text-primary-custom-500 mt-1\">\n        {grandTotal.label}\n      </div>\n      {grandTotal.subtitle && (\n        <div className=\"text-xs text-primary-custom-600 dark:text-primary-custom-500 mt-0.5\">\n          {grandTotal.subtitle}\n        </div>\n      )}\n\n      {hasSections && (\n        <div className=\"h-px bg-primary-custom-300 dark:bg-primary-custom-600/40 my-2.5\" />\n      )}\n\n      {/* ── KPI grid 2×2 ────────────────────────────── */}\n      {kpis.length > 0 && (\n        <div className=\"grid grid-cols-2 gap-x-3 gap-y-2\">\n          {kpis.map((kpi) => (\n            <div key={kpi.label} className=\"flex flex-col gap-0.5\">\n              <span className=\"text-xs text-primary-custom-600 dark:text-primary-custom-500 leading-tight\">\n                {kpi.label}\n              </span>\n              <span\n                className={clsx(\n                  'text-xs font-bold tabular-nums leading-tight',\n                  kpi.color ? kpi.color : 'text-primary-custom-700 dark:text-primary-custom-400',\n                )}\n              >\n                {kpi.value}\n              </span>\n            </div>\n          ))}\n        </div>\n      )}\n\n      {/* ── Breakdown rows ───────────────────────────── */}\n      {breakdown.length > 0 && (\n        <div className=\"mt-2.5 flex flex-col gap-0\">\n          {breakdown.map((item) => (\n            <div key={item.label}>\n              {item.isSummary && (\n                <div className=\"h-px bg-primary-custom-300 dark:bg-primary-custom-600/40 my-2\" />\n              )}\n              <div className=\"flex items-center justify-between py-[3px]\">\n                <span\n                  className={clsx(\n                    item.isSummary\n                      ? 'text-xs font-bold text-primary-custom-700 dark:text-primary-custom-400'\n                      : 'text-xs text-primary-custom-600 dark:text-primary-custom-500',\n                  )}\n                >\n                  {item.label}\n                </span>\n                <span\n                  className={clsx(\n                    'tabular-nums',\n                    item.isSummary\n                      ? 'text-sm font-extrabold text-primary-custom-700 dark:text-primary-custom-400'\n                      : 'text-xs font-semibold',\n                    item.color\n                      ? item.color\n                      : 'text-primary-custom-700 dark:text-primary-custom-400',\n                  )}\n                >\n                  {item.value}\n                </span>\n              </div>\n            </div>\n          ))}\n        </div>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { FactBoxCfdeProps, CfdeStatus } from './MasterDocument.types';\n\n/**\n * Configuración de colores por estado DIAN.\n *\n * Se utilizan colores semánticos de Tailwind (amber, blue, green, red) porque\n * el sistema de tokens actual solo define `error-*`. Cuando se agreguen tokens\n * `success-*`, `warning-*` e `info-*` al sistema, migrar a esos tokens.\n */\nconst statusConfig: Record<CfdeStatus, { translationKey: string; bg: string; color: string; icon: string }> = {\n  PENDING:  { translationKey: 'master_document.cfde.status.pending',  bg: 'bg-amber-100 dark:bg-amber-900/20', color: 'text-amber-700 dark:text-amber-400', icon: '⏳' },\n  SENT:     { translationKey: 'master_document.cfde.status.sent',     bg: 'bg-blue-100 dark:bg-blue-900/20',   color: 'text-blue-700 dark:text-blue-400',   icon: '📤' },\n  ACCEPTED: { translationKey: 'master_document.cfde.status.accepted', bg: 'bg-green-100 dark:bg-green-900/20', color: 'text-green-700 dark:text-green-400', icon: '✓' },\n  REJECTED: { translationKey: 'master_document.cfde.status.rejected', bg: 'bg-error-bg dark:bg-error-bg/20',   color: 'text-error-content dark:text-error-content', icon: '✗' },\n  ERROR:    { translationKey: 'master_document.cfde.status.error',    bg: 'bg-error-bg dark:bg-error-bg/20',   color: 'text-error-content dark:text-error-content', icon: '!' },\n};\n\n/**\n * Widget de información DIAN (Factura Electrónica) para el panel FactBox.\n *\n * Muestra el estado de transmisión DIAN con su insignia de color, el número de\n * FE, CUFE, fecha de emisión, contador de impresiones y enlace al QR. Expone\n * acciones de Retransmitir (estados REJECTED/ERROR) y Descargar PDF (estado\n * ACCEPTED) cuando se proveen los callbacks correspondientes.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - FactBoxCfdeProps, CfdeStatus\n *\n * @example\n * ```tsx\n * <FactBoxCfde\n *   data={{ status: 'ACCEPTED', number: 'FE-0001', cufe: 'abc123' }}\n *   onDownloadPdf={() => downloadPdf()}\n * />\n * ```\n */\nexport function FactBoxCfde({ data, onRetransmit, onDownloadPdf, className }: FactBoxCfdeProps) {\n  const { t } = useMasterDocumentTranslation();\n  const cfg = statusConfig[data.status];\n  const statusLabel = t(cfg.translationKey);\n\n  return (\n    <div className={clsx('flex flex-col gap-2.5', className)}>\n      {/* Status badge */}\n      <div className=\"flex items-center justify-between\">\n        <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary\">{t('master_document.cfde.dianStatus')}</span>\n        <span\n          className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${cfg.bg} ${cfg.color}`}\n          aria-label={t('master_document.cfde.statusAria', { status: statusLabel })}\n        >\n          <span className=\"text-[10px]\" aria-hidden=\"true\">{cfg.icon}</span>\n          {statusLabel}\n        </span>\n      </div>\n\n      {/* CFDE Number */}\n      {data.number && (\n        <div className=\"flex items-center justify-between\">\n          <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary\">{t('master_document.cfde.feNumber')}</span>\n          <span className=\"text-xs font-semibold text-content-primary dark:text-dark-content-primary\">\n            {data.number}\n          </span>\n        </div>\n      )}\n\n      {/* CUFE */}\n      {data.cufe && (\n        <div>\n          <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary block mb-0.5\">CUFE</span>\n          <span className=\"text-[10px] text-content-secondary dark:text-dark-content-secondary break-all leading-relaxed\">\n            {data.cufe}\n          </span>\n        </div>\n      )}\n\n      {/* Issue date */}\n      {data.issueDate && (\n        <div className=\"flex items-center justify-between\">\n          <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary\">{t('master_document.cfde.issueDate')}</span>\n          <span className=\"text-xs text-content-primary dark:text-dark-content-primary\">\n            {data.issueDate}\n          </span>\n        </div>\n      )}\n\n      {/* Print count */}\n      {data.printCount != null && (\n        <div className=\"flex items-center justify-between\">\n          <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary\">{t('master_document.cfde.prints')}</span>\n          <span className=\"text-xs font-semibold text-content-primary dark:text-dark-content-primary\">\n            {data.printCount}\n          </span>\n        </div>\n      )}\n\n      {/* QR link */}\n      {data.qrUrl && (\n        <a\n          href={data.qrUrl}\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n          className=\"text-xs font-semibold text-primary-600 dark:text-primary-400 hover:underline\"\n        >\n          {t('master_document.cfde.viewQr')}\n        </a>\n      )}\n\n      {/* Actions */}\n      {(onRetransmit || onDownloadPdf) && (\n        <div className=\"flex gap-2 pt-1 border-t border-border-secondary dark:border-dark-border-primary\">\n          {onRetransmit && (data.status === 'REJECTED' || data.status === 'ERROR') && (\n            <button\n              type=\"button\"\n              onClick={onRetransmit}\n              aria-label={t('master_document.cfde.retransmit')}\n              className=\"flex-1 text-xs font-semibold text-primary-600 dark:text-primary-400 py-1.5 rounded-md hover:bg-primary-100 dark:hover:bg-primary-600/10 transition-colors\"\n            >\n              {t('master_document.cfde.retransmitButton')}\n            </button>\n          )}\n          {onDownloadPdf && data.status === 'ACCEPTED' && (\n            <button\n              type=\"button\"\n              onClick={onDownloadPdf}\n              aria-label={t('master_document.cfde.downloadPdf')}\n              className=\"flex-1 text-xs font-semibold text-primary-600 dark:text-primary-400 py-1.5 rounded-md hover:bg-primary-100 dark:hover:bg-primary-600/10 transition-colors\"\n            >\n              {t('master_document.cfde.downloadPdfButton')}\n            </button>\n          )}\n        </div>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { useMasterDocumentFormatters } from './formatters';\nimport type { FactBoxPaymentTermsProps, PeriodMode } from './MasterDocument.types';\n\nconst periodModeTranslationKeys: Record<PeriodMode, string> = {\n  days: 'master_document.factBox.paymentTerms.periodDays',\n  months: 'master_document.factBox.paymentTerms.periodMonths',\n  custom: 'master_document.factBox.paymentTerms.periodCustom',\n};\n\nfunction Row({ label, value, mono, accent }: { label: string; value: string | number; mono?: boolean; accent?: boolean }) {\n  return (\n    <div className=\"flex items-center justify-between py-1\">\n      <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary\">{label}</span>\n      <span\n        className={clsx(\n          'text-xs font-semibold',\n          mono && 'tabular-nums',\n          accent\n            ? 'text-primary-custom-600 dark:text-primary-custom-400'\n            : 'text-content-primary dark:text-dark-content-primary',\n        )}\n      >\n        {value}\n      </span>\n    </div>\n  );\n}\n\n/**\n * Widget de condiciones de pago para el panel FactBox.\n *\n * Muestra el código y nombre del plazo, número de cuotas, modo de período y\n * días de vencimiento. Cuando el pronto pago está habilitado, presenta una\n * sección con indicador visual verde, ventana en días y porcentaje de descuento.\n * Si existe anticipo requerido, lo muestra con su monto calculado.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - FactBoxPaymentTermsProps, PeriodMode\n *\n * @example\n * ```tsx\n * <FactBoxPaymentTerms\n *   data={{\n *     code: 'C30',\n *     name: 'Crédito 30 días',\n *     installmentCount: 1,\n *     periodMode: 'days',\n *     dueDays: 30,\n *     earlyPaymentEnabled: true,\n *     earlyPaymentDays: 10,\n *     earlyPaymentDiscountPct: 2,\n *   }}\n * />\n * ```\n */\nexport function FactBoxPaymentTerms({ data, className }: FactBoxPaymentTermsProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatCurrency } = useMasterDocumentFormatters();\n  return (\n    <div className={clsx('flex flex-col gap-0.5', className)}>\n      {/* Header: code + name */}\n      <div className=\"flex items-center gap-2 mb-1\">\n        <span className=\"text-xs font-bold text-primary-custom-600 dark:text-primary-custom-400\">\n          {data.code}\n        </span>\n        <span className=\"text-xs font-semibold text-content-primary dark:text-dark-content-primary\">\n          {data.name}\n        </span>\n      </div>\n\n      <Row label={t('master_document.factBox.paymentTerms.installments')} value={data.installmentCount} mono />\n      <Row label={t('master_document.factBox.paymentTerms.mode')} value={t(periodModeTranslationKeys[data.periodMode])} />\n      <Row label={t('master_document.factBox.paymentTerms.dueDays')} value={data.dueDays} mono />\n\n      {/* Early payment section */}\n      {data.earlyPaymentEnabled && (\n        <>\n          <div className=\"h-px bg-border-secondary dark:bg-dark-border-primary my-1.5\" />\n          {/* Color semántico verde para estado activo. Migrar a token success-* cuando exista */}\n          <div className=\"flex items-center gap-1.5 mb-0.5\">\n            <span className=\"w-1.5 h-1.5 rounded-full bg-green-600 dark:bg-green-400\" aria-hidden=\"true\" />\n            <span className=\"text-xs font-semibold text-green-700 dark:text-green-400\">{t('master_document.factBox.paymentTerms.earlyPaymentEnabled')}</span>\n          </div>\n          {data.earlyPaymentDays != null && (\n            <Row label={t('master_document.factBox.paymentTerms.window')} value={t('master_document.factBox.paymentTerms.days', { count: data.earlyPaymentDays })} mono />\n          )}\n          {data.earlyPaymentDiscountPct != null && (\n            <Row label={t('master_document.factBox.paymentTerms.discount')} value={`${data.earlyPaymentDiscountPct}%`} mono accent />\n          )}\n        </>\n      )}\n\n      {/* Advance payment */}\n      {(data.advancePaymentPct != null && data.advancePaymentPct > 0) && (\n        <>\n          <div className=\"h-px bg-border-secondary dark:bg-dark-border-primary my-1.5\" />\n          <Row label={t('master_document.factBox.paymentTerms.advanceRequired')} value={`${data.advancePaymentPct}%`} mono accent />\n          {data.advancePaymentAmount != null && (\n            <Row label={t('master_document.factBox.paymentTerms.advanceAmount')} value={formatCurrency(data.advancePaymentAmount)} mono />\n          )}\n        </>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { FactBoxFinancialProps } from './MasterDocument.types';\n\nfunction Row({\n  label,\n  value,\n  color,\n  bold,\n}: {\n  label: string;\n  value: string;\n  color?: string;\n  bold?: boolean;\n}) {\n  return (\n    <div className=\"flex items-center justify-between py-1\">\n      <span\n        className={clsx(\n          'text-xs',\n          bold\n            ? 'font-bold text-content-primary dark:text-dark-content-primary'\n            : 'text-content-tertiary dark:text-dark-content-secondary',\n        )}\n      >\n        {label}\n      </span>\n      <span\n        className={clsx(\n          'text-xs tabular-nums',\n          bold ? 'font-bold' : 'font-semibold',\n          color ? color : 'text-content-primary dark:text-dark-content-primary',\n        )}\n      >\n        {value}\n      </span>\n    </div>\n  );\n}\n\n/**\n * Widget de movimientos financieros para el panel FactBox.\n *\n * Presenta cuentas por cobrar, cuentas por pagar, anticipos cruzados y efectivo\n * en una lista de filas etiqueta/valor. Cuando el documento opera en moneda\n * extranjera, muestra un bloque adicional con los equivalentes en moneda local\n * (COP). Si no existe ningún movimiento registrado, renderiza un mensaje de\n * \"Pendiente de contabilización\".\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - FactBoxFinancialProps\n *\n * @example\n * ```tsx\n * <FactBoxFinancial\n *   data={{ receivableAmount: 1500000 }}\n *   formatCurrency={formatCurrency}   // de useMasterDocumentFormatters()\n * />\n * ```\n */\nexport function FactBoxFinancial({ data, formatCurrency, className }: FactBoxFinancialProps) {\n  const { t } = useMasterDocumentTranslation();\n  const hasReceivable = data.receivableAmount != null && data.receivableAmount !== 0;\n  const hasPayable = data.payableAmount != null && data.payableAmount !== 0;\n  const hasAdvance = data.advanceAmount != null && data.advanceAmount !== 0;\n  const hasCash = data.cashAmount != null && data.cashAmount !== 0;\n  const hasLocal = data.receivableAmountLocal != null || data.payableAmountLocal != null;\n\n  const isEmpty = !hasReceivable && !hasPayable && !hasAdvance && !hasCash;\n\n  if (isEmpty) {\n    return (\n      <div className={clsx('text-xs text-content-secondary dark:text-dark-content-secondary italic', className)}>\n        {t('master_document.factBox.financial.pendingPosting')}\n      </div>\n    );\n  }\n\n  return (\n    <div className={clsx('flex flex-col gap-0.5', className)}>\n      {/* Colores semánticos: verde=cobrar, rojo=pagar. Migrar a tokens success/error cuando existan */}\n      {hasReceivable && (\n        <Row label={t('master_document.factBox.financial.receivables')} value={formatCurrency(data.receivableAmount!)} color=\"text-green-700 dark:text-green-400\" />\n      )}\n      {hasPayable && (\n        <Row label={t('master_document.factBox.financial.payables')} value={formatCurrency(data.payableAmount!)} color=\"text-error-content dark:text-error-content\" />\n      )}\n      {hasAdvance && (\n        <Row label={t('master_document.factBox.financial.crossedAdvances')} value={formatCurrency(data.advanceAmount!)} />\n      )}\n      {hasCash && (\n        <Row label={t('master_document.factBox.financial.cash')} value={formatCurrency(data.cashAmount!)} />\n      )}\n\n      {/* Local currency equivalents */}\n      {hasLocal && data.currencyCode && (\n        <>\n          <div className=\"h-px bg-border-secondary dark:bg-dark-border-primary my-1.5\" />\n          <span className=\"text-[10px] font-semibold text-content-tertiary dark:text-dark-content-secondary mb-0.5\">\n            {t('master_document.factBox.financial.localEquivalent')}\n          </span>\n          {data.receivableAmountLocal != null && data.receivableAmountLocal !== 0 && (\n            <Row label={t('master_document.factBox.financial.localReceivables')} value={formatCurrency(data.receivableAmountLocal)} />\n          )}\n          {data.payableAmountLocal != null && data.payableAmountLocal !== 0 && (\n            <Row label={t('master_document.factBox.financial.localPayables')} value={formatCurrency(data.payableAmountLocal)} />\n          )}\n        </>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { MasterDocumentT } from './i18n';\nimport type { StatusHistoryEntry } from './adapter/MasterDocumentAdapter.types';\n\n// ════════════════════════════════════════════════════════════\n// PROPS\n// ════════════════════════════════════════════════════════════\n\nexport interface FactBoxStatusHistoryProps {\n  /** Entradas de historial — el componente las re-ordena por fecha DESC. */\n  entries: StatusHistoryEntry[];\n  /** Formateador de fecha del adapter (locale-aware). Si no se provee, muestra tiempo relativo. */\n  formatDate?: (value: string) => string;\n  className?: string;\n}\n\n// ════════════════════════════════════════════════════════════\n// ACTION KEY → TRANSLATION KEY MAP\n// Gap: C7 aún no está implementado. El backend devuelve action_key (string\n// crudo). Este diccionario local los resuelve a claves de `master_document.\n// statusHistory.action.*`, traducidas en el punto de render con `t()`.\n// Cuando el backend devuelva processName resuelto, ese campo toma prioridad.\n// ════════════════════════════════════════════════════════════\n\nconst ACTION_KEY_TRANSLATION_KEYS: Record<string, string> = {\n  // Operaciones base (DocumentCore)\n  create:              'master_document.statusHistory.action.create',\n  save:                'master_document.statusHistory.action.save',\n  approve:             'master_document.statusHistory.action.approve',\n  reject:              'master_document.statusHistory.action.reject',\n  cancel:              'master_document.statusHistory.action.void',\n  print:               'master_document.statusHistory.action.print',\n\n  // Transiciones de estado\n  send_to_approval:    'master_document.statusHistory.action.sendToApproval',\n  hold:                'master_document.statusHistory.action.hold',\n  release:             'master_document.statusHistory.action.release',\n  commit:              'master_document.statusHistory.action.commit',\n  dispatch:            'master_document.statusHistory.action.dispatch',\n  post:                'master_document.statusHistory.action.post',\n  invoice:             'master_document.statusHistory.action.invoice',\n  complete:            'master_document.statusHistory.action.fulfill',\n  partial_fulfill:     'master_document.statusHistory.action.partialFulfillment',\n\n  // Interfaces de capacidad (IContabilizar, IComprometer, IAnticipo…)\n  contabilizar:        'master_document.statusHistory.action.post',\n  comprometer:         'master_document.statusHistory.action.commit',\n  anticipo:            'master_document.statusHistory.action.advance',\n  recaudo:             'master_document.statusHistory.action.collection',\n  cumplir:             'master_document.statusHistory.action.fulfill',\n  anular:              'master_document.statusHistory.action.void',\n};\n\nfunction resolveProcessLabel(entry: StatusHistoryEntry, t: MasterDocumentT): string | undefined {\n  if (entry.processName) return entry.processName;\n  if (entry.actionKey) {\n    const translationKey = ACTION_KEY_TRANSLATION_KEYS[entry.actionKey];\n    return translationKey ? t(translationKey) : entry.actionKey;\n  }\n  return undefined;\n}\n\n// ════════════════════════════════════════════════════════════\n// HELPERS\n// ════════════════════════════════════════════════════════════\n\n// El endpoint siempre resuelve changedByName (contrato explícito del backend).\n// No se detectan UUIDs — el componente simplemente usa changedByName ?? changedBy.\nfunction displayUser(changedBy: string, changedByName?: string): string {\n  return changedByName ?? changedBy;\n}\n\nfunction relativeTime(isoString: string): string {\n  const diff = Date.now() - new Date(isoString).getTime();\n  const mins = Math.floor(diff / 60000);\n  if (mins < 1) return 'hace un momento';\n  if (mins < 60) return `hace ${mins} min`;\n  const hrs = Math.floor(mins / 60);\n  if (hrs < 24) return `hace ${hrs}h`;\n  const days = Math.floor(hrs / 24);\n  if (days < 30) return `hace ${days}d`;\n  const months = Math.floor(days / 30);\n  return `hace ${months} mes${months > 1 ? 'es' : ''}`;\n}\n\nfunction formatTimestamp(isoString: string, formatDate?: (v: string) => string): string {\n  if (formatDate) return formatDate(isoString);\n  return relativeTime(isoString);\n}\n\n// ════════════════════════════════════════════════════════════\n// COMPONENT\n// ════════════════════════════════════════════════════════════\n\n/**\n * FactBoxStatusHistory — timeline vertical del historial de transiciones del documento.\n *\n * Muestra cada entrada de `document_status_history` (OP1) con:\n * - Transición de estado: de → a (o \"Creación\" para la entrada inicial)\n * - Nombre del proceso: resuelto desde `processName`, o desde `actionKey`\n *   via diccionario local (gap temporal hasta que C7 esté implementado)\n * - Usuario: usa `changedByName` (el endpoint siempre lo resuelve, ej: \"Sistema\"\n *   mientras no haya auth real). Fallback a `changedBy` si ausente.\n * - Timestamp relativo o formateado via `adapter.formatDate`\n * - Notas opcionales registradas durante la transición\n *\n * Los registros se muestran en orden cronológico inverso (más reciente primero).\n *\n * @see IMasterDocumentAdapter.getStatusHistory — endpoint que alimenta este componente\n * @see document_status_history (OP1) — tabla append-only del backend\n *\n * @example\n * ```tsx\n * <FactBoxStatusHistory\n *   entries={historyEntries}\n *   formatDate={adapter.formatDate}\n * />\n * ```\n */\nexport function FactBoxStatusHistory({ entries, formatDate, className }: FactBoxStatusHistoryProps) {\n  const { t } = useMasterDocumentTranslation();\n  if (!entries || entries.length === 0) {\n    return (\n      <p className=\"text-xs text-content-tertiary dark:text-dark-content-secondary italic py-1\">\n        {t('master_document.statusHistory.empty')}\n      </p>\n    );\n  }\n\n  // Más reciente primero\n  const sorted = [...entries].sort(\n    (a, b) => new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime(),\n  );\n\n  return (\n    <div className={clsx('flex flex-col', className)}>\n      {sorted.map((entry, idx) => {\n        const processLabel = resolveProcessLabel(entry, t);\n        const userLabel = displayUser(entry.changedBy, entry.changedByName);\n\n        return (\n          <div key={entry.id} className=\"relative flex gap-2.5 pb-3 last:pb-0\">\n\n            {/* Línea vertical de la timeline */}\n            {idx < sorted.length - 1 && (\n              <div\n                aria-hidden=\"true\"\n                className=\"absolute left-[5px] top-[14px] bottom-0 w-px bg-border-secondary dark:bg-dark-border-primary\"\n              />\n            )}\n\n            {/* Punto de la timeline — relleno en el más reciente */}\n            <div\n              aria-hidden=\"true\"\n              className={clsx(\n                'relative mt-[5px] flex-shrink-0 w-[11px] h-[11px] rounded-full border-2',\n                idx === 0\n                  ? 'border-primary-500 dark:border-primary-400 bg-primary-500 dark:bg-primary-400'\n                  : 'border-primary-400 dark:border-primary-600 bg-background-primary dark:bg-dark-bg-primary',\n              )}\n            />\n\n            {/* Contenido */}\n            <div className=\"flex-1 min-w-0\">\n\n              {/* Transición de estado */}\n              <div className=\"flex items-center gap-1 flex-wrap leading-tight\">\n                {entry.previousState ? (\n                  <>\n                    <span className=\"text-[11px] font-medium text-content-secondary dark:text-dark-content-secondary truncate\">\n                      {entry.previousStateLabel ?? entry.previousState}\n                    </span>\n                    <span\n                      className=\"text-[11px] text-content-tertiary dark:text-dark-content-secondary flex-shrink-0\"\n                      aria-hidden=\"true\"\n                    >\n                      →\n                    </span>\n                  </>\n                ) : (\n                  <span className=\"text-[11px] font-medium text-content-tertiary dark:text-dark-content-secondary\">\n                    {t('master_document.statusHistory.creation')}\n                  </span>\n                )}\n                <span className=\"text-[11px] font-semibold text-content-primary dark:text-dark-content-primary truncate\">\n                  {entry.newStateLabel ?? entry.newState}\n                </span>\n              </div>\n\n              {/* Nombre del proceso (C7) */}\n              {processLabel && (\n                <div className=\"text-[10px] text-content-tertiary dark:text-dark-content-secondary truncate mt-0.5\">\n                  {processLabel}\n                </div>\n              )}\n\n              {/* Usuario · timestamp */}\n              <div className=\"flex items-center gap-1 mt-0.5\">\n                <span className=\"text-[10px] font-medium text-content-secondary dark:text-dark-content-secondary truncate\">\n                  {userLabel}\n                </span>\n                <span\n                  className=\"text-[10px] text-content-tertiary dark:text-dark-content-secondary flex-shrink-0\"\n                  aria-hidden=\"true\"\n                >\n                  ·\n                </span>\n                <time\n                  dateTime={entry.changedAt}\n                  className=\"text-[10px] text-content-tertiary dark:text-dark-content-secondary flex-shrink-0\"\n                >\n                  {formatTimestamp(entry.changedAt, formatDate)}\n                </time>\n              </div>\n\n              {/* Notas opcionales */}\n              {entry.notes && (\n                <p className=\"text-[10px] text-content-secondary dark:text-dark-content-secondary italic mt-1 leading-relaxed line-clamp-2\">\n                  &ldquo;{entry.notes}&rdquo;\n                </p>\n              )}\n            </div>\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n","import React from 'react';\nimport { evaluateCondition } from '../fieldCondition';\nimport type { FieldCondition } from '../fieldCondition';\n\nimport { FactBoxTotals } from '../FactBoxTotals';\nimport { FactBoxCfde } from '../FactBoxCfde';\nimport { FactBoxPaymentTerms } from '../FactBoxPaymentTerms';\nimport { FactBoxFinancial } from '../FactBoxFinancial';\nimport { FactBoxStatusHistory } from '../FactBoxStatusHistory';\nimport { StateBadge } from '../StateBadge';\nimport type { StatusHistoryEntry } from '../adapter/MasterDocumentAdapter.types';\n\nimport type { FactBoxSectionConfig, DocumentLineData } from '../MasterDocument.types';\nimport type { DocumentState, IMasterDocumentAdapter } from '../adapter/MasterDocumentAdapter.types';\nimport type { FactBoxWidget } from '../provider/MasterDocumentProvider';\nimport { INERT_REFRESH, type MasterDocumentRefreshApi } from '../provider/MasterDocumentRefreshProvider';\nimport type {\n  FactBoxSectionTemplate,\n  TotalsWidgetConfig,\n  TotalsAggregation,\n  KeyValueWidgetConfig,\n  ProgressBarWidgetConfig,\n} from '../template/MasterDocumentTemplate.types';\nimport { MASTER_DOCUMENT_TRANSLATIONS_ES } from '../i18n';\nimport type { TranslateFn } from '../i18nFactory';\n\n// ════════════════════════════════════════════════════════════\n// DATA RESOLVER — obtiene datos de la fuente correcta\n// ════════════════════════════════════════════════════════════\n\nfunction resolveData(\n  section: FactBoxSectionTemplate,\n  state: DocumentState,\n): Record<string, unknown> {\n  if (section.dataSource === 'adapter') {\n    return state.factBoxData[section.key] ?? {};\n  }\n  // documentState: merge header + computed totals\n  return { ...state.headerValues, _lines: state.lines, _lineCount: state.lines.length };\n}\n\nfunction resolveField(data: Record<string, unknown>, field: string): unknown {\n  return data[field];\n}\n\n// ════════════════════════════════════════════════════════════\n// AGGREGATION ENGINE — calcula totales desde state.lines\n// ════════════════════════════════════════════════════════════\n\nfunction computeAggregations(\n  aggregations: Record<string, TotalsAggregation>,\n  lines: DocumentLineData[],\n): Record<string, number> {\n  const result: Record<string, number> = {};\n\n  for (const [key, agg] of Object.entries(aggregations)) {\n    switch (agg.op) {\n      case 'sum':\n        result[key] = lines.reduce((acc, l) => acc + (Number(l[agg.field]) || 0), 0);\n        break;\n      case 'sumProduct':\n        result[key] = lines.reduce((acc, l) => {\n          const product = agg.fields.reduce((p, f) => p * (Number(l[f]) || 0), 1);\n          return acc + product;\n        }, 0);\n        break;\n      case 'sumDiscount':\n        result[key] = lines.reduce((acc, l) => {\n          const qty = Number(l[agg.qtyField]) || 0;\n          const price = Number(l[agg.priceField]) || 0;\n          const discount = Number(l[agg.discountField]) || 0;\n          return acc + qty * price * (1 - discount / 100);\n        }, 0);\n        break;\n      case 'diff':\n        result[key] = (result[agg.a] ?? 0) - (result[agg.b] ?? 0);\n        break;\n      case 'add':\n        result[key] = agg.fields.reduce((acc, f) => acc + (result[f] ?? 0), 0);\n        break;\n      case 'ref':\n        result[key] = (result[agg.field] ?? 0) * (agg.multiplier ?? 1);\n        break;\n    }\n  }\n\n  return result;\n}\n\n// ════════════════════════════════════════════════════════════\n// WIDGET RENDERERS\n// ════════════════════════════════════════════════════════════\n\nfunction renderTotals(\n  config: TotalsWidgetConfig,\n  data: Record<string, unknown>,\n  adapter: IMasterDocumentAdapter,\n): React.ReactNode {\n  // Calcular aggregations desde líneas si están configuradas\n  const resolvedData: Record<string, unknown> = config.aggregations\n    ? { ...data, ...computeAggregations(config.aggregations, (data._lines as DocumentLineData[]) ?? []) }\n    : data;\n\n  const fmtValue = (field: string, negated?: boolean) => {\n    const v = Number(resolveField(resolvedData, field)) || 0;\n    const formatted = adapter.formatCurrency(Math.abs(v));\n    return negated ? `–${formatted}` : formatted;\n  };\n\n  const subtitle = config.subtitleTemplate\n    ? config.subtitleTemplate.replace(\n        /\\{(\\w+)\\}/g,\n        (_, key) => String(resolveField(resolvedData, key) ?? ''),\n      )\n    : undefined;\n\n  return (\n    <FactBoxTotals\n      grandTotal={{\n        label: config.grandTotalLabel,\n        value: fmtValue(config.grandTotalField),\n        subtitle,\n      }}\n      kpis={config.kpis.map((kpi) => ({\n        label: kpi.label,\n        value: fmtValue(kpi.field, kpi.negated),\n        color: kpi.color,\n      }))}\n      breakdown={config.breakdown.map((item) => ({\n        label: item.label,\n        value: fmtValue(item.field, item.negated),\n        color: item.color,\n        isSummary: item.isSummary,\n      }))}\n    />\n  );\n}\n\nfunction renderCfde(data: Record<string, unknown>): React.ReactNode {\n  return (\n    <FactBoxCfde\n      data={{\n        status: (data.status as 'PENDING' | 'SENT' | 'ACCEPTED' | 'REJECTED' | 'ERROR') ?? 'PENDING',\n        number: data.number as string | undefined,\n        cufe: data.cufe as string | undefined,\n        issueDate: data.issueDate as string | undefined,\n        qrUrl: data.qrUrl as string | undefined,\n        printCount: data.printCount as number | undefined,\n        isTransmitted: data.isTransmitted as boolean | undefined,\n      }}\n    />\n  );\n}\n\nfunction renderPaymentTerms(data: Record<string, unknown>): React.ReactNode {\n  return (\n    <FactBoxPaymentTerms\n      data={{\n        code: String(data.code ?? ''),\n        name: String(data.name ?? ''),\n        installmentCount: Number(data.installmentCount) || 0,\n        periodMode: (data.periodMode as 'days' | 'months' | 'custom') ?? 'days',\n        dueDays: Number(data.dueDays) || 0,\n        earlyPaymentEnabled: data.earlyPaymentEnabled as boolean | undefined,\n        earlyPaymentDays: data.earlyPaymentDays as number | undefined,\n        earlyPaymentDiscountPct: data.earlyPaymentDiscountPct as number | undefined,\n        advancePaymentPct: data.advancePaymentPct as number | undefined,\n        advancePaymentAmount: data.advancePaymentAmount as number | undefined,\n      }}\n    />\n  );\n}\n\nfunction renderFinancial(\n  data: Record<string, unknown>,\n  adapter: IMasterDocumentAdapter,\n): React.ReactNode {\n  return (\n    <FactBoxFinancial\n      data={{\n        receivableAmount: data.receivableAmount as number | undefined,\n        payableAmount: data.payableAmount as number | undefined,\n        advanceAmount: data.advanceAmount as number | undefined,\n        cashAmount: data.cashAmount as number | undefined,\n        receivableAmountLocal: data.receivableAmountLocal as number | undefined,\n        payableAmountLocal: data.payableAmountLocal as number | undefined,\n        currencyCode: data.currencyCode as string | undefined,\n      }}\n      formatCurrency={adapter.formatCurrency}\n    />\n  );\n}\n\nfunction renderKeyValue(\n  config: KeyValueWidgetConfig,\n  data: Record<string, unknown>,\n  adapter: IMasterDocumentAdapter,\n): React.ReactNode {\n  return (\n    <div className=\"space-y-1.5\">\n      {config.fields.map((f) => {\n        const raw = resolveField(data, f.field);\n        let display: string;\n        switch (f.format) {\n          case 'currency':\n            display = adapter.formatCurrency(Number(raw) || 0);\n            break;\n          case 'date':\n            display = adapter.formatDate ? adapter.formatDate(String(raw ?? '')) : String(raw ?? '—');\n            break;\n          case 'number':\n            display = adapter.formatNumber ? adapter.formatNumber(Number(raw) || 0) : String(Number(raw) || 0);\n            break;\n          default:\n            display = String(raw ?? '—');\n        }\n        return (\n          <div key={f.field} className=\"flex justify-between text-xs py-0.5\">\n            <span className=\"text-content-secondary dark:text-dark-content-secondary\">{f.label}</span>\n            <span className=\"font-semibold tabular-nums text-content-primary dark:text-dark-content-primary\">{display}</span>\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\nfunction renderProgressBar(\n  config: ProgressBarWidgetConfig,\n  data: Record<string, unknown>,\n): React.ReactNode {\n  const value = Number(resolveField(data, config.valueField)) || 0;\n  const max = Number(resolveField(data, config.maxField)) || 1;\n  const pct = Math.min(Math.round((value / max) * 100), 100);\n\n  return (\n    <div className=\"space-y-1.5\">\n      <div className=\"flex justify-between text-xs text-content-secondary dark:text-dark-content-secondary\">\n        <span>{config.label}</span>\n        <span className=\"font-semibold\">{pct}%</span>\n      </div>\n      <div className=\"h-[5px] bg-background-secondary dark:bg-dark-bg-secondary rounded-full overflow-hidden\">\n        <div\n          className=\"h-full rounded-full transition-all duration-300 bg-green-700 dark:bg-green-500\"\n          style={{ width: `${pct}%`, backgroundColor: config.color ?? undefined }}\n        />\n      </div>\n    </div>\n  );\n}\n\n// ════════════════════════════════════════════════════════════\n// BUILD FACTBOX SECTIONS\n// ════════════════════════════════════════════════════════════\n\nexport function buildFactBoxSections(\n  sectionTemplates: FactBoxSectionTemplate[],\n  state: DocumentState,\n  adapter: IMasterDocumentAdapter,\n  userPermissions: string[] | null = null,\n  factBoxWidgets: Record<string, FactBoxWidget> = {},\n  /**\n   * Traductor del kit. Se recibe como parámetro porque esto es una función pura\n   * llamada desde un `useMemo`, no un componente: no puede usar el hook.\n   */\n  t: TranslateFn = (key) => MASTER_DOCUMENT_TRANSLATIONS_ES[key] ?? key,\n  /**\n   * Resincronización del documento, que se entrega tal cual a los widgets custom.\n   * Por defecto inerte: esta función también se usa desde pruebas y stories, y\n   * ahí no hay reducer que recargar.\n   */\n  refresh: MasterDocumentRefreshApi = INERT_REFRESH,\n): FactBoxSectionConfig[] {\n  const headerValues = state.headerValues as Record<string, unknown>;\n  return sectionTemplates\n    .filter((s) => {\n      if (s.visibleOn && s.visibleOn.length > 0) {\n        if (!s.visibleOn.includes(state.docState) && !s.visibleOn.includes('*')) return false;\n      }\n      if (s.visibleWhen && !evaluateCondition(s.visibleWhen as FieldCondition, headerValues)) return false;\n      if (s.hiddenWhen && evaluateCondition(s.hiddenWhen as FieldCondition, headerValues)) return false;\n      if (s.permissionVisibility && userPermissions !== null && !userPermissions.includes(s.permissionVisibility)) return false;\n      return true;\n    })\n    .map((s) => {\n      const data = resolveData(s, state);\n\n      // Resolve badge\n      let badge: React.ReactNode = undefined;\n      if (s.badgeField && s.badgeMap) {\n        const badgeValue = String(data[s.badgeField] ?? '');\n        const badgeConfig = s.badgeMap[badgeValue];\n        if (badgeConfig) {\n          badge = <StateBadge {...badgeConfig} />;\n        }\n      }\n\n      // Render widget\n      let children: React.ReactNode;\n      switch (s.widget.type) {\n        case 'totals':\n          children = renderTotals(s.widget.config, data, adapter);\n          break;\n        case 'cfde':\n          children = renderCfde(data);\n          break;\n        case 'paymentTerms':\n          children = renderPaymentTerms(data);\n          break;\n        case 'financial':\n          children = renderFinancial(data, adapter);\n          break;\n        case 'keyValue':\n          children = renderKeyValue(s.widget.config, data, adapter);\n          break;\n        case 'progressBar':\n          children = renderProgressBar(s.widget.config, data);\n          break;\n        case 'statusHistory': {\n          const historyEntries = (data.entries ?? []) as StatusHistoryEntry[];\n          children = (\n            <FactBoxStatusHistory\n              entries={historyEntries}\n              formatDate={adapter.formatDate}\n            />\n          );\n          break;\n        }\n        case 'custom': {\n          const widget = factBoxWidgets[s.widget.widgetKey];\n          if (typeof widget === 'function') {\n            children = widget({\n              documentId: state.documentId ?? '',\n              docState: state.docState,\n              mode: state.mode,\n              headerValues,\n              data,\n              adapter,\n              reload: refresh.reload,\n              refreshToken: refresh.refreshToken,\n            });\n          } else if (widget != null && widget !== false) {\n            children = widget;\n          } else {\n            children = (\n              <div className=\"text-xs text-content-secondary dark:text-dark-content-secondary italic\">\n                {t('master_document.factBox.customWidget', { key: s.widget.widgetKey })}\n              </div>\n            );\n          }\n          break;\n        }\n      }\n\n      return {\n        key: s.key,\n        label: s.label,\n        defaultOpen: s.defaultOpen,\n        badge,\n        children,\n      };\n    });\n}\n","import type { FieldDescriptor } from '../MasterDocument.types';\n\n/**\n * Visibilidad por estado de un campo de LÍNEA en el modal (SBC-3846).\n *\n * Trata `visibleOn` igual que el filtro de FactBox del kit, de modo que un array\n * vacío significa \"visible en ningún estado\" = oculto:\n *\n * - `visibleOn` ausente/undefined → sin restricción → visible (retrocompatible).\n * - `visibleOn: []`               → visible en ningún estado → OCULTO.\n * - `visibleOn: ['*']`            → siempre visible.\n * - `visibleOn: ['DRAFT', ...]`   → visible solo en esos estados.\n *\n * Nota: SOLO aplica a campos de línea/línea-detalle. El filtro de cabecera\n * conserva el comportamiento histórico (un `[]` de cabecera sigue siendo visible)\n * porque hay campos de header que dependen de ello.\n */\nexport function isLineFieldVisibleInState(\n  field: Pick<FieldDescriptor, 'visibleOn'>,\n  docState: string,\n): boolean {\n  if (!field.visibleOn) return true;\n  return field.visibleOn.includes('*') || field.visibleOn.includes(docState);\n}\n","import { useEffect, useState, useCallback } from 'react';\nimport { clsx } from 'clsx';\nimport { Input } from '../Input';\nimport { Select } from '../Select';\nimport { Textarea } from '../Textarea/Textarea';\nimport { InputNumber } from '../InputNumber/InputNumber';\nimport type { LineActionField } from './template/MasterDocumentTemplate.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n// ─── Icons ─────────────────────────────────────────────────\n\nfunction XIcon(props: React.SVGProps<SVGSVGElement>) {\n  return (\n    <svg viewBox=\"0 0 20 20\" fill=\"currentColor\" {...props}>\n      <path d=\"M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z\" />\n    </svg>\n  );\n}\n\n// ─── Props ─────────────────────────────────────────────────\n\nexport interface LineActionFormModalProps {\n  open: boolean;\n  onClose: () => void;\n  /** Título del modal (de `LineActionEntry.formModal.title`). */\n  title: string;\n  /** Etiqueta del botón de confirmación. Por defecto \"Confirmar\". */\n  submitLabel?: string;\n  /** Campos declarativos a renderizar. */\n  fields: LineActionField[];\n  /** Se invoca con los valores del formulario al confirmar (tras validar `required`). */\n  onSubmit: (formData: Record<string, unknown>) => void;\n  /** Deshabilita los controles y el submit mientras la acción está en curso. */\n  busy?: boolean;\n  /** Mensaje de error a nivel de modal (p.ej. fallo del endpoint). */\n  error?: string;\n}\n\n// ─── Helpers ───────────────────────────────────────────────\n\nfunction isEmpty(value: unknown): boolean {\n  return value == null || value === '';\n}\n\n// ─── LineActionFormModal ───────────────────────────────────\n\n/**\n * Modal de formulario genérico para acciones de línea ADICIONALES declarativas\n * (`LineActionEntry.actionType === 'formModal'`), p.ej. \"cerrar línea\" (tipo de\n * cierre + notas).\n *\n * Renderiza los `fields` declarados reutilizando los primitivos de form del kit\n * (`Select`, `Textarea`, `Input`, `InputNumber`), valida los campos `required` y\n * emite `onSubmit(formData)` con los valores capturados. No conoce el endpoint ni\n * el adapter: solo recolecta y valida. El estado del formulario se reinicia cada\n * vez que el modal se abre.\n *\n * @see LineActionField, LineActionEntry\n */\nexport function LineActionFormModal({\n  open,\n  onClose,\n  title,\n  submitLabel,\n  fields,\n  onSubmit,\n  busy = false,\n  error,\n}: LineActionFormModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const [values, setValues] = useState<Record<string, unknown>>({});\n  const [errors, setErrors] = useState<Record<string, string>>({});\n\n  // Reinicia el formulario cada vez que el modal se abre.\n  useEffect(() => {\n    if (open) {\n      setValues({});\n      setErrors({});\n    }\n  }, [open]);\n\n  // Cierra con Escape.\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  const setField = useCallback((name: string, value: unknown) => {\n    setValues((prev) => ({ ...prev, [name]: value }));\n    setErrors((prev) => {\n      if (!prev[name]) return prev;\n      const next = { ...prev };\n      delete next[name];\n      return next;\n    });\n  }, []);\n\n  const handleSubmit = useCallback(() => {\n    const nextErrors: Record<string, string> = {};\n    for (const field of fields) {\n      if (field.required && isEmpty(values[field.name])) {\n        nextErrors[field.name] = t('master_document.field.required');\n      }\n    }\n    if (Object.keys(nextErrors).length > 0) {\n      setErrors(nextErrors);\n      return;\n    }\n    onSubmit(values);\n  }, [fields, values, onSubmit, t]);\n\n  if (!open) return null;\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        onClick={onClose}\n        aria-hidden=\"true\"\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] bg-bg-primary rounded-2xl overflow-hidden shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[520px] max-h-[85vh]',\n          'max-sm:top-auto max-sm:bottom-0 max-sm:left-0 max-sm:right-0 max-sm:translate-x-0 max-sm:translate-y-0',\n          'max-sm:w-full max-sm:max-w-none max-sm:rounded-b-none max-sm:max-h-[90vh]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={title}\n      >\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-b border-border-secondary dark:border-dark-border-primary\">\n          <h2 className=\"text-base font-bold text-content-primary dark:text-dark-content-primary\">\n            {title}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"p-1.5 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n            aria-label={t('master_document.chrome.closeDialog')}\n          >\n            <XIcon className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/* Body */}\n        <div className=\"overflow-y-auto px-6 py-5 flex flex-col gap-4\" style={{ maxHeight: 'calc(85vh - 130px)' }}>\n          {error && (\n            <div\n              role=\"alert\"\n              className=\"rounded-md bg-error-bg px-3 py-2 text-sm text-error-content dark:bg-error-content/10\"\n            >\n              {error}\n            </div>\n          )}\n\n          {fields.map((field) => {\n            const fieldError = errors[field.name];\n            const commonId = `line-action-field-${field.name}`;\n\n            if (field.type === 'select') {\n              return (\n                <Select\n                  key={field.name}\n                  id={commonId}\n                  name={field.name}\n                  label={field.label}\n                  showLabel\n                  required={field.required}\n                  placeholder={field.placeholder ?? t('master_document.field.selectPlaceholder')}\n                  options={(field.options ?? []).map((o) => ({ value: o.value, label: o.label }))}\n                  value={(values[field.name] as string | number | undefined) ?? ''}\n                  onChange={(value) => setField(field.name, value)}\n                  disabled={busy}\n                  error={fieldError ? true : undefined}\n                  errorMessage={fieldError}\n                />\n              );\n            }\n\n            if (field.type === 'textarea') {\n              return (\n                <Textarea\n                  key={field.name}\n                  id={commonId}\n                  name={field.name}\n                  label={field.label}\n                  required={field.required}\n                  placeholder={field.placeholder}\n                  value={(values[field.name] as string | undefined) ?? ''}\n                  onChange={(e) => setField(field.name, e.target.value)}\n                  disabled={busy}\n                  error={fieldError ? true : undefined}\n                  errorMessage={fieldError}\n                />\n              );\n            }\n\n            if (field.type === 'number') {\n              return (\n                <InputNumber\n                  key={field.name}\n                  id={commonId}\n                  name={field.name}\n                  label={field.label}\n                  required={field.required}\n                  placeholder={field.placeholder}\n                  value={(values[field.name] as string | number | undefined) ?? ''}\n                  onChange={(e) => setField(field.name, e.target.value)}\n                  disabled={busy}\n                  error={fieldError ? true : undefined}\n                  errorMessage={fieldError}\n                />\n              );\n            }\n\n            // 'text'\n            return (\n              <Input\n                key={field.name}\n                id={commonId}\n                name={field.name}\n                label={field.label}\n                required={field.required}\n                placeholder={field.placeholder}\n                value={(values[field.name] as string | undefined) ?? ''}\n                onChange={(e) => setField(field.name, e.target.value)}\n                disabled={busy}\n                error={fieldError ? true : undefined}\n                errorMessage={fieldError}\n              />\n            );\n          })}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-border-secondary dark:border-dark-border-primary\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            disabled={busy}\n            className={clsx(\n              // Secundario del canon: LLEVA borde (ver la nota en `LineFormModal`).\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary dark:border-dark-border-primary',\n              'text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n              'disabled:opacity-50 disabled:cursor-not-allowed',\n            )}\n          >\n            {t('master_document.chrome.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={handleSubmit}\n            disabled={busy}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'bg-primary-600 text-white hover:bg-primary-700 transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'disabled:opacity-50 disabled:cursor-not-allowed',\n            )}\n          >\n            {submitLabel ?? t('master_document.chrome.confirm')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { MASTER_DOCUMENT_TRANSLATIONS_ES } from '../i18n';\nimport type { LineActionEntry } from '../template/MasterDocumentTemplate.types';\nimport type { DocumentLineData } from '../MasterDocument.types';\nimport type { IMasterDocumentAdapter, ActionResult, DocumentState } from '../adapter/MasterDocumentAdapter.types';\n\n// ════════════════════════════════════════════════════════════\n// LINE ACTION GATING — Visibilidad/habilitación de acciones de línea (D2)\n// ════════════════════════════════════════════════════════════\n\n/**\n * Evalúa el gateo de una acción de línea adicional (declarada en\n * `template.lineActionRegistry`) SIN asumir un `line.status` canónico. Lo usa\n * `getLineActions` en `SmartMasterDocument` para decidir, por fila, si la acción\n * es visible y si está deshabilitada:\n *\n * - `statusField` + `visibleStates`/`disabledStates` → contra `line[statusField]`.\n * - `visibleDocStates`/`disabledDocStates` → contra el `docState` del documento.\n * - `permissionVisibility` → oculta si el usuario no tiene el permiso.\n * - Sin declaración → visible y habilitada.\n */\nexport function evaluateLineActionGate(\n  entry: LineActionEntry,\n  line: DocumentLineData,\n  docState: string,\n  permissions: string[] | null,\n): { visible: boolean; disabled: boolean } {\n  if (\n    entry.permissionVisibility &&\n    permissions !== null &&\n    !permissions.includes(entry.permissionVisibility)\n  ) {\n    return { visible: false, disabled: false };\n  }\n\n  const statusValue =\n    entry.statusField != null ? String(line[entry.statusField] ?? '') : undefined;\n\n  if (entry.visibleStates && (statusValue == null || !entry.visibleStates.includes(statusValue))) {\n    return { visible: false, disabled: false };\n  }\n  if (entry.visibleDocStates && !entry.visibleDocStates.includes(docState)) {\n    return { visible: false, disabled: false };\n  }\n\n  const disabledByState =\n    statusValue != null && (entry.disabledStates?.includes(statusValue) ?? false);\n  const disabledByDocState = entry.disabledDocStates?.includes(docState) ?? false;\n\n  return { visible: true, disabled: disabledByState || disabledByDocState };\n}\n\n/**\n * Sustituye los placeholders del `endpoint.path` de una acción de línea por el\n * documentId y el lineId. Soporta `{id}` y `{documentId}` (documento) y\n * `{lineId}` (línea). Lo usa la vía POR DEFECTO de ejecución de acciones de línea\n * (`adapter.genericFetch`) cuando el adapter no implementa `executeLineAction`.\n */\nexport function buildLineActionPath(\n  path: string,\n  documentId: string | undefined,\n  lineId: string,\n): string {\n  return path\n    .replace(/\\{id\\}/g, documentId ?? '')\n    .replace(/\\{documentId\\}/g, documentId ?? '')\n    .replace(/\\{lineId\\}/g, lineId);\n}\n\n/**\n * Resultado de ejecutar una acción de línea: separa la DECISIÓN (qué pasó y cómo\n * resincronizar) de los efectos (dispatch/toast), para poder testearla sin render.\n */\nexport interface LineActionOutcome {\n  /** `false` ⇒ mostrar `error` en el modal y no cerrar. */\n  ok: boolean;\n  /** Mensaje de éxito (toast) cuando `ok`. */\n  message?: string;\n  /** Mensaje de error (modal) cuando `!ok`. */\n  error?: string;\n  /**\n   * Clave i18n del error cuando el mensaje lo generó el kit y no el backend.\n   *\n   * Este módulo es una función pura consumida desde hooks, así que no puede llamar\n   * a `useMasterDocumentTranslation`. En su lugar propaga la clave: el hook\n   * llamante hace `errorKey ? t(errorKey) : error`. `error` viene relleno con el\n   * texto español del catálogo para que un consumidor que ignore `errorKey` siga\n   * mostrando algo legible.\n   */\n  errorKey?: string;\n  /** Si presente, el caller hace `MERGE_STATE` con este payload. */\n  merge?: Partial<DocumentState>;\n  /** Si `true`, el caller recarga el documento (`getDocument` + `LOAD_SUCCESS`). */\n  refetch?: boolean;\n}\n\n/**\n * Ejecuta una acción de línea adicional y decide cómo resincronizar el estado.\n * Dos vías:\n *\n *  - OVERRIDE (`adapter.executeLineAction`): lógica bespoke; el sync depende solo\n *    de su `updatedData` (el override es responsable de devolver lo que cambió).\n *    NO se fuerza refetch.\n *  - GENÉRICA (`endpoint` + `adapter.genericFetch`): ejecuta el endpoint\n *    interpolado. Como el kit no puede inferir `lineStatuses`/`docState`, si la\n *    respuesta NO trae `updatedData` (típico 204) marca `refetch` para que la UI\n *    no quede stale.\n */\n/** Clave i18n del error genérico cuando el backend no envía mensaje propio. */\nconst ACTION_FAILED_KEY = 'master_document.error.actionFailed';\n\n/**\n * Normaliza el fallo de una acción de línea.\n *\n * Si el backend mandó `message`, se respeta tal cual (ya llega traducido: el kit\n * envía `Accept-Language`). Si no, se propaga la clave del kit junto con su texto\n * español, para que el hook llamante pueda traducirla al idioma activo.\n */\nfunction actionFailed(message?: string): LineActionOutcome {\n  if (message) return { ok: false, error: message };\n  return {\n    ok: false,\n    error: MASTER_DOCUMENT_TRANSLATIONS_ES[ACTION_FAILED_KEY],\n    errorKey: ACTION_FAILED_KEY,\n  };\n}\n\nexport async function runLineAction(\n  adapter: IMasterDocumentAdapter,\n  state: DocumentState,\n  entry: LineActionEntry,\n  actionKey: string,\n  lineId: string,\n  payload: Record<string, unknown>,\n): Promise<LineActionOutcome> {\n  if (adapter.executeLineAction) {\n    const result = await adapter.executeLineAction(actionKey, lineId, payload, state);\n    if (!result.success) return actionFailed(result.message);\n    // Override: el sync depende exclusivamente de su `updatedData`.\n    return { ok: true, message: result.message, merge: result.updatedData };\n  }\n\n  if (entry.endpoint && adapter.genericFetch) {\n    const path = buildLineActionPath(entry.endpoint.path, state.documentId, lineId);\n    const res = await adapter.genericFetch(entry.endpoint.method, path, payload);\n    const result: ActionResult = res && typeof res === 'object' && 'success' in (res as object)\n      ? (res as ActionResult)\n      : { success: true };\n    if (!result.success) return actionFailed(result.message);\n    if (result.updatedData) return { ok: true, message: result.message, merge: result.updatedData };\n    // Sin datos frescos en la respuesta → recargar el documento.\n    return { ok: true, message: result.message, refetch: !!state.documentId && !!adapter.getDocument };\n  }\n\n  return {\n    ok: false,\n    error: 'No hay forma de ejecutar la acción de línea: implementa adapter.executeLineAction o adapter.genericFetch.',\n  };\n}\n","/**\n * ¿Se permite esta operación de línea en el estado actual del documento?\n *\n * Cruza las dos formas de declararlo, en este orden:\n *\n *  1. La LISTA de estados (`editableOn` / `deletableOn` / `addableOn`), si está.\n *     Vocabulario idéntico al de `FieldDescriptor.editableOn`, incluido el comodín\n *     `'*'`, a propósito: el encabezado ya se declara así y no tiene sentido inventar\n *     un segundo idioma para las líneas.\n *  2. El BOOLEANO (`editable` / `deletable`), que se conserva como atajo de\n *     `[]` / `['*']`.\n *  3. Ausentes los dos, permitido — para que el cambio no rompa a nadie.\n *\n * La lista gana cuando están las dos. El booleano se evalúa igual si es `false`\n * explícito: una clase que declara `editable: false` no edita en ningún estado, diga\n * lo que diga la lista, porque ese `false` describe una capacidad que el backend no\n * tiene (no existe `PUT /lines/{lineId}`), no una regla de estado.\n *\n * Sin `docState` —el documento todavía no cargó— sólo manda el booleano: negar por\n * un estado que aún no se conoce apagaría los botones durante la carga y los\n * encendería después, que se lee como un parpadeo.\n */\nexport function operacionDeLineaPermitida(\n  booleano: boolean | undefined,\n  estados: string[] | undefined,\n  docState: string | undefined,\n): boolean {\n  if (booleano === false) return false;\n  if (!estados) return booleano ?? true;\n  if (estados.includes('*')) return true;\n  if (!docState) return booleano ?? true;\n  return estados.includes(docState);\n}\n","import type { ActionRegistryEntry } from './template/MasterDocumentTemplate.types';\n\n/**\n * Resultado de evaluar el soporte declarativo de \"acción deshabilitada con\n * motivo\" para una entrada del `actionRegistry`.\n */\nexport interface ActionDisabledState {\n  /** true cuando el `docState` actual está incluido en `entry.disabledStates`. */\n  disabled: boolean;\n  /** Tooltip (atributo `title`) a mostrar cuando `disabled` es true. */\n  disabledReason?: string;\n}\n\n/**\n * Evalúa si una acción debe mostrarse VISIBLE pero DESHABILITADA en el estado\n * actual del documento.\n *\n * Una acción cuyo `disabledStates` incluye el `docState` actual se renderiza\n * deshabilitada (en vez de oculta), mostrando `disabledTooltip` como tooltip.\n * Acciones sin `disabledStates` devuelven `{ disabled: false }`, es decir, se\n * comportan exactamente como antes (retrocompatibilidad total).\n *\n * @see ActionRegistryEntry.disabledStates\n * @see ActionRegistryEntry.disabledTooltip\n */\nexport function resolveActionDisabledState(\n  entry: Pick<ActionRegistryEntry, 'disabledStates' | 'disabledTooltip'>,\n  docState: string,\n): ActionDisabledState {\n  const disabled = entry.disabledStates?.includes(docState) ?? false;\n  return {\n    disabled,\n    disabledReason: disabled ? entry.disabledTooltip : undefined,\n  };\n}\n","import { useMemo, useCallback, useEffect, useState, useRef, type ReactNode } from 'react';\n\nimport { MasterDocument } from '../MasterDocument';\nimport { DocumentDynamicEntities } from '../DocumentDynamicEntities';\nimport {\n  useDocumentDynamicEntities,\n  type DocumentDynamicEntitiesHandle,\n} from './useDocumentDynamicEntities';\nimport { CurrencyPanel } from '../CurrencyPanel';\nimport { CurrencySelectorModal } from '../CurrencySelectorModal';\nimport { DocumentModalList, ConfirmDialog } from '../DocumentModalList';\nimport { CreateFromSourceModal } from '../CreateFromSourceModal';\nimport type { CurrencyInfo, IMasterDocumentAdapter } from '../adapter/MasterDocumentAdapter.types';\nimport type { DocumentModalListConfig } from '../template/MasterDocumentTemplate.types';\nimport {\n  useMasterDocumentAdapter,\n  useMasterDocumentTemplate,\n  useIconRegistry,\n  useUserPermissions,\n  useFactBoxWidgets,\n  useLineTabRenderers,\n} from '../provider/MasterDocumentProvider';\nimport {\n  MasterDocumentRefreshProvider,\n  type MasterDocumentRefreshApi,\n} from '../provider/MasterDocumentRefreshProvider';\nimport { useMasterDocumentPrint } from '../printing/MasterDocumentPrintProvider';\nimport { useMasterDocumentAudit } from '../audit/MasterDocumentAuditProvider';\nimport type { AuditContext } from '../audit/MasterDocumentAuditProvider';\nimport type { PrintContext } from '../printing/MasterDocumentPrinting.types';\nimport { PrintIcon, HistoryIcon } from '../icons';\nimport { useMasterDocumentReducer } from './useMasterDocumentReducer';\nimport { toast } from '../../Toast';\nimport { useFactBoxData } from './useFactBoxData';\nimport { useCrossing } from './useCrossing';\nimport { createCrossingFetch } from './crossingFetch';\nimport { buildFactBoxSections } from './factBoxBuilder';\nimport { isLineFieldVisibleInState } from './lineFieldVisibility';\n\nimport type {\n  TransitionConfig,\n  ActionConfig,\n  ContextStripItem,\n  ComputedRule,\n  LookupFieldConfig,\n  RowAction,\n  DocumentLineData,\n  LineTabConfig,\n  LineTabExternalFilter,\n} from '../MasterDocument.types';\nimport type { SerializableTransitionConfig, SerializableActionConfig, ActionRegistryEntry, LineModalWidgetConfig, LineActionEntry, DetailTabFlexQuery } from '../template/MasterDocumentTemplate.types';\nimport { LineActionFormModal } from '../LineActionFormModal';\nimport { evaluateLineActionGate, runLineAction } from './lineActionGating';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport { operacionDeLineaPermitida } from '../lineStateAxis';\nimport { classifyError } from './userFacingError';\nimport { createCurrencyFormatter, useMasterDocumentFormatters } from '../formatters';\nimport { resolveActionDisabledState } from '../actionVisibility';\nimport { evaluateCondition } from '../fieldCondition';\nimport type { FieldCondition } from '../fieldCondition';\nimport { evaluateExpression } from '../template/expressionEvaluator';\n\n// ════════════════════════════════════════════════════════════\n// PERMISSIONS HELPER — Filtra campos según permisos del usuario\n// ════════════════════════════════════════════════════════════\n\nimport type { FieldDescriptor } from '../MasterDocument.types';\n\n/**\n * Aplica RBAC declarativo sobre un array de campos.\n *\n * - `permissions === null` → sistema no activo → devuelve campos sin cambios.\n * - `permissionVisibility` ausente → campo siempre visible.\n * - `permissionEnable` ausente → editabilidad controlada solo por editableOn/docState.\n */\nfunction applyPermissions(\n  fields: FieldDescriptor[],\n  permissions: string[] | null,\n): FieldDescriptor[] {\n  if (permissions === null) return fields;\n\n  return fields\n    .filter((f) => !f.permissionVisibility || permissions.includes(f.permissionVisibility))\n    .map((f) => {\n      if (!f.permissionEnable || permissions.includes(f.permissionEnable)) return f;\n      return { ...f, editableOn: [] };\n    });\n}\n\n// ════════════════════════════════════════════════════════════\n// LINE WIDGET PANEL — Sidebar panel que se carga vía adapter\n// ════════════════════════════════════════════════════════════\n\nfunction LineWidgetPanel({\n  config,\n  formValues,\n  documentId,\n  adapter,\n}: {\n  config: LineModalWidgetConfig;\n  formValues: Record<string, unknown>;\n  documentId: string | undefined;\n  adapter: IMasterDocumentAdapter;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const [data, setData] = useState<Record<string, unknown>>({});\n  const [loading, setLoading] = useState(false);\n  const generationRef = useRef(0);\n  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  // Build a snapshot of only the watched fields to avoid unnecessary fetches\n  const watchSnapshot = useMemo(() => {\n    const snap: Record<string, unknown> = {};\n    config.watchFields.forEach((k) => { snap[k] = formValues[k]; });\n    return snap;\n  }, [config.watchFields, formValues]);\n\n  useEffect(() => {\n    if (!adapter.getLineWidgetData) return;\n\n    if (timerRef.current) clearTimeout(timerRef.current);\n\n    const delay = config.debounceMs ?? 300;\n    timerRef.current = setTimeout(async () => {\n      const gen = ++generationRef.current;\n      setLoading(true);\n      try {\n        const result = await adapter.getLineWidgetData!(config.widgetKey, watchSnapshot, documentId);\n        if (generationRef.current === gen) setData(result);\n      } catch {\n        // Leave previous data on error\n      } finally {\n        if (generationRef.current === gen) setLoading(false);\n      }\n    }, delay);\n\n    return () => {\n      if (timerRef.current) clearTimeout(timerRef.current);\n    };\n  }, [watchSnapshot]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const entries = Object.entries(data);\n\n  return (\n    <div className=\"flex flex-col h-full\">\n      {/* Panel header */}\n      <div className=\"flex items-center justify-between px-4 py-3 border-b border-border-secondary dark:border-dark-border-primary shrink-0\">\n        <span className=\"text-xs font-semibold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary\">\n          {config.title}\n        </span>\n        {loading && (\n          <svg className=\"w-3.5 h-3.5 animate-spin text-primary-custom-500 dark:text-dark-border-custom\" viewBox=\"0 0 24 24\" fill=\"none\">\n            <circle className=\"opacity-25\" cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"3\" />\n            <path className=\"opacity-80\" fill=\"currentColor\" d=\"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z\" />\n          </svg>\n        )}\n      </div>\n\n      {/* KV list */}\n      <div className=\"flex-1 overflow-y-auto px-4 py-3 space-y-2.5\">\n        {entries.length === 0 && !loading && (\n          <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary italic\">\n            {t('master_document.chrome.noData')}\n          </p>\n        )}\n        {entries.map(([key, value]) => (\n          <div key={key} className=\"flex flex-col gap-0.5\">\n            <span className=\"text-[10px] font-medium uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary\">\n              {key}\n            </span>\n            <span className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary break-words\">\n              {String(value ?? '—')}\n            </span>\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n\n// ════════════════════════════════════════════════════════════\n// PROPS — Solo documentId. Todo lo demás viene del template\n//         y del adapter via MasterDocumentProvider.\n// ════════════════════════════════════════════════════════════\n\n/**\n * Motivo por el que el kit pide navegar a otro documento que ya existe en el backend.\n *\n * Los dos orígenes piden destinos distintos, y por eso el motivo viaja al host:\n * - `'traceability'`: nodo del grafo de trazabilidad → normalmente solo lectura.\n * - `'generated'`: documento recién generado por un cruce → normalmente edición.\n */\nexport type DocumentNavigationReason = 'traceability' | 'generated';\n\n/** Contexto entregado a `onNavigateToDocument`. */\nexport interface DocumentNavigationContext {\n  reason: DocumentNavigationReason;\n}\n\nexport interface SmartMasterDocumentProps {\n  /**\n   * UUID (v7) del documento a cargar. Es la PK de document_headers.id.\n   * Si no se pasa, entra en modo 'create'.\n   *\n   * NO es el document_number legible (\"PV-2026-004821\"), sino el UUID\n   * globalmente único que identifica el registro sin ambigüedad,\n   * independiente de compañía, centro de operación o tipo de documento.\n   */\n  documentId?: string;\n\n  /**\n   * Estado inicial pre-poblado por el backend via GET /documents/new.\n   * Cuando se provee, el documento arranca en modo 'create' con los\n   * headerValues ya resueltos (compañía, CO, tipo). No hay ID todavía;\n   * el POST se hace al guardar por primera vez.\n   */\n  initialState?: import('../adapter/MasterDocumentAdapter.types').DocumentState;\n\n  /** Llamado tras un guardado exitoso. Usado por MasterDocumentPage para volver al listado. */\n  onSaved?: () => void;\n\n  /**\n   * Llamado cuando una acción elimina el documento y devuelve\n   * `{ success: true, navigateToList: true }`. Usado por MasterDocumentPage\n   * para volver al listado tras borrar/anular el documento desde el detalle.\n   */\n  onNavigateToList?: () => void;\n\n  /**\n   * Fuerza el modo 'view' (solo lectura) independiente de lo que retorne el adapter.\n   * Usado por \"Ver detalle\" en el listado.\n   */\n  viewOnly?: boolean;\n\n  /**\n   * Adapter alternativo. Si se pasa, toma precedencia sobre el del contexto.\n   * Usado por MasterDocumentPage para inyectar un adapter con navegación interceptada.\n   */\n  adapterOverride?: IMasterDocumentAdapter;\n\n  /**\n   * Navegación a OTRO documento que ya existe en el backend, pedida desde el detalle:\n   * un nodo del grafo de trazabilidad, o el documento recién generado por un cruce.\n   *\n   * ⚠️ Sin este prop el kit emite el pseudo-key `navigate_document:<id>` por el canal\n   * de `adapter.executeAction` — comportamiento histórico, que solo\n   * `MasterDocumentPage` intercepta. Un host que renderiza este componente en su\n   * propia ruta DEBE pasarlo: de lo contrario el pseudo-key llega a su `executeAction`\n   * real, que no lo conoce, y el clic termina en un error visible o en nada.\n   *\n   * @see DocumentNavigationReason — para distinguir el origen y elegir el destino\n   */\n  onNavigateToDocument?: (documentId: string, context: DocumentNavigationContext) => void;\n}\n\n// ════════════════════════════════════════════════════════════\n// CURRENCY PANEL — renderizado desde template.currency\n// ════════════════════════════════════════════════════════════\n\n\n// ════════════════════════════════════════════════════════════\n// COMPONENT\n// ════════════════════════════════════════════════════════════\n\n/**\n * SmartMasterDocument — componente inteligente que conecta el template JSON\n * con el adaptador de datos para renderizar un documento maestro completo.\n *\n * Orquesta el ciclo de vida del documento:\n * - Carga y mutación de estado vía `useMasterDocumentReducer`\n * - Carga asíncrona de datos del FactBox vía `useFactBoxData`\n * - Conflicto de concurrencia duro derivado del 409 del servidor (`state.conflict`)\n * - Construcción de transiciones, acciones y secciones del FactBox\n *   a partir del template declarativo\n *\n * @see MasterDocumentProvider — proveedor que inyecta el template y el adaptador\n * @see MasterDocument — componente de presentación pura que recibe los datos\n *\n * @example\n * ```tsx\n * <MasterDocumentProvider template={invoiceTemplate} adapter={myAdapter}>\n *   <SmartMasterDocument documentId=\"FA-001\" />\n * </MasterDocumentProvider>\n * ```\n */\nexport function SmartMasterDocument({ documentId, initialState, onSaved, viewOnly, adapterOverride, onNavigateToList, onNavigateToDocument }: SmartMasterDocumentProps) {\n  const contextAdapter = useMasterDocumentAdapter();\n  const adapter = adapterOverride ?? contextAdapter;\n  const template = useMasterDocumentTemplate();\n  const iconRegistry = useIconRegistry();\n  const userPermissions = useUserPermissions();\n  const factBoxWidgets = useFactBoxWidgets();\n  const lineTabRenderers = useLineTabRenderers();\n  const print = useMasterDocumentPrint();\n  const audit = useMasterDocumentAudit();\n  const { t } = useMasterDocumentTranslation();\n  const { locale } = useMasterDocumentFormatters();\n\n  // ── Campos adicionales (EAV): segunda fase del guardado ──\n  //\n  // Indirección por ref a propósito. El reducer necesita los callbacks para\n  // invocarlos DESPUÉS de persistir, pero el hook que los produce necesita\n  // `state.documentClass`, que sale del propio reducer. Un ref rompe el ciclo sin\n  // duplicar estado: los callbacks son estables y leen el valor vigente.\n  const dynamicEntitiesRef = useRef<DocumentDynamicEntitiesHandle | null>(null);\n\n  const persistDynamicHeader = useCallback(async (persistedDocumentId: string) => {\n    await dynamicEntitiesRef.current?.header?.save(persistedDocumentId);\n  }, []);\n\n  const persistDynamicLine = useCallback(async (persistedLineId: string) => {\n    await dynamicEntitiesRef.current?.line?.save(persistedLineId);\n  }, []);\n\n  const persistenceHooks = useMemo(\n    () => ({ onHeaderPersisted: persistDynamicHeader, onLinePersisted: persistDynamicLine }),\n    [persistDynamicHeader, persistDynamicLine],\n  );\n\n  const {\n    state,\n    dispatch,\n    handleHeaderFieldChange,\n    handleLineSave,\n    handleDeleteLine,\n    handleDuplicateLine,\n    handleTransition,\n    handleAction,\n  } = useMasterDocumentReducer(\n    template,\n    adapter,\n    documentId,\n    initialState,\n    onSaved,\n    viewOnly,\n    onNavigateToList,\n    persistenceHooks,\n  );\n\n  const dynamicEntities = useDocumentDynamicEntities({\n    config: template.dynamicEntities,\n    documentClass: state.documentClass ?? template.identity.documentClass,\n  });\n\n  // El ref se sincroniza en un efecto y no en el render: los callbacks de arriba\n  // solo corren desde un evento del usuario, siempre después de pintar.\n  useEffect(() => {\n    dynamicEntitiesRef.current = dynamicEntities;\n  }, [dynamicEntities]);\n\n  // ── Error toast ───────────────────────────────────\n  useEffect(() => {\n    if (!state.error) return;\n    toast.error(t('master_document.chrome.error'), { description: state.error });\n    dispatch({ type: 'SET_ERROR', error: undefined });\n  }, [state.error, t]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  // ── FactBox data loading ──────────────────────────\n  useFactBoxData(\n    template.factBox.sections,\n    adapter,\n    state,\n    dispatch,\n  );\n\n  // ── Conflict detection ────────────────────────────\n  // La fuente de verdad de un conflicto es el 409 del servidor\n  // (`OPTIMISTIC_LOCK_VIOLATION`) en cualquier mutación, persistido por el reducer\n  // en `state.conflict` con `hard: true`. Se eliminó el polling blando\n  // (`useConflictDetection`): llegaba segundos tarde y era descartable, permitiendo\n  // guardar con un token viejo. Ahora el conflicto es duro y no descartable.\n\n  // ── Clase del documento abierto ──────────────────────────\n  // `template.identity.documentClass` es una constante POR SUPERFICIE, así que no\n  // sirve cuando una superficie sirve a varias clases (p.ej. notas crédito de\n  // venta y de solo valor comparten visor). La clase del estado —puesta por el\n  // wizard vía `initialState`, o devuelta por el adapter en `getDocument`— manda\n  // sobre ella. Ausente ⇒ la del template, que es el caso de todos los documentos\n  // de una sola clase.\n  const resolvedDocClass = state.documentClass ?? template.identity.documentClass;\n\n  // ── Dynamic document states (from API) ───────────────────\n  // GET /api/v1/documents/{documentClass}/states\n  // Allows adding/modifying states in the DB without touching the template.\n  // Falls back to template.stateMachine.states when the endpoint is unavailable.\n  const [dynamicStates, setDynamicStates] = useState<import('../adapter/MasterDocumentAdapter.types').DocumentStatesResponse | null>(null);\n\n  useEffect(() => {\n    if (!adapter.getDocumentStates) return;\n    let cancelled = false;\n    adapter.getDocumentStates(resolvedDocClass)\n      .then((s) => { if (!cancelled) setDynamicStates(s); })\n      .catch(() => { if (!cancelled) setDynamicStates(null); });\n    return () => { cancelled = true; };\n  }, [adapter, resolvedDocClass]);\n\n  // ── Available actions (from DocumentProcess endpoint) ────\n  // GET /api/v1/documents/{id}/available-actions?state={docState}\n  // Returns the keys of actions enabled for the current user/state/role.\n  // When null (method not implemented), falls back to template's visibleOn.\n  const [availableActionKeys, setAvailableActionKeys] = useState<string[] | null>(null);\n\n  useEffect(() => {\n    if (!adapter.getAvailableActions) {\n      setAvailableActionKeys(null);\n      return;\n    }\n    const docId = state.documentId ?? '';\n    let cancelled = false;\n    adapter.getAvailableActions(docId, state.docState)\n      .then((keys) => { if (!cancelled) setAvailableActionKeys(keys); })\n      .catch(() => { if (!cancelled) setAvailableActionKeys(null); });\n    return () => { cancelled = true; };\n  }, [adapter, state.documentId, state.docState]);\n\n  // ── Resolve icon string → ReactNode ───────────────\n  const resolveIcon = useCallback(\n    (iconName?: string): ReactNode => {\n      if (!iconName) return undefined;\n      const Icon = iconRegistry[iconName];\n      if (!Icon) return undefined;\n      return <Icon className=\"w-4 h-4\" />;\n    },\n    [iconRegistry],\n  );\n\n  // ── Acciones de línea ADICIONALES (declarativas) ──────────\n  // Espejo, a nivel de línea, del flujo de `handleAction`, PERO solo para las\n  // acciones EXTRA declaradas en `template.lineActionRegistry`. Las acciones de\n  // línea quemadas (Editar/Ver/Duplicar/Cerrar-reabrir/Eliminar) NO pasan por aquí.\n  // Qué acción de la ActionBar está en vuelo (P1 de LOADING-INTEGRATION.md).\n  // `state.saving` dice que HAY una mutación, no CUÁL: con él solo se puede\n  // deshabilitar toda la barra, que es lo que ya se hacía. Este estado local\n  // añade la identidad para que gire el botón que el usuario pulsó.\n  //\n  // Vive aquí y no en el reducer a propósito: es presentación, y el reducer es\n  // contrato público que consumen los hosts.\n  //\n  // El prefijo desambigua: una transición se identifica por su destino y una\n  // acción por su clave, y nada impide que coincidan.\n  const [runningAction, setRunningAction] = useState<string | null>(null);\n\n  const runTransition = useCallback(async (to: string) => {\n    setRunningAction(`t:${to}`);\n    try {\n      await handleTransition(to);\n    } finally {\n      setRunningAction(null);\n    }\n  }, [handleTransition]);\n\n  const runAction = useCallback(async (key: string) => {\n    setRunningAction(`a:${key}`);\n    try {\n      await handleAction(key);\n    } finally {\n      setRunningAction(null);\n    }\n  }, [handleAction]);\n\n  // Resincroniza el documento completo desde el backend (P8 de\n  // LOADING-INTEGRATION.md).\n  //\n  // Los tres sitios que llaman aquí REEMPLAZAN el documento entero y lo hacían\n  // de forma invisible: `getDocument` sin `LOAD_START`, así que el usuario veía\n  // los datos viejos hasta que cambiaban de golpe. Con el despacho, el mismo\n  // `SkeletonDocument` de la carga inicial cubre la espera. No lleva `Loading`\n  // a propósito: para una vista completa la máscara de layout es mejor que un\n  // spinner, y ya existe.\n  //\n  // El `LOAD_ERROR` NO es opcional: sin él un refetch fallido deja el skeleton\n  // girando para siempre. Antes ese fallo era inocuo porque no había skeleton\n  // que colgar — de hecho uno de los tres sitios ni siquiera tenía `.catch`, y\n  // otro lo tragaba en silencio.\n  // Señal de \"las líneas cambiaron\" para los listados que NO son la grilla nativa\n  // (pestañas Tipo 2 / Tipo 3). El host no puede observar `state.lines` —vive en\n  // su propio fetch—, así que se le entrega un contador que sube en cada mutación\n  // del kit y que él usa como dependencia. Es declarativo a propósito: la\n  // alternativa era guardar un `refetch` imperativo del componente del host, con\n  // el riesgo de quedarse con una referencia muerta al desmontar la pestaña.\n  const [refreshToken, setRefreshToken] = useState(0);\n  const bumpRefresh = useCallback(() => setRefreshToken((n) => n + 1), []);\n\n  const refetchDocument = useCallback(async () => {\n    if (!state.documentId || !adapter.getDocument) return;\n    dispatch({ type: 'LOAD_START' });\n    try {\n      const fresh = await adapter.getDocument(state.documentId);\n      dispatch({ type: 'LOAD_SUCCESS', payload: fresh });\n      // Cubre lo que no pasa por las tres mutaciones de línea: acciones de fila,\n      // recarga por conflicto y anexado desde origen.\n      bumpRefresh();\n    } catch (err) {\n      // Mismo tratamiento que la carga inicial: el texto técnico va al log y el\n      // saneado a `state.error`, que ya dispara el toast.\n      const { message, technical } = classifyError(err, t);\n      if (technical) console.error('[MasterDocument] resincronización falló:', technical);\n      dispatch({ type: 'LOAD_ERROR', payload: message });\n    }\n  }, [state.documentId, adapter, dispatch, t, bumpRefresh]);\n\n  // Lo que el host ve de la resincronización: recargar el documento y saber que\n  // algo cambió. Se publica al subárbol entero (widgets del FactBox, renderers de\n  // pestañas, paneles propios) porque hasta ahora un componente del host que\n  // persistía por su cuenta no tenía forma de avisarle al kit — y el kit solo\n  // mergea lo que guarda él, así que la pantalla se quedaba con los valores\n  // previos hasta un F5.\n  const refreshApi = useMemo<MasterDocumentRefreshApi>(\n    () => ({ reload: refetchDocument, refreshToken }),\n    [refetchDocument, refreshToken],\n  );\n\n  // Qué línea está mutando (P4 de LOADING-INTEGRATION.md). Mismo patrón que\n  // `runningAction`: `state.saving` dice que HAY una mutación, no sobre qué fila.\n  //\n  // Se rastrea aquí y NO en el reducer —que era lo que el análisis preveía—\n  // porque las tres operaciones ya reciben el `lineId` como primer argumento:\n  // no hace falta tocar el contrato que consumen los hosts.\n  const [busyLineId, setBusyLineId] = useState<string | null>(null);\n\n  const runLineSave = useCallback(async (lineId: string | null, data: Record<string, unknown>) => {\n    // `lineId === null` es una línea nueva: todavía no hay fila que marcar.\n    setBusyLineId(lineId);\n    try {\n      const errors = await handleLineSave(lineId, data);\n      // Solo cuenta como mutación si el guardado pasó: un rechazo de validación\n      // no cambió las líneas y no debe hacer refetch a los listados del host.\n      if (!errors || Object.keys(errors).length === 0) bumpRefresh();\n      return errors;\n    } finally {\n      setBusyLineId(null);\n    }\n  }, [handleLineSave, bumpRefresh]);\n\n  // Línea pendiente de confirmar el borrado (null = sin diálogo abierto). Antes el borrado se\n  // confirmaba con un `window.confirm` dentro del reducer: un cuadro del navegador, ajeno al estilo\n  // del kit, que bloquea el hilo y no se puede probar sin parchear `window`. Ahora la pregunta la\n  // hace el `ConfirmDialog` del kit, igual que `DocumentList` para las acciones de fila.\n  const [pendingDeleteLineId, setPendingDeleteLineId] = useState<string | null>(null);\n\n  const runDeleteLine = useCallback((lineId: string) => {\n    setPendingDeleteLineId(lineId);\n  }, []);\n\n  const confirmDeleteLine = useCallback(async () => {\n    const lineId = pendingDeleteLineId;\n    if (!lineId) return;\n    setPendingDeleteLineId(null);\n    setBusyLineId(lineId);\n    try {\n      await handleDeleteLine(lineId);\n      bumpRefresh();\n    } finally {\n      setBusyLineId(null);\n    }\n  }, [pendingDeleteLineId, handleDeleteLine, bumpRefresh]);\n\n  const runDuplicateLine = useCallback(async (lineId: string) => {\n    setBusyLineId(lineId);\n    try {\n      await handleDuplicateLine(lineId);\n      bumpRefresh();\n    } finally {\n      setBusyLineId(null);\n    }\n  }, [handleDuplicateLine, bumpRefresh]);\n\n  const [activeLineAction, setActiveLineAction] = useState<{ key: string; entry: LineActionEntry } | null>(null);\n  const [lineActionLineId, setLineActionLineId] = useState<string>('');\n  const [lineActionBusy, setLineActionBusy] = useState(false);\n  const [lineActionError, setLineActionError] = useState<string | undefined>(undefined);\n\n  // Ejecuta una acción de línea adicional (vía override `executeLineAction` o vía\n  // genérica `endpoint`+`genericFetch`) y aplica el outcome: merge de\n  // `updatedData`, o refetch del documento cuando la vía genérica no devuelve\n  // datos frescos, + toast. La decisión vive en `runLineAction` (testeable).\n  const handleLineAction = useCallback(\n    async (\n      actionKey: string,\n      lineId: string,\n      payload: Record<string, unknown>,\n      entry: LineActionEntry,\n    ) => {\n      setLineActionBusy(true);\n      setLineActionError(undefined);\n      try {\n        const outcome = await runLineAction(adapter, state, entry, actionKey, lineId, payload);\n        if (!outcome.ok) {\n          // `runLineAction` es puro y no traduce: si el mensaje lo generó el kit\n          // propaga `errorKey` y lo resolvemos aquí al idioma activo. Si vino del\n          // backend, `error` ya llega traducido (el kit envía `Accept-Language`).\n          const errorText = outcome.errorKey ? t(outcome.errorKey) : outcome.error;\n          // `custom` no abre modal del kit: el error se muestra vía toast. El\n          // `formModal` lo muestra dentro del propio modal (setLineActionError).\n          if (entry.actionType === 'custom') {\n            if (errorText) toast.error(errorText);\n          } else {\n            setLineActionError(errorText);\n          }\n          return;\n        }\n        // Resincronización: `merge` (preciso) o `refetch` (recarga del documento\n        // cuando la vía genérica no devuelve datos frescos). Ver runLineAction.\n        if (outcome.merge) {\n          dispatch({ type: 'MERGE_STATE', payload: outcome.merge });\n        } else if (outcome.refetch) {\n          // `refetchDocument` no relanza: un fallo de resincronización ya no se\n          // confunde con un fallo de la acción, que a estas alturas YA tuvo\n          // éxito. Antes caía en el `catch` de abajo y el usuario leía \"la\n          // acción falló\" sobre una acción que sí se aplicó.\n          await refetchDocument();\n        }\n        if (outcome.message) toast.success(outcome.message);\n        setActiveLineAction(null);\n        setLineActionLineId('');\n      } catch (err) {\n        const { message, technical } = classifyError(err, t);\n        if (technical) console.error('[MasterDocument] acción de línea falló:', technical);\n        if (entry.actionType === 'custom') {\n          toast.error(message);\n        } else {\n          setLineActionError(message);\n        }\n      } finally {\n        setLineActionBusy(false);\n      }\n    },\n    [adapter, state, dispatch, t, refetchDocument],\n  );\n\n  // Construye las acciones de línea EXTRA para una fila, gateadas por D2. Las\n  // acciones quemadas se anexan en `LinesSection` (no aquí). Sin\n  // `lineActionRegistry` ⇒ no hay acciones extra (retrocompatible).\n  const getLineActions = useCallback(\n    (line: DocumentLineData): RowAction[] => {\n      const registry = template.lineActionRegistry;\n      if (!registry) return [];\n      const actions: RowAction[] = [];\n      for (const [key, entry] of Object.entries(registry)) {\n        const gate = evaluateLineActionGate(entry, line, state.docState, userPermissions);\n        if (!gate.visible) continue;\n        actions.push({\n          key,\n          label: entry.label,\n          icon: resolveIcon(entry.icon),\n          variant: entry.variant,\n          disabled: gate.disabled,\n          onClick: () => {\n            if (entry.actionType === 'formModal') {\n              setLineActionError(undefined);\n              setActiveLineAction({ key, entry });\n              setLineActionLineId(line.id);\n            } else if (entry.actionType === 'custom') {\n              // El kit NO abre su modal: delega en `adapter.executeLineAction`\n              // con payload vacío. El consumidor aporta su propia UX (p.ej. un\n              // modal con picker) dentro del override. El merge/refetch/toast del\n              // `ActionResult` los aplica `handleLineAction` igual que el formModal.\n              void handleLineAction(key, line.id, {}, entry);\n            }\n          },\n        });\n      }\n      return actions;\n    },\n    [template.lineActionRegistry, state.docState, userPermissions, resolveIcon, handleLineAction],\n  );\n\n  // ── Map serializable transitions → TransitionConfig[]\n  // API transitions take priority; fall back to template-embedded transitions.\n  const transitions = useMemo<TransitionConfig[]>(() => {\n    // API transitions: use when getDocumentStates returned them\n    if (dynamicStates?.transitions && dynamicStates.transitions.length > 0) {\n      const seen = new Set<string>();\n      return dynamicStates.transitions\n        .filter((t) => t.from === state.docState)\n        .filter((t) => {\n          // Deduplicate by actionKey — show only the first transition per action.\n          if (seen.has(t.actionKey)) return false;\n          seen.add(t.actionKey);\n          return true;\n        })\n        .map((t) => {\n          // Look up action metadata (label, icon, style):\n          // 1. Inline in transition (backend-provided) → 2. actionRegistry (v1.1) → 3. actions[] (v1.0) → 4. raw key\n          const registryEntry: ActionRegistryEntry | undefined = template.actionRegistry?.[t.actionKey];\n          const legacyMeta = registryEntry ? undefined : template.actions?.find((a: SerializableActionConfig) => a.key === t.actionKey);\n          const label = t.label ?? registryEntry?.label ?? legacyMeta?.label ?? t.actionKey;\n          const icon = resolveIcon(t.icon ?? registryEntry?.icon ?? legacyMeta?.icon);\n          const style = (t.variant ?? registryEntry?.variant ?? legacyMeta?.variant ?? 'secondary') as import('../MasterDocument.types').ActionVariant;\n          // Gating in-flight (Caso B): mientras hay una mutación en curso, las\n          // transiciones (aprobar/anular) se deshabilitan para evitar doble disparo.\n          return {\n            to: t.to,\n            actionKey: t.actionKey,\n            label,\n            icon,\n            style,\n            hasGuard: t.hasGuard,\n            disabled: state.saving,\n            loading: runningAction === `t:${t.to}`,\n          };\n        });\n    }\n    // Template fallback (v1.0 format with embedded transitions)\n    const templateTransitions = template.stateMachine.transitions ?? [];\n    return templateTransitions\n      .filter((t: SerializableTransitionConfig) => t.from.includes(state.docState))\n      .map((t: SerializableTransitionConfig) => ({\n        to: t.to,\n        label: t.label,\n        icon: resolveIcon(t.icon),\n        style: t.style,\n        hasGuard: t.hasGuard,\n        shortcut: t.shortcut,\n        disabled: state.saving,\n        loading: runningAction === `t:${t.to}`,\n      }));\n  }, [template.stateMachine.transitions, template.actions, template.actionRegistry, dynamicStates, state.docState, state.saving, resolveIcon, runningAction]);\n\n  // ── Map serializable actions → ActionConfig[] ─────\n  // Priority: API (availableActionKeys) > template visibleOn\n  // When the API returns a list, it acts as the whitelist — only those keys are shown.\n  // When null (endpoint not implemented), falls back to template's visibleOn logic.\n  const actions = useMemo<ActionConfig[]>(() => {\n    // Keys for the current state that are already rendered as transition buttons.\n    // These must NOT also appear as action buttons (would create visible duplicates).\n    const activeTransitionKeys = new Set(\n      (dynamicStates?.transitions ?? [])\n        .filter((t) => t.from === state.docState)\n        .map((t) => t.actionKey),\n    );\n\n    // v1.1: use actionRegistry only when the API provides availableActionKeys.\n    // Without that whitelist every registry entry would render as a button,\n    // including transition-label entries that are only used for key→label resolution.\n    if (template.actionRegistry && availableActionKeys !== null) {\n      return Object.entries(template.actionRegistry)\n        .filter(([key, entry]) => {\n          if (activeTransitionKeys.has(key)) return false;\n          if (entry.permissionVisibility && userPermissions !== null && !userPermissions.includes(entry.permissionVisibility)) return false;\n          // Una acción con `disabledStates` que incluya el estado actual se\n          // muestra (deshabilitada) aunque no venga en availableActionKeys.\n          const { disabled } = resolveActionDisabledState(entry, state.docState);\n          return availableActionKeys.includes(key) || (entry.alwaysVisible && !!state.documentId) || disabled;\n        })\n        .map(([key, entry]: [string, ActionRegistryEntry]) => {\n          const { disabled, disabledReason } = resolveActionDisabledState(entry, state.docState);\n          return {\n            key,\n            label: entry.label,\n            icon: resolveIcon(entry.icon),\n            variant: entry.variant,\n            // Una acción deshabilitada no ejecuta nada (ni abre confirmación).\n            onClick: disabled\n              ? () => {}\n              : entry.actionType === 'modalList' && entry.modalList\n                ? () => {\n                    setActiveModalListConfig(entry.modalList!);\n                    setModalListLineId(undefined);\n                    setModalListOpen(true);\n                  }\n                : entry.actionType === 'createFromSource'\n                  ? () => setCreateFromSourceOpen(true)\n                  : () => { void runAction(key); },\n            // Gating in-flight (Caso B): además de su estado declarativo, la acción\n            // se deshabilita mientras haya una mutación en curso.\n            disabled: disabled || state.saving,\n            // Solo la pulsada gira; las demás siguen solo deshabilitadas. Las que\n            // abren un modal (modalList / createFromSource) son síncronas y nunca\n            // llegan aquí en vuelo.\n            loading: runningAction === `a:${key}`,\n            disabledReason,\n            position: entry.position,\n            requiresConfirmation: disabled ? false : (entry.actionType === 'modalList' ? false : entry.requiresConfirmation),\n            confirmationMessage: disabled ? undefined : (entry.actionType === 'modalList' ? undefined : entry.confirmationMessage),\n          };\n        });\n    }\n\n    // v1.0 fallback: actions array with visibleOn\n    return (template.actions ?? [])\n      .filter((a: SerializableActionConfig) => {\n        if (a.permissionVisibility && userPermissions !== null && !userPermissions.includes(a.permissionVisibility)) return false;\n        if (availableActionKeys !== null) {\n          return availableActionKeys.includes(a.key) && !activeTransitionKeys.has(a.key);\n        }\n        if (a.visibleOn && a.visibleOn.length > 0) {\n          return a.visibleOn.includes(state.docState) || a.visibleOn.includes('*');\n        }\n        return true;\n      })\n      .map((a: SerializableActionConfig) => {\n        // Even in v1.0 mode, check if this key has a modalList config in actionRegistry\n        const registryEntry = template.actionRegistry?.[a.key];\n        const isModalList = registryEntry?.actionType === 'modalList' && !!registryEntry.modalList;\n        const isCreateFromSource = registryEntry?.actionType === 'createFromSource';\n        return {\n          key: a.key,\n          label: a.label,\n          icon: resolveIcon(a.icon),\n          variant: a.variant,\n          onClick: isModalList\n            ? () => {\n                setActiveModalListConfig(registryEntry!.modalList!);\n                setModalListLineId(undefined);\n                setModalListOpen(true);\n              }\n            : isCreateFromSource\n              ? () => setCreateFromSourceOpen(true)\n              : () => { void runAction(a.key); },\n          disabled: (a.disabledOn?.includes(state.docState) ?? false) || state.saving,\n          loading: runningAction === `a:${a.key}`,\n          position: a.position,\n        };\n      });\n  }, [template.actions, template.actionRegistry, state.docState, state.saving, resolveIcon, handleAction, runAction, runningAction, availableActionKeys, dynamicStates, userPermissions]);\n\n  // ── Impresión nativa (botón en la barra del detalle) ──\n  // Acción de presentación: NO pasa por adapter.executeAction ni por el\n  // actionRegistry. Se anexa al array de acciones cuando la impresión está\n  // disponible para el documento guardado (regla §4.3-a).\n  const actionsWithPrint = useMemo<ActionConfig[]>(() => {\n    if (!print) return actions;\n    const ctx: PrintContext = {\n      source: 'detail',\n      documentId: state.documentId ?? '',\n      documentNumber: (state.headerValues['_documentNumber'] as string | undefined) ?? null,\n      docState: state.docState || null,\n    };\n    if (!print.isPrintAvailable(ctx)) return actions;\n    return [\n      ...actions,\n      {\n        key: 'print',\n        label: print.label,\n        icon: <PrintIcon className=\"w-4 h-4\" />,\n        // 'ghost' por defecto → texto primary-600 legible (SPEC §5.2), no compite\n        // con la primaria. Configurable vía printing.buttonVariant.\n        variant: print.buttonVariant,\n        onClick: () => print.openPrint(ctx),\n      },\n    ];\n  }, [print, actions, state.documentId, state.headerValues, state.docState]);\n\n  // ── Historial de auditoría (acción en la barra del detalle) ──\n  // Acción de presentación (no pasa por adapter/actionRegistry). Se anexa cuando la\n  // auditoría está disponible (enabled + documento guardado). Se encadena sobre\n  // actionsWithPrint para no perder el botón de impresión.\n  const actionsWithAudit = useMemo<ActionConfig[]>(() => {\n    if (!audit) return actionsWithPrint;\n    const ctx: AuditContext = {\n      source: 'detail',\n      documentId: state.documentId ?? '',\n    };\n    if (!audit.isAuditAvailable(ctx)) return actionsWithPrint;\n    return [\n      ...actionsWithPrint,\n      {\n        key: 'audit-history',\n        label: audit.label,\n        icon: <HistoryIcon className=\"w-4 h-4\" />,\n        variant: 'ghost',\n        onClick: () => audit.openAudit(ctx),\n      },\n    ];\n  }, [audit, actionsWithPrint, state.documentId]);\n\n  // ── Context strip items ───────────────────────────\n  // La COMPAÑÍA sube a la cabecera, como badge bajo el título (canon del detalle\n  // de MasterCrud), así que se excluye de la franja: dejarla en los dos sitios la\n  // pintaría dos veces en la misma pantalla. `_companyName` es la clave de la\n  // convención — la declaran 19 de las 43 plantillas de core; donde no está, la\n  // cabecera simplemente no pinta el badge y la franja no pierde nada.\n  const COMPANY_FIELD = '_companyName';\n\n  const contextItems = useMemo<ContextStripItem[]>(() => {\n    return template.contextStrip\n      .filter((m) => m.field !== COMPANY_FIELD)\n      .map((m) => ({\n        label: m.label,\n        value: String(state.headerValues[m.field] ?? ''),\n        mono: m.mono,\n        accent: m.accent,\n      }));\n  }, [template.contextStrip, state.headerValues]);\n\n  const companyName = useMemo(() => {\n    const declarada = template.contextStrip.some((m) => m.field === COMPANY_FIELD);\n    if (!declarada) return undefined;\n    const valor = String(state.headerValues[COMPANY_FIELD] ?? '').trim();\n    return valor || undefined;\n  }, [template.contextStrip, state.headerValues]);\n\n  // ── Currency code (resolved from headerValues or defaultCode) ──\n  const currencyCode = useMemo(() => {\n    const cfg = template.currency;\n    if (!cfg) return '';\n    return String(state.headerValues[cfg.codeField] ?? '') || cfg.defaultCode || '';\n  }, [template.currency, state.headerValues]);\n\n  // ── Fetch exchange rate from backend ──────────────\n  const [exchangeRate, setExchangeRate] = useState<{ rate: number; label: string } | null>(null);\n\n  useEffect(() => {\n    if (!currencyCode || !adapter.getExchangeRate) {\n      setExchangeRate(null);\n      return;\n    }\n    let cancelled = false;\n    adapter.getExchangeRate(currencyCode)\n      .then((result) => { if (!cancelled) setExchangeRate(result); })\n      .catch(() => { if (!cancelled) setExchangeRate(null); });\n    return () => { cancelled = true; };\n  }, [currencyCode, adapter]);\n\n  // ── DocumentModalList state ───────────────────────\n  const [modalListOpen, setModalListOpen] = useState(false);\n  const [activeModalListConfig, setActiveModalListConfig] = useState<DocumentModalListConfig | null>(null);\n  const [modalListLineId, setModalListLineId] = useState<string | undefined>(undefined);\n\n  // ── CreateFromSource state (modo append, caso B) ──\n  const [createFromSourceOpen, setCreateFromSourceOpen] = useState(false);\n\n  // ── Currency selector modal ───────────────────────\n  const [currencyModalOpen, setCurrencyModalOpen] = useState(false);\n  const [availableCurrencies, setAvailableCurrencies] = useState<CurrencyInfo[]>([]);\n  const [currenciesLoading, setCurrenciesLoading] = useState(false);\n\n  const handleOpenCurrencyModal = useCallback(() => {\n    setCurrencyModalOpen(true);\n    if (availableCurrencies.length === 0 && adapter.listCurrencies) {\n      setCurrenciesLoading(true);\n      adapter.listCurrencies(true)\n        .then((list) => setAvailableCurrencies(list))\n        .catch(() => {})\n        .finally(() => setCurrenciesLoading(false));\n    }\n  }, [adapter, availableCurrencies.length]);\n\n  const handleCurrencySelect = useCallback(\n    (currency: CurrencyInfo) => {\n      setCurrencyModalOpen(false);\n      // Actualización optimista: el panel cambia de inmediato\n      const cfg = template.currency;\n      if (cfg) handleHeaderFieldChange(cfg.codeField, currency.code);\n      // Persiste en backend en background (si el adapter lo soporta)\n      adapter.changeCurrency?.(state.documentId ?? '', currency.code);\n    },\n    [adapter, state.documentId, template.currency, handleHeaderFieldChange],\n  );\n\n  // ── Currency panel ────────────────────────────────\n  const currencyPanel = useMemo<ReactNode>(() => {\n    const cfg = template.currency;\n    if (!cfg || !currencyCode) return undefined;\n\n    const rate = exchangeRate?.rate ?? (cfg.rateField ? state.headerValues[cfg.rateField] : undefined);\n    const rateLabel = exchangeRate?.label ?? cfg.rateLabel;\n    const canEdit = cfg.editable && state.mode !== 'view';\n\n    return (\n      <CurrencyPanel\n        code={currencyCode}\n        rate={rate as string | number | undefined}\n        rateLabel={rateLabel}\n        onClick={canEdit ? handleOpenCurrencyModal : undefined}\n      />\n    );\n  }, [template.currency, currencyCode, exchangeRate, state.headerValues, state.mode, handleOpenCurrencyModal]);\n\n  // ── Computed rules → bridge to function-based ─────\n  const lineComputedRules = useMemo<ComputedRule[]>(() => {\n    return template.computedRules\n      .filter((r) => {\n        const field = template.fields.find((f) => f.key === r.targetField);\n        return field?.context === 'line';\n      })\n      .map((r) => ({\n        targetField: r.targetField,\n        watch: r.watch,\n        compute: (formData: Record<string, unknown>) =>\n          evaluateExpression(r.expression, formData, adapter.evaluateCustomRule?.bind(adapter)),\n      }));\n  }, [template.computedRules, template.fields, adapter]);\n\n  // ── Adapter con formatCurrency ajustado a la moneda activa ──\n  // Usa el MISMO formateador que la grilla de líneas (`createCurrencyFormatter`):\n  // el widget de Totales y la grilla leen los mismos números y no pueden\n  // discrepar en los decimales.\n  const factBoxAdapter = useMemo(() => {\n    if (!currencyCode) return adapter;\n    try {\n      const fmt = createCurrencyFormatter(locale, currencyCode);\n      return { ...adapter, formatCurrency: fmt };\n    } catch {\n      return adapter;\n    }\n  }, [adapter, currencyCode, locale]);\n\n  // ── FactBox sections → ReactNode children ─────────\n  const factBoxSections = useMemo(\n    () => buildFactBoxSections(template.factBox.sections, state, factBoxAdapter, userPermissions, factBoxWidgets, t, refreshApi),\n    [template.factBox.sections, state, factBoxAdapter, userPermissions, factBoxWidgets, t, refreshApi],\n  );\n\n  // ── Conflict config ───────────────────────────────\n  // Único origen: el 409 del servidor (`state.conflict`, `hard: true`). El modal\n  // duro no es descartable: la única acción es \"Recargar documento\", que descarta\n  // la edición en vuelo, re-obtiene el documento + row_version y reconcilia.\n  const conflictProp = useMemo(() => {\n    const active = state.conflict;\n    if (!active) return undefined;\n    const clear = () => dispatch({ type: 'CLEAR_CONFLICT' });\n    return {\n      modifiedBy: active.modifiedBy,\n      modifiedAgo: active.modifiedAgo,\n      message: active.message,\n      // hard ⇒ no descartable (sin \"seguir con mis cambios\"); blando ⇒ descartable.\n      dismissable: !active.hard,\n      onReload: () => {\n        clear();\n        void refetchDocument();\n      },\n      // En el conflicto duro no se permite seguir editando con el token viejo.\n      onKeepEditing: active.hard ? undefined : clear,\n    };\n  }, [state.conflict, dispatch, refetchDocument]);\n\n  // ── Forbidden / 403 banner ────────────────────────\n  const forbiddenProp = useMemo(() => {\n    if (!state.forbidden) return undefined;\n    return {\n      message: state.forbidden.message,\n      onDismiss: () => dispatch({ type: 'CLEAR_FORBIDDEN' }),\n    };\n  }, [state.forbidden, dispatch]);\n\n  // Resolved badge: API overrides template for the current state\n  const resolvedStateBadge = useMemo(() => {\n    if (dynamicStates) {\n      const entry = dynamicStates.states.find((s) => s.key === state.docState);\n      if (entry) return { label: entry.label, bg: entry.bg, color: entry.color };\n    }\n    // Fallback to template (old record format)\n    return template.stateMachine.states?.[state.docState];\n  }, [dynamicStates, state.docState, template.stateMachine.states]);\n\n  // ── Field rules (from API) ────────────────────────────────\n  // GET /api/v1/documents/{documentClass}/field-rules?state={docState}\n  // Overrides editableOn/visibleOn from the template for the current state.\n  // When null (method not implemented), falls back to template field arrays.\n  const [fieldRules, setFieldRules] = useState<Record<string, { editable: boolean; visible: boolean }> | null>(null);\n\n  useEffect(() => {\n    if (!adapter.getFieldRules) {\n      setFieldRules(null);\n      return;\n    }\n    let cancelled = false;\n    adapter.getFieldRules(resolvedDocClass, state.docState)\n      .then((rules) => { if (!cancelled) setFieldRules(rules); })\n      .catch(() => { if (!cancelled) setFieldRules(null); });\n    return () => { cancelled = true; };\n  }, [adapter, resolvedDocClass, state.docState]);\n\n  // ── Dynamic select options (optionsSource) ───────────────\n  // For fields with optionsSource, fetch options from API once per companyId/coId change.\n  // Stored as Record<fieldKey, SelectOption[]> — merged into the field's options array.\n  const [dynamicOptions, setDynamicOptions] = useState<Record<string, Array<{ label: string; value: string }>>>({});\n\n  useEffect(() => {\n    if (!adapter.getSelectOptions) return;\n\n    const companyId = String(state.headerValues._companyId ?? '');\n    const coId = String(state.headerValues._coId ?? '');\n\n    const fieldsWithSource = template.fields.filter(\n      (f) => f.context === 'header' || f.context === 'line' || f.context === 'line-detail',\n    ).filter((f) => (f as import('../MasterDocument.types').FieldDescriptor & { optionsSource?: string }).optionsSource);\n\n    if (fieldsWithSource.length === 0) return;\n\n    let cancelled = false;\n    const loads = fieldsWithSource.map(async (f) => {\n      const src = (f as { optionsSource?: string }).optionsSource!;\n      try {\n        const opts = await adapter.getSelectOptions!(src, companyId || undefined, coId || undefined);\n        if (!cancelled) setDynamicOptions((prev) => ({ ...prev, [f.key]: opts }));\n      } catch { /* fallback: keep static options */ }\n    });\n    Promise.allSettled(loads);\n\n    return () => { cancelled = true; };\n  }, [adapter, template.fields, state.headerValues._companyId, state.headerValues._coId]);\n\n  // ── Separate header vs line fields ────────────────\n  // Applies template visibleOn filtering + visibleWhen/hiddenWhen conditions\n  // + API field-rules overrides + dynamic options.\n  const headerFields = useMemo(() => {\n    const base = template.fields.filter((f) => {\n      if (f.context !== 'header') return false;\n      if (f.visibleOn && f.visibleOn.length > 0 && !f.visibleOn.includes('*')) {\n        if (!f.visibleOn.includes(state.docState)) return false;\n      }\n      // Field-level conditional visibility, evaluated against the current header\n      // values — parity with resolvedHeaderSections / resolvedLineColumns. Without\n      // this, a header field's visibleWhen/hiddenWhen was silently ignored and the\n      // field always rendered (e.g. exchange-rate always shown in local currency).\n      if (f.visibleWhen && !evaluateCondition(f.visibleWhen, state.headerValues as Record<string, unknown>)) return false;\n      if (f.hiddenWhen && evaluateCondition(f.hiddenWhen, state.headerValues as Record<string, unknown>)) return false;\n      return true;\n    });\n    const withRules = base\n      .filter((f) => !fieldRules || fieldRules[f.key]?.visible !== false)\n      .map((f) => {\n        let updated = f;\n        if (fieldRules?.[f.key]) {\n          const rule = fieldRules[f.key];\n          const editableOn = rule.editable\n            ? [...new Set([...f.editableOn, state.docState])]\n            : f.editableOn.filter((s) => s !== state.docState && s !== '*');\n          updated = { ...updated, editableOn };\n        }\n        if (dynamicOptions[f.key]) {\n          updated = { ...updated, options: dynamicOptions[f.key] };\n        }\n        return updated;\n      });\n    return applyPermissions(withRules, userPermissions);\n  }, [template.fields, fieldRules, dynamicOptions, state.docState, state.headerValues, userPermissions]);\n\n  const lineFields = useMemo(() => {\n    const base = template.fields.filter((f) => {\n      if (f.context !== 'line' && f.context !== 'line-detail') return false;\n      return isLineFieldVisibleInState(f, state.docState);\n    });\n    const withRules = base\n      .filter((f) => !fieldRules || fieldRules[f.key]?.visible !== false)\n      .map((f) => {\n        let updated = f;\n        if (fieldRules?.[f.key]) {\n          const rule = fieldRules[f.key];\n          const editableOn = rule.editable\n            ? [...new Set([...f.editableOn, state.docState])]\n            : f.editableOn.filter((s) => s !== state.docState && s !== '*');\n          updated = { ...updated, editableOn };\n        }\n        if (dynamicOptions[f.key]) {\n          updated = { ...updated, options: dynamicOptions[f.key] };\n        }\n        return updated;\n      });\n    return applyPermissions(withRules, userPermissions);\n  }, [template.fields, fieldRules, dynamicOptions, state.docState, userPermissions]);\n\n  // ── Resolved header sections (H1) ────────────────\n  // Filters by docState (visibleOn), field conditions (visibleWhen/hiddenWhen) and RBAC.\n  const resolvedHeaderSections = useMemo(() => {\n    return template.layout.header.sections.filter((s) => {\n      if (s.visibleOn && s.visibleOn.length > 0 && !s.visibleOn.includes('*')) {\n        if (!s.visibleOn.includes(state.docState)) return false;\n      }\n      if (s.visibleWhen && !evaluateCondition(s.visibleWhen, state.headerValues as Record<string, unknown>)) return false;\n      if (s.hiddenWhen && evaluateCondition(s.hiddenWhen, state.headerValues as Record<string, unknown>)) return false;\n      if (s.permissionVisibility && userPermissions !== null && !userPermissions.includes(s.permissionVisibility)) return false;\n      return true;\n    });\n  }, [template.layout.header.sections, state.docState, state.headerValues, userPermissions]);\n\n  // ── Resolved line columns (H2) ───────────────────\n  // Filters by field conditions (visibleWhen/hiddenWhen) and RBAC.\n  const resolvedLineColumns = useMemo(() => {\n    return template.layout.detail.columns.filter((c) => {\n      if (c.visibleWhen && !evaluateCondition(c.visibleWhen, state.headerValues as Record<string, unknown>)) return false;\n      if (c.hiddenWhen && evaluateCondition(c.hiddenWhen, state.headerValues as Record<string, unknown>)) return false;\n      if (c.permissionVisibility && userPermissions !== null && !userPermissions.includes(c.permissionVisibility)) return false;\n      return true;\n    });\n  }, [template.layout.detail.columns, state.headerValues, userPermissions]);\n\n  // ── Detail tabs (multi-listados de líneas) ───────────\n  //\n  // Traduce `template.layout.detail.tabs` (declarativo) a `LineTabConfig[]` (ya\n  // resuelto), que es lo único que ve el nivel presentacional. Aquí se aplica\n  // todo lo que `MasterDocument` no puede saber: permisos, condiciones sobre el\n  // encabezado, catálogo i18n, registro de iconos y registro de renderers.\n  //\n  // Ausente ⇒ `undefined`, no `[]`: es lo que le dice a `MasterDocument` que pinte\n  // la grilla directamente, sin barra ni panel.\n  const lineTabs = useMemo<LineTabConfig[] | undefined>(() => {\n    const declared = template.layout.detail.tabs;\n    if (!declared || declared.length === 0) return undefined;\n\n    const headerValues = state.headerValues as Record<string, unknown>;\n\n    const visible = declared.filter((tab) => {\n      const type = tab.type ?? 'lines';\n      // La pestaña de líneas no se filtra: es el único tipo con CRUD y el\n      // documento no puede quedarse sin sus líneas por una condición mal puesta.\n      if (type === 'lines') return true;\n      if (tab.visibleWhen && !evaluateCondition(tab.visibleWhen, headerValues)) return false;\n      if (tab.hiddenWhen && evaluateCondition(tab.hiddenWhen, headerValues)) return false;\n      if (\n        tab.permissionVisibility &&\n        userPermissions !== null &&\n        !userPermissions.includes(tab.permissionVisibility)\n      ) {\n        return false;\n      }\n      return true;\n    });\n\n    if (visible.length === 0) return undefined;\n\n    return visible.map((tab) => {\n      const type = tab.type ?? 'lines';\n      // `labelKey` gana solo si el catálogo la resuelve; si el motor devuelve la\n      // propia clave, se cae a `label` en vez de mostrar `master_document.…`.\n      const translated = tab.labelKey ? t(tab.labelKey) : undefined;\n      const label =\n        (translated && translated !== tab.labelKey ? translated : undefined) ??\n        tab.label ??\n        (type === 'lines' ? t('master_document.lines.tab') : tab.key);\n\n      const base: LineTabConfig = {\n        key: tab.key,\n        label,\n        icon: resolveIcon(tab.icon),\n        type,\n      };\n\n      if (type === 'lines') return base;\n\n      const renderKey = (tab as { renderKey: string }).renderKey;\n      const renderer = lineTabRenderers[renderKey];\n      if (!renderer) {\n        // Error de cableado del host: el template pide un renderer que nadie\n        // registró. Se avisa aquí, que es donde se conoce el registro; la pestaña\n        // queda con el estado vacío explícito de `LineTabsRegion`.\n        console.warn(\n          `[MasterDocument] la pestaña \"${tab.key}\" declara renderKey \"${renderKey}\" ` +\n            'y no está registrado en MasterDocumentProvider.lineTabRenderers',\n        );\n        return base;\n      }\n\n      const flexQuery = type === 'flexQuery' ? (tab as DetailTabFlexQuery).flexQuery : undefined;\n      const allowedActions =\n        type === 'flexQuery' ? (tab as DetailTabFlexQuery).rowActions : undefined;\n\n      // Filtros externos resueltos contra el documento, con la forma que espera\n      // la prop `externalFilters` de <FlexQuery>. Un filtro cuyo valor no existe\n      // NO viaja: un filtro `undefined` no es un filtro, y dejarlo pasar haría\n      // que la consulta trajera todo el universo en vez de las líneas de este\n      // documento. `isNull`/`isNotNull` son la excepción: no necesitan valor.\n      const externalFilters = flexQuery?.externalFilters\n        ?.map((filter): LineTabExternalFilter | null => {\n          const op = filter.op ?? 'eq';\n          if (op === 'isNull' || op === 'isNotNull') {\n            return { column: filter.column, op, value: null };\n          }\n          const value = filter.headerField\n            ? filter.headerField === '_documentId'\n              ? state.documentId\n              : headerValues[filter.headerField]\n            : filter.value;\n          if (value === undefined || value === null) return null;\n          return { column: filter.column, op, value };\n        })\n        .filter((filter): filter is LineTabExternalFilter => filter !== null);\n\n      const rowActions = (row: Record<string, unknown>): RowAction[] => {\n        if (allowedActions === false) return [];\n        const actions = getLineActions(row as DocumentLineData);\n        if (Array.isArray(allowedActions)) {\n          return actions.filter((action) => allowedActions.includes(action.key));\n        }\n        return actions;\n      };\n\n      return {\n        ...base,\n        // `helpers` los aporta `MasterDocument`, que es dueño del modal de línea:\n        // el contexto se completa en el momento del render, no aquí.\n        render: (helpers) =>\n          renderer({\n            openLineDetail: helpers.openLineDetail,\n            rowClick: tab.type === 'flexQuery' ? ((tab as DetailTabFlexQuery).rowClick ?? 'none') : undefined,\n            tabKey: tab.key,\n            // Documento nuevo aún sin guardar ⇒ cadena vacía, que es la\n            // convención del contrato (`DocumentState.documentId`).\n            documentId: state.documentId ?? '',\n            documentClass: state.documentClass ?? template.identity.documentClass,\n            docState: state.docState,\n            mode: state.mode,\n            headerValues: state.headerValues,\n            locale,\n            flexQuery: flexQuery\n              ? {\n                  reportCode: flexQuery.reportCode,\n                  contractBaseUrl: flexQuery.contractBaseUrl,\n                  labelNamespace: flexQuery.labelNamespace,\n                  view: flexQuery.view,\n                  params: flexQuery.params,\n                }\n              : undefined,\n            externalFilters,\n            columns: resolvedLineColumns,\n            rowActions,\n            refreshToken,\n            busy: state.saving,\n            formatCurrency: adapter.formatCurrency,\n            formatDate: adapter.formatDate?.bind(adapter),\n            formatNumber: adapter.formatNumber?.bind(adapter),\n          }),\n      };\n    });\n  }, [\n    template.layout.detail.tabs,\n    template.identity.documentClass,\n    state.headerValues,\n    state.documentId,\n    state.documentClass,\n    state.docState,\n    state.mode,\n    state.saving,\n    userPermissions,\n    lineTabRenderers,\n    resolvedLineColumns,\n    getLineActions,\n    refreshToken,\n    locale,\n    resolveIcon,\n    adapter,\n    t,\n  ]);\n\n  // ── canAddLine — encabezado lleno (§13.3.1) ─────────\n  // Bloquea agregar líneas hasta que todos los campos required del encabezado tengan valor.\n  // Además, si el template declara `layout.detail.addLineLockedWhen` y esa condición se cumple\n  // contra `headerValues`, el botón queda deshabilitado (p.ej. descuento global activo).\n  const canAddLine = useMemo(() => {\n    if (state.mode === 'view') return false;\n    const requiredFilled = headerFields\n      .filter((f) => f.required)\n      .every((f) => {\n        const val = state.headerValues[f.key];\n        return val !== null && val !== undefined && val !== '';\n      });\n    if (!requiredFilled) return false;\n    const addLineLockedWhen = template.layout.detail.addLineLockedWhen;\n    if (\n      addLineLockedWhen &&\n      evaluateCondition(addLineLockedWhen, state.headerValues as Record<string, unknown>)\n    ) {\n      return false;\n    }\n    return true;\n  }, [state.mode, headerFields, state.headerValues, template.layout.detail.addLineLockedWhen]);\n\n  // ── LookupField configs from template.searchers ──\n  const lookupConfigs = useMemo(() => {\n    const configs: Record<string, LookupFieldConfig> = {};\n    for (const [fieldKey, cfg] of Object.entries(template.searchers ?? {})) {\n      configs[fieldKey] = {\n        entity: cfg.entity,\n        displayFields: cfg.displayFields,\n        searchFields: cfg.searchFields,\n        displayTemplate: cfg.displayTemplate,\n        valueField: cfg.valueField,\n        pageSize: cfg.pageSize,\n        filters: cfg.filters,\n        bindFields: cfg.bindFields,\n        filterDependencies: cfg.filterDependencies,\n      };\n    }\n    return configs;\n  }, [template.searchers]);\n\n  // ── Handle LookupField record selection (bindFields) ──\n  const handleRecordSelect = useCallback(\n    (fieldKey: string, record: Record<string, unknown> | null) => {\n      if (!record) return;\n      const searcherCfg = template.searchers?.[fieldKey];\n      if (!searcherCfg?.bindFields) return;\n      // Apply bindFields: { \"item_name\": \"nombre\" } → set headerValues.item_name = record.nombre\n      for (const [targetField, sourceField] of Object.entries(searcherCfg.bindFields)) {\n        const value = record[sourceField];\n        if (value !== undefined) {\n          handleHeaderFieldChange(targetField, value);\n        }\n      }\n    },\n    [template.searchers, handleHeaderFieldChange],\n  );\n\n  // ── Server rules callback ────────────────────────\n  const handleEvaluateServerRule = useCallback(\n    (ruleId: string, formData: Record<string, unknown>) => {\n      if (!adapter.evaluateServerRule) return Promise.resolve({});\n      return adapter.evaluateServerRule(ruleId, formData, state.documentId);\n    },\n    [adapter, state.documentId],\n  );\n\n  // ── Widget slot (G4) ─────────────────────────────\n  // Tracks the current form values from the line modal; fed by onLineFormValuesChange.\n  const [lineFormValues, setLineFormValues] = useState<Record<string, unknown>>({});\n\n  const lineWidgetSlot = useMemo<ReactNode>(() => {\n    const widgets = template.layout.detail.lineModal?.widgets;\n    if (!widgets || widgets.length === 0 || !adapter.getLineWidgetData) return undefined;\n\n    // Filter widgets by visibleWhen/hiddenWhen conditions evaluated against current form values\n    const visibleWidgets = widgets.filter((w: LineModalWidgetConfig) => {\n      if (w.visibleWhen && !evaluateCondition(w.visibleWhen as FieldCondition, lineFormValues)) return false;\n      if (w.hiddenWhen && evaluateCondition(w.hiddenWhen as FieldCondition, lineFormValues)) return false;\n      return true;\n    });\n\n    if (visibleWidgets.length === 0) return undefined;\n\n    return (\n      <div className=\"flex flex-col h-full divide-y divide-border-secondary dark:divide-dark-border-primary\">\n        {visibleWidgets.map((w: LineModalWidgetConfig) => (\n          <LineWidgetPanel\n            key={w.widgetKey}\n            config={w}\n            formValues={lineFormValues}\n            documentId={state.documentId}\n            adapter={adapter}\n          />\n        ))}\n      </div>\n    );\n  }, [template.layout.detail.lineModal?.widgets, adapter, lineFormValues, state.documentId]);\n\n  // ── Navegación a otro documento existente ─────────\n  // Se delega en el host si pasó el callback; si no, se emite el pseudo-key histórico\n  // `navigate_document:<id>`, que MasterDocumentPage intercepta en su adapter. Los dos\n  // orígenes (trazabilidad y generación por cruce) entran por aquí para que el host\n  // resuelva el destino en un solo lugar.\n  const navigateToDocument = useCallback(\n    (targetDocumentId: string, reason: DocumentNavigationReason) => {\n      if (onNavigateToDocument) {\n        onNavigateToDocument(targetDocumentId, { reason });\n        return;\n      }\n      void handleAction(`navigate_document:${targetDocumentId}`);\n    },\n    [onNavigateToDocument, handleAction],\n  );\n\n  // ── Crossing ──────────────────────────────────────\n  const baseUrl = (adapter as { baseUrl?: string }).baseUrl ?? 'http://localhost:5204';\n  const crossingFetch = useMemo(() => createCrossingFetch(adapter, baseUrl), [adapter, baseUrl]);\n\n  const crossing = useCrossing({\n    config: template.crossing,\n    documentId: state.documentId,\n    docState: state.docState,\n    hasLines: state.lines.length > 0,\n    crossingFetch,\n    onDocumentGenerated: (docId) => navigateToDocument(docId, 'generated'),\n  });\n\n  const crossingProps = useMemo(() => {\n    if (!crossing || !template.crossing) return undefined;\n    const { state: cs, actions: ca } = crossing;\n    return {\n      sourceSelector: {\n        selectedDocuments: cs.selectedSourceDocuments,\n        onAdd: ca.addSourceDocument,\n        onRemove: ca.removeSourceDocument,\n        locked: cs.sourceSelectorLocked,\n        searchDocuments: ca.searchSourceDocuments,\n      },\n      selectionMode: template.crossing.generateOn.includes(state.docState),\n      selectedLineIds: cs.selectedLineIds,\n      onLineSelect: ca.toggleLineSelection,\n      onTrySelectTerminalLine: ca.trySelectTerminalLine,\n      lineStatuses: cs.lineStatuses,\n      lineSelectionErrors: cs.lineSelectionErrors,\n      pendingLines: cs.pendingLines,\n      quantitiesToCross: cs.quantitiesToCross,\n      onQuantityChange: ca.setQuantityToCross,\n      formatNumber: adapter.formatNumber,\n      pendingLinesFetchedAt: cs.pendingLinesFetchedAt,\n      pendingLinesLoading: cs.pendingLinesLoading,\n      onRefreshPendingLines: ca.refreshPendingLines,\n      activeTab: cs.activeTab,\n      onTabChange: ca.setActiveTab,\n      traceabilityLabel: template.crossing.traceability?.label ?? t('master_document.document.traceability'),\n      traceabilityTree: cs.traceabilityTree,\n      traceabilityLoading: cs.traceabilityLoading,\n      traceabilityError: cs.traceabilityError,\n      onRetryTraceability: ca.refreshTraceability,\n      onTraceabilityNodeClick: (nodeId: string) => navigateToDocument(nodeId, 'traceability'),\n      classMenuOptions: cs.crossingClassOptions,\n      // selectClass cierra el menú y abre el modal de header con la clase elegida.\n      onSelectClass: ca.selectClass,\n      canGenerate: cs.canGenerate,\n      lineCloseModal: cs.lineCloseModal,\n      onOpenLineCloseModal: ca.openLineCloseModal,\n      onCloseLineCloseModal: ca.closeLineCloseModal,\n      onConfirmLineClose: ca.confirmLineClose,\n      lineActions: template.crossing?.lineActions,\n      generateModal: cs.generateModal,\n      onOpenGenerateModal: ca.openGenerateModal,\n      onCancelGenerateModal: ca.cancelGenerateModal,\n      onConfirmGenerate: ca.confirmGenerate,\n      generateError: cs.generateError,\n      onClearGenerateError: ca.clearGenerateError,\n      generateHeaderFields: template.crossing?.generateHeaderFields ?? [],\n      pageErrors: cs.pageErrors,\n      onDismissPageError: ca.dismissPageError,\n    };\n  }, [crossing, template.crossing, state.docState, state.lines.length, navigateToDocument, t]);\n\n  // ── Render ────────────────────────────────────────\n  return (\n    <MasterDocumentRefreshProvider value={refreshApi}>\n      <MasterDocument\n        documentId={state.documentId}\n        documentNumber={(state.headerValues['_documentNumber'] as string) ?? undefined}\n        docTypeBadge={template.identity.label}\n        breadcrumbLabel={template.identity.breadcrumbLabel}\n        documentTitle={template.identity.label}\n        companyName={companyName}\n        onBreadcrumbClick={() => handleAction('navigate_back')}\n        docState={state.docState}\n        stateBadge={resolvedStateBadge}\n        mode={state.mode}\n        transitions={transitions}\n        onTransition={runTransition}\n        actions={actionsWithAudit}\n        contextItems={contextItems}\n        currencyPanel={currencyPanel}\n        headerLayout={{ ...template.layout.header, sections: resolvedHeaderSections }}\n        headerFields={headerFields}\n        headerValues={state.headerValues}\n        headerErrors={state.headerErrors}\n        onHeaderFieldChange={handleHeaderFieldChange}\n        dynamicEntitiesSlot={\n          dynamicEntities.header ? (\n            <DocumentDynamicEntities\n              grain={dynamicEntities.header}\n              // Vacío en creación: el bloque se captura igual y los valores se\n              // persisten cuando el POST del documento devuelve su id.\n              recordId={state.documentId || undefined}\n              defaultTitleKey=\"master_document.dynamicEntities.headerTitle\"\n              readOnly={state.mode === 'view'}\n            />\n          ) : undefined\n        }\n        lineDynamicEntitiesSlot={\n          dynamicEntities.line\n            ? ({ lineId }) => (\n                <DocumentDynamicEntities\n                  // Remontar al cambiar de línea es intencional: los valores de\n                  // una entidad viven dentro de su formulario, y reutilizar la\n                  // instancia arrastraría lo capturado en la línea anterior.\n                  key={lineId ?? '__new__'}\n                  grain={dynamicEntities.line!}\n                  recordId={lineId ?? undefined}\n                  defaultTitleKey=\"master_document.dynamicEntities.lineTitle\"\n                  readOnly={state.mode === 'view'}\n                  // Dentro del modal de línea el marco ya lo pone el modal: una\n                  // tarjeta aquí sería una caja dentro de otra caja.\n                  variant=\"bare\"\n                />\n              )\n            : undefined\n        }\n        lookupConfigs={lookupConfigs}\n        fetcher={adapter.fetcher}\n        onRecordSelect={handleRecordSelect}\n        linesTitle={template.layout.detail.title}\n        lines={state.lines}\n        lineColumns={resolvedLineColumns}\n        lineFields={lineFields}\n        lineComputedRules={lineComputedRules}\n        lineServerRules={template.serverRules}\n        onEvaluateServerRule={adapter.evaluateServerRule ? handleEvaluateServerRule : undefined}\n        lineModalSections={template.layout.detail.lineModal?.sections}\n        serialSupport={template.layout.detail.serialSupport}\n        serialReadOnly={\n          state.mode === 'view' ||\n          (template.layout.detail.serialSupport\n            ? state.docState !== template.stateMachine.initial\n            : undefined)\n        }\n        validateSerial={adapter.validateSerial?.bind(adapter)}\n        fetchAvailableSerials={adapter.fetchAvailableSerials?.bind(adapter)}\n        lineWidgetSlot={lineWidgetSlot}\n        onLineFormValuesChange={adapter.getLineWidgetData ? setLineFormValues : undefined}\n        canAddLine={canAddLine && operacionDeLineaPermitida(\n          undefined,\n          template.layout.detail.lineModal?.addableOn,\n          state.docState,\n        )}\n        onAddLine={() => {}}\n        onEditLine={() => {}}\n        onDeleteLine={runDeleteLine}\n        onDuplicateLine={state.mode !== 'view' ? runDuplicateLine : undefined}\n        getLineActions={template.lineActionRegistry ? getLineActions : undefined}\n        lineTabs={lineTabs}\n        // Se derivan del template y de SU PROPIO `docState`, no se piden al host:\n        // `SmartMasterDocumentProps` no expone callbacks ni estado de línea, así que\n        // sin esta derivación una página que monta este componente no tendría forma\n        // de declarar nada. `operacionDeLineaPermitida` cruza el booleano con la\n        // lista de estados; ausentes ambos, el comportamiento no cambia.\n        lineEditable={operacionDeLineaPermitida(\n          template.layout.detail.lineModal?.editable,\n          template.layout.detail.lineModal?.editableOn,\n          state.docState,\n        )}\n        lineDeletable={operacionDeLineaPermitida(\n          template.layout.detail.lineModal?.deletable,\n          template.layout.detail.lineModal?.deletableOn,\n          state.docState,\n        )}\n        onLineSave={runLineSave}\n        factBoxSections={factBoxSections}\n        conflict={conflictProp}\n        forbidden={forbiddenProp}\n        crossing={crossingProps}\n        loading={state.loading}\n        error={state.error}\n        busy={state.saving}\n        busyLineId={busyLineId}\n      />\n\n      <CurrencySelectorModal\n        open={currencyModalOpen}\n        currentCode={currencyCode}\n        currencies={availableCurrencies}\n        loading={currenciesLoading}\n        onSelect={handleCurrencySelect}\n        onClose={() => setCurrencyModalOpen(false)}\n      />\n\n      {activeModalListConfig && adapter.genericFetch && (\n        <DocumentModalList\n          open={modalListOpen}\n          onClose={() => setModalListOpen(false)}\n          config={activeModalListConfig}\n          documentId={state.documentId}\n          lineId={modalListLineId}\n          fetcher={adapter.genericFetch.bind(adapter)}\n          formatCurrency={adapter.formatCurrency}\n          formatDate={adapter.formatDate}\n        />\n      )}\n\n      {template.createFromSource && (\n        <CreateFromSourceModal\n          open={createFromSourceOpen}\n          mode=\"append\"\n          config={template.createFromSource}\n          adapter={adapter}\n          documentId={state.documentId}\n          operationCenterId={String(state.headerValues['operationCenterId'] ?? state.headerValues['operation_center_id'] ?? '') || undefined}\n          lockedThirdPartyId={\n            template.createFromSource.thirdPartyHeaderField\n              ? String(state.headerValues[template.createFromSource.thirdPartyHeaderField] ?? '') || undefined\n              : undefined\n          }\n          userPermissions={userPermissions}\n          formatCurrency={adapter.formatCurrency}\n          formatNumber={adapter.formatNumber}\n          onClose={() => setCreateFromSourceOpen(false)}\n          onAppended={() => {\n            setCreateFromSourceOpen(false);\n            void refetchDocument();\n          }}\n        />\n      )}\n\n      {activeLineAction && activeLineAction.entry.formModal && (\n        <LineActionFormModal\n          open\n          onClose={() => {\n            if (lineActionBusy) return;\n            setActiveLineAction(null);\n            setLineActionLineId('');\n            setLineActionError(undefined);\n          }}\n          title={activeLineAction.entry.formModal.title}\n          submitLabel={activeLineAction.entry.formModal.submitLabel}\n          fields={activeLineAction.entry.formModal.fields}\n          busy={lineActionBusy}\n          error={lineActionError}\n          onSubmit={(formData) => handleLineAction(activeLineAction.key, lineActionLineId, formData, activeLineAction.entry)}\n        />\n      )}\n\n      {pendingDeleteLineId !== null && (\n        <ConfirmDialog\n          message={t('master_document.lines.deleteConfirm')}\n          onConfirm={confirmDeleteLine}\n          onCancel={() => setPendingDeleteLineId(null)}\n        />\n      )}\n    </MasterDocumentRefreshProvider>\n  );\n}\n","import { useState, useEffect, useRef, useCallback, useLayoutEffect, useMemo, type CSSProperties } from 'react';\nimport { createPortal } from 'react-dom';\nimport { clsx } from 'clsx';\nimport { Table } from '../Table';\nimport type { TableColumn } from '../Table';\nimport { Button } from '../Button';\nimport { MagnifyingGlassIcon, ArrowUpTrayIcon, PlusIcon, EllipsisVerticalIcon, PencilIcon, EyeIcon, TrashIcon, NoSymbolIcon, GlobeAltIcon, BuildingOffice2Icon, ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline';\nimport type { DocumentListProps, DocumentListColumn, DocumentListCompany, LookupFieldConfig, RowAction } from './MasterDocument.types';\nimport { Loading } from './components/loading';\nimport { CrossingClassMenu } from './CrossingClassMenu';\nimport { ConfirmDialog } from './DocumentModalList';\nimport { SearcherControl } from './FieldRenderer';\nimport { buildDependentLookupProps, isFilterValueEmpty } from './lookupFilters';\nimport { PrintIcon } from './icons';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { MoreOptionsMenu } from './MoreOptionsMenu';\nimport { ROW_ACTION_BTN, ajustarTamanoIcono } from './rowActionStyles';\nimport { accionDeEstadoAlCanon, clasesDeTonoBoton, ACTIVAR_FG, type AccionTono } from './stateActionCanon';\n\n// Íconos por defecto para acciones de fila sin ícono explícito.\nconst DEFAULT_ROW_ACTION_ICONS: Record<string, typeof TrashIcon> = {\n  delete: TrashIcon,\n  cancel: NoSymbolIcon,\n};\n\n// ─── Acciones por fila (canon MasterCrud) ──────────────────\n\n/** Acción de fila ya normalizada: da igual de qué prop venga. */\ninterface AccionDeFila {\n  key: string;\n  label: string;\n  icon: React.ReactNode;\n  danger?: boolean;\n  /** Tono del canon. Manda sobre `danger`, que se conserva por retrocompatibilidad. */\n  tone?: AccionTono;\n  /**\n   * Destino de la acción cuando ES una navegación (ver/editar). Presente ⇒ se\n   * pinta como `<a href>`; ausente ⇒ `<button>`, como todas las demás.\n   * Ver `DocumentListProps.getRowHref` para el por qué.\n   */\n  href?: string;\n  onClick: () => void;\n}\n\n/**\n * ¿Este clic lo tiene que atender el NAVEGADOR en vez de la SPA?\n *\n * Sí cuando el usuario pidió explícitamente otra ventana o pestaña: Ctrl (⌘ en\n * Mac), Shift, Alt, o un botón que no es el primario. En esos casos la acción por\n * defecto del `<a href>` es justo lo que se quiere, así que NO se cancela y NO se\n * corre el `onClick` de la SPA — cancelarlo es el error clásico que deja Ctrl+clic\n * comportándose como un clic normal.\n *\n * El clic con la RUEDA no llega hasta aquí: los navegadores lo despachan como\n * `auxclick`, no como `click`, así que sin handler de por medio el ancla abre la\n * pestaña nueva por su cuenta. Para ese gesto no hay nada que programar — lo\n * único que hay que hacer es no estorbarlo.\n */\nfunction elNavegadorSeEncarga(e: React.MouseEvent): boolean {\n  return e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.button !== 0;\n}\n\n// ─── Geometría de los overlays anclados a un trigger (ADR-027 §P) ──────────\n// Compartidas por el menú «Más acciones» de la fila y por el `CompanyDropdown`\n// del pie de este mismo archivo: los dos se anclan igual y deben comportarse igual.\n\n/** Aire entre el borde del overlay y el del viewport. Mismos valores que el\n *  `CompanySelector` de MasterCrud, para que los dos combos se comporten igual. */\nconst MARGEN_VIEWPORT = 8;\n/** Separación del overlay al trigger. */\nconst SEPARACION_TRIGGER = 4;\n/** Altura mínima que se le deja al menú de fila aunque el hueco sea menor (≈2 opciones).\n *  Sólo entra en juego cuando NINGUNO de los dos lados da más: sin este suelo, un trigger\n *  pegado al borde dejaría el menú sin alto útil. */\nconst ALTO_MINIMO_MENU_FILA = 96;\n\n/**\n * Celda de acciones de una fila del listado, con la MISMA regla de reparto que\n * MasterCrud (`MasterCrudTable.tsx`, `MAX_DIRECT = 3`):\n *\n * - hasta 3 acciones visibles ⇒ las 3 se pintan de frente, sin kebab;\n * - 4 o más ⇒ 2 directas + el botón «Más acciones», que completa 3; el resto va\n *   dentro del desplegable.\n *\n * Prioriza «Ver» y «Editar» como directas —el equivalente aquí del `edit`/`link`\n * de MasterCrud—; si no existen, toma las dos primeras.\n *\n * El desplegable se pinta en un PORTAL a `document.body` con `position: fixed`.\n * Antes era un `absolute` dentro de la celda sticky, y con pocas filas el menú\n * quedaba recortado por el `overflow` del contenedor de la tabla: se abría por\n * debajo del pie y no había forma de verlo ni de pulsarlo (ADR-027 §P.2 — el\n * defecto no son los píxeles de desborde, son las opciones inalcanzables).\n * Se reposiciona al abrir y se cierra en `scroll` (en captura, porque el scroll\n * de un contenedor intermedio no burbujea) y en `resize`.\n *\n * El alto va acotado al hueco disponible contra el trigger (§P.1) y el menú scrollea\n * por dentro: cuando ni arriba ni abajo cabe entero, las opciones siguen siendo\n * alcanzables en vez de quedar fuera de pantalla sin scroll que las alcance (§P.2).\n */\nfunction RowActionsCell({\n  acciones,\n  busy = false,\n}: {\n  acciones: AccionDeFila[];\n  busy?: boolean;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const [open, setOpen] = useState(false);\n  const btnRef = useRef<HTMLButtonElement>(null);\n  const menuRef = useRef<HTMLDivElement>(null);\n  const [pos, setPos] = useState<{ top: number; left: number; altoMaximo: number; haciaArriba: boolean }>(\n    { top: -9999, left: -9999, altoMaximo: ALTO_MINIMO_MENU_FILA, haciaArriba: false },\n  );\n\n  const reposition = useCallback(() => {\n    const btn = btnRef.current;\n    if (!btn) return;\n    const r = btn.getBoundingClientRect();\n    const mw = menuRef.current?.offsetWidth || 210;\n    const mh = menuRef.current?.offsetHeight || 0;\n    const espacioDebajo = window.innerHeight - r.bottom - SEPARACION_TRIGGER - MARGEN_VIEWPORT;\n    const espacioEncima = r.top - SEPARACION_TRIGGER - MARGEN_VIEWPORT;\n    // Si abajo no cabe, se abre hacia arriba. Es justo el caso de «2 registros»:\n    // el menú medía más que el hueco entre la fila y el pie de la tabla.\n    // El criterio es EL MISMO de antes: `mh > espacioDebajo` es la forma despejada de\n    // `top + mh > window.innerHeight - 8` con `top = r.bottom + 4`. Esto no cambia hacia\n    // qué lado abre el menú; sólo le pone techo al lado que elija.\n    const haciaArriba = mh > 0 && mh > espacioDebajo;\n    // Techo acotado al hueco, medido contra el trigger igual que hace `CompanyDropdown`\n    // en este mismo archivo (ADR-027 §P.1). Sin él el menú declaraba `max-height: none` y\n    // `overflow-y: visible`, así que cuando no cabía entero en el lado elegido sus últimas\n    // opciones quedaban FÍSICAMENTE inalcanzables: ni el menú ni el documento ofrecían\n    // scroll (§P.2 — el defecto no son los píxeles de desborde, son las opciones que no se\n    // pueden pulsar). Con el techo, ese caso degrada a un menú con scroll propio.\n    const altoMaximo = Math.round(Math.max(haciaArriba ? espacioEncima : espacioDebajo, ALTO_MINIMO_MENU_FILA));\n    const top = haciaArriba ? Math.round(r.top - SEPARACION_TRIGGER) : Math.round(r.bottom + SEPARACION_TRIGGER);\n    const left = Math.round(Math.max(MARGEN_VIEWPORT, r.right - mw));\n    setPos({ top, left, altoMaximo, haciaArriba });\n  }, []);\n\n  useLayoutEffect(() => {\n    if (open) reposition();\n  }, [open, reposition]);\n\n  // El menú se cierra solo al disparar una acción, así que un indicador DENTRO\n  // del desplegable no se vería nunca: va en el disparador de la fila.\n  useEffect(() => {\n    if (busy) setOpen(false);\n  }, [busy]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onDocClick = (e: MouseEvent) => {\n      if (menuRef.current?.contains(e.target as Node) || btnRef.current?.contains(e.target as Node)) return;\n      setOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };\n    const onScroll = () => setOpen(false);\n    document.addEventListener('click', onDocClick);\n    document.addEventListener('keydown', onKey);\n    window.addEventListener('resize', onScroll);\n    document.addEventListener('scroll', onScroll, true);\n    return () => {\n      document.removeEventListener('click', onDocClick);\n      document.removeEventListener('keydown', onKey);\n      window.removeEventListener('resize', onScroll);\n      document.removeEventListener('scroll', onScroll, true);\n    };\n  }, [open]);\n\n  // Fila en vuelo: el indicador sustituye a las acciones, dentro de un botón\n  // DESHABILITADO y no de un `div` suelto. Dos razones: sin el botón el usuario\n  // vuelve a disparar «anular» sobre el mismo documento (la mitad no visual del\n  // problema), y el botón conserva la caja de 28px, que es la que sostiene los\n  // 45px de alto de fila del canon — un spinner desnudo encogería esa fila y\n  // sólo esa.\n  if (busy) {\n    return (\n      <div className=\"flex items-center justify-center\">\n        <button type=\"button\" disabled className={ROW_ACTION_BTN}>\n          <Loading size=\"sm\" layout=\"inline\" ariaLabel={t('master_document.chrome.actionRunning')} />\n        </button>\n      </div>\n    );\n  }\n\n  if (acciones.length === 0) return null;\n\n  // Reparto del canon: se decide ANTES de pintar para no «gastar» un hueco.\n  const MAX_DIRECT = 3;\n  let directas: AccionDeFila[];\n  let enMenu: AccionDeFila[];\n  if (acciones.length <= MAX_DIRECT) {\n    directas = acciones;\n    enMenu = [];\n  } else {\n    const prioritarias = acciones.filter((a) => ['view', 'edit'].includes(a.key)).slice(0, 2);\n    const relleno = prioritarias.length < 2\n      ? acciones.filter((a) => !prioritarias.includes(a)).slice(0, 2 - prioritarias.length)\n      : [];\n    directas = [...prioritarias, ...relleno];\n    enMenu = acciones.filter((a) => !directas.includes(a));\n  }\n\n  return (\n    <div className=\"flex items-center justify-center gap-3\" onClick={(e) => e.stopPropagation()}>\n      {directas.map((a) => {\n        const contenido = (\n          <span className=\"w-[15px] h-[15px] inline-flex items-center justify-center\">\n            {ajustarTamanoIcono(a.icon)}\n          </span>\n        );\n        // MISMAS clases y MISMA caja (28x28 de `ROW_ACTION_BTN`) en las dos ramas:\n        // el ancla no debe verse distinta del botón, sólo comportarse como enlace.\n        // `no-underline` porque el reset de la app puede subrayar los `<a>`, y el\n        // botón hermano no va subrayado.\n        const clases = clsx(ROW_ACTION_BTN, clasesDeTonoBoton(a.tone), a.href && 'no-underline');\n        const estilo = a.tone === 'success' ? { color: ACTIVAR_FG } : undefined;\n\n        // Acción de NAVEGACIÓN con destino conocido ⇒ ancla real. Le da al usuario\n        // Ctrl/⌘+clic, clic con la rueda y «Abrir en pestaña nueva» del menú\n        // contextual sin que el kit programe ninguno de los tres.\n        if (a.href) {\n          return (\n            <a\n              key={a.key}\n              href={a.href}\n              title={a.label}\n              aria-label={a.label}\n              onClick={(e) => {\n                // Gesto de «otra pestaña»: se deja pasar tal cual. Ni\n                // `preventDefault` ni `onClick` de la SPA — sólo se corta la\n                // propagación para que el `onRowClick` de la fila no se dispare\n                // además de la navegación.\n                if (elNavegadorSeEncarga(e)) { e.stopPropagation(); return; }\n                e.preventDefault();\n                e.stopPropagation();\n                a.onClick();\n              }}\n              className={clases}\n              style={estilo}\n            >\n              {contenido}\n            </a>\n          );\n        }\n\n        return (\n          <button\n            key={a.key}\n            type=\"button\"\n            title={a.label}\n            aria-label={a.label}\n            onClick={(e) => { e.stopPropagation(); a.onClick(); }}\n            className={clases}\n            style={estilo}\n          >\n            {contenido}\n          </button>\n        );\n      })}\n\n      {enMenu.length > 0 && (\n        <>\n          <button\n            ref={btnRef}\n            type=\"button\"\n            title={t('master_document.list.moreActions')}\n            aria-label={t('master_document.list.moreActions')}\n            aria-haspopup=\"menu\"\n            aria-expanded={open}\n            onClick={(e) => { e.stopPropagation(); setOpen((v) => !v); }}\n            className={ROW_ACTION_BTN}\n          >\n            <EllipsisVerticalIcon className=\"w-[15px] h-[15px]\" />\n          </button>\n          {open && createPortal(\n            <div\n              ref={menuRef}\n              role=\"menu\"\n              style={{\n                position: 'fixed',\n                left: pos.left,\n                // Al abrir hacia arriba se ancla por ABAJO, para que crezca alejándose del\n                // trigger. Anclado por `top` un menú más alto que el hueco de encima se\n                // colocaba en negativo y quedaba recortado por la cabecera: el mismo defecto\n                // de §P.2, sólo que por el otro borde.\n                ...(pos.haciaArriba\n                  ? { bottom: Math.max(0, window.innerHeight - pos.top) }\n                  : { top: pos.top }),\n                maxHeight: pos.altoMaximo,\n                overflowY: 'auto',\n                // Evita que, al llegar al final de la lista, la rueda arrastre la página\n                // que hay detrás (§P.3).\n                overscrollBehavior: 'contain',\n              }}\n              className=\"z-[60] min-w-[210px] bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-md shadow-md py-1\"\n            >\n              {enMenu.map((a) => (\n                <button\n                  key={a.key}\n                  type=\"button\"\n                  role=\"menuitem\"\n                  onClick={(e) => { e.stopPropagation(); setOpen(false); a.onClick(); }}\n                  className={clsx(\n                    'w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors disabled:opacity-40',\n                    a.tone === 'danger' || a.danger\n                      ? 'text-error-content hover:bg-error-bg/10'\n                      : 'text-content-primary hover:bg-background-secondary dark:text-dark-content-primary dark:hover:bg-dark-bg-secondary',\n                  )}\n                  style={a.tone === 'success' ? { color: ACTIVAR_FG } : undefined}\n                >\n                  <span className=\"w-4 h-4 flex-shrink-0 inline-flex items-center justify-center\">{a.icon}</span>\n                  <span>{a.label}</span>\n                </button>\n              ))}\n            </div>,\n            document.body,\n          )}\n        </>\n      )}\n    </div>\n  );\n}\n\n\n/**\n * Control del panel de búsqueda avanzada, literal del canon\n * (`MasterCrudAdvancedSearch`): 14px, `rounded-md`, y el foco con borde\n * `#93d1fd` más el anillo tenue de la marca en vez del `primary-600` plano.\n */\nconst ADV_CONTROL_CLS =\n  'w-full px-3 py-2 text-sm border border-border-primary dark:border-dark-border-primary rounded-md ' +\n  'bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary ' +\n  'focus:outline-none focus:border-[#93d1fd] focus:ring-[3px] focus:ring-primary-500/10 transition-colors';\n\n// ─── Company Dropdown ──────────────────────────────────────\n\n/** Altura mínima que se considera usable para desplegar hacia abajo (≈5 opciones). */\nconst ALTO_MINIMO_UTIL = 180;\n\nfunction CompanyDropdown({\n  companies,\n  selectedCompany,\n  onCompanyChange,\n}: {\n  companies: DocumentListCompany[];\n  selectedCompany?: DocumentListCompany;\n  onCompanyChange?: (company: DocumentListCompany) => void;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const [open, setOpen] = useState(false);\n  const [menuPos, setMenuPos] = useState<{ top: number; left: number; altoMaximo: number; haciaArriba: boolean }>({ top: 0, left: 0, altoMaximo: ALTO_MINIMO_UTIL, haciaArriba: false });\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const menuRef = useRef<HTMLDivElement>(null);\n\n  // Alto máximo acotado al viewport, medido contra el trigger (ADR-027 §P.1).\n  // Sin esto la lista crece tanto como compañías haya y, como el menú declaraba\n  // `max-height: none`, las últimas quedaban FÍSICAMENTE inalcanzables: ni el menú ni el\n  // documento ofrecían scroll (§P.2). Se mide en cada apertura, y en `resize` y `scroll`,\n  // porque la altura disponible depende de dónde esté el trigger — en el listado va bajo\n  // la cabecera y en el detalle mucho más abajo, así que un `vh` fijo acertaría en un caso\n  // y fallaría en el otro.\n  const updatePos = useCallback(() => {\n    if (!triggerRef.current) return;\n    const rect = triggerRef.current.getBoundingClientRect();\n    const espacioDebajo = window.innerHeight - rect.bottom - SEPARACION_TRIGGER - MARGEN_VIEWPORT;\n    const espacioEncima = rect.top - SEPARACION_TRIGGER - MARGEN_VIEWPORT;\n    // Sólo se voltea si abajo no cabe lo mínimo Y arriba hay más sitio: abrir hacia arriba\n    // cuando abajo alcanza sería mover el menú sin motivo.\n    const haciaArriba = espacioDebajo < ALTO_MINIMO_UTIL && espacioEncima > espacioDebajo;\n    // Se redondea porque es un píxel de CSS: un rect fraccionario (zoom, transform de un\n    // ancestro) daría un valor distinto en cada evento, y esto cuelga de `scroll` en captura,\n    // que dispara por frame. Y sólo se re-renderiza si el resultado CAMBIA (§P.4).\n    const altoMaximo = Math.round(Math.max(haciaArriba ? espacioEncima : espacioDebajo, ALTO_MINIMO_UTIL));\n    const top = haciaArriba ? Math.round(rect.top - SEPARACION_TRIGGER) : Math.round(rect.bottom + SEPARACION_TRIGGER);\n    const left = Math.round(rect.left);\n    setMenuPos((prev) =>\n      prev.top === top && prev.left === left && prev.altoMaximo === altoMaximo && prev.haciaArriba === haciaArriba\n        ? prev\n        : { top, left, altoMaximo, haciaArriba });\n  }, []);\n\n  const handleToggle = () => {\n    if (!open) updatePos();\n    setOpen((o) => !o);\n  };\n\n  useEffect(() => {\n    if (!open) return;\n    function onMouseDown(e: MouseEvent) {\n      if (\n        triggerRef.current?.contains(e.target as Node) ||\n        menuRef.current?.contains(e.target as Node)\n      ) return;\n      setOpen(false);\n    }\n    function onScroll() { updatePos(); }\n    function onKey(e: KeyboardEvent) { if (e.key === 'Escape') setOpen(false); }\n    document.addEventListener('mousedown', onMouseDown);\n    document.addEventListener('keydown', onKey);\n    window.addEventListener('scroll', onScroll, true);\n    window.addEventListener('resize', updatePos);\n    return () => {\n      document.removeEventListener('mousedown', onMouseDown);\n      document.removeEventListener('keydown', onKey);\n      window.removeEventListener('scroll', onScroll, true);\n      window.removeEventListener('resize', updatePos);\n    };\n  }, [open, updatePos]);\n\n  const isGlobal = !selectedCompany || String(selectedCompany.uuid) === '000';\n  const Icon = isGlobal ? GlobeAltIcon : BuildingOffice2Icon;\n\n  return (\n    <div className=\"relative inline-block\">\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        onClick={handleToggle}\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        // Trigger del canon (`CompanySelector` de MasterCrud, medido en /app/items el\n        // 2026-09-04): 28px de alto, radio 6px, padding 6/12, fondo #eff8ff, borde #93d1fd\n        // y texto #1355b7. Antes era una píldora de 26px con el azul de Google\n        // (#E8F0FE/#1A73E8/#1557B0), que no es el azul de marca del producto.\n        className={clsx(\n          'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold leading-none select-none transition-colors',\n          'bg-[#eff8ff] border border-[#93d1fd] text-[#1355b7] cursor-pointer',\n          'hover:bg-[#dbeefe] hover:border-[#3c9bf6]',\n          'dark:bg-primary-900/20 dark:text-primary-300 dark:border-primary-800 dark:hover:bg-primary-900/40',\n        )}\n      >\n        <Icon className=\"w-3.5 h-3.5 shrink-0\" aria-hidden=\"true\" />\n        <span className=\"max-w-[180px] truncate\" title={selectedCompany?.name}>\n          {selectedCompany?.name ?? t('master_document.list.selectCompany')}\n        </span>\n        <ChevronDownIcon className={clsx('w-3 h-3 shrink-0 transition-transform', open && 'rotate-180')} aria-hidden=\"true\" />\n      </button>\n\n      {open && (\n        <div\n          ref={menuRef}\n          role=\"menu\"\n          style={{\n            position: 'fixed',\n            left: menuPos.left,\n            // Al abrir hacia arriba se ancla por abajo, para que crezca alejándose del trigger.\n            ...(menuPos.haciaArriba\n              ? { bottom: Math.max(0, window.innerHeight - menuPos.top) }\n              : { top: menuPos.top }),\n            maxHeight: menuPos.altoMaximo,\n            overflowY: 'auto',\n            // Evita que, al llegar al final de la lista, la rueda arrastre la página detrás (§P.3).\n            overscrollBehavior: 'contain',\n          }}\n          className={clsx(\n            'z-[9999] min-w-[280px] max-w-[380px]',\n            'rounded-lg border border-border-primary shadow-md py-1',\n            'bg-white dark:bg-dark-bg-primary dark:border-dark-border-primary',\n          )}\n        >\n          {companies.map((company, idx) => {\n            const optIsGlobal = String(company.uuid) === '000';\n            const OptIcon = optIsGlobal ? GlobeAltIcon : BuildingOffice2Icon;\n            const active = selectedCompany?.uuid === company.uuid || (isGlobal && optIsGlobal);\n            // Divisor entre la opción Global y las compañías reales, como en el canon.\n            const abreGrupoReal = !optIsGlobal && idx > 0 && String(companies[idx - 1].uuid) === '000';\n            return (\n              <div key={String(company.uuid)}>\n                {abreGrupoReal && (\n                  <hr className=\"my-1 border-border-primary dark:border-dark-border-primary\" />\n                )}\n                <button\n                  type=\"button\"\n                  role=\"menuitem\"\n                  onClick={() => { onCompanyChange?.(company); setOpen(false); }}\n                  // Opción del canon: UNA línea — check azul de la activa, icono de contexto,\n                  // nombre y código a la derecha. Antes eran dos líneas apiladas y la activa se\n                  // marcaba con `bg-purple-50`, un morado que no está en la paleta del producto.\n                  className={clsx(\n                    'w-full flex items-center gap-2 px-3 py-2 text-xs text-left transition-colors cursor-pointer',\n                    'text-content-primary dark:text-dark-content-primary',\n                    'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n                  )}\n                >\n                  <span className=\"w-3 shrink-0 text-[#0e79fd]\">\n                    {active && <CheckIcon className=\"w-3 h-3\" />}\n                  </span>\n                  <span className=\"shrink-0 text-[#1355b7] dark:text-primary-300\">\n                    <OptIcon className=\"w-3.5 h-3.5\" />\n                  </span>\n                  <span className=\"font-medium truncate min-w-0\" title={company.name}>{company.name}</span>\n                  {!optIsGlobal && company.code != null && (\n                    <span className=\"ml-auto shrink-0 text-content-secondary dark:text-dark-content-secondary tabular-nums\">\n                      {company.code}\n                    </span>\n                  )}\n                </button>\n              </div>\n            );\n          })}\n        </div>\n      )}\n    </div>\n  );\n}\n\n// ─── Control del embudo de una columna foránea ─────────────\n\n/**\n * Control del embudo de una columna FORÁNEA: el mismo searcher (`LookupField`)\n * que usa el formulario del documento, en vez de un campo donde haya que\n * conocer y teclear el id.\n *\n * Emite el valor del `valueField` del registro elegido (por defecto `Id`) —lo\n * que la columna filtra— y `undefined` al limpiar, para que el contenedor\n * descarte la clave en lugar de mandar un filtro vacío.\n *\n * Sin `searcher` o sin `fetcher`, `SearcherControl` degrada solo al input de\n * texto con lupa: nunca deja la columna sin filtro.\n */\nfunction LookupColumnFilter({\n  field,\n  searcher,\n  placeholder,\n  values,\n  onChange,\n  fetcher,\n}: {\n  field: string;\n  searcher?: LookupFieldConfig;\n  placeholder?: string;\n  /** Filtros activos: de aquí sale el valor propio y los padres de la cascada. */\n  values: Record<string, unknown>;\n  onChange: (field: string, value: unknown) => void;\n  fetcher?: unknown;\n}) {\n  // Cascada ENTRE embudos de la grilla (p.ej. Sucursal filtrada por el Cliente\n  // ya elegido): el padre se resuelve contra los filtros activos.\n  const dep = buildDependentLookupProps(searcher, (parentField) => values[parentField]);\n\n  return (\n    // `--lf-field-gap` a 0 porque el rótulo lo pinta el encabezado y la label del\n    // LookupField queda vacía: ese hueco sólo desalinearía el control. La altura\n    // reducida es la métrica del embudo, que vive en una celda de encabezado.\n    <div style={{ '--lf-field-gap': '0rem', '--lf-trigger-height': '1.625rem' } as CSSProperties}>\n      <SearcherControl\n        value={values[field] ?? null}\n        onChange={(v) => onChange(field, v ?? undefined)}\n        placeholder={placeholder}\n        hasError={false}\n        lookupConfig={searcher}\n        fetcher={fetcher}\n        getLookupFilters={dep?.getFilters}\n        lookupDependencies={dep?.dependencies}\n        disabled={dep?.parentMissing}\n      />\n    </div>\n  );\n}\n\n// ─── Embudo de filtro por columna ──────────────────────────\n\n/** Campo por el que filtra una columna: el declarado, o el de sus datos. */\nfunction columnFilterField(col: DocumentListColumn): string {\n  return col.filter?.field ?? col.dataKey ?? col.key;\n}\n\n/** Icono de embudo del encabezado (mismo trazo que el resto de la grilla). */\nfunction FunnelIcon({ className }: { className?: string }) {\n  return (\n    <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <polygon points=\"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3\" />\n    </svg>\n  );\n}\n\n/**\n * Encabezado de columna con embudo: el rótulo y, si la columna declara `filter`,\n * un botón que despliega el control debajo — texto, fecha, select o searcher.\n *\n * Una columna FORÁNEA (`type: 'lookup'`) despliega el mismo `LookupField` del\n * formulario y filtra por el id del registro elegido: es el caso que hoy no se\n * podía filtrar sin conocer y teclear el código.\n *\n * El embudo queda MARCADO mientras el filtro tenga valor, para que un filtro\n * activo con el panel plegado no sea invisible. El control se despliega solo si\n * ya hay valor (un filtro activo no se esconde al recargar la página).\n */\nfunction ColumnHeaderFilter({\n  col,\n  value,\n  onChange,\n  fetcher,\n  columnFilters,\n}: {\n  col: DocumentListColumn;\n  value: unknown;\n  onChange: (field: string, value: unknown) => void;\n  fetcher?: unknown;\n  columnFilters: Record<string, unknown>;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const filter = col.filter!;\n  const field = columnFilterField(col);\n  const active = !isFilterValueEmpty(value);\n  const [open, setOpen] = useState(active);\n  const [text, setText] = useState(value == null ? '' : String(value));\n\n  // Debounce del texto: filtrar server-side por cada tecla es una petición por\n  // pulsación. Los demás controles (select/fecha/searcher) emiten al instante.\n  useEffect(() => {\n    if (filter.type !== 'text') return;\n    const current = value == null ? '' : String(value);\n    if (text === current) return;\n    const id = window.setTimeout(() => onChange(field, text === '' ? undefined : text), 350);\n    return () => window.clearTimeout(id);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [text]);\n\n  // Un filtro que el contenedor limpió por fuera (botón \"Limpiar\") debe vaciar\n  // también la caja de texto; sin esto seguiría mostrando lo tecleado.\n  useEffect(() => {\n    if (filter.type !== 'text') return;\n    if (isFilterValueEmpty(value)) setText('');\n  }, [value, filter.type]);\n\n  // Control del embudo, literal del canon (MasterCrudTable.tsx:134): 11px sobre blanco y\n  // foco con el borde #93d1fd más el anillo tenue de la marca, no el `primary-600` plano.\n  // `font-normal normal-case tracking-normal` se conservan porque el input hereda de la\n  // celda de cabecera y hay que neutralizar su peso.\n  const controlCls = 'w-full min-w-0 h-[26px] box-border border border-border-primary dark:border-dark-border-primary rounded-[5px] px-1.5 text-[11px] font-normal normal-case tracking-normal text-content-primary dark:text-dark-content-primary bg-white dark:bg-dark-bg-primary outline-none focus:border-[#93d1fd] focus:ring-2 focus:ring-primary-500/10 transition-colors';\n\n  return (\n    // Cabecera del embudo, literal del canon (`ColumnFilterHeader` de\n    // MasterCrudTable): el rótulo a la izquierda con la tipografía de encabezado\n    // —14px/600 en `content-primary`— y el embudo empujado al borde derecho por\n    // `justify-between`. La banda de 28px es la que iguala el alto con el de una\n    // columna SIN filtro, para que la fila de cabecera no cambie de altura según\n    // qué columnas filtren.\n    <div className=\"flex flex-col gap-1 w-full\">\n      <div className=\"flex items-center justify-between w-full gap-1 min-h-[28px] select-none\">\n        <span className=\"text-sm font-semibold truncate min-w-0 text-content-primary dark:text-dark-content-primary\">{col.header}</span>\n        <button\n          type=\"button\"\n          aria-expanded={open}\n          aria-label={`${t('master_document.list.filterColumn')}: ${col.header}`}\n          title={`${t('master_document.list.filterColumn')}: ${col.header}`}\n          onClick={() => setOpen((o) => !o)}\n          className={clsx(\n            'shrink-0 inline-flex items-center justify-center p-0.5 rounded transition-colors',\n            'hover:bg-[#eff8ff] dark:hover:bg-primary-900/20',\n            open || active\n              ? 'text-primary-600 hover:text-primary-600'\n              : 'text-content-secondary hover:text-primary-600',\n          )}\n        >\n          <FunnelIcon className=\"w-3 h-3\" />\n        </button>\n      </div>\n\n      {open && (\n        <div className=\"font-normal normal-case tracking-normal\">\n          {filter.type === 'lookup' ? (\n            <LookupColumnFilter\n              field={field}\n              searcher={filter.searcher}\n              placeholder={filter.placeholder}\n              values={columnFilters}\n              onChange={onChange}\n              fetcher={fetcher}\n            />\n          ) : filter.type === 'select' ? (\n            <select\n              className={clsx(controlCls, 'cursor-pointer')}\n              value={value == null ? '' : String(value)}\n              onChange={(e) => onChange(field, e.target.value === '' ? undefined : e.target.value)}\n              aria-label={`${t('master_document.list.filterColumn')}: ${col.header}`}\n            >\n              <option value=\"\">{t('master_document.list.filterAll')}</option>\n              {filter.options?.map((opt) => (\n                <option key={String(opt.value)} value={String(opt.value)}>{opt.label}</option>\n              ))}\n            </select>\n          ) : filter.type === 'date' ? (\n            <input\n              type=\"date\"\n              className={controlCls}\n              // ADR-027 §O.9: un control nativo de fecha no puede encoger — el navegador\n              // dibuja su contenido y lo RECORTA en vez de poner elipsis. En una columna de\n              // 90px el valor se lee `31/10/202` con el glifo del calendario encima del año,\n              // y la sonda no lo ve porque Chrome comprime su layout interno y deja\n              // `scrollWidth === clientWidth`. `min-content` deja ganar al ancho intrínseco;\n              // nunca el 114px medido, que se mueve con la fuente y el navegador. Si la\n              // columna es más estrecha, el scroll horizontal de la tabla es el desenlace\n              // correcto; un valor ilegible no lo es.\n              style={{ minWidth: 'min-content' }}\n              value={value == null ? '' : String(value)}\n              onChange={(e) => onChange(field, e.target.value === '' ? undefined : e.target.value)}\n              aria-label={`${t('master_document.list.filterColumn')}: ${col.header}`}\n            />\n          ) : (\n            <input\n              type=\"text\"\n              size={1}\n              autoComplete=\"off\"\n              className={controlCls}\n              placeholder={filter.placeholder ?? t('master_document.list.filterPlaceholder')}\n              value={text}\n              onChange={(e) => setText(e.target.value)}\n              aria-label={`${t('master_document.list.filterColumn')}: ${col.header}`}\n            />\n          )}\n        </div>\n      )}\n    </div>\n  );\n}\n\n// ─── DocumentList ──────────────────────────────────────────\n\n/**\n * Vista de lista de documentos con filtros, búsqueda avanzada y paginación.\n *\n * Renderiza un encabezado con título, chip de compañía y acciones (exportar,\n * crear nuevo), una barra de pills de estado, un panel de búsqueda avanzada\n * colapsable, la tabla de resultados y controles de paginación.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - DocumentListProps\n *\n * @example\n * ```tsx\n * <DocumentList\n *   title=\"Pedidos de Venta\"\n *   companyName=\"Siesa SAS\"\n *   pills={[{ key: 'all', label: 'Todos', count: 42, active: true }]}\n *   columns={[{ key: 'number', header: 'Número' }]}\n *   rows={data}\n *   totalCount={42}\n *   page={1}\n *   pageSize={10}\n *   onPageChange={setPage}\n *   onRowClick={(row) => navigate(row.id)}\n *   {...otherProps}\n * />\n * ```\n */\nexport function DocumentList({\n  title,\n  subtitle,\n  companies,\n  selectedCompany,\n  companyName,\n  onCompanyChange,\n  onExport,\n  onCreateNew,\n  createNewLabel,\n  canCreate = true,\n  pills,\n  onPillClick,\n  searchFields,\n  searchValues,\n  onSearchChange,\n  fetcher,\n  columnFilters = {},\n  onColumnFilterChange,\n  onSearch,\n  onClearSearch,\n  searchOpen,\n  onToggleSearch,\n  columns,\n  rows,\n  totalCount,\n  onRowClick,\n  onViewRow,\n  onEditRow,\n  getRowHref,\n  onDeleteRow,\n  getRowActions,\n  busyRowIds,\n  onPrintRow,\n  isPrintRowAvailable,\n  printLabel,\n  bulkMode = false,\n  selectedRowIds = [],\n  onRowSelect,\n  getRowId = (row) => String(row.id ?? row.uuid ?? ''),\n  bulkConvertOptions,\n  onBulkConvert,\n  emptyState,\n  page,\n  pageSize,\n  onPageChange,\n  onPageSizeChange,\n  quickSearchEnabled = false,\n  quickSearchPlaceholder,\n  quickSearchValue,\n  onQuickSearchChange,\n  loading,\n  error,\n  onRetry,\n  className,\n}: DocumentListProps) {\n  const { t } = useMasterDocumentTranslation();\n  const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));\n\n  // Confirmación de acciones de fila (DEF-4 / DEF-3): respeta\n  // `requiresConfirmation` usando el ConfirmDialog del kit en lugar de window.confirm.\n  const [pendingConfirm, setPendingConfirm] = useState<{ message: string; run: () => void } | null>(null);\n\n  const handleRowAction = useCallback((action: RowAction, row: Record<string, unknown>) => {\n    if (action.requiresConfirmation) {\n      setPendingConfirm({\n        message: action.confirmationMessage ?? t('master_document.list.confirmAction'),\n        run: () => { setPendingConfirm(null); action.onClick(row); },\n      });\n    } else {\n      action.onClick(row);\n    }\n  }, [t]);\n\n  // Una fila ofrece acciones si hay ver/editar, borrado legacy, acciones por\n  // estado o impresión nativa.\n  const hasRowMenu = !!(onViewRow || onEditRow || onDeleteRow || getRowActions || onPrintRow);\n\n  /**\n   * Normaliza a UNA lista las acciones que llegan por cinco props distintas, para\n   * que el reparto «3 directas / 2 + kebab» del canon se decida sobre el conjunto\n   * real y no por el origen de cada acción.\n   *\n   * Se conserva la precedencia previa: `getRowActions` gobierna lo destructivo y\n   * deja fuera el `onDeleteRow` legacy; «Imprimir» solo aparece si la fila lo\n   * admite. Es el MISMO criterio que antes decidía qué entraba en el desplegable.\n   */\n  const buildRowActions = useCallback((row: Record<string, unknown>): AccionDeFila[] => {\n    const lista: AccionDeFila[] = [];\n    // «Ver» ya NO sale por defecto: con la resolución interna de MasterDocumentPage\n    // llevaba al MISMO detalle que «Editar» —la editabilidad la decide el estado del\n    // documento, no la puerta por la que se entra— y MasterCrud no tiene ese botón.\n    // Una segunda puerta al mismo sitio gastaba uno de los tres huecos directos.\n    //\n    // Sobrevive como OPT-IN porque hay listados donde no es la misma puerta:\n    // despachos y notas crédito tienen ruta de sólo lectura (`/$id`) distinta de la\n    // de edición (`/$id/edit`), y quitarla a secas dejaba esa ruta inalcanzable desde\n    // el listado. `MasterDocumentPage` sólo pasa este callback cuando el host declaró\n    // el suyo, así que el default no lo trae.\n    // `href` sólo lo llevan «Ver» y «Editar»: son las DOS acciones que navegan a\n    // una URL. Anular, borrar o imprimir mutan o abren un modal —no tienen destino\n    // que abrir en otra pestaña— y por eso siguen siendo botones.\n    if (onViewRow) {\n      lista.push({ key: 'view', label: t('master_document.list.viewDetail'), icon: <EyeIcon className=\"w-4 h-4\" />, href: getRowHref?.(row, 'view'), onClick: () => onViewRow(row) });\n    }\n    if (onEditRow) {\n      lista.push({ key: 'edit', label: t('master_document.lines.edit'), icon: <PencilIcon className=\"w-4 h-4\" />, href: getRowHref?.(row, 'edit'), onClick: () => onEditRow(row) });\n    }\n    if (onPrintRow && (isPrintRowAvailable?.(row) ?? true)) {\n      lista.push({ key: 'print', label: printLabel ?? t('master_document.list.print'), icon: <PrintIcon className=\"w-4 h-4\" />, onClick: () => onPrintRow(row) });\n    }\n    const porEstado = getRowActions?.(row);\n    if (porEstado) {\n      porEstado.forEach((a) => {\n        const canon = accionDeEstadoAlCanon(a, t);\n        const DefaultIcon = DEFAULT_ROW_ACTION_ICONS[a.key];\n        lista.push({\n          key: a.key,\n          label: canon?.label ?? a.label,\n          danger: canon ? canon.tone === 'danger' : a.variant === 'danger',\n          tone: canon?.tone,\n          icon: canon ? <canon.Icon className=\"w-4 h-4\" /> : (a.icon ?? (DefaultIcon ? <DefaultIcon className=\"w-4 h-4\" /> : <EllipsisVerticalIcon className=\"w-4 h-4\" />)),\n          onClick: () => handleRowAction(a, row),\n        });\n      });\n    } else if (onDeleteRow) {\n      // Legacy: borrar gobernado por flag global (retrocompat).\n      lista.push({ key: 'delete', label: t('master_document.list.action.delete'), danger: true, tone: 'danger', icon: <TrashIcon className=\"w-4 h-4\" />, onClick: () => onDeleteRow(row) });\n    }\n    return lista;\n  }, [onViewRow, onEditRow, getRowHref, onPrintRow, isPrintRowAvailable, printLabel, getRowActions, onDeleteRow, handleRowAction, t]);\n\n  const todasSeleccionadas = rows.length > 0 && selectedRowIds.length === rows.length;\n  const algunaSeleccionada = selectedRowIds.length > 0 && selectedRowIds.length < rows.length;\n\n  const alternarTodas = useCallback((marcar: boolean) => {\n    rows.forEach((row) => {\n      const id = getRowId(row);\n      const yaEsta = selectedRowIds.includes(id);\n      if (marcar && !yaEsta) onRowSelect?.(id, true);\n      if (!marcar && yaEsta) onRowSelect?.(id, false);\n    });\n  }, [rows, selectedRowIds, onRowSelect, getRowId]);\n\n  /**\n   * Columnas para el `Table` del kit — el MISMO componente que usa MasterCrud a\n   * través de `MasterCrudTable`.\n   *\n   * Antes esta tabla se pintaba a mano (banda de cabecera, filas, celda sticky y\n   * un paginador propio), y por eso divergía: esquinas, densidad, embudos y\n   * paginación eran una imitación que había que mantener sincronizada. Al montar\n   * el `Table` con las mismas props que pasa MasterCrud, la apariencia deja de\n   * ser una copia y pasa a ser el mismo componente (ADR-027 §E.17).\n   */\n  const tableColumns = useMemo<TableColumn<Record<string, unknown>>[]>(() => {\n    const cols: TableColumn<Record<string, unknown>>[] = [];\n\n    if (bulkMode) {\n      cols.push({\n        header: (\n          <input\n            type=\"checkbox\"\n            checked={todasSeleccionadas}\n            ref={(el) => { if (el) el.indeterminate = algunaSeleccionada; }}\n            onChange={(e) => alternarTodas(e.target.checked)}\n            className=\"w-4 h-4 rounded accent-primary-custom-600 cursor-pointer\"\n            aria-label={t('master_document.list.selectAll')}\n          />\n        ),\n        headerRaw: true,\n        accessor: (() => null) as never,\n        align: 'center',\n        width: '48px',\n        fixedWidth: true,\n        render: (_v, row) => (\n          <input\n            type=\"checkbox\"\n            checked={selectedRowIds.includes(getRowId(row))}\n            onClick={(e) => e.stopPropagation()}\n            onChange={(e) => onRowSelect?.(getRowId(row), e.target.checked)}\n            className=\"w-4 h-4 rounded accent-primary-custom-600 cursor-pointer\"\n            aria-label={t('master_document.list.selectRow')}\n          />\n        ),\n      });\n    }\n\n    columns.forEach((col) => {\n      const conEmbudo = !!(col.filter && onColumnFilterChange);\n      cols.push({\n        header: conEmbudo\n          ? (\n            <ColumnHeaderFilter\n              col={col}\n              value={columnFilters[columnFilterField(col)]}\n              onChange={onColumnFilterChange!}\n              fetcher={fetcher}\n              columnFilters={columnFilters}\n            />\n          )\n          : col.header,\n        headerRaw: conEmbudo,\n        accessor: (() => null) as never,\n        align: col.align,\n        width: col.width,\n        // El `render` emite CONTENIDO, sin padding propio: la celda del kit ya\n        // trae el suyo (8/16 con `dense`) y pagarlo dos veces engorda la fila\n        // sin nada en pantalla que lo explique (ADR-027 §E.8). El `span` es solo\n        // control de desborde, que esa misma regla permite.\n        render: (_v, row) => (\n          <span className={clsx('block w-full min-w-0 truncate', col.mono && 'tabular-nums font-medium')}>\n            {col.render ? col.render(row) : (String(row[col.dataKey ?? col.key] ?? '').trim() || '—')}\n          </span>\n        ),\n      });\n    });\n\n    if (hasRowMenu) {\n      cols.push({\n        header: t('master_document.list.rowActions'),\n        accessor: (() => null) as never,\n        align: 'center',\n        // Literal del canon (MasterCrudTable): 3×28px + 2×12px de gap = 108px\n        // + 32px de padding de celda = 140px, y `fixedWidth` para que la columna\n        // no se expanda a repartir el sobrante (§E.5).\n        width: '140px',\n        fixedWidth: true,\n        stickyRight: true,\n        render: (_v, row) => (\n          <RowActionsCell\n            acciones={buildRowActions(row)}\n            busy={busyRowIds?.includes(getRowId(row))}\n          />\n        ),\n      });\n    }\n\n    return cols;\n  }, [columns, bulkMode, todasSeleccionadas, algunaSeleccionada, alternarTodas, selectedRowIds, onRowSelect, getRowId, columnFilters, onColumnFilterChange, fetcher, hasRowMenu, buildRowActions, busyRowIds, t]);\n\n  // Hay filtro puesto si el usuario tocó la búsqueda básica, el panel avanzado o\n  // un embudo de columna. Sin esto, una búsqueda sin resultados pintaría el\n  // estado vacío de «aún no tienes documentos», que es un mensaje falso.\n  const hayFiltroActivo = !!(\n    (quickSearchValue ?? '').trim() ||\n    Object.values(searchValues).some((v) => !isFilterValueEmpty(v)) ||\n    Object.values(columnFilters).some((v) => !isFilterValueEmpty(v))\n  );\n\n  const paginacion = {\n    currentPage: page,\n    totalPages,\n    onPageChange,\n    pageSize,\n    pageSizeOptions: [10, 25, 50, 100],\n    onPageSizeChange,\n    totalRecords: totalCount,\n    previousLabel: t('master_document.list.previousPage'),\n    nextLabel: t('master_document.list.nextPage'),\n    perPageLabel: t('master_document.list.perPage'),\n    recordsLabel: t('master_document.list.records'),\n    goToPageLabel: t('master_document.list.goToPage'),\n  };\n\n  // Caja de la búsqueda básica, con el toggle del panel avanzado DENTRO — es\n  // donde lo pone MasterCrud, no en una fila propia con su cabecera.\n  const cajaBusqueda = quickSearchEnabled && onQuickSearchChange ? (\n    <div className=\"relative flex items-center\">\n      <span className=\"absolute left-2.5 top-1/2 -translate-y-1/2 text-content-tertiary dark:text-dark-content-tertiary pointer-events-none\">\n        <MagnifyingGlassIcon className=\"w-3.5 h-3.5\" />\n      </span>\n      <input\n        type=\"search\"\n        placeholder={quickSearchPlaceholder ?? t('master_document.field.search')}\n        value={quickSearchValue ?? ''}\n        autoComplete=\"off\"\n        onChange={(e) => onQuickSearchChange(e.target.value)}\n        className={clsx(\n          'pl-8 h-9 w-64 text-sm border border-border-primary dark:border-dark-border-primary rounded-md',\n          'bg-white dark:bg-dark-bg-primary text-content-primary dark:text-dark-content-primary',\n          'placeholder:text-content-tertiary focus:outline-none focus:border-[#93d1fd]',\n          'focus:ring-[3px] focus:ring-primary-500/10 transition-colors disabled:opacity-60',\n          onToggleSearch ? 'pr-10' : 'pr-3',\n        )}\n      />\n      {onToggleSearch && (\n        <button\n          type=\"button\"\n          onClick={onToggleSearch}\n          aria-expanded={!!searchOpen}\n          title={searchOpen ? t('master_document.list.hideAdvancedSearch') : t('master_document.list.advancedSearch')}\n          aria-label={searchOpen ? t('master_document.list.hideAdvancedSearch') : t('master_document.list.advancedSearch')}\n          className={clsx(\n            'absolute right-1.5 inline-flex items-center justify-center w-7 h-7 rounded-md transition-colors',\n            searchOpen\n              ? 'bg-primary-600 text-white'\n              : 'text-content-tertiary hover:text-primary-600 hover:bg-[#eff8ff] dark:hover:bg-primary-900/20',\n          )}\n        >\n          {searchOpen\n            ? <ChevronDownIcon className=\"w-4 h-4 rotate-180\" />\n            : <FunnelIcon className=\"w-4 h-4\" />}\n        </button>\n      )}\n    </div>\n  ) : null;\n\n  return (\n    // Contenedor SIN caja: ni fondo, ni borde, ni sombra. La única caja del\n    // listado es la de la tabla, igual que en MasterCrud — cuyo root es\n    // `flex flex-col w-full relative flex-1 min-h-0 h-full` y cuyo contenido va\n    // en un envoltorio con el aire de la página. La cadena de `min-h-0` es la\n    // que hace que la tabla ocupe el alto disponible en vez de desbordar la\n    // página (ADR-027 §C.5).\n    <div className={clsx('flex flex-col w-full relative flex-1 min-h-0 h-full', className)}>\n      <div className=\"flex-1 min-h-0 flex flex-col w-full px-4 md:px-6 py-4 md:py-6 gap-4 md:gap-6\">\n\n        {/* ── Toolbar: título + compañía a la izquierda; búsqueda, Nuevo y kebab a la derecha ── */}\n        <div className=\"flex-shrink-0\">\n          <div className=\"flex flex-col md:flex-row md:items-center md:justify-between gap-4 w-full\">\n            <div className=\"flex flex-col items-start gap-1.5 min-w-0\">\n              {/* Título literal del canon (MasterCrudToolbar): 20px/600, tracking\n                  ajustado y el azul de marca #1355b7. Antes era 24px/700 en\n                  `content-primary`, que junto a un maestro se leía como otra app. */}\n              <h1 className=\"text-xl font-semibold tracking-tight text-[#1355b7] dark:text-primary-600 truncate max-w-full\">\n                {title}\n              </h1>\n              {subtitle && (\n                <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary truncate max-w-full\">\n                  {subtitle}\n                </p>\n              )}\n              {companies && companies.length > 0 ? (\n                <CompanyDropdown\n                  companies={companies}\n                  selectedCompany={selectedCompany}\n                  onCompanyChange={onCompanyChange}\n                />\n              ) : companyName ? (\n                <span className={clsx(\n                  'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold',\n                  'bg-primary-100 text-primary-600 border border-primary-600/30',\n                  'dark:bg-primary-600/10 dark:text-primary-400 dark:border-primary-600/30',\n                )}>\n                  {companyName}\n                </span>\n              ) : null}\n            </div>\n\n            <div className=\"flex items-center gap-2 flex-shrink-0\">\n              {cajaBusqueda}\n\n              {/* Sin búsqueda básica el toggle del panel avanzado no tiene dónde\n                  vivir, así que toma la geometría del kebab (36x36 con borde):\n                  el mismo vocabulario de la barra, y el panel sigue alcanzable. */}\n              {!cajaBusqueda && onToggleSearch && (\n                <button\n                  type=\"button\"\n                  onClick={onToggleSearch}\n                  aria-expanded={!!searchOpen}\n                  title={searchOpen ? t('master_document.list.hideAdvancedSearch') : t('master_document.list.advancedSearch')}\n                  aria-label={searchOpen ? t('master_document.list.hideAdvancedSearch') : t('master_document.list.advancedSearch')}\n                  className={clsx(\n                    'inline-flex items-center justify-center w-9 h-9 border rounded-md transition-colors',\n                    searchOpen\n                      ? 'bg-primary-600 text-white border-primary-600'\n                      : 'border-border-primary dark:border-dark-border-primary bg-background-secondary dark:bg-dark-bg-secondary hover:bg-[#ebebec] dark:hover:bg-dark-bg-primary text-content-tertiary',\n                  )}\n                >\n                  <FunnelIcon className=\"w-4 h-4\" />\n                </button>\n              )}\n\n              {/* Botón «Nuevo»: icono + rótulo, con el `Button` del kit y las\n                  mismas props que MasterCrud le pasa. Ausente —no deshabilitado—\n                  cuando no aplica: un botón sin acción es un afordance que miente. */}\n              {canCreate && onCreateNew && (\n                <Button\n                  type=\"default\"\n                  size=\"base\"\n                  className=\"!text-sm font-medium\"\n                  leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n                  onClick={onCreateNew}\n                >\n                  {createNewLabel ?? t('master_document.list.new')}\n                </Button>\n              )}\n\n              {/* Opciones adicionales en el kebab, como MasterCrud: lo que no es\n                  la acción principal no compite con ella en la barra. */}\n              {onExport && (\n                <MoreOptionsMenu\n                  options={[{\n                    key: 'export',\n                    label: t('master_document.list.export'),\n                    icon: <ArrowUpTrayIcon className=\"w-4 h-4 text-content-tertiary\" />,\n                    onClick: onExport,\n                  }]}\n                />\n              )}\n            </div>\n          </div>\n        </div>\n\n        {/* ── Pills de estado ── */}\n        {pills.length > 0 && (\n          <div className=\"flex-shrink-0 flex items-center gap-2 overflow-x-auto\">\n            {pills.map((pill) => (\n              <button\n                key={pill.key}\n                type=\"button\"\n                onClick={() => onPillClick(pill.key)}\n                className={clsx(\n                  'flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap',\n                  'transition-all duration-150 shrink-0',\n                  pill.active && 'ring-2 ring-inset ring-black/15',\n                )}\n                style={{\n                  backgroundColor: pill.bg ?? 'var(--color-primary-600, #0e79fd)',\n                  color: pill.color ?? '#fff',\n                }}\n              >\n                {pill.label}\n                {pill.count != null && (\n                  <span\n                    className={clsx(\n                      'inline-flex items-center justify-center px-1.5 min-w-[18px] h-[18px] rounded-full text-xs font-bold',\n                      pill.active ? 'bg-white/20 dark:bg-black/20 text-inherit' : 'bg-background-secondary text-content-tertiary',\n                    )}\n                  >\n                    {pill.count}\n                  </span>\n                )}\n              </button>\n            ))}\n          </div>\n        )}\n\n        <div className=\"flex-1 min-h-0 flex flex-col overflow-hidden\">\n\n          {/* ── Panel de búsqueda avanzada ── Caja propia del canon\n              (MasterCrudAdvancedSearch): blanca, borde, `rounded-lg shadow-sm`,\n              cuerpo `p-5` y los dos botones al pie a la derecha. Ya no lleva la\n              fila-cabecera «Búsqueda avanzada» con su chevron: el disparador es\n              el embudo de la caja de búsqueda, igual que en MasterCrud. */}\n          {onToggleSearch && searchOpen && searchFields.length > 0 && (\n            <section\n              aria-label={t('master_document.list.advancedSearch')}\n              className=\"mb-4 flex-shrink-0 bg-white dark:bg-dark-bg-primary border border-border-primary dark:border-dark-border-primary rounded-lg shadow-sm\"\n            >\n              <form\n                onSubmit={(e) => { e.preventDefault(); onSearch(); }}\n                onReset={(e) => { e.preventDefault(); onClearSearch(); }}\n              >\n                <div className=\"p-5\">\n                  <div className=\"grid grid-cols-1 md:grid-cols-3 gap-4\">\n                    {searchFields.map((field) => (\n                      <div key={field.key}>\n                        <label\n                          htmlFor={`mdl-search-${field.key}`}\n                          className=\"block text-[11px] font-semibold text-content-tertiary dark:text-dark-content-tertiary tracking-[0.3px] mb-1\"\n                        >\n                          {field.label}\n                        </label>\n                        {field.type === 'select' ? (\n                          <select\n                            id={`mdl-search-${field.key}`}\n                            className={`${ADV_CONTROL_CLS} cursor-pointer`}\n                            value={String(searchValues[field.key] ?? '')}\n                            onChange={(e) => onSearchChange(field.key, e.target.value)}\n                          >\n                            <option value=\"\">{field.placeholder ?? t('master_document.field.selectPlaceholder')}</option>\n                            {field.options?.map((opt) => (\n                              <option key={opt.value} value={opt.value}>{opt.label}</option>\n                            ))}\n                          </select>\n                        ) : (\n                          <input\n                            id={`mdl-search-${field.key}`}\n                            type={field.type}\n                            autoComplete=\"off\"\n                            className={clsx(ADV_CONTROL_CLS, field.type === 'date' && 'cursor-pointer')}\n                            style={field.type === 'date' ? { minWidth: 'min-content' } : undefined}\n                            value={String(searchValues[field.key] ?? '')}\n                            onChange={(e) => onSearchChange(field.key, e.target.value)}\n                            placeholder={field.placeholder}\n                          />\n                        )}\n                      </div>\n                    ))}\n                  </div>\n                </div>\n                <div className=\"flex justify-end gap-2 px-5 pb-5\">\n                  <button\n                    type=\"reset\"\n                    className=\"inline-flex items-center justify-center gap-2 h-9 px-3 rounded-md text-sm font-medium whitespace-nowrap bg-transparent border border-[#93d1fd] text-primary-600 shadow-sm hover:bg-[#dbeefe] dark:hover:bg-primary-900/20 transition-all duration-150\"\n                  >\n                    {t('master_document.list.clear')}\n                  </button>\n                  <button\n                    type=\"submit\"\n                    className=\"inline-flex items-center justify-center gap-2 h-9 px-3 rounded-md text-sm font-medium whitespace-nowrap bg-primary-600 text-white shadow-inner hover:brightness-110 transition-all duration-150\"\n                  >\n                    <MagnifyingGlassIcon className=\"w-4 h-4 shrink-0\" />\n                    {t('master_document.field.search')}\n                  </button>\n                </div>\n              </form>\n            </section>\n          )}\n\n          {/* ── Barra de selección masiva ── */}\n          {bulkMode && (\n            <div className={clsx(\n              'flex-shrink-0 flex items-center justify-between gap-3 px-4 py-2.5 mb-4 rounded-lg',\n              'bg-primary-custom-100 dark:bg-dark-bg-custom',\n              'border border-primary-custom-300 dark:border-dark-border-custom',\n            )}>\n              <span className=\"text-sm font-semibold text-primary-custom-700 dark:text-dark-content-custom\">\n                {selectedRowIds.length > 0\n                  ? t('master_document.list.selectedCount', { count: selectedRowIds.length })\n                  : t('master_document.list.noneSelected')}\n              </span>\n              {bulkConvertOptions && bulkConvertOptions.length > 0 && (\n                <CrossingClassMenu\n                  options={bulkConvertOptions}\n                  onSelect={(classId) => onBulkConvert?.(classId, selectedRowIds)}\n                  disabled={selectedRowIds.length === 0}\n                />\n              )}\n            </div>\n          )}\n\n          {/* ── Error ── */}\n          {error && (\n            <div className=\"flex-shrink-0 flex items-center justify-center gap-3 px-5 py-8\">\n              <span className=\"text-sm text-error-content\">{error}</span>\n              {onRetry && (\n                <button\n                  type=\"button\"\n                  onClick={onRetry}\n                  className=\"px-3 py-1.5 rounded-md text-xs font-semibold bg-error-bg text-error-content hover:bg-error-bg/80 transition-colors\"\n                >\n                  {t('master_document.chrome.retry')}\n                </button>\n              )}\n            </div>\n          )}\n\n          {/* ── Tabla ── Una sola caja alrededor del `Table`, con el radio del\n              canon (`rounded-xl`). El `Table` va sin caja propia\n              (`showBorder`/`showShadow` en false y el `className` que neutraliza\n              fondo, sombra, radio y padding) para no pintar dos bordes\n              concéntricos (ADR-027 §E.7). Es literalmente lo que hace\n              MasterCrud. */}\n          {!error && (\n            rows.length === 0 && !loading && !hayFiltroActivo && emptyState ? (\n              <div className=\"flex flex-1 min-h-0 flex-col items-center justify-center py-16 text-center px-5\">\n                {emptyState.icon && (\n                  <div className=\"mb-4 text-border-primary dark:text-dark-border-primary\">{emptyState.icon}</div>\n                )}\n                <p className=\"text-base font-semibold text-content-primary dark:text-dark-content-primary\">\n                  {emptyState.title}\n                </p>\n                {emptyState.description && (\n                  <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary mt-1 max-w-sm\">\n                    {emptyState.description}\n                  </p>\n                )}\n                {emptyState.action && (\n                  <Button\n                    type=\"default\"\n                    size=\"base\"\n                    className=\"!text-sm font-medium mt-4\"\n                    onClick={emptyState.action.onClick}\n                  >\n                    {emptyState.action.label}\n                  </Button>\n                )}\n              </div>\n            ) : (\n              <div className=\"flex flex-col flex-1 min-h-0 bg-white dark:bg-dark-bg-primary rounded-xl border border-border-primary dark:border-dark-border-primary overflow-hidden w-full\">\n                <Table\n                  columns={tableColumns}\n                  data={rows}\n                  loading={loading}\n                  emptyMessage={emptyState?.title ?? t('master_document.list.noResults')}\n                  variant=\"basic\"\n                  showBorder={false}\n                  showShadow={false}\n                  showPadding={false}\n                  fullWidth\n                  stickyHeader\n                  accentHover\n                  dense\n                  // La FILA no navega por defecto. Medido en MasterCrud (`/app/items`,\n                  // 2026-09-09): sus filas son `tabindex: null` y `cursor: auto` — no\n                  // son un enlace. Aquí lo eran por la resolución interna de\n                  // `MasterDocumentPage`, así que cualquier clic dentro de la fila\n                  // —incluido fallar un botón por dos píxeles— sacaba al usuario de la\n                  // lista. La puerta al detalle es «Editar».\n                  //\n                  // Se respeta el opt-in: `MasterDocumentPage` sólo pasa este callback\n                  // cuando el host declaró su propio `onRowClick` (lo hace, p. ej.,\n                  // `EcdListPage`), y ahí la fila SÍ es un destino elegido a propósito.\n                  onRowClick={onRowClick}\n                  pagination={paginacion}\n                  className=\"!bg-transparent !shadow-none !rounded-none !p-0\"\n                />\n              </div>\n            )\n          )}\n        </div>\n      </div>\n\n      {/* Confirmación de acción de fila (DEF-4) */}\n      {pendingConfirm && (\n        <ConfirmDialog\n          message={pendingConfirm.message}\n          onConfirm={pendingConfirm.run}\n          onCancel={() => setPendingConfirm(null)}\n        />\n      )}\n    </div>\n  );\n}\n","import { useMemo } from 'react';\nimport type { FilterCondition, FilterExpression } from '../LookupField/types/filter.types';\nimport type { Fetcher, SearchRequest, SearchResponse } from '../LookupField/services/api.types';\nimport type { WizardOption } from './MasterDocument.types';\n\n/**\n * `Fetcher` de LookupField servido DESDE MEMORIA, para los pasos del wizard de\n * creación cuya lista ya está cargada.\n *\n * ¿Por qué existe? Compañía y centro de operación se eligen en un `LookupField`\n * —el usuario necesita BUSCAR, no desplegar cien opciones— pero sus listas no son\n * una entidad consultable: las trae el adapter (`listCompanies` /\n * `listOperationCenters`) y llegan al wizard como `WizardOption[]` ya resueltas,\n * filtradas por permiso y por la compañía elegida. No hay endpoint `/search` al\n * que apuntar, y montar uno sería pedir dos veces lo mismo.\n *\n * `LookupField` sólo habla con su `fetcher`, así que basta con darle uno que\n * responda con el array que ya tenemos. La búsqueda, el orden y la paginación se\n * resuelven aquí con la misma semántica que espera del backend, de modo que el\n * componente no distingue un caso del otro.\n *\n * ⚠️ **Alcance deliberadamente corto.** Sólo implementa lo que LookupField llega a\n * pedir en este uso: búsqueda por `label` con los tres operadores y filtros de\n * IGUALDAD (los que manda al resolver el valor controlado por su `Id`). No\n * implementa `__contains`, `__in`, rangos ni `orderBy` por campo arbitrario,\n * porque el wizard no pasa `filters` ni `orderBy`. Si algún día se pasan, esto\n * los ignoraría en silencio — de ahí el aviso.\n */\n\n/** Campo único de etiqueta: es el que se muestra y por el que se busca. */\nexport const WIZARD_LOOKUP_LABEL_FIELD = 'label';\n\n/** Registro que ve LookupField. `Id` en PascalCase es su contrato. */\nexport interface WizardLookupRecord {\n  Id: string;\n  label: string;\n  [key: string]: unknown;\n}\n\n/**\n * Texto comparable: minúsculas y SIN tildes. Sin plegar acentos, buscar \"compa\"\n * no encontraría \"Compañía\" en cuanto el usuario llega a la \"ñ\", que es justo el\n * caso de casi todos los nombres de compañía de Siesa.\n */\nfunction plegar(valor: unknown): string {\n  return String(valor ?? '')\n    .normalize('NFD')\n    .replace(/\\p{Diacritic}/gu, '')\n    .toLocaleLowerCase();\n}\n\n/**\n * `startsWith` sobre una etiqueta COMPUESTA, que es lo que son estas: el adapter\n * las entrega como «código - nombre» («01 - SIESA SAS»).\n *\n * Un prefijo sobre la cadena completa sólo sirve para el código: teclear «SIESA»\n * no encontraría nada y el usuario concluiría que el buscador no funciona, cuando\n * el operador por defecto de LookupField es precisamente `startsWith` y no hay\n * prop para cambiarlo desde fuera. Así que aquí «empieza por» se evalúa también\n * contra cada PALABRA de la etiqueta.\n *\n * Es un superconjunto del prefijo estricto —todo lo que casaba antes sigue\n * casando—, así que no puede ocultar resultados; y `contains`, que el usuario\n * activa con el icono del buscador, se mantiene tal cual.\n */\nfunction empiezaPorAlgunaPalabra(valor: string, texto: string): boolean {\n  // Los separadores cubren las formas en que el adapter compone la etiqueta:\n  // «01 - Principal», «01 — Centro A», «Bodega/Norte`».\n  return valor.startsWith(texto)\n    || valor.split(/[\\s\\-–—/·|,()]+/).some((palabra) => palabra.startsWith(texto));\n}\n\nfunction coincideBusqueda(\n  registro: WizardLookupRecord,\n  request: SearchRequest,\n): boolean {\n  const texto = plegar(request.search).trim();\n  if (!texto) return true;\n  const campos = request.searchFields?.length ? request.searchFields : [WIZARD_LOOKUP_LABEL_FIELD];\n  return campos.some((campo) => {\n    const valor = plegar(registro[campo]);\n    switch (request.searchOperator) {\n      // `equals` no es un modo que el usuario active: LookupField lo manda solo\n      // cuando se teclea un código completo y se pulsa Enter sin haber navegado\n      // por los resultados. Ahí sí es igualdad estricta contra la etiqueta entera.\n      case 'equals': return valor === texto;\n      case 'contains': return valor.includes(texto);\n      // `startsWith` es el default del contrato cuando no viene operador.\n      default: return empiezaPorAlgunaPalabra(valor, texto);\n    }\n  });\n}\n\n/** Igualdad laxa: los `Id` viajan como cadena y las opciones también. */\nfunction igual(valorRegistro: unknown, valorFiltro: unknown): boolean {\n  return String(valorRegistro ?? '') === String(valorFiltro ?? '');\n}\n\n/**\n * Filtros en formato expresivo: el array externo son AND, el interno OR\n * (`[[{a:1},{a:2}],[{b:3}]]` ⇒ `(a=1 OR a=2) AND b=3`), tal como los construye\n * LookupField para resolver el valor seleccionado.\n */\nfunction pasaFiltros(registro: WizardLookupRecord, filters?: FilterExpression): boolean {\n  if (!filters?.length) return true;\n  return filters.every((grupo) =>\n    !grupo?.length || grupo.some((condicion: FilterCondition) =>\n      Object.entries(condicion).every(([campo, valor]) => igual(registro[campo], valor)),\n    ),\n  );\n}\n\n/** `WizardOption` → registro de LookupField. Sólo `id` y `label` intervienen. */\nfunction aRegistro(option: WizardOption): WizardLookupRecord {\n  return { Id: option.id, label: option.label };\n}\n\n/**\n * Construye el `Fetcher` que sirve `options` desde memoria.\n *\n * Conserva el ORDEN de entrada, que ya viene decidido por el adapter; ordenar\n * aquí alfabéticamente pisaría ese criterio (p. ej. la compañía por defecto\n * primero).\n */\nexport function crearFetcherDeOpciones(options: WizardOption[]): Fetcher {\n  const registros = options.map(aRegistro);\n  return (<TRecord,>(_entity: string, request: SearchRequest): Promise<SearchResponse<TRecord>> => {\n    const coincidencias = registros\n      .filter((r) => pasaFiltros(r, request.filters))\n      .filter((r) => coincideBusqueda(r, request));\n    // El paginado es lo que sostiene el scroll infinito de LookupField: decide que\n    // hay más páginas cuando recibe exactamente `pageSize` registros, así que la\n    // porción tiene que ser real y no el array completo.\n    const desde = Math.max(0, (request.page - 1) * request.pageSize);\n    const pagina = coincidencias.slice(desde, desde + request.pageSize);\n    return Promise.resolve({\n      // El contrato de `Fetcher` es genérico en el registro y aquí el tipo real es\n      // `WizardLookupRecord`; LookupField sólo lee `Id` y los `displayFields`, que\n      // es exactamente lo que se entrega.\n      data: pagina as unknown as TRecord[],\n      page: request.page,\n      pageSize: request.pageSize,\n    });\n  }) as Fetcher;\n}\n\n/**\n * Igual que `crearFetcherDeOpciones`, pero con IDENTIDAD ESTABLE mientras el\n * contenido no cambie.\n *\n * Importa: `fetcher` está en las dependencias de los `useCallback` de carga de\n * LookupField, así que un fetcher nuevo en cada render invalida esos callbacks y\n * vuelve a disparar la carga. Y las listas llegan como props que el host\n * reconstruye a su ritmo, así que no se puede depender de la identidad del array:\n * la clave se deriva del CONTENIDO (`id` y `label` de cada opción), el mismo\n * recurso que usa LookupField con sus `displayFieldsKey`.\n */\nexport function useWizardOptionFetcher(options: WizardOption[]): Fetcher {\n  const clave = options.map((o) => `${o.id}␟${o.label}`).join('␞');\n  // `options` se lee a través de `clave`, que es lo que de verdad decide el\n  // resultado; incluir el array reintroduciría la inestabilidad de identidad.\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  return useMemo(() => crearFetcherDeOpciones(options), [clave]);\n}\n","import { useEffect } from 'react';\nimport { clsx } from 'clsx';\nimport { LookupField } from '../LookupField';\nimport type { DocumentCreationWizardProps, WizardOption } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { useWizardOptionFetcher, WIZARD_LOOKUP_LABEL_FIELD, type WizardLookupRecord } from './wizardOptionLookup';\n\n// ─── Icons ─────────────────────────────────────────────────\n\nfunction XIcon(props: React.SVGProps<SVGSVGElement>) {\n  return (\n    <svg viewBox=\"0 0 20 20\" fill=\"currentColor\" {...props}>\n      <path d=\"M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z\" />\n    </svg>\n  );\n}\n\n// ─── Option Card ───────────────────────────────────────────\n\nfunction OptionCard({\n  option,\n  selected,\n  onClick,\n}: {\n  option: WizardOption;\n  selected: boolean;\n  onClick: () => void;\n}) {\n  return (\n    <button\n      type=\"button\"\n      onClick={onClick}\n      className={clsx(\n        'flex items-start gap-3 w-full rounded-xl px-4 py-3 text-left transition-all duration-150',\n        'border-2',\n        'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n        'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n        selected\n          ? 'bg-primary-100 border-primary-600 border-l-[3px] dark:bg-primary-600/10 dark:border-primary-600'\n          : 'bg-bg-primary border-border-secondary hover:border-border-primary hover:bg-background-secondary dark:bg-dark-bg-primary dark:border-dark-border-primary dark:hover:bg-dark-bg-secondary',\n      )}\n      style={selected && option.color ? { borderLeftColor: option.color } : undefined}\n    >\n      {option.icon && (\n        <span className=\"shrink-0 mt-0.5\">{option.icon}</span>\n      )}\n      <div className=\"min-w-0\">\n        <span className={clsx(\n          'text-sm font-semibold',\n          selected ? 'text-primary-600 dark:text-primary-400' : 'text-content-primary dark:text-dark-content-primary',\n        )}>\n          {option.label}\n        </span>\n        {option.description && (\n          <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary mt-0.5\">\n            {option.description}\n          </p>\n        )}\n      </div>\n    </button>\n  );\n}\n\n// ─── Paso buscable (compañía, centro de operación) ─────────\n\n/**\n * Paso del wizard resuelto con un `LookupField` en vez de un `<select>` nativo.\n *\n * El `<select>` obliga a ENCONTRAR la opción a ojo dentro de la lista desplegada;\n * el `LookupField` deja TECLEAR para filtrar, que es lo que se necesita en cuanto\n * el usuario tiene decenas de compañías o de centros de operación —y es además el\n * control con el que ya se eligen las FK en el resto del documento\n * (`FieldRenderer`, control `searcher`), así que el wizard deja de ser la\n * excepción de la pantalla.\n *\n * Los datos NO se piden a ningún endpoint: llegan ya resueltos por props y se\n * sirven desde memoria (ver `wizardOptionLookup`).\n *\n * Vive en UN solo sitio a propósito: son dos pasos con exactamente la misma\n * configuración, y dos copias de estas props vuelven a divergir en el siguiente\n * cambio.\n */\nfunction WizardOptionLookup({\n  entity,\n  label,\n  options,\n  value,\n  onChange,\n  placeholder,\n  disabled,\n}: {\n  entity: string;\n  label: string;\n  options: WizardOption[];\n  value: string | undefined;\n  onChange: (id: string) => void;\n  placeholder: string;\n  disabled?: boolean;\n}) {\n  const fetcher = useWizardOptionFetcher(options);\n  return (\n    <LookupField<WizardLookupRecord>\n      /*\n       * `entity` es un nombre SINTÉTICO, no una entidad del backend: aquí no hay\n       * endpoint al que apuntar porque los datos ya vienen por props. LookupField\n       * lo exige y lo usa en dos sitios —lo pasa al `fetcher` (que lo ignora) y lo\n       * mete en las dependencias de sus callbacks de carga—, así que lo único que\n       * se le pide es ser estable y distinto entre los dos pasos.\n       */\n      entity={entity}\n      /*\n       * El label VISIBLE lo pinta el paso del wizard, con el mismo estilo que los\n       * pasos que siguen siendo `select`; el del componente se oculta con la clase\n       * que LookupField expone justo para los hosts que ponen su propia etiqueta.\n       *\n       * El TEXTO sí se pasa: la raíz lo referencia con `aria-labelledby`, y el\n       * nombre accesible se computa igual desde un nodo oculto cuando se llega a\n       * él por esa vía. El `<select>` anterior no tenía ninguno —ni `id`/`htmlFor`\n       * ni `aria-label`—, así que el control GANA nombre accesible, no lo pierde.\n       */\n      label={label}\n      className=\"lookup-field--label-hidden\"\n      displayFields={[WIZARD_LOOKUP_LABEL_FIELD]}\n      fetcher={fetcher}\n      value={value ?? null}\n      onChange={(record) => onChange(record ? String(record.Id) : '')}\n      placeholder={placeholder}\n      /*\n       * El `<select>` no permitía volver al vacío: su opción de placeholder era\n       * `disabled`. El paso es obligatorio, así que sin botón de limpiar se\n       * conserva esa regla en lugar de abrir un estado que el wizard no sabe\n       * representar (y que dejaría `canConfirm` en falso sin explicar por qué).\n       */\n      clearable={false}\n      /*\n       * El asterisco lo pinta el wizard junto a su propia etiqueta, así que el\n       * indicador del componente se apaga —vive dentro del label oculto—. Pero\n       * `required` se conserva: es lo que pone `aria-required` en la raíz, y eso\n       * no es decoración (ADR-027 §Apéndice C: la semántica no se mueve con lo\n       * cosmético).\n       */\n      required\n      showRequiredIndicator={false}\n      disabled={disabled}\n    />\n  );\n}\n\n// ─── Skeleton Loader ───────────────────────────────────────\n\nfunction StepSkeleton() {\n  return (\n    <div className=\"grid grid-cols-2 gap-3\">\n      {Array.from({ length: 4 }).map((_, i) => (\n        <div key={i} className=\"h-16 rounded-xl bg-gradient-to-r from-background-secondary to-background-secondary animate-pulse\" />\n      ))}\n    </div>\n  );\n}\n\n// ─── DocumentCreationWizard ────────────────────────────────\n\n/**\n * Asistente paso a paso para crear un nuevo documento maestro.\n *\n * Guía al usuario a seleccionar compañía, centro de operación y tipo de\n * documento en tres pasos secuenciales. Soporta estados de carga y error\n * por paso, y confirma la creación cuando todos los pasos están completos.\n *\n * Cuando el consumidor pasa `documentClasses`, aparece un cuarto paso —la clase\n * del documento, entre compañía y centro de operación— para las superficies que\n * sirven a más de una clase. Es opt-in: sin ese prop, el render y el\n * comportamiento son los de siempre.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - DocumentCreationWizardProps, WizardOption\n *\n * @example\n * ```tsx\n * <DocumentCreationWizard\n *   open={showWizard}\n *   onClose={() => setShowWizard(false)}\n *   companies={[{ id: '1', label: 'Siesa SAS' }]}\n *   onSelectCompany={(id) => setCompany(id)}\n *   onConfirm={() => createDocument()}\n *   {...otherProps}\n * />\n * ```\n */\nexport function DocumentCreationWizard({\n  open,\n  onClose,\n  companies,\n  selectedCompany,\n  onSelectCompany,\n  documentClasses,\n  selectedDocumentClass,\n  onSelectDocumentClass,\n  operationCenters,\n  selectedCO,\n  onSelectCO,\n  documentTypes,\n  selectedType,\n  onSelectType,\n  onConfirm,\n  loadingStep,\n  errorStep,\n  className,\n}: DocumentCreationWizardProps) {\n  const { t } = useMasterDocumentTranslation();\n  // Close on Escape\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  if (!open) return null;\n\n  // ── Paso de clase: opt-in ────────────────────────────────\n  // Sin `documentClasses` (ausente o vacío) NADA de lo que sigue se activa: no se\n  // renderiza el bloque, `canConfirm` mantiene sus tres términos, el centro de\n  // operación conserva su única condición de deshabilitado y los índices de paso\n  // siguen siendo 1/2/3. Es la garantía para los consumidores ya en producción.\n  const hasClassStep = !!documentClasses && documentClasses.length > 0;\n\n  // Los índices de paso son POSICIONALES: cuando la clase está activa toma el 2 y\n  // corre el centro de operación al 3 y el tipo al 4.\n  const coStepIndex = hasClassStep ? 3 : 2;\n  const typeStepIndex = hasClassStep ? 4 : 3;\n\n  const canConfirm = !!selectedCompany && !!selectedCO && !!selectedType\n    && (!hasClassStep || !!selectedDocumentClass);\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        onClick={onClose}\n        aria-hidden=\"true\"\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[620px] max-h-[85vh] overflow-hidden',\n          'bg-bg-primary rounded-2xl',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          className,\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={t('master_document.wizard.aria')}\n      >\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-b border-border-secondary dark:border-dark-border-primary\">\n          <div>\n            <h2 className=\"text-lg font-bold text-content-primary dark:text-dark-content-primary\">\n              {t('master_document.wizard.aria')}\n            </h2>\n            <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary mt-0.5\">\n              {t('master_document.wizard.subtitle')}\n            </p>\n          </div>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"p-1.5 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XIcon className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/* Body */}\n        <div className=\"overflow-y-auto px-6 py-5 flex flex-col gap-5\" style={{ maxHeight: 'calc(85vh - 140px)' }}>\n          {/* Step 1: Company */}\n          <div>\n            <label className=\"block text-xs font-semibold uppercase tracking-[0.06em] text-content-secondary mb-2\">\n              {t('master_document.wizard.company')} <span className=\"text-error-content\">*</span>\n            </label>\n            {loadingStep === 1 ? (\n              <StepSkeleton />\n            ) : errorStep?.step === 1 ? (\n              <StepError message={errorStep.message} onRetry={errorStep.onRetry} />\n            ) : (\n              <WizardOptionLookup\n                entity=\"wizard-companies\"\n                label={t('master_document.wizard.company')}\n                options={companies}\n                value={selectedCompany}\n                onChange={onSelectCompany}\n                placeholder={t('master_document.wizard.selectCompany')}\n              />\n            )}\n          </div>\n\n          {/* Step 2 (opcional): Document Class */}\n          {/* Estructuralmente igual al bloque de compañía: un `select` que no\n              depende de ningún paso anterior. Las etiquetas de clase son frases\n              largas (\"Nota crédito de venta de solo valor\"), así que la grilla de\n              OptionCard del paso de tipo no encaja aquí. */}\n          {hasClassStep && (\n            <div>\n              <label className=\"block text-xs font-semibold uppercase tracking-[0.06em] text-content-secondary mb-2\">\n                {t('master_document.wizard.documentClass')} <span className=\"text-error-content\">*</span>\n              </label>\n              {loadingStep === 2 ? (\n                <StepSkeleton />\n              ) : errorStep?.step === 2 ? (\n                <StepError message={errorStep.message} onRetry={errorStep.onRetry} />\n              ) : (\n                <select\n                  className=\"w-full rounded-md border border-border-primary bg-bg-primary px-3 py-2.5 text-sm text-content-primary focus:outline-hidden focus:border-primary-600 focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:border-dark-border-primary dark:bg-dark-bg-primary dark:text-dark-content-primary\"\n                  value={selectedDocumentClass ?? ''}\n                  onChange={(e) => onSelectDocumentClass?.(e.target.value)}\n                  aria-label={t('master_document.wizard.documentClass')}\n                >\n                  <option value=\"\" disabled>{t('master_document.wizard.selectDocumentClass')}</option>\n                  {documentClasses.map((dc) => (\n                    <option key={dc.id} value={dc.id}>{dc.label}</option>\n                  ))}\n                </select>\n              )}\n            </div>\n          )}\n\n          {/* Step 2 (o 3 con paso de clase): Operation Center */}\n          <div>\n            <label className=\"block text-xs font-semibold uppercase tracking-[0.06em] text-content-secondary mb-2\">\n              {t('master_document.wizard.operationCenter')} <span className=\"text-error-content\">*</span>\n            </label>\n            {loadingStep === coStepIndex ? (\n              <StepSkeleton />\n            ) : errorStep?.step === coStepIndex ? (\n              <StepError message={errorStep.message} onRetry={errorStep.onRetry} />\n            ) : (\n              <WizardOptionLookup\n                entity=\"wizard-operation-centers\"\n                label={t('master_document.wizard.operationCenter')}\n                options={operationCenters}\n                value={selectedCO}\n                onChange={onSelectCO}\n                placeholder={t('master_document.wizard.selectOperationCenter')}\n                disabled={!selectedCompany || (hasClassStep && !selectedDocumentClass)}\n              />\n            )}\n          </div>\n\n          {/* Step 3 (o 4 con paso de clase): Document Type */}\n          <div>\n            <label className=\"block text-xs font-semibold uppercase tracking-[0.06em] text-content-secondary mb-2\">\n              {t('master_document.wizard.documentType')} <span className=\"text-error-content\">*</span>\n            </label>\n            {loadingStep === typeStepIndex ? (\n              <StepSkeleton />\n            ) : errorStep?.step === typeStepIndex ? (\n              <StepError message={errorStep.message} onRetry={errorStep.onRetry} />\n            ) : !selectedCO ? (\n              <p className=\"text-xs text-content-secondary italic\">\n                {t('master_document.wizard.selectOperationCenterHint')}\n              </p>\n            ) : (\n              <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-3\">\n                {documentTypes.map((dt) => (\n                  <OptionCard\n                    key={dt.id}\n                    option={dt}\n                    selected={dt.id === selectedType}\n                    onClick={() => onSelectType(dt.id)}\n                  />\n                ))}\n              </div>\n            )}\n          </div>\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-border-secondary dark:border-dark-border-primary\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"px-4 py-2 rounded-md text-sm font-semibold text-content-tertiary hover:bg-background-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary\"\n          >\n            {t('master_document.chrome.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={onConfirm}\n            disabled={!canConfirm}\n            className={clsx(\n              'px-5 py-2 rounded-md text-sm font-semibold transition-all duration-150 min-h-[36px]',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              canConfirm\n                ? 'bg-primary-inverse-background text-white hover:bg-primary-700 dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90'\n                : 'bg-border-primary text-content-secondary cursor-not-allowed dark:bg-dark-bg-secondary dark:text-dark-content-secondary',\n            )}\n          >\n            {t('master_document.statusHistory.action.create')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n\n// ─── Step Error ────────────────────────────────────────────\n\nfunction StepError({ message, onRetry }: { message: string; onRetry: () => void }) {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div className=\"flex items-center gap-3 px-4 py-3 rounded-xl bg-error-bg dark:bg-error-content/10\">\n      <span className=\"text-xs text-error-content\">{message}</span>\n      <button\n        type=\"button\"\n        onClick={onRetry}\n        className=\"px-3 py-1 rounded-md text-xs font-semibold text-error-content border border-error-border/30 hover:bg-error-content/10 transition-all duration-150 shrink-0 focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2\"\n      >\n        {t('master_document.chrome.retry')}\n      </button>\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport { XMarkIcon } from '@heroicons/react/24/outline';\nimport type { BulkConversionProgressProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { inlineActionButtonDanger } from './inlineActions';\n\nfunction SpinnerIcon({ className }: { className?: string }) {\n  return (\n    <svg\n      className={clsx('animate-spin', className)}\n      xmlns=\"http://www.w3.org/2000/svg\"\n      fill=\"none\"\n      viewBox=\"0 0 24 24\"\n      aria-hidden=\"true\"\n    >\n      <circle className=\"opacity-25\" cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"4\" />\n      <path\n        className=\"opacity-75\"\n        fill=\"currentColor\"\n        d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z\"\n      />\n    </svg>\n  );\n}\n\nfunction CheckCircleIcon({ className }: { className?: string }) {\n  return (\n    <svg className={className} xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" strokeWidth={2} aria-hidden=\"true\">\n      <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z\" />\n    </svg>\n  );\n}\n\nfunction XCircleIcon({ className }: { className?: string }) {\n  return (\n    <svg className={className} xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" strokeWidth={2} aria-hidden=\"true\">\n      <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z\" />\n    </svg>\n  );\n}\n\nexport function BulkConversionProgress({\n  job,\n  onCancel,\n  onClose,\n  onViewResults,\n  className,\n}: BulkConversionProgressProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { status, total, processed, results } = job;\n\n  const failedCount = results.filter((r) => r.status === 'failed').length;\n  const partialCount = results.filter((r) => r.status === 'partial').length;\n  const pct = total > 0 ? (processed / total) * 100 : 0;\n  const isActive = status === 'running' || status === 'pending';\n  const isTerminal = status === 'completed' || status === 'failed' || status === 'cancelled';\n\n  // \"Completado — 2 errores, 1 parcial\": son DOS contadores independientes en una\n  // sola frase y `count` solo resuelve un plural, así que cada fragmento se\n  // pluraliza por separado y se inyecta como `{detail}`.\n  const conErrores = t('master_document.crossing.bulkErrorCount', { count: failedCount });\n  const conParciales = t('master_document.crossing.bulkPartialCount', { count: partialCount });\n  const detalleCompletado =\n    failedCount > 0 && partialCount > 0\n      ? `${conErrores}, ${conParciales}`\n      : failedCount > 0\n        ? conErrores\n        : conParciales;\n\n  return (\n    <div\n      className={clsx(\n        'fixed bottom-5 right-5 z-[200] w-80',\n        'bg-bg-primary dark:bg-dark-bg-primary',\n        'rounded-2xl',\n        'shadow-[0_8px_32px_rgba(0,0,0,.18)] dark:shadow-[0_8px_32px_rgba(0,0,0,.5)]',\n        'border border-border-primary dark:border-dark-border-primary',\n        'overflow-hidden',\n        className,\n      )}\n      role=\"status\"\n      aria-live=\"polite\"\n    >\n      {/* Header */}\n      <div className=\"flex items-center gap-2 px-4 py-3 bg-background-secondary dark:bg-dark-bg-secondary\">\n        {isActive && (\n          <SpinnerIcon className=\"w-4 h-4 shrink-0 text-primary-custom-600\" />\n        )}\n        {status === 'completed' && (\n          <CheckCircleIcon className=\"w-4 h-4 shrink-0 text-green-600\" />\n        )}\n        {status === 'failed' && (\n          <XCircleIcon className=\"w-4 h-4 shrink-0 text-red-600\" />\n        )}\n        {status === 'cancelled' && (\n          <XCircleIcon className=\"w-4 h-4 shrink-0 text-zinc-400\" />\n        )}\n        <span className=\"flex-1 text-sm font-bold text-content-primary dark:text-dark-content-primary\">\n          {t('master_document.crossing.bulkTitle')}\n        </span>\n        {isTerminal && (\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'p-1 rounded-md transition-colors',\n              'text-content-secondary hover:bg-border-primary',\n              'dark:text-dark-content-secondary dark:hover:bg-dark-bg-primary',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          </button>\n        )}\n      </div>\n\n      {/* Body */}\n      <div className=\"px-4 py-3 space-y-3\">\n        {/* Progress bar */}\n        <div className=\"space-y-1.5\">\n          <div className=\"flex justify-between text-xs text-content-secondary dark:text-dark-content-secondary\">\n            <span>{t('master_document.crossing.bulkProgress')}</span>\n            <span className=\"tabular-nums\">{processed} / {total}</span>\n          </div>\n          <div className=\"w-full h-2 rounded-full bg-border-primary dark:bg-dark-border-primary overflow-hidden\">\n            <div\n              className={clsx(\n                'h-full rounded-full transition-all duration-500',\n                status === 'completed' ? 'bg-green-500' :\n                status === 'failed' ? 'bg-red-500' :\n                status === 'cancelled' ? 'bg-zinc-400' : 'bg-primary-custom-500',\n              )}\n              style={{ width: `${pct}%` }}\n            />\n          </div>\n        </div>\n\n        {/* Status message */}\n        {isActive && (\n          <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">\n            {t('master_document.crossing.bulkBackgroundNote')}\n          </p>\n        )}\n        {status === 'completed' && (\n          <p className={clsx('text-xs font-semibold', failedCount > 0 ? 'text-red-600 dark:text-red-400' : partialCount > 0 ? 'text-amber-600 dark:text-amber-400' : 'text-green-600 dark:text-green-400')}>\n            {failedCount > 0 || partialCount > 0\n              ? t('master_document.crossing.bulkCompletedWith', { detail: detalleCompletado })\n              : t('master_document.crossing.bulkCompleted')}\n          </p>\n        )}\n        {status === 'failed' && (\n          <p className=\"text-xs font-semibold text-red-600 dark:text-red-400\">\n            {t('master_document.crossing.bulkFailed')}\n          </p>\n        )}\n        {status === 'cancelled' && (\n          <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">\n            {t('master_document.crossing.bulkCancelled', { count: processed })}\n          </p>\n        )}\n\n        {/* Actions */}\n        <div className=\"flex items-center justify-end gap-2 pt-1\">\n          {isActive && (\n            <button\n              type=\"button\"\n              onClick={onCancel}\n              className={inlineActionButtonDanger}\n            >\n              {t('master_document.chrome.cancel')}\n            </button>\n          )}\n          {isTerminal && results.length > 0 && (\n            <button\n              type=\"button\"\n              onClick={onViewResults}\n              className={clsx(\n                'px-3 py-1.5 rounded-md text-xs font-semibold transition-colors',\n                'bg-primary-inverse-background text-primary-inverse-content hover:bg-primary-custom-700',\n                'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              )}\n            >\n              {t('master_document.crossing.bulkViewResults')}\n            </button>\n          )}\n        </div>\n      </div>\n    </div>\n  );\n}\n","import { useEffect } from 'react';\nimport { clsx } from 'clsx';\nimport { XMarkIcon } from '@heroicons/react/24/outline';\nimport type { BulkResultsSummaryProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\nexport function BulkResultsSummary({\n  open,\n  results,\n  onRetryFailed,\n  onClose,\n  className,\n}: BulkResultsSummaryProps) {\n  const { t } = useMasterDocumentTranslation();\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  if (!open) return null;\n\n  const successCount = results.filter((r) => r.status === 'success').length;\n  const partialCount = results.filter((r) => r.status === 'partial').length;\n  const failedCount = results.filter((r) => r.status === 'failed').length;\n  const failedIds = results.filter((r) => r.status === 'failed').map((r) => r.sourceDocumentId);\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n        onClick={onClose}\n      />\n\n      {/* Panel */}\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'max-w-2xl w-[calc(100%-32px)]',\n          'bg-bg-primary dark:bg-dark-bg-primary',\n          'rounded-2xl',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:shadow-none dark:border dark:border-dark-border-primary',\n          'overflow-hidden',\n          className,\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"bulk-results-title\"\n      >\n        {/* Header */}\n        <div className=\"flex items-center gap-3 px-6 py-4 border-b border-border-primary dark:border-dark-border-primary\">\n          <h2\n            id=\"bulk-results-title\"\n            className=\"flex-1 text-base font-bold text-content-primary dark:text-dark-content-primary\"\n          >\n            {t('master_document.crossing.bulkResultsTitle')}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'p-1 rounded-md transition-colors',\n              'text-content-secondary hover:bg-background-secondary',\n              'dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          </button>\n        </div>\n\n        <div className=\"px-6 py-4 space-y-4\">\n          {/* Summary chips */}\n          <div className=\"flex items-center gap-2 flex-wrap\">\n            <span className=\"inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400\">\n              {t('master_document.crossing.bulkSuccessCount', { count: successCount })}\n            </span>\n            {partialCount > 0 && (\n              <span className=\"inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400\">\n                {t('master_document.crossing.bulkPartialCount', { count: partialCount })}\n              </span>\n            )}\n            {failedCount > 0 && (\n              <span className=\"inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400\">\n                {t('master_document.crossing.bulkWithErrorCount', { count: failedCount })}\n              </span>\n            )}\n          </div>\n\n          {/* Results table */}\n          <div className=\"overflow-auto max-h-72 rounded-lg border border-border-primary dark:border-dark-border-primary\">\n            <table className=\"w-full text-sm\">\n              <thead className=\"bg-background-secondary dark:bg-dark-bg-secondary sticky top-0\">\n                <tr>\n                  <th className=\"px-3 py-2 text-left text-xs font-bold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary\">\n                    {t('master_document.crossing.bulkColumn.sourceDocument')}\n                  </th>\n                  <th className=\"px-3 py-2 text-left text-xs font-bold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary\">\n                    {t('master_document.crossing.bulkColumn.result')}\n                  </th>\n                  <th className=\"px-3 py-2 text-left text-xs font-bold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary\">\n                    {t('master_document.crossing.bulkColumn.generatedDocument')}\n                  </th>\n                  <th className=\"px-3 py-2 text-left text-xs font-bold uppercase tracking-wide text-content-secondary dark:text-dark-content-secondary\">\n                    {t('master_document.chrome.error')}\n                  </th>\n                </tr>\n              </thead>\n              <tbody>\n                {results.map((result, idx) => (\n                  <tr\n                    key={result.sourceDocumentId}\n                    className={clsx(\n                      'border-t border-border-primary dark:border-dark-border-primary',\n                      idx % 2 === 0 ? 'bg-bg-primary dark:bg-dark-bg-primary' : 'bg-background-secondary dark:bg-dark-bg-secondary',\n                    )}\n                  >\n                    <td className=\"px-3 py-2.5 text-sm text-content-primary dark:text-dark-content-primary font-medium whitespace-nowrap\">\n                      {result.sourceDocumentNumber ?? result.sourceDocumentId}\n                    </td>\n                    <td className=\"px-3 py-2.5 whitespace-nowrap\">\n                      {result.status === 'success' ? (\n                        <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400\">\n                          {t('master_document.crossing.bulkStatus.success')}\n                        </span>\n                      ) : result.status === 'partial' ? (\n                        <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400\">\n                          {t('master_document.lineFulfillment.partial')}\n                        </span>\n                      ) : (\n                        <span className=\"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400\">\n                          {t('master_document.chrome.error')}\n                        </span>\n                      )}\n                    </td>\n                    {/*\n                      Número del documento hijo. NO es accionable: no tiene `onClick` ni lo\n                      tuvo nunca, así que el `cursor-pointer` + `hover:underline` que llevaba\n                      era una afordancia falsa — se leía como un enlace que al pulsar no hacía\n                      nada. Se pinta como el dato que es, con la cifra tabular que el canon\n                      usa para códigos.\n                    */}\n                    <td className=\"px-3 py-2.5\">\n                      {result.status !== 'failed' && result.childDocumentNumber ? (\n                        <span className=\"font-medium text-sm tabular-nums text-content-primary dark:text-dark-content-primary\">\n                          {result.childDocumentNumber}\n                        </span>\n                      ) : (\n                        <span className=\"text-content-secondary dark:text-dark-content-secondary\">—</span>\n                      )}\n                    </td>\n                    <td className=\"px-3 py-2.5 max-w-[200px]\">\n                      {result.status === 'partial' && result.blockedLines && result.blockedLines.length > 0 ? (\n                        <span\n                          className=\"text-xs text-amber-600 dark:text-amber-400 truncate block max-w-[200px]\"\n                          title={t('master_document.crossing.blockedLinesCount', {\n                            count: result.blockedLines.length,\n                          })}\n                        >\n                          {t('master_document.crossing.bulkBlockedLines', { count: result.blockedLines.length })}\n                        </span>\n                      ) : result.status === 'failed' && result.errorMessage ? (\n                        <span\n                          className=\"text-xs text-red-600 dark:text-red-400 truncate block max-w-[200px]\"\n                          title={result.errorMessage}\n                        >\n                          {result.errorMessage}\n                        </span>\n                      ) : (\n                        <span className=\"text-content-secondary dark:text-dark-content-secondary\">—</span>\n                      )}\n                    </td>\n                  </tr>\n                ))}\n              </tbody>\n            </table>\n          </div>\n\n          {/* Retry section */}\n          {failedCount > 0 && (\n            <div className=\"flex items-center justify-between gap-3 pt-1 border-t border-border-primary dark:border-dark-border-primary\">\n              <span className=\"text-sm text-content-secondary dark:text-dark-content-secondary\">\n                {t('master_document.crossing.bulkSelectFailed')}\n              </span>\n              <button\n                type=\"button\"\n                onClick={() => onRetryFailed(failedIds)}\n                className={clsx(\n                  'px-3 py-1.5 rounded-md text-xs font-semibold transition-colors',\n                  'bg-primary-inverse-background text-primary-inverse-content hover:bg-primary-custom-700',\n                  'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n                  'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                  'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n                )}\n              >\n                {t('master_document.crossing.bulkRetryFailed', { count: failedCount })}\n              </button>\n            </div>\n          )}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end px-6 py-4 border-t border-border-primary dark:border-dark-border-primary\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold transition-colors',\n              'border border-border-primary text-content-secondary hover:bg-background-secondary',\n              'dark:border-dark-border-primary dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            {t('master_document.chrome.close')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { useState, useEffect, useRef, useCallback } from 'react';\nimport type {\n  BulkConversionJob,\n  BulkConversionJobStatus,\n  BulkConversionResult,\n  BulkConversionResultStatus,\n} from '../MasterDocument.types';\nimport { resolveCrossingError } from './crossingFetch';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport type { CrossingFetch } from './crossingFetch';\n\ninterface UseBulkConversionOptions {\n  /**\n   * Salida HTTP del bulk-convert. Enruta por `adapter.genericFetch` (auth,\n   * baseUrl, remapeo de rutas) — ver {@link createCrossingFetch}.\n   */\n  crossingFetch: CrossingFetch;\n}\n\ninterface UseBulkConversionReturn {\n  job: BulkConversionJob | null;\n  showResults: boolean;\n  lastClassId: string | null;\n  error: string | undefined;\n  startJob: (\n    classId: string,\n    documentIds: string[],\n    headerValues?: Record<string, unknown>,\n  ) => Promise<void>;\n  cancelJob: () => Promise<void>;\n  closeProgress: () => void;\n  openResults: () => void;\n  closeResults: () => void;\n  retryFailed: (failedIds: string[]) => Promise<void>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeResultStatus(raw: any): BulkConversionResultStatus {\n  // Acepta el status textual del backend (Successful/Partial/Failed) o el\n  // booleano `success` legado.\n  const s = String(raw.status ?? '').toLowerCase();\n  if (s === 'partial') return 'partial';\n  if (s === 'failed' || s === 'error') return 'failed';\n  if (s === 'successful' || s === 'success' || s === 'completed') return 'success';\n  if (typeof raw.success === 'boolean') return raw.success ? 'success' : 'failed';\n  // Sin status explícito: si hay líneas bloqueadas pero se generó hijo → partial.\n  const blocked = raw.blocked_lines ?? raw.blockedLines;\n  if (Array.isArray(blocked) && blocked.length > 0 && (raw.generated_document_id ?? raw.child_document_id)) {\n    return 'partial';\n  }\n  return 'failed';\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction mapResult(raw: any): BulkConversionResult {\n  return {\n    sourceDocumentId: raw.source_document_id ?? raw.parent_document_id,\n    sourceDocumentNumber: raw.source_document_number,\n    status: normalizeResultStatus(raw),\n    childDocumentId: raw.generated_document_id ?? raw.child_document_id,\n    childDocumentNumber: raw.generated_document_number,\n    blockedLines: raw.blocked_lines ?? raw.blockedLines,\n    errorCode: raw.error_code ?? raw.errorCode,\n    errorMessage: raw.error ?? raw.error_reason ?? raw.errorReason,\n  };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeJobStatus(raw: any): BulkConversionJobStatus {\n  const s = String(raw ?? '').toLowerCase();\n  if (s === 'pending') return 'pending';\n  if (s === 'completed' || s === 'complete') return 'completed';\n  if (s === 'failed') return 'failed';\n  if (s === 'cancelled' || s === 'canceled') return 'cancelled';\n  return 'running';\n}\n\n/** Estados terminales: el polling se detiene al alcanzarlos. */\nfunction isTerminalJobStatus(status: BulkConversionJobStatus): boolean {\n  return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n\nexport function useBulkConversion({ crossingFetch }: UseBulkConversionOptions): UseBulkConversionReturn {\n  // Traduce los errores que genera el kit; los que trae el backend pasan intactos.\n  const { t } = useMasterDocumentTranslation();\n  const [job, setJob] = useState<BulkConversionJob | null>(null);\n  const [showResults, setShowResults] = useState(false);\n  const [lastClassId, setLastClassId] = useState<string | null>(null);\n  const [lastHeaderValues, setLastHeaderValues] = useState<Record<string, unknown> | undefined>(undefined);\n  const [error, setError] = useState<string | undefined>(undefined);\n  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);\n\n  const stopPolling = useCallback(() => {\n    if (intervalRef.current !== null) {\n      clearInterval(intervalRef.current);\n      intervalRef.current = null;\n    }\n  }, []);\n\n  const pollJob = useCallback(async (jobId: string) => {\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const payload: any = await crossingFetch<any>(\n        'GET',\n        `/api/v1/crossing/jobs/${encodeURIComponent(jobId)}`,\n      );\n      const updated: BulkConversionJob = {\n        jobId: payload.job_id,\n        status: normalizeJobStatus(payload.status),\n        total: payload.total,\n        processed: payload.processed,\n        results: (payload.results ?? []).map(mapResult),\n      };\n      setJob(updated);\n      if (isTerminalJobStatus(updated.status)) {\n        stopPolling();\n      }\n    } catch {\n      // El polling es transitorio: un fallo puntual no detiene el seguimiento\n      // (el siguiente tick reintenta). Los fallos terminales se ven al cancelar.\n    }\n  }, [crossingFetch, stopPolling]);\n\n  const startJob = useCallback(async (\n    classId: string,\n    documentIds: string[],\n    headerValues?: Record<string, unknown>,\n  ) => {\n    stopPolling();\n    setShowResults(false);\n    setError(undefined);\n    setLastClassId(classId);\n    setLastHeaderValues(headerValues);\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const body: any = { document_ids: documentIds, child_class_id: classId };\n      // Header común (FE-07): solo se envía si el consumidor lo provee.\n      if (headerValues && Object.keys(headerValues).length > 0) {\n        body.header_values = headerValues;\n      }\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const payload: any = await crossingFetch<any>('POST', '/api/v1/crossing/bulk-convert', body);\n      const newJob: BulkConversionJob = {\n        jobId: payload.job_id,\n        status: 'running',\n        total: payload.total,\n        processed: 0,\n        results: [],\n      };\n      setJob(newJob);\n      intervalRef.current = setInterval(() => {\n        void pollJob(payload.job_id);\n      }, 3000);\n    } catch (err) {\n      setError(resolveCrossingError(err, t).message);\n    }\n  }, [crossingFetch, stopPolling, pollJob, t]);\n\n  const cancelJob = useCallback(async () => {\n    if (!job) return;\n    stopPolling();\n    try {\n      await crossingFetch('DELETE', `/api/v1/crossing/jobs/${encodeURIComponent(job.jobId)}`);\n      setJob((prev) => prev ? { ...prev, status: 'cancelled' } : null);\n    } catch (err) {\n      setError(resolveCrossingError(err, t).message);\n    }\n  }, [job, crossingFetch, stopPolling, t]);\n\n  const closeProgress = useCallback(() => {\n    stopPolling();\n    setJob(null);\n    setShowResults(false);\n    setError(undefined);\n  }, [stopPolling]);\n\n  const openResults = useCallback(() => setShowResults(true), []);\n  const closeResults = useCallback(() => setShowResults(false), []);\n\n  const retryFailed = useCallback(async (failedIds: string[]) => {\n    if (!lastClassId) return;\n    await startJob(lastClassId, failedIds, lastHeaderValues);\n  }, [lastClassId, lastHeaderValues, startJob]);\n\n  useEffect(() => {\n    return () => stopPolling();\n  }, [stopPolling]);\n\n  return { job, showResults, lastClassId, error, startJob, cancelJob, closeProgress, openResults, closeResults, retryFailed };\n}\n","import { useState, useCallback, useEffect, useMemo, useRef, type ReactNode } from 'react';\n\nimport { DocumentList } from '../DocumentList';\nimport { DocumentCreationWizard } from '../DocumentCreationWizard';\nimport { CreateFromSourceModal } from '../CreateFromSourceModal';\nimport { ConfirmDialog } from '../DocumentModalList';\nimport { BulkConversionProgress } from '../BulkConversionProgress';\nimport { BulkResultsSummary } from '../BulkResultsSummary';\nimport { SmartMasterDocument } from './SmartMasterDocument';\nimport type { DocumentNavigationContext } from './SmartMasterDocument';\nimport { StateBadge } from '../StateBadge';\nimport { toast } from '../../Toast';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport { classifyError } from './userFacingError';\nimport type { TranslateFn } from '../i18nFactory';\nimport { useBulkConversion } from './useBulkConversion';\nimport { createCrossingFetch } from './crossingFetch';\nimport { isFilterValueEmpty } from '../lookupFilters';\nimport {\n  useMasterDocumentAdapter,\n  useMasterDocumentTemplate,\n  useIconRegistry,\n  useUserPermissions,\n} from '../provider/MasterDocumentProvider';\nimport { useMasterDocumentPrint } from '../printing/MasterDocumentPrintProvider';\nimport type { PrintContext } from '../printing/MasterDocumentPrinting.types';\n\nimport type {\n  DocumentListColumn,\n  DocumentListColumnFilter,\n  DocumentListCompany,\n  FilterPill,\n  SearchField,\n  WizardOption,\n  CrossingClassOption,\n  RowAction,\n} from '../MasterDocument.types';\nimport type { DocumentListRequest, DocumentState } from '../adapter/MasterDocumentAdapter.types';\nimport type {\n  DocumentListColumnTemplate,\n  DocumentListFilterTemplate,\n  DocumentListPillTemplate,\n  SearcherFieldConfig,\n} from '../template/MasterDocumentTemplate.types';\n\n// ════════════════════════════════════════════════════════════\n// PROPS\n// ════════════════════════════════════════════════════════════\n\n/**\n * Contexto de creación entregado a `onCreateDocument`.\n *\n * Coincide con los cuatro argumentos de `adapter.getNewDocument` /\n * `adapter.createDocument`, así que la ruta destino del host puede resolver el\n * estado inicial por su cuenta, sin datos adicionales y sin depender de estado\n * en memoria que un F5 destruiría.\n */\nexport interface MasterDocumentPageCreateContext {\n  /**\n   * Clase del documento ya resuelta: la elegida en el paso de clase del wizard cuando el\n   * consumidor pasa `documentClasses`; si no, la prop `documentClass` o\n   * `template.identity.documentClass`.\n   */\n  documentClass: string;\n  /** Compañía elegida en el wizard. */\n  companyId: string;\n  /** Centro de operación elegido en el wizard. */\n  operationCenterId: string;\n  /** Tipo de documento elegido en el wizard. */\n  documentTypeId: string;\n}\n\nexport interface MasterDocumentPageProps {\n  /** Clase del documento. Fallback: template.identity.documentClass */\n  documentClass?: string;\n\n  /**\n   * Clases que esta superficie puede crear. Habilita el paso de CLASE en el\n   * wizard, entre compañía y centro de operación.\n   *\n   * Solo tiene sentido cuando una misma página sirve a más de una clase (p.ej.\n   * nota crédito de venta y nota crédito de venta de solo valor): la clase no se\n   * puede derivar del tipo de documento —la relación es N:M— así que pasa a ser\n   * un dato que captura el usuario. **Ausente ⇒ nada cambia**: la clase sigue\n   * siendo la constante de `documentClass` / `template.identity.documentClass`.\n   *\n   * Se espera la lista ya filtrada por permisos de creación del usuario: el kit\n   * no la filtra. Con una sola clase, la página la preselecciona.\n   *\n   * `documentClass` y `documentClasses` son alternativas, no complementos: con este\n   * prop presente, `documentClass` queda inerte.\n   *\n   * ⚠️ Si la lista se resuelve de forma asíncrona, NO montes la página hasta tenerla.\n   * Un array ausente o vacío equivale a \"superficie de una sola clase\", así que\n   * durante la carga el wizard mostraría tres pasos y crearía el documento con la\n   * clase pineada. El fallo es silencioso: nace un documento de la clase equivocada.\n   *\n   * Cuando está presente, la clase ELEGIDA es la que viaja al filtro de tipos de\n   * documento, a `getNewDocument` y a `createDocument`; y el listado se pide para\n   * TODAS las clases declaradas (`filters.documentClasses`), porque un visor\n   * compartido lista los documentos de ambas.\n   */\n  documentClasses?: WizardOption[];\n\n  /** Compañía del contexto del usuario (obligatorio) */\n  companyId: string;\n\n  /** Centro de operación del contexto del usuario (obligatorio) */\n  operationCenterId: string;\n\n  /** Si se pasa, arranca directo en el documento (edit/view). Si no, en el listado. */\n  documentId?: string;\n\n  // ── Delegación de navegación al host (opcional) ──────────\n  //\n  // Ausentes estos props, la página resuelve la navegación EN LÍNEA sobre su propia\n  // ruta: comportamiento histórico, sin cambios para ningún consumidor actual.\n  // Presente uno, la página delega ESE camino en el host y no cambia de vista, de\n  // modo que una superficie pueda enrutar a su propia pantalla de detalle (p.ej.\n  // para montar bloques propios junto al documento).\n  //\n  // La delegación es por camino e independiente: los props ausentes conservan su\n  // comportamiento interno. Un host que delega el menú de fila pero no el clic de\n  // fila obtiene navegación mixta — normalmente conviene delegar los tres juntos.\n\n  /**\n   * Clic sobre una fila del listado.\n   * @default Abre el documento en línea, en modo edición.\n   */\n  onRowClick?: (row: Record<string, unknown>) => void;\n\n  /**\n   * Acción de fila «Ver detalle».\n   * @default Abre el documento en línea, en modo solo lectura.\n   */\n  onViewRow?: (row: Record<string, unknown>) => void;\n\n  /**\n   * Acción de fila «Editar».\n   * @default Abre el documento en línea, en modo edición.\n   */\n  onEditRow?: (row: Record<string, unknown>) => void;\n\n  /**\n   * URL del detalle de una fila, para que «Ver»/«Editar» se pinten como enlace y\n   * el usuario recupere Ctrl/⌘+clic, clic con la rueda y «Abrir en pestaña nueva».\n   * Ver `DocumentListProps.getRowHref`.\n   *\n   * **Sólo hace falta declararlo cuando el HOST gobierna la navegación** (pasa\n   * `onEditRow`/`onViewRow` y navega con su router): ahí únicamente él conoce la\n   * ruta. Constrúyela con el router —`router.buildLocation({...}).href` en\n   * TanStack— y nunca concatenando cadenas, o en modo microfrontend el enlace\n   * saldría sin el basepath y la pestaña nueva caería en una ruta inexistente.\n   *\n   * @default Cuando la navegación la resuelve esta página en línea, calcula el\n   * `href` ella misma a partir de la URL actual (`?doc=<id>`, más `&mode=view`\n   * para «Ver»), que es exactamente la URL que ya escribe al abrir el detalle y\n   * la que restaura al montar.\n   */\n  getRowHref?: (row: Record<string, unknown>, action: 'view' | 'edit') => string | undefined;\n\n  /**\n   * Confirmación del wizard de creación.\n   *\n   * ⚠️ El documento AÚN NO EXISTE en el backend, así que no hay `documentId` que\n   * entregar. Cuando se delega, `adapter.getNewDocument` NO se invoca: la ruta\n   * destino resuelve el estado inicial con el contexto recibido, de modo que sea\n   * recargable por URL.\n   *\n   * @default Resuelve el estado inicial vía `getNewDocument` y abre el documento nuevo en línea.\n   */\n  onCreateDocument?: (context: MasterDocumentPageCreateContext) => void;\n\n  /**\n   * Documento recién creado desde el modal «crear a partir de origen».\n   *\n   * A diferencia de `onCreateDocument`, aquí el documento YA EXISTE en el backend\n   * y llega su id real.\n   *\n   * @default Abre el documento creado en línea, en modo edición.\n   */\n  onDocumentCreated?: (documentId: string) => void;\n\n  /**\n   * Navegación a OTRO documento existente pedida desde el detalle abierto en línea: un\n   * nodo del grafo de trazabilidad, o el documento recién generado por un cruce.\n   *\n   * @default Intercepta el pseudo-key `navigate_document:<id>` en su adapter y abre el documento en línea.\n   */\n  onNavigateToDocument?: (documentId: string, context: DocumentNavigationContext) => void;\n}\n\n// ════════════════════════════════════════════════════════════\n// HELPERS\n// ════════════════════════════════════════════════════════════\n\nfunction buildColumns(\n  templateCols: DocumentListColumnTemplate[],\n  formatCurrency: (n: number) => string,\n  searchers?: Record<string, SearcherFieldConfig>,\n): DocumentListColumn[] {\n  return templateCols.map((col) => {\n    const base: DocumentListColumn = {\n      key: col.key,\n      dataKey: col.dataKey,\n      header: col.header,\n      align: col.align,\n      mono: col.mono,\n      width: col.width,\n      ...(col.filter ? { filter: buildColumnFilter(col, searchers) } : {}),\n    };\n    if (col.badgeMap) {\n      const map = col.badgeMap;\n      base.render = (row) => {\n        const val = String(row[col.key] ?? '');\n        const badge = map[val];\n        if (!badge) return val;\n        return <StateBadge label={badge.label} bg={badge.bg} color={badge.color} />;\n      };\n    } else if (col.format === 'currency') {\n      base.render = (row) => {\n        const val = row[col.key];\n        return typeof val === 'number' ? formatCurrency(val) : String(val ?? '');\n      };\n    }\n    return base;\n  });\n}\n\n/**\n * Filtro declarado en una columna → el que consume la grilla.\n *\n * Para una columna FORÁNEA (`type: 'lookup'`) resuelve la config del searcher:\n * `searcher` inline → `searchers[searcherKey]` → `searchers[field]` →\n * `searchers[key de la columna]`. Reusar el searcher que el template ya declara\n * para el campo equivalente del detalle es el caso normal. Sin config que\n * resolver, el embudo degrada al input de texto.\n */\nfunction buildColumnFilter(\n  col: DocumentListColumnTemplate,\n  searchers?: Record<string, SearcherFieldConfig>,\n): DocumentListColumnFilter {\n  const f = col.filter!;\n  const searcher = f.type === 'lookup'\n    ? f.searcher ?? searchers?.[f.searcherKey ?? ''] ?? (f.field ? searchers?.[f.field] : undefined) ?? searchers?.[col.key]\n    : undefined;\n  return {\n    type: f.type,\n    field: f.field,\n    options: f.options as DocumentListColumnFilter['options'],\n    placeholder: f.placeholder,\n    ...(searcher ? { searcher: { ...searcher } } : {}),\n  };\n}\n\nfunction buildPills(pills: DocumentListPillTemplate[], activeKey: string): FilterPill[] {\n  return pills.map((p) => ({\n    key: p.key,\n    label: p.label,\n    bg: p.bg,\n    color: p.color,\n    active: p.key === activeKey,\n  }));\n}\n\nfunction buildSearchFields(filters: DocumentListFilterTemplate[]): SearchField[] {\n  return filters.map((f) => ({\n    key: f.key,\n    label: f.label,\n    type: f.type,\n    options: f.options as SearchField['options'],\n    placeholder: f.placeholder,\n  }));\n}\n\n// ════════════════════════════════════════════════════════════\n// GLOBAL COMPANY SENTINEL\n// ════════════════════════════════════════════════════════════\n\n/**\n * Centinela \"todas las compañías\" del selector del listado.\n *\n * Es una función y no una constante porque su `name` es texto visible: se resuelve\n * con el traductor en el idioma activo al montar. (La etiqueta ya seleccionada no\n * se re-traduce si el usuario cambia de idioma en caliente, porque vive en estado\n * de selección; el resto del listado sí.)\n */\nconst globalCompany = (t: TranslateFn): DocumentListCompany => ({\n  uuid: '000',\n  code: '000',\n  name: t('master_document.list.allCompanies'),\n});\n\n// ════════════════════════════════════════════════════════════\n// VIEWS\n// ════════════════════════════════════════════════════════════\n\n/**\n * Nombre del parámetro de URL que recuerda qué documento está abierto.\n *\n * El detalle se abre EN LÍNEA —la página no cambia de ruta— así que hasta ahora\n * vivía sólo en el estado de React: al refrescar (F5) el navegador volvía a montar\n * el componente en `{ kind: 'list' }` y el usuario aterrizaba en el listado,\n * perdiendo de vista el documento que estaba editando. Reflejarlo en la barra de\n * direcciones lo arregla y, de paso, hace el detalle enlazable y compartible.\n *\n * Se escribe con `replaceState` y NO con `pushState`: la página vive dentro del\n * router del host (TanStack Router en los MFE de comercial) y empujar entradas de\n * historial a su espalda le desincroniza la pila. `replaceState` sobre la MISMA\n * ruta sólo cambia la query, que es lo que el refresco necesita leer.\n */\nconst PARAM_DOCUMENTO = 'doc';\n/** `?mode=view` marca que el documento se abrió en sólo lectura. */\nconst PARAM_MODO = 'mode';\n\n/** Lee de la URL el documento que hay que restaurar al montar (o tras un `popstate`). */\nfunction leerVistaDeLaUrl(): { documentId: string; viewOnly: boolean } | null {\n  if (typeof window === 'undefined') return null;\n  const params = new URLSearchParams(window.location.search);\n  const id = params.get(PARAM_DOCUMENTO);\n  if (!id) return null;\n  return { documentId: id, viewOnly: params.get(PARAM_MODO) === 'view' };\n}\n\ntype View =\n  | { kind: 'list' }\n  | { kind: 'wizard' }\n  | { kind: 'document'; documentId: string; viewOnly?: boolean }\n  | { kind: 'new'; initialState: import('../adapter/MasterDocumentAdapter.types').DocumentState }\n  | { kind: 'create'; documentTypeId: string };\n\n// ════════════════════════════════════════════════════════════\n// COMPONENT\n// ════════════════════════════════════════════════════════════\n\n/**\n * MasterDocumentPage — Punto de entrada único por clase de documento.\n *\n * Recibe la compañía y centro de operación del contexto del usuario.\n * El wizard solo pide el tipo de documento — compañía y CO ya están seteados.\n *\n * @example\n * ```tsx\n * <MasterDocumentProvider template={pedidoVentaTemplate} adapter={adapter}>\n *   <MasterDocumentPage\n *     companyId=\"C001\"\n *     operationCenterId=\"CO001\"\n *   />\n * </MasterDocumentProvider>\n * ```\n *\n * @example Delegando la navegación a las rutas del host\n * ```tsx\n * // La página no abre el documento en línea: enruta a las pantallas propias del\n * // host, donde éste puede montar bloques que el kit no conoce.\n * <MasterDocumentPage\n *   companyId=\"C001\"\n *   operationCenterId=\"CO001\"\n *   // String(row.id): la fila es Record<string, unknown> y TS no interpola `unknown`.\n *   onRowClick={(row) => navigate(`/notas-credito/${String(row.id)}/edit`)}\n *   onViewRow={(row) => navigate(`/notas-credito/${String(row.id)}`)}\n *   onEditRow={(row) => navigate(`/notas-credito/${String(row.id)}/edit`)}\n *   onCreateDocument={(ctx) => navigate(`/notas-credito/nuevo?tipo=${ctx.documentTypeId}`)}\n *   onDocumentCreated={(id) => navigate(`/notas-credito/${id}/edit`)}\n *   onNavigateToDocument={(id, { reason }) =>\n *     navigate(reason === 'traceability' ? `/notas-credito/${id}` : `/notas-credito/${id}/edit`)}\n * />\n * ```\n */\nexport function MasterDocumentPage({\n  documentClass,\n  documentClasses,\n  companyId,\n  operationCenterId,\n  documentId,\n  onRowClick,\n  onViewRow,\n  onEditRow,\n  getRowHref,\n  onCreateDocument,\n  onDocumentCreated,\n  onNavigateToDocument,\n}: MasterDocumentPageProps) {\n  const { t } = useMasterDocumentTranslation();\n  const adapter = useMasterDocumentAdapter();\n  const template = useMasterDocumentTemplate();\n  const iconRegistry = useIconRegistry();\n  const print = useMasterDocumentPrint();\n  const userPermissions = useUserPermissions();\n\n  const docClass = documentClass ?? template.identity.documentClass;\n  const listConfig = template.list;\n  const wizardConfig = template.wizard;\n\n  // ── Paso de clase en el wizard (opt-in) ─────────────────\n  // `documentClasses` suele llegar como literal, con identidad nueva en cada\n  // render. Todo lo que alimente efectos o `useCallback` se deriva de una CLAVE\n  // primitiva estable: si no, `fetchList` cambiaría de identidad en cada render y\n  // el efecto del listado volvería a pedir la página sin parar.\n  const documentClassIdsKey = JSON.stringify(documentClasses?.map((dc) => dc.id) ?? []);\n  const documentClassIds = useMemo(\n    () => JSON.parse(documentClassIdsKey) as string[],\n    [documentClassIdsKey],\n  );\n  const hasClassStep = documentClassIds.length > 0;\n\n  // Con una sola clase permitida, la página la preselecciona: el estado del wizard\n  // es suyo, así que el consumidor no puede preseleccionarla desde fuera. Un\n  // `select` de una opción ya se lee como informativo.\n  const singleClassId = documentClassIds.length === 1 ? documentClassIds[0] : undefined;\n\n  // Índices POSICIONALES de los pasos del wizard (ver DocumentCreationWizardProps):\n  // con el paso de clase activo, la clase toma el 2 y corre CO al 3 y tipo al 4.\n  const coStepIndex = hasClassStep ? 3 : 2;\n  const typeStepIndex = hasClassStep ? 4 : 3;\n\n  // ── Create-from-source (caso A): ¿el listado abre el selector de origen? ──\n  // Activo cuando el template declara `createFromSource`, el adapter implementa\n  // `createFromSource` y existe una acción `actionType:'createFromSource'` en modo\n  // `create` cuyo permiso el usuario tiene. Entonces \"+ Nuevo\" abre el modal en\n  // lugar del wizard de documento en blanco.\n  const createFromSourceEnabled = useMemo(() => {\n    if (!template.createFromSource || !adapter.createFromSource) return false;\n    const registry = template.actionRegistry ?? {};\n    return Object.values(registry).some((entry) => {\n      if (entry.actionType !== 'createFromSource' || entry.createFromSource?.mode !== 'create') return false;\n      if (entry.permissionVisibility && userPermissions !== null && !userPermissions.includes(entry.permissionVisibility)) return false;\n      return true;\n    });\n  }, [template.createFromSource, template.actionRegistry, adapter, userPermissions]);\n\n  const [createFromSourceOpen, setCreateFromSourceOpen] = useState(false);\n\n  // ── ¿El listado ofrece la acción de crear? ───────────────\n  // `list.createPermission` gatea el afordance de crear completo — tanto el wizard\n  // de documento en blanco como el flujo `createFromSource`, porque lo que se gatea\n  // es \"crear\", no la ruta que toma. Sin permiso el botón queda AUSENTE, no\n  // deshabilitado: una acción que el usuario no puede ejecutar no se ofrece.\n  //\n  // Convención de permisos del kit: `userPermissions === null` significa que no hay\n  // sistema de permisos activo, y el fallback es permisivo (mismo criterio que\n  // `permissionVisibility` arriba). Así, un consumidor que no pasa `userPermissions`\n  // al provider no pierde su botón de crear.\n  //\n  // `list.canCreate === false` es una condición distinta y previa: esa clase no se\n  // crea a mano en absoluto —nace de un proceso de generación—, así que no hay\n  // permiso que declarar y ningún permiso la revierte.\n  const canCreate = useMemo(() => {\n    if (listConfig?.canCreate === false) return false;\n    const required = listConfig?.createPermission;\n    if (!required) return true;\n    if (userPermissions === null) return true;\n    return userPermissions.includes(required);\n  }, [listConfig?.canCreate, listConfig?.createPermission, userPermissions]);\n\n  // ── View state ──────────────────────────────────────────\n  // El `documentId` del host manda; si no lo hay, se restaura lo que diga la URL,\n  // que es lo que sobrevive a un refresco.\n  const [view, setView] = useState<View>(() => {\n    if (documentId) return { kind: 'document', documentId };\n    const deLaUrl = leerVistaDeLaUrl();\n    return deLaUrl\n      ? { kind: 'document', documentId: deLaUrl.documentId, viewOnly: deLaUrl.viewOnly }\n      : { kind: 'list' };\n  });\n\n  useEffect(() => {\n    if (documentId) setView({ kind: 'document', documentId });\n  }, [documentId]);\n\n  // Refleja la vista en la URL. Sólo el detalle: un asistente de creación a medias\n  // no se restaura —volver a un formulario en construcción con los datos perdidos\n  // desorienta más que aterrizar en el listado.\n  //\n  // No se toca la URL cuando el host gobierna la navegación (`documentId` por prop):\n  // ahí la ruta ya identifica al documento y escribir encima duplicaría el dato.\n  useEffect(() => {\n    if (typeof window === 'undefined' || documentId) return;\n    const url = new URL(window.location.href);\n    const actual = url.searchParams.get(PARAM_DOCUMENTO);\n    if (view.kind === 'document') {\n      url.searchParams.set(PARAM_DOCUMENTO, view.documentId);\n      if (view.viewOnly) url.searchParams.set(PARAM_MODO, 'view');\n      else url.searchParams.delete(PARAM_MODO);\n    } else if (actual === null) {\n      return; // nada que limpiar: evita un `replaceState` por cada render del listado\n    } else {\n      url.searchParams.delete(PARAM_DOCUMENTO);\n      url.searchParams.delete(PARAM_MODO);\n    }\n    const destino = `${url.pathname}${url.search}${url.hash}`;\n    if (destino !== `${window.location.pathname}${window.location.search}${window.location.hash}`) {\n      window.history.replaceState(window.history.state, '', destino);\n    }\n  }, [view, documentId]);\n\n  // Si el usuario usa atrás/adelante del navegador, la URL cambia sin que React se\n  // entere: sin esto la barra de direcciones y la pantalla dirían cosas distintas.\n  useEffect(() => {\n    if (typeof window === 'undefined' || documentId) return;\n    const alNavegar = () => {\n      const deLaUrl = leerVistaDeLaUrl();\n      setView(deLaUrl\n        ? { kind: 'document', documentId: deLaUrl.documentId, viewOnly: deLaUrl.viewOnly }\n        : { kind: 'list' });\n    };\n    window.addEventListener('popstate', alNavegar);\n    return () => window.removeEventListener('popstate', alNavegar);\n  }, [documentId]);\n\n  // ── List state ──────────────────────────────────────────\n  const [rows, setRows] = useState<Record<string, unknown>[]>([]);\n  const [totalCount, setTotalCount] = useState(0);\n  const [page, setPage] = useState(1);\n  const [activePill, setActivePill] = useState('all');\n  const [searchValues, setSearchValues] = useState<Record<string, unknown>>({});\n  const [searchOpen, setSearchOpen] = useState(false);\n  const [listLoading, setListLoading] = useState(false);\n  const [listError, setListError] = useState<string | undefined>();\n\n  // ── Company selector del listado ────────────────────────\n  const [availableCompanies, setAvailableCompanies] = useState<DocumentListCompany[]>([]);\n  const [selectedListCompany, setSelectedListCompany] = useState<DocumentListCompany>(() => globalCompany(t));\n\n  // El paginador del canon ofrece selector de «registros por página», así que el\n  // tamaño deja de ser una constante de la plantilla y pasa a ser estado. La\n  // plantilla sigue decidiendo el valor INICIAL.\n  const [pageSize, setPageSize] = useState(listConfig?.defaultPageSize ?? 10);\n\n  // Búsqueda básica (opt-in por plantilla, ver `DocumentListTemplateConfig.quickSearch`).\n  const quickSearchCfg = listConfig?.quickSearch;\n  const quickSearchEnabled = !!quickSearchCfg && quickSearchCfg.enabled !== false;\n  const [quickSearch, setQuickSearch] = useState('');\n  // Lo que se MANDA al servidor va con debounce: sin él, filtrar sería una\n  // petición por tecla. 350ms es el mismo retardo que usan los embudos de\n  // columna, aquí y en MasterCrud.\n  const [quickSearchApplied, setQuickSearchApplied] = useState('');\n  useEffect(() => {\n    if (!quickSearchEnabled) return;\n    const id = window.setTimeout(() => setQuickSearchApplied(quickSearch.trim()), 350);\n    return () => window.clearTimeout(id);\n  }, [quickSearch, quickSearchEnabled]);\n\n  // ── Wizard state ────────────────────────────────────────\n  const [companies, setCompanies] = useState<WizardOption[]>([]);\n  const [operationCenters, setOperationCenters] = useState<WizardOption[]>([]);\n  const [documentTypes, setDocumentTypes] = useState<WizardOption[]>([]);\n  const [selectedType, setSelectedType] = useState<string>();\n  const [companiesLoading, setCompaniesLoading] = useState(false);\n  const [cosLoading, setCosLoading] = useState(false);\n  const [typesLoading, setTypesLoading] = useState(false);\n  const [confirmLoading, setConfirmLoading] = useState(false);\n\n  // Filas con una acción destructiva en vuelo (P3 de LOADING-INTEGRATION.md).\n  // Es un conjunto y no un solo id porque `runRowAction` no serializa: nada\n  // impide disparar \"anular\" en una fila y \"eliminar\" en otra antes de que la\n  // primera responda, y con un único id la primera perdería su indicador.\n  const [busyRowIds, setBusyRowIds] = useState<string[]>([]);\n\n  const markRowBusy = useCallback((id: string, busy: boolean) => {\n    setBusyRowIds((prev) =>\n      busy ? (prev.includes(id) ? prev : [...prev, id]) : prev.filter((x) => x !== id),\n    );\n  }, []);\n\n  // Cache SWR: evita flash de loading cuando los datos ya fueron fetched antes\n  const wizardCacheRef = useRef<Map<string, WizardOption[]>>(new Map());\n\n  // Cancela respuestas en vuelo cuando el paso 1 o 2 cambia de selección\n  const latestCOKeyRef = useRef('');\n  const latestTypesKeyRef = useRef('');\n\n  // Selecciones locales del wizard (arrancan con el contexto, el usuario puede sobreescribir)\n  const [wizardCompanyId, setWizardCompanyId] = useState(companyId);\n  const [wizardCOId, setWizardCOId] = useState(operationCenterId);\n  // Clase elegida en el wizard. Solo se puebla cuando hay paso de clase; sin él\n  // queda `undefined` para siempre y `effectiveDocClass` es la clase de siempre.\n  const [wizardDocClass, setWizardDocClass] = useState<string | undefined>(singleClassId);\n\n  // Clase que gobierna la CREACIÓN: la elegida cuando la superficie sirve a varias\n  // clases, la pineada en cualquier otro caso. Un solo símbolo para no dejar\n  // ningún call site leyendo la constante por descuido.\n  const effectiveDocClass = wizardDocClass || docClass;\n\n  // ── Bulk conversion state ───────────────────────────────\n  const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);\n  const [bulkConvertOptions, setBulkConvertOptions] = useState<CrossingClassOption[]>([]);\n\n  // ── Bulk conversion ─────────────────────────────────────\n  const baseUrl = (adapter as any).baseUrl ?? 'http://localhost:5204'; // eslint-disable-line @typescript-eslint/no-explicit-any\n  const crossingFetch = useMemo(() => createCrossingFetch(adapter, baseUrl), [adapter, baseUrl]);\n  const {\n    job: bulkJob,\n    showResults: showBulkResults,\n    startJob: startBulkJob,\n    cancelJob: cancelBulkJob,\n    closeProgress: closeBulkProgress,\n    openResults: openBulkResults,\n    closeResults: closeBulkResults,\n    retryFailed: retryBulkFailed,\n  } = useBulkConversion({ crossingFetch });\n\n  useEffect(() => {\n    if (!template.crossing?.enabled) return;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    crossingFetch<any>('GET', '/api/v1/crossing/rules')\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      .then((payload: any) => {\n        const rules: any[] = Array.isArray(payload) ? payload : (payload?.data ?? []); // eslint-disable-line @typescript-eslint/no-explicit-any\n        setBulkConvertOptions(rules.map((rule: any) => ({ // eslint-disable-line @typescript-eslint/no-explicit-any\n          id: rule.child_class_id,\n          label: rule.child_class_label,\n          description: rule.description,\n        })));\n      })\n      .catch(() => {});\n  }, [template.crossing?.enabled, crossingFetch]);\n\n  // ── Fetch companies for list selector ──────────────────\n  useEffect(() => {\n    if (!adapter.listCompanies) return;\n    adapter.listCompanies()\n      .then((fetchedCompanies) => {\n        setAvailableCompanies(fetchedCompanies);\n        const match = fetchedCompanies.find((c) => String(c.uuid) === String(companyId));\n        if (match) {\n          setSelectedListCompany(match);\n        } else if (fetchedCompanies.length > 0) {\n          setSelectedListCompany(fetchedCompanies[0]);\n        }\n      })\n      .catch(() => { /* no-op */ });\n  }, [adapter]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  // ── Fetch list ──────────────────────────────────────────\n  // Filtros del embudo de cada columna, indexados por el campo que filtran.\n  // Van aparte de los del panel: son dos afordances distintos y \"Limpiar\" (del\n  // panel) no debe borrar en silencio un embudo que el usuario dejó activo.\n  const [columnFilters, setColumnFilters] = useState<Record<string, unknown>>({});\n\n  // Cambio de un embudo: recarga desde la página 1. La recarga la dispara el\n  // efecto del listado, porque `columnFilters` entra en las deps de `fetchList`\n  // (el control de texto ya viene con debounce, así que no hay una petición por\n  // tecla). Un valor vacío BORRA la clave en vez de mandar `{ campo: '' }`.\n  const handleColumnFilterChange = useCallback((field: string, value: unknown) => {\n    setColumnFilters((prev) => {\n      if (!isFilterValueEmpty(value)) return { ...prev, [field]: value };\n      if (!(field in prev)) return prev;\n      const next = { ...prev };\n      delete next[field];\n      return next;\n    });\n    setPage(1);\n  }, []);\n\n  const fetchList = useCallback(async (\n    pageNum: number,\n    pillKey: string,\n    filters: Record<string, unknown>,\n    companyFilter: DocumentListCompany = selectedListCompany,\n  ) => {\n    if (!adapter.listDocuments) return;\n    setListLoading(true);\n    setListError(undefined);\n    try {\n      const pillConfig = Array.isArray(listConfig?.pills) ? listConfig.pills.find((p) => p.key === pillKey) : undefined;\n      const isGlobal = String(companyFilter.uuid) === '000';\n      const request: DocumentListRequest = {\n        page: pageNum,\n        pageSize,\n        companyId: isGlobal ? undefined : String(companyFilter.uuid),\n        stateFilter: pillConfig?.stateFilter ?? undefined,\n        // Búsqueda básica. Sólo viaja si la plantilla la declaró: en una\n        // superficie sin `quickSearch` la caja no existe y el valor es ''.\n        search: quickSearchApplied || undefined,\n        filters: {\n          ...filters,\n          // El embudo de la columna es el control más inmediato: si coincide con\n          // un filtro del panel sobre el mismo campo, manda el de la columna.\n          ...columnFilters,\n          // Un visor compartido lista los documentos de TODAS sus clases, no de la\n          // que esté elegida en el wizard. Se manda `documentClasses` y se OMITE\n          // `documentClass`: enviar las dos sería un request que se contradice a sí\n          // mismo, y obligaría al adapter a decidir cuál gana.\n          ...(hasClassStep\n            ? { documentClasses: documentClassIds }\n            : { documentClass: docClass }),\n          operationCenterId,\n        },\n      };\n      const response = await adapter.listDocuments(request);\n      setRows(response.rows);\n      setTotalCount(response.totalCount);\n    } catch (err) {\n      setListError(String(err));\n    } finally {\n      setListLoading(false);\n    }\n  }, [adapter, listConfig, pageSize, docClass, hasClassStep, documentClassIds, selectedListCompany, operationCenterId, columnFilters, quickSearchApplied]);\n\n  useEffect(() => {\n    if (view.kind === 'list') {\n      fetchList(page, activePill, searchValues);\n    }\n  }, [view.kind, page, activePill, fetchList]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  // ── Wizard SWR helper ───────────────────────────────────\n  // Muestra datos cacheados inmediatamente (sin loading) y revalida en background.\n  // Solo muestra skeleton en el primer fetch real (sin cache).\n  // latestKeyRef: si la clave ya no coincide cuando llega la respuesta, la descarta\n  // (previene que un fetch en vuelo pise datos de una selección posterior).\n  const fetchWizardStep = useCallback(async (\n    entity: string,\n    request: Record<string, unknown>,\n    setter: (opts: WizardOption[]) => void,\n    mapper: (item: Record<string, unknown>) => WizardOption,\n    setLoading: (v: boolean) => void,\n    latestKeyRef?: React.MutableRefObject<string>,\n  ) => {\n    const key = `${entity}:${JSON.stringify(request)}`;\n    if (latestKeyRef) latestKeyRef.current = key;\n\n    const cached = wizardCacheRef.current.get(key);\n    if (cached) {\n      setter(cached);\n    } else {\n      setLoading(true);\n    }\n    try {\n      const res = await adapter.fetcher(entity, request as never);\n      if (latestKeyRef && latestKeyRef.current !== key) return;\n      const opts = (res.data as Record<string, unknown>[]).map(mapper);\n      wizardCacheRef.current.set(key, opts);\n      setter(opts);\n    } catch { /* no-op */ } finally {\n      // Se limpia el flag de carga en dos casos: cuando esta petición sigue siendo\n      // la vigente, y cuando ya NADIE está pidiendo (clave invalidada a '').\n      //\n      // Ese segundo caso era un skeleton eterno: al cancelar un paso sin lanzar otra\n      // petición —cambiar de clase o de compañía mientras los tipos cargaban, o\n      // reabrir el wizard con un fetch en vuelo— la respuesta descartada salía por\n      // el `return` de arriba y nadie apagaba el flag.\n      //\n      // Cuando la clave es OTRA petición en vuelo, el flag es suyo y lo apaga ella:\n      // apagarlo aquí haría desaparecer el skeleton mientras esa sigue cargando.\n      const idle = latestKeyRef?.current === '';\n      if (!latestKeyRef || latestKeyRef.current === key || idle) setLoading(false);\n    }\n  }, [adapter]);\n\n  // ── Wizard: sincroniza selecciones + carga datos cuando se abre ──\n  // El filtrado de los pasos dependientes (CO y tipo de documento) depende\n  // EXCLUSIVAMENTE del estado interno del wizard (wizardCompanyId/wizardCOId),\n  // nunca del listado/contexto. La única conveniencia es pre-seleccionar la\n  // compañía + CO del contexto cuando el listado está en una compañía específica;\n  // en \"Global\" (uuid='000') todo arranca vacío y deshabilitado.\n  useEffect(() => {\n    if (view.kind !== 'wizard') return;\n\n    const isGlobal = String(selectedListCompany.uuid) === '000';\n    const initialCompanyId = isGlobal ? '' : String(selectedListCompany.uuid);\n    // Con paso de clase, la clase arranca elegida solo si hay una sola.\n    const initialClass = hasClassStep ? singleClassId : undefined;\n    // El CO solo se pre-selecciona junto a una compañía específica. Sin compañía\n    // (caso Global) no se pre-llena para evitar un estado inconsistente.\n    //\n    // Tampoco se pre-llena mientras falte la clase: elegirla limpia el CO (la\n    // clase acota los tipos), así que mostrarlo relleno-y-deshabilitado solo para\n    // vaciarlo en el primer clic sería peor que dejarlo vacío.\n    const initialCOId = initialCompanyId && (!hasClassStep || initialClass) ? operationCenterId : '';\n    // Clase que filtra los tipos en esta apertura.\n    const initialDocClass = initialClass || docClass;\n\n    setWizardCompanyId(initialCompanyId);\n    setWizardCOId(initialCOId);\n    setWizardDocClass(initialClass);\n    setSelectedType(undefined);\n\n    // Los pasos dependientes arrancan vacíos; solo se llenan vía los fetches de\n    // abajo cuando hay selección en el wizard. Invalida fetches en vuelo de una\n    // apertura previa para evitar condiciones de carrera.\n    setOperationCenters([]);\n    setDocumentTypes([]);\n    latestCOKeyRef.current = '';\n    latestTypesKeyRef.current = '';\n\n    if (!wizardConfig) return;\n\n    const companyStep = wizardConfig.steps.find((s) => s.key === 'company');\n    const coStep      = wizardConfig.steps.find((s) => s.key === 'co');\n    const typeStep    = wizardConfig.steps.find((s) => s.key === 'docType')\n      ?? wizardConfig.steps[wizardConfig.steps.length - 1];\n\n    // La lista de compañías es independiente: siempre se carga.\n    if (companyStep) {\n      void fetchWizardStep(\n        companyStep.entity,\n        { page: 1, pageSize: 100, fields: [] },\n        setCompanies,\n        (item) => ({ id: String(item.Id ?? item.id ?? ''), label: String(item.name ?? item.nombre ?? item.label ?? '') }),\n        setCompaniesLoading,\n      );\n    }\n\n    // CObs: solo si hay compañía pre-seleccionada en el wizard, filtrando por ella.\n    if (coStep && initialCompanyId) {\n      void fetchWizardStep(\n        coStep.entity,\n        { page: 1, pageSize: 100, fields: [], filters: { companyId: initialCompanyId } },\n        setOperationCenters,\n        (item) => ({ id: String(item.Id ?? item.id ?? ''), label: [item.code, item.name].filter(Boolean).join(' — ') }),\n        setCosLoading,\n        latestCOKeyRef,\n      );\n    }\n\n    // Tipos: solo si hay compañía + CO pre-seleccionados en el wizard, filtrando\n    // por AMBOS valores del wizard (nunca por el contexto/listado).\n    if (typeStep && initialCompanyId && initialCOId) {\n      void fetchWizardStep(\n        typeStep.entity,\n        { page: 1, pageSize: 50, fields: [], filters: { companyId: initialCompanyId, operationCenterId: initialCOId, documentClass: initialDocClass } },\n        setDocumentTypes,\n        (item) => ({ id: String(item.Id ?? item.id ?? ''), label: String(item.name ?? item.nombre ?? item.label ?? ''), description: String(item.description ?? '') }),\n        setTypesLoading,\n        latestTypesKeyRef,\n      );\n    }\n  }, [view.kind, wizardConfig, fetchWizardStep, selectedListCompany, operationCenterId, docClass, hasClassStep, singleClassId]);\n\n  // ── Wizard: handler de cambio de compañía ──\n  const handleWizardCompanyChange = useCallback((id: string) => {\n    setWizardCompanyId(id);\n    setWizardCOId('');\n    setSelectedType(undefined);\n    setOperationCenters([]);\n    setDocumentTypes([]);\n    // Invalida cualquier fetch en vuelo de pasos dependientes\n    latestCOKeyRef.current = '';\n    latestTypesKeyRef.current = '';\n    if (!wizardConfig) return;\n    const coStep = wizardConfig.steps.find((s) => s.key === 'co');\n    if (!coStep) return;\n    void fetchWizardStep(\n      coStep.entity,\n      { page: 1, pageSize: 100, fields: [], filters: { companyId: id } },\n      setOperationCenters,\n      (item) => ({ id: String(item.Id ?? item.id ?? ''), label: [item.code, item.name].filter(Boolean).join(' — ') }),\n      setCosLoading,\n      latestCOKeyRef,\n    );\n  }, [fetchWizardStep, wizardConfig]);\n\n  // ── Wizard: handler de cambio de clase de documento ──\n  // La clase acota la lista de tipos, así que al cambiarla se limpian los pasos de\n  // abajo igual que ya se limpian al cambiar de compañía. Los centros de operación\n  // NO se recargan ni se vacían: dependen de la compañía, no de la clase.\n  const handleWizardClassChange = useCallback((id: string) => {\n    setWizardDocClass(id);\n    setWizardCOId('');\n    setSelectedType(undefined);\n    setDocumentTypes([]);\n    latestTypesKeyRef.current = '';\n  }, []);\n\n  // ── Wizard: handler de cambio de centro de operación ──\n  const handleWizardCOChange = useCallback((id: string) => {\n    setWizardCOId(id);\n    setSelectedType(undefined);\n    setDocumentTypes([]);\n    latestTypesKeyRef.current = '';\n    if (!wizardConfig) return;\n    const typeStep = wizardConfig.steps.find((s) => s.key === 'docType')\n      ?? wizardConfig.steps[wizardConfig.steps.length - 1];\n    if (!typeStep) return;\n    void fetchWizardStep(\n      typeStep.entity,\n      { page: 1, pageSize: 50, fields: [], filters: { companyId: wizardCompanyId, operationCenterId: id, documentClass: effectiveDocClass } },\n      setDocumentTypes,\n      (item) => ({ id: String(item.Id ?? item.id ?? ''), label: String(item.name ?? item.nombre ?? item.label ?? ''), description: String(item.description ?? '') }),\n      setTypesLoading,\n      latestTypesKeyRef,\n    );\n  }, [fetchWizardStep, wizardConfig, wizardCompanyId, effectiveDocClass]);\n\n  // ── Wizard confirm ──────────────────────────────────────\n  // Llama a getNewDocument para traer el template pre-poblado del backend\n  // sin persistir. El POST real ocurre solo al guardar por primera vez.\n  const handleWizardConfirm = useCallback(async () => {\n    if (!selectedType) return;\n    // Con paso de clase, sin clase elegida no se crea nada. El botón ya está\n    // deshabilitado, pero la invariante se defiende aquí también: caer al\n    // `docClass` del template crearía el documento con la clase equivocada, que es\n    // justo el problema que este paso resuelve.\n    if (hasClassStep && !wizardDocClass) return;\n    const typeId = selectedType;\n    setSelectedType(undefined);\n\n    // Delegación: el host enruta a su propia pantalla de creación. `getNewDocument`\n    // NO se invoca aquí — la ruta destino lo resuelve con el contexto entregado, para\n    // que sea recargable por URL en lugar de depender de estado en memoria.\n    // Se vuelve al listado para cerrar el wizard: si la navegación del host no\n    // desmonta esta página, el usuario no queda atrapado en el modal.\n    //\n    // La clase que viaja es `effectiveDocClass`, no `docClass`: con paso de clase en el\n    // wizard es la que eligió el usuario. Entregar la del template crearía el documento\n    // con la clase equivocada, que es justo lo que ese paso resuelve.\n    if (onCreateDocument) {\n      onCreateDocument({\n        documentClass: effectiveDocClass,\n        companyId: wizardCompanyId,\n        operationCenterId: wizardCOId,\n        documentTypeId: typeId,\n      });\n      setView({ kind: 'list' });\n      return;\n    }\n\n    if (adapter.getNewDocument) {\n      setConfirmLoading(true);\n      try {\n        const initialState = await adapter.getNewDocument(\n          effectiveDocClass, wizardCompanyId, wizardCOId, typeId,\n        );\n        // La clase viaja en el estado del documento para que el POST del primer\n        // guardado (`createDocument`, en el reducer) y las consultas por clase del\n        // detalle usen ESTA clase y no la constante del template. Sin paso de\n        // clase el valor es justo esa constante, así que nada cambia.\n        setView({ kind: 'new', initialState: { ...initialState, documentClass: effectiveDocClass } });\n      } catch {\n        setView({ kind: 'create', documentTypeId: typeId });\n      } finally {\n        setConfirmLoading(false);\n      }\n    } else {\n      setView({ kind: 'create', documentTypeId: typeId });\n    }\n  }, [selectedType, adapter, effectiveDocClass, hasClassStep, wizardDocClass, wizardCompanyId, wizardCOId, onCreateDocument]);\n\n  // ── Build list props ────────────────────────────────────\n  const columns = useMemo(\n    () => Array.isArray(listConfig?.columns)\n      ? buildColumns(listConfig!.columns, adapter.formatCurrency, template.searchers)\n      : [],\n    [listConfig?.columns, adapter.formatCurrency, template.searchers],\n  );\n  const pills = useMemo(\n    () => Array.isArray(listConfig?.pills) ? buildPills(listConfig!.pills, activePill) : [],\n    [listConfig?.pills, activePill],\n  );\n  const searchFields = useMemo(\n    () => Array.isArray(listConfig?.filters) ? buildSearchFields(listConfig!.filters) : [],\n    [listConfig?.filters],\n  );\n\n  // ── Company change in list ──────────────────────────────\n  const handleListCompanyChange = useCallback((company: DocumentListCompany) => {\n    setSelectedListCompany(company);\n    setPage(1);\n    fetchList(1, activePill, searchValues, company);\n  }, [fetchList, activePill, searchValues]);\n\n  // ── Navigation ──────────────────────────────────────────\n  // Cada camino delega en el host si recibió su callback; si no, resuelve en línea\n  // como siempre. El `return` temprano es lo que garantiza que la página NO cambie\n  // de vista cuando delega: el host es dueño de la navegación desde ese punto.\n  const handleRowClick = useCallback((row: Record<string, unknown>) => {\n    if (onRowClick) {\n      onRowClick(row);\n      return;\n    }\n    const id = String(row.id ?? row.documentId ?? '');\n    if (id) setView({ kind: 'document', documentId: id });\n  }, [onRowClick]);\n\n  const handleViewRow = useCallback((row: Record<string, unknown>) => {\n    if (onViewRow) {\n      onViewRow(row);\n      return;\n    }\n    const id = String(row.id ?? row.documentId ?? '');\n    if (id) setView({ kind: 'document', documentId: id, viewOnly: true });\n  }, [onViewRow]);\n\n  const handleEditRow = useCallback((row: Record<string, unknown>) => {\n    if (onEditRow) {\n      onEditRow(row);\n      return;\n    }\n    const id = String(row.id ?? row.documentId ?? '');\n    if (id) setView({ kind: 'document', documentId: id, viewOnly: false });\n  }, [onEditRow]);\n\n  /**\n   * `href` de «Ver»/«Editar», que es lo que convierte esas acciones en enlaces y\n   * devuelve al usuario Ctrl/⌘+clic y clic con la rueda para abrir el detalle en\n   * otra pestaña (ver `DocumentListProps.getRowHref`).\n   *\n   * El del host manda siempre. Cuando no lo hay, esta página lo resuelve SÓLO\n   * para los caminos que ella misma gobierna, y ese matiz es lo importante:\n   *\n   * - Si el host delegó esa acción concreta (`onEditRow` / `onViewRow`), la\n   *   navegación es suya y `?doc=<id>` NO es su destino. Enlazar ahí abriría en la\n   *   pestaña nueva el detalle EN LÍNEA en vez de la ruta del host —que en varios\n   *   módulos es la única superficie que monta sus bloques propios—, así que la\n   *   pestaña nueva mostraría algo distinto del clic normal. Sin `href`: la acción\n   *   sigue siendo un botón y el host puede declarar el suyo cuando quiera el\n   *   enlace.\n   * - Si el host gobierna por `documentId`, esta página no escribe la URL (ver el\n   *   efecto de sincronización), así que tampoco puede construirla.\n   *\n   * La URL se calcula sobre `window.location`, que es la MISMA que el efecto de\n   * sincronización escribe al abrir el detalle y la que `leerVistaDeLaUrl()`\n   * restaura al montar: la pestaña nueva aterriza exactamente donde aterriza un\n   * refresco. Conserva los demás parámetros de la lista (filtros, página), que el\n   * detalle ignora y que quedan ahí para cuando esa pestaña vuelva al listado.\n   */\n  const resolverHrefDeFila = useCallback((row: Record<string, unknown>, action: 'view' | 'edit') => {\n    if (getRowHref) return getRowHref(row, action);\n    if (typeof window === 'undefined' || documentId) return undefined;\n    if (action === 'edit' && onEditRow) return undefined;\n    if (action === 'view' && onViewRow) return undefined;\n    const id = String(row.id ?? row.documentId ?? '');\n    if (!id) return undefined;   // sin id no hay destino: se queda como botón\n    const url = new URL(window.location.href);\n    url.searchParams.set(PARAM_DOCUMENTO, id);\n    if (action === 'view') url.searchParams.set(PARAM_MODO, 'view');\n    else url.searchParams.delete(PARAM_MODO);\n    return `${url.pathname}${url.search}${url.hash}`;\n  }, [getRowHref, documentId, onEditRow, onViewRow]);\n\n  // ── Estado de la fila (DEF-4) ────────────────────────────\n  // Resuelve el `docState` de una fila del listado. El campo es configurable vía\n  // template.list.rowStateField; si no, prueba claves comunes.\n  const rowStateField = listConfig?.rowStateField;\n  const getRowState = useCallback((row: Record<string, unknown>): string => {\n    if (rowStateField) return String(row[rowStateField] ?? '');\n    return String(row.docState ?? row.state ?? row.estado ?? '');\n  }, [rowStateField]);\n\n  const getRowId = useCallback(\n    (row: Record<string, unknown>) => String(row.id ?? row.documentId ?? ''),\n    [],\n  );\n\n  // ── Acciones disponibles por estado (DEF-4) ──────────────\n  // getAvailableActions(documentId, docState) es la fuente de verdad de qué\n  // acciones (delete/cancel) ofrece cada fila. El resultado depende del estado,\n  // así que se cachea por docState: una página de N filas con M estados ⇒ M\n  // llamadas, no N. Si el adapter no lo implementa, no hay gateo por estado y se\n  // mantiene el comportamiento legacy vía onDeleteRow.\n  const [availableByState, setAvailableByState] = useState<Record<string, string[]>>({});\n\n  const distinctRowStates = useMemo(\n    () => [...new Set(rows.map(getRowState))].filter(Boolean).sort().join(','),\n    [rows, getRowState],\n  );\n\n  useEffect(() => {\n    if (!adapter.getAvailableActions) return;\n    const states = distinctRowStates ? distinctRowStates.split(',') : [];\n    if (states.length === 0) {\n      setAvailableByState({});\n      return;\n    }\n    let cancelled = false;\n    Promise.all(\n      states.map(async (st) => {\n        const repRow = rows.find((r) => getRowState(r) === st);\n        const repId = repRow ? getRowId(repRow) : '';\n        try {\n          const keys = await adapter.getAvailableActions!(repId, st);\n          return [st, keys] as const;\n        } catch {\n          return [st, [] as string[]] as const;\n        }\n      }),\n    ).then((entries) => {\n      if (!cancelled) setAvailableByState(Object.fromEntries(entries));\n    });\n    return () => { cancelled = true; };\n  }, [distinctRowStates, adapter, rows, getRowState, getRowId]);\n\n  // Resuelve un ícono del template (string) a ReactNode vía el iconRegistry.\n  const resolveIcon = useCallback(\n    (iconName?: string): ReactNode => {\n      if (!iconName) return undefined;\n      const Icon = iconRegistry[iconName];\n      return Icon ? <Icon className=\"w-4 h-4\" /> : undefined;\n    },\n    [iconRegistry],\n  );\n\n  // ── Token de concurrencia de la fila ─────────────────────\n  // Campo de la fila que transporta el row_version de la cabecera (configurable\n  // vía template.list.concurrencyTokenField; por defecto `rowVersion`). Clave del\n  // header en el DocumentState: la misma del detalle (template.versionKeys.header,\n  // por defecto `_rowVersion`).\n  const concurrencyTokenField = listConfig?.concurrencyTokenField ?? 'rowVersion';\n  const headerVersionKey = template.versionKeys?.header ?? '_rowVersion';\n\n  // Lee el token de concurrencia de una fila. Devuelve undefined cuando la fila\n  // no expone el campo (NO se fuerza 0): así el adapter distingue \"no hay token\"\n  // de \"token = 0\" y se preserva la retrocompatibilidad.\n  const getRowVersion = useCallback((row: Record<string, unknown>): string | undefined => {\n    const raw = row[concurrencyTokenField];\n    return raw == null ? undefined : String(raw);\n  }, [concurrencyTokenField]);\n\n  // Construye un DocumentState mínimo para ejecutar la acción vía el adapter,\n  // preservando documentId y docState reales de la fila. Cuando la fila trae el\n  // token de concurrencia, lo propaga en `serverVersion` y en\n  // `headerValues[headerVersionKey]` (las mismas claves que el flujo de detalle),\n  // para que el backend detecte conflictos de edición concurrente (409).\n  const buildRowState = useCallback((\n    id: string,\n    docState: string,\n    serverVersion?: string,\n  ): DocumentState => ({\n    documentId: id,\n    mode: 'edit',\n    docState,\n    headerValues: serverVersion != null ? { [headerVersionKey]: serverVersion } : {},\n    lines: [],\n    headerErrors: {},\n    lineErrors: {},\n    loading: false,\n    saving: false,\n    serverVersion,\n    factBoxData: {},\n  }), [headerVersionKey]);\n\n  // Ejecuta una acción de fila vía el adapter, igual que el action bar del\n  // detalle. DEF-3: el error ya NO se traga — se propaga como feedback (toast).\n  const runRowAction = useCallback(async (\n    actionKey: string,\n    id: string,\n    docState: string,\n    serverVersion?: string,\n  ) => {\n    if (!id) return;\n    markRowBusy(id, true);\n    try {\n      if (actionKey === 'delete' && adapter.deleteDocument) {\n        await adapter.deleteDocument(id);\n      } else {\n        const result = await adapter.executeAction(actionKey, buildRowState(id, docState, serverVersion));\n        if (result && result.success === false) {\n          // El `message` del adapter YA es texto redactado para el usuario. NO se envuelve en un\n          // `Error` para que lo reclasifique el `catch` de abajo: `classifyError` toma el `message`\n          // de un `Error` por texto técnico de JS y lo sustituye por el genérico, así que ese rodeo\n          // le mostraba \"Ocurrió un error inesperado\" en lugar del motivo real del rechazo. Mismo\n          // criterio que `handleAction` del reducer, que ya despacha `result.message` directo.\n          toast.error(t('master_document.chrome.error'), {\n            description: result.message || t('master_document.error.actionFailed'),\n          });\n          return;\n        }\n      }\n      fetchList(page, activePill, searchValues);\n    } catch (err) {\n      // El texto técnico de JS no se le muestra al usuario: va al log. La\n      // descripción del toast sale del backend o de una clave del catálogo.\n      const { message, technical } = classifyError(err, t);\n      if (technical) console.error('[MasterDocument] acción de fila falló:', technical);\n      toast.error(t('master_document.chrome.error'), { description: message });\n    } finally {\n      // En `finally` y no al final del `try`: el rechazo del adapter\n      // (`result.success === false`) sale por un `return` temprano, y sin esto\n      // esa fila se quedaría girando para siempre tras un toast de error.\n      markRowBusy(id, false);\n    }\n  }, [adapter, buildRowState, fetchList, page, activePill, searchValues, t, markRowBusy]);\n\n  // ── Row actions (DEF-4) ──────────────────────────────────\n  // Por fila, devuelve las acciones gateadas por el estado de esa fila. Reutiliza\n  // el actionRegistry para label/variant/ícono/confirmación; delete y cancel caen\n  // a defaults sensatos cuando el registry no los define.\n  const getRowActions = useCallback((row: Record<string, unknown>): RowAction[] => {\n    const st = getRowState(row);\n    const id = getRowId(row);\n    const rowVersion = getRowVersion(row);\n    const keys = availableByState[st] ?? [];\n    const registry = template.actionRegistry ?? {};\n    const actions: RowAction[] = [];\n\n    if (keys.includes('delete')) {\n      const entry = registry.delete;\n      actions.push({\n        key: 'delete',\n        label: entry?.label ?? t('master_document.list.action.delete'),\n        icon: resolveIcon(entry?.icon),\n        variant: entry?.variant ?? 'danger',\n        requiresConfirmation: entry?.requiresConfirmation ?? true,\n        confirmationMessage: entry?.confirmationMessage\n          ?? t('master_document.document.deleteConfirm'),\n        onClick: () => { void runRowAction('delete', id, st, rowVersion); },\n      });\n    }\n\n    if (keys.includes('cancel')) {\n      const entry = registry.cancel;\n      actions.push({\n        key: 'cancel',\n        label: entry?.label ?? t('master_document.list.action.void'),\n        icon: resolveIcon(entry?.icon),\n        variant: entry?.variant ?? 'danger',\n        // El adapter puede abrir su propio modal de motivo, por eso cancel no\n        // exige confirmación por defecto (sí la respeta si el registry la declara).\n        requiresConfirmation: entry?.requiresConfirmation ?? false,\n        confirmationMessage: entry?.confirmationMessage,\n        onClick: () => { void runRowAction('cancel', id, st, rowVersion); },\n      });\n    }\n\n    return actions;\n  }, [getRowState, getRowId, getRowVersion, availableByState, template.actionRegistry, resolveIcon, runRowAction, t]);\n\n  // ── Impresión nativa por fila ────────────────────────────\n  // Construye el PrintContext de una fila y delega en la API del provider\n  // (openPrint / isPrintAvailable). NO pasa por el adapter: es presentación.\n  const buildRowPrintContext = useCallback((row: Record<string, unknown>): PrintContext => ({\n    source: 'row',\n    documentId: getRowId(row),\n    documentNumber: (row._documentNumber as string | undefined) ?? null,\n    docState: getRowState(row) || null,\n    row,\n  }), [getRowId, getRowState]);\n\n  const isPrintRowAvailable = useCallback(\n    (row: Record<string, unknown>) => print?.isPrintAvailable(buildRowPrintContext(row)) ?? false,\n    [print, buildRowPrintContext],\n  );\n\n  const onPrintRow = useCallback(\n    (row: Record<string, unknown>) => print?.openPrint(buildRowPrintContext(row)),\n    [print, buildRowPrintContext],\n  );\n\n  // Legacy (retrocompat): borrado gobernado por flag global, sólo cuando el\n  // adapter NO implementa getAvailableActions. Antes tragaba el error (DEF-3);\n  // ahora lo propaga como feedback.\n  // Documento pendiente de confirmar el borrado (null = sin diálogo abierto). Antes se preguntaba\n  // con un `window.confirm` nativo; ahora usa el `ConfirmDialog` del kit, igual que las acciones de\n  // fila de `DocumentList` y que el borrado de línea de `SmartMasterDocument`.\n  // Se guarda la FILA completa, no solo su id: la rama legacy (sin `deleteDocument`) arma el estado\n  // con `getRowState(row)` / `getRowVersion(row)` al confirmar.\n  const [pendingDeleteRow, setPendingDeleteRow] = useState<Record<string, unknown> | null>(null);\n\n  const handleDeleteRow = useCallback((row: Record<string, unknown>) => {\n    if (!getRowId(row)) return;\n    setPendingDeleteRow(row);\n  }, [getRowId]);\n\n  const confirmDeleteRow = useCallback(async () => {\n    const row = pendingDeleteRow;\n    if (!row) return;\n    const id = getRowId(row);\n    if (!id) return;\n    setPendingDeleteRow(null);\n    markRowBusy(id, true);\n    try {\n      if (adapter.deleteDocument) {\n        await adapter.deleteDocument(id);\n      } else {\n        await adapter.executeAction('delete', buildRowState(id, getRowState(row), getRowVersion(row)));\n      }\n      fetchList(page, activePill, searchValues);\n    } catch (err) {\n      // El texto técnico de JS no se le muestra al usuario: va al log. La\n      // descripción del toast sale del backend o de una clave del catálogo.\n      const { message, technical } = classifyError(err, t);\n      if (technical) console.error('[MasterDocument] acción de fila falló:', technical);\n      toast.error(t('master_document.chrome.error'), { description: message });\n    } finally {\n      markRowBusy(id, false);\n    }\n  }, [adapter, buildRowState, pendingDeleteRow, getRowId, getRowState, getRowVersion, fetchList, page, activePill, searchValues, t, markRowBusy]);\n\n  const handleBackToList = useCallback(() => {\n    setView({ kind: 'list' });\n  }, []);\n\n  const adapterWithNav = useMemo(() => {\n    const wrapped = { ...adapter };\n    const origAction = adapter.executeAction;\n    wrapped.executeAction = async (key, state) => {\n      if (key === 'navigate_back') {\n        handleBackToList();\n        return { success: true };\n      }\n      if (key.startsWith('navigate_document:')) {\n        const docId = key.replace('navigate_document:', '');\n        if (docId) setView({ kind: 'document', documentId: docId });\n        return { success: true };\n      }\n      return origAction(key, state);\n    };\n    return wrapped;\n  }, [adapter, handleBackToList]);\n\n  // ═══════════════════════════════════════════════════════\n  // RENDER\n  // ═══════════════════════════════════════════════════════\n\n  if ((view.kind === 'list' || view.kind === 'wizard') && listConfig) {\n    return (\n      <>\n        <DocumentList\n          title={listConfig.title}\n          subtitle={listConfig.subtitle}\n          companies={availableCompanies}\n          selectedCompany={selectedListCompany}\n          onCompanyChange={handleListCompanyChange}\n          onCreateNew={() => createFromSourceEnabled ? setCreateFromSourceOpen(true) : setView({ kind: 'wizard' })}\n          createNewLabel={listConfig.createNewLabel}\n          canCreate={canCreate}\n          pills={pills}\n          onPillClick={(key) => { setActivePill(key); setPage(1); }}\n          searchFields={searchFields}\n          searchValues={searchValues}\n          onSearchChange={(k, v) => setSearchValues((prev) => ({ ...prev, [k]: v }))}\n          fetcher={adapter.fetcher}\n          columnFilters={columnFilters}\n          onColumnFilterChange={handleColumnFilterChange}\n          onSearch={() => fetchList(1, activePill, searchValues)}\n          onClearSearch={() => { setSearchValues({}); fetchList(1, activePill, {}); }}\n          searchOpen={searchOpen}\n          onToggleSearch={() => setSearchOpen((o) => !o)}\n          columns={columns}\n          rows={rows}\n          totalCount={totalCount}\n          {...(\n            // Fila-enlace y «Ver» son OPT-IN del host, no default del kit. Resueltos\n            // aquí dentro llevaban al MISMO detalle que «Editar» —el `viewOnly`\n            // interno cambia el modo, no la puerta—, así que el listado ofrecía dos\n            // accesos indistinguibles y la fila entera era un enlace. Cuando el host\n            // SÍ declara los suyos son destinos distintos de verdad (despachos y\n            // notas crédito tienen `/$id` de sólo lectura aparte de `/$id/edit`), y\n            // entonces se pasan tal cual.\n            onRowClick ? { onRowClick: handleRowClick } : {}\n          )}\n          {...(onViewRow ? { onViewRow: handleViewRow } : {})}\n          onEditRow={handleEditRow}\n          getRowHref={resolverHrefDeFila}\n          {...(adapter.getAvailableActions\n            ? { getRowActions }\n            : { onDeleteRow: handleDeleteRow })}\n          {...(print\n            ? { onPrintRow, isPrintRowAvailable, printLabel: print.label }\n            : {})}\n          page={page}\n          pageSize={pageSize}\n          onPageChange={setPage}\n          // Cambiar el tamaño de página vuelve a la 1: quedarse en la página N\n          // con un tamaño nuevo apunta a otros registros y se lee como que el\n          // listado «saltó» solo.\n          onPageSizeChange={(size) => { setPageSize(size); setPage(1); }}\n          quickSearchEnabled={quickSearchEnabled}\n          quickSearchPlaceholder={quickSearchCfg?.placeholder}\n          quickSearchValue={quickSearch}\n          // Teclear devuelve a la primera página: el resultado filtrado tiene\n          // menos páginas y quedarse en la 7 mostraría un listado vacío.\n          onQuickSearchChange={(v) => { setQuickSearch(v); setPage(1); }}\n          loading={listLoading}\n          busyRowIds={busyRowIds}\n          error={listError}\n          onRetry={() => fetchList(page, activePill, searchValues)}\n          bulkMode={!!(template.crossing?.enabled && template.crossing?.allowBulkConvert)}\n          selectedRowIds={selectedRowIds}\n          onRowSelect={(id, selected) =>\n            setSelectedRowIds((prev) =>\n              selected ? [...prev.filter((x) => x !== id), id] : prev.filter((x) => x !== id)\n            )\n          }\n          bulkConvertOptions={bulkConvertOptions}\n          onBulkConvert={(classId, ids, headerValues) => { void startBulkJob(classId, ids, headerValues); }}\n        />\n\n        <DocumentCreationWizard\n          open={view.kind === 'wizard'}\n          onClose={() => setView({ kind: 'list' })}\n          companies={companies}\n          selectedCompany={wizardCompanyId}\n          onSelectCompany={handleWizardCompanyChange}\n          documentClasses={documentClasses}\n          selectedDocumentClass={wizardDocClass}\n          onSelectDocumentClass={handleWizardClassChange}\n          operationCenters={operationCenters}\n          selectedCO={wizardCOId}\n          onSelectCO={handleWizardCOChange}\n          documentTypes={documentTypes}\n          selectedType={selectedType}\n          onSelectType={setSelectedType}\n          onConfirm={handleWizardConfirm}\n          loadingStep={\n            // Las clases llegan por prop, no por fetch: el paso 2 nunca está en\n            // carga cuando está activo. Los índices de CO y tipo se corren con él.\n            companiesLoading ? 1\n            : cosLoading ? coStepIndex\n            : (typesLoading || confirmLoading) ? typeStepIndex\n            : undefined\n          }\n        />\n\n        {template.createFromSource && (\n          <CreateFromSourceModal\n            open={createFromSourceOpen}\n            mode=\"create\"\n            config={template.createFromSource}\n            adapter={adapter}\n            operationCenterId={operationCenterId}\n            userPermissions={userPermissions}\n            formatCurrency={adapter.formatCurrency}\n            formatNumber={adapter.formatNumber}\n            onClose={() => setCreateFromSourceOpen(false)}\n            onCreated={(newId) => {\n              setCreateFromSourceOpen(false);\n              if (onDocumentCreated) {\n                onDocumentCreated(newId);\n                return;\n              }\n              setView({ kind: 'document', documentId: newId });\n            }}\n            onFreeCapture={() => {\n              // Captura libre (P25): en el kit equivale a crear un documento en\n              // blanco vía el wizard. El consumidor puede enrutar a su propia\n              // ruta (p.ej. /new?direct=true) inyectando su propio handler.\n              setCreateFromSourceOpen(false);\n              setView({ kind: 'wizard' });\n            }}\n          />\n        )}\n\n        {bulkJob && (\n          <BulkConversionProgress\n            job={bulkJob}\n            onCancel={() => { void cancelBulkJob(); }}\n            onClose={closeBulkProgress}\n            onViewResults={openBulkResults}\n          />\n        )}\n        <BulkResultsSummary\n          open={showBulkResults}\n          results={bulkJob?.results ?? []}\n          onRetryFailed={(ids) => { void retryBulkFailed(ids); }}\n          onClose={closeBulkResults}\n        />\n        {pendingDeleteRow !== null && (\n          <ConfirmDialog\n            message={t('master_document.document.deleteConfirm')}\n            onConfirm={confirmDeleteRow}\n            onCancel={() => setPendingDeleteRow(null)}\n          />\n        )}\n      </>\n    );\n  }\n\n  if (view.kind === 'new') {\n    return <SmartMasterDocument initialState={view.initialState} onSaved={handleBackToList} onNavigateToList={handleBackToList} adapterOverride={adapterWithNav} onNavigateToDocument={onNavigateToDocument} />;\n  }\n\n  const docId = view.kind === 'document' ? view.documentId : undefined;\n  const docViewOnly = view.kind === 'document' ? view.viewOnly : undefined;\n  return <SmartMasterDocument documentId={docId} viewOnly={docViewOnly} onSaved={handleBackToList} onNavigateToList={handleBackToList} adapterOverride={adapterWithNav} onNavigateToDocument={onNavigateToDocument} />;\n}\n","import type { ReactNode } from 'react';\nimport type { RowAction } from './MasterDocument.types';\n\n/**\n * Forma de `FlexRowAction` del paquete `@SiesaTeams/flex-query` (npm 0.4.0).\n *\n * Se declara estructuralmente en vez de importarse porque el kit **no depende**\n * de FlexQuery y no puede: ese paquete construye su UI con `siesa-ui-kit`, así\n * que la dependencia inversa cerraría un ciclo. Si su tipo cambia, el error\n * aparece donde el host asigna el resultado a la prop `rowActions` — que es\n * exactamente donde se quiere ver.\n */\nexport interface FlexRowActionLike {\n  label: string;\n  icon?: ReactNode;\n  onClick: (row: Record<string, unknown>) => void;\n  placement?: 'inline' | 'context' | 'both';\n}\n\nexport interface ToFlexRowActionsOptions {\n  /** Dónde se dibujan las acciones. Se aplica a todas. Ausente ⇒ el de FlexQuery. */\n  placement?: FlexRowActionLike['placement'];\n  /**\n   * Qué hacer con una acción que el kit marcó `disabled` (el gateo D2 «visible\n   * pero deshabilitada»).\n   *\n   * - `'omit'` (por defecto): no se pasa. `FlexRowAction` **no tiene** campo\n   *   `disabled`, así que pasarla la dibujaría clicable y prometería algo que el\n   *   estado del documento no permite.\n   * - `'inert'`: se pasa con `onClick` neutralizado. La acción se ve pero no hace\n   *   nada — solo úsalo si tu UI ya comunica por otro medio que no aplica.\n   */\n  disabledActions?: 'omit' | 'inert';\n}\n\n/**\n * Traduce las acciones de fila del kit a las de `<FlexQuery>`.\n *\n * `ctx.rowActions(row)` devuelve `RowAction[]`, el tipo del kit: trae `key`,\n * `variant`, `disabled`, `requiresConfirmation` y `confirmationMessage`, que\n * `FlexRowAction` no tiene. Este mapeo existe para que cada host no reescriba la\n * misma conversión, y para dejar por escrito lo que se pierde en ella.\n *\n * **Lo que no sobrevive al mapeo, y qué hacer:**\n *\n * - `disabled` → ver `disabledActions`. Es el hueco importante: sin campo\n *   equivalente en FlexQuery, «visible pero deshabilitada» no se puede\n *   representar y por defecto se omite la acción.\n * - `requiresConfirmation` / `confirmationMessage` → **el host debe confirmar**.\n *   El kit solo pide confirmación por su cuenta en el menú de fila del listado\n *   (`DocumentList`); dentro de una consulta del host, la UI es del host. Estas\n *   acciones se pasan igual, así que si tu documento declara alguna con\n *   confirmación, envuélvela tú antes de ejecutarla.\n * - `key` y `variant` → se descartan. `key` sigue disponible en el `RowAction`\n *   original si necesitas ordenar o filtrar antes de mapear.\n *\n * @example\n * ```tsx\n * <FlexQuery\n *   contractBaseUrl={ctx.flexQuery!.contractBaseUrl ?? API_BASE}\n *   reportCode={ctx.flexQuery!.reportCode}\n *   locale={ctx.locale}\n *   externalFilters={ctx.externalFilters}\n *   rowActions={toFlexRowActions(ctx.rowActions(row))}\n * />\n * ```\n */\nexport function toFlexRowActions(\n  actions: RowAction[],\n  options: ToFlexRowActionsOptions = {},\n): FlexRowActionLike[] {\n  const { placement, disabledActions = 'omit' } = options;\n\n  return actions\n    .filter((action) => !action.disabled || disabledActions === 'inert')\n    .map((action) => ({\n      label: action.label,\n      icon: action.icon,\n      onClick: action.disabled ? () => {} : action.onClick,\n      ...(placement ? { placement } : {}),\n    }));\n}\n","import { clsx } from 'clsx';\nimport { useMasterDocumentTranslation } from './i18n';\nimport type { ApprovalBannerProps, ApprovalStep } from './MasterDocument.types';\n\n// ─── Step Circle ───────────────────────────────────────────\n\nfunction StepCircle({ step, index }: { step: ApprovalStep; index: number }) {\n  const baseCircle = 'flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0';\n\n  switch (step.status) {\n    case 'completed':\n      return (\n        <div className={clsx(baseCircle, 'bg-green-700 dark:bg-green-600 text-white dark:text-dark-content-inverse')}>\n          <svg className=\"w-3.5 h-3.5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" strokeWidth={3}>\n            <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M5 13l4 4L19 7\" />\n          </svg>\n        </div>\n      );\n    case 'current':\n      return (\n        <div className={clsx(baseCircle, 'border-2 border-amber-700 dark:border-amber-500 text-amber-700 dark:text-amber-400 bg-transparent')}>\n          {index + 1}\n        </div>\n      );\n    case 'pending':\n      return (\n        <div className={clsx(baseCircle, 'bg-background-secondary dark:bg-dark-bg-secondary text-content-secondary dark:text-dark-content-secondary')}>\n          {index + 1}\n        </div>\n      );\n  }\n}\n\n// ─── Connector Line ────────────────────────────────────────\n\nfunction ConnectorLine({ status }: { status: ApprovalStep['status'] }) {\n  return (\n    <div\n      className={clsx(\n        'flex-1 h-0.5 mx-1',\n        status === 'completed' ? 'bg-green-700 dark:bg-green-600' : 'bg-background-secondary dark:bg-dark-bg-secondary',\n      )}\n    />\n  );\n}\n\n// ─── ApprovalBanner ────────────────────────────────────────\n\nexport function ApprovalBanner({\n  steps,\n  message,\n  onApprove,\n  approveLabel,\n  onReject,\n  rejectLabel,\n  className,\n}: ApprovalBannerProps) {\n  const { t } = useMasterDocumentTranslation();\n  return (\n    <div\n      className={clsx(\n        'rounded-xl px-[18px] py-3 bg-amber-50 animate-[fadeIn_200ms_ease-out]',\n        'dark:bg-amber-700/15',\n        className,\n      )}\n      role=\"alert\"\n    >\n      <div className=\"flex flex-col sm:flex-row sm:items-center gap-3\">\n        {/* Steps visual */}\n        <div className=\"flex items-center gap-0 flex-1 min-w-0\">\n          {steps.map((step, i) => (\n            <div key={step.label} className=\"contents\">\n              {i > 0 && <ConnectorLine status={steps[i - 1].status} />}\n              <div className=\"flex flex-col items-center gap-0.5 shrink-0\">\n                <StepCircle step={step} index={i} />\n                <span\n                  className={clsx(\n                    'text-xs font-semibold whitespace-nowrap max-w-[60px] truncate text-center',\n                    step.status === 'current' ? 'text-amber-700 dark:text-amber-400' : 'text-content-secondary dark:text-dark-content-secondary',\n                    step.status === 'completed' && 'text-green-700 dark:text-green-400',\n                  )}\n                >\n                  {step.label}\n                </span>\n              </div>\n            </div>\n          ))}\n        </div>\n\n        {/* Message */}\n        <p className=\"text-sm text-amber-700 dark:text-amber-400 flex-1 min-w-0\">\n          {message}\n        </p>\n\n        {/* Actions */}\n        <div className=\"flex items-center gap-2 shrink-0\">\n          <button\n            type=\"button\"\n            onClick={onReject}\n            className={clsx(\n              'px-3.5 py-1.5 rounded-md text-xs font-semibold',\n              'border border-amber-700/30 text-amber-700 hover:bg-amber-700/10 dark:hover:bg-amber-700/20 transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'dark:text-amber-400 dark:border-amber-400/30',\n            )}\n          >\n            {rejectLabel ?? t('master_document.approval.reject')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={onApprove}\n            className={clsx(\n              'px-4 py-1.5 rounded-md text-xs font-semibold',\n              'bg-primary-inverse-background text-white hover:bg-primary-700 transition-all duration-150',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'min-h-[32px]',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            {approveLabel ?? t('master_document.approval.approve')}\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n","import React, { useEffect, useCallback, useRef, useMemo, useState } from 'react';\nimport { useForm, useWatch } from 'react-hook-form';\nimport { clsx } from 'clsx';\nimport { FieldRenderer } from './FieldRenderer';\nimport type { MasterDocumentFormModalProps, MasterDocumentFormModalSection, ComputedRule, FieldError } from './MasterDocument.types';\nimport type { ServerRuleConfig } from './template/MasterDocumentTemplate.types';\nimport { evaluateCondition, extractDependencyFields } from './fieldCondition';\nimport type { FieldCondition } from './fieldCondition';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { FieldLoadingIndicator } from './components/loading';\n\n// ─── Icons ─────────────────────────────────────────────────\n\nfunction XIcon(props: React.SVGProps<SVGSVGElement>) {\n  return (\n    <svg viewBox=\"0 0 20 20\" fill=\"currentColor\" {...props}>\n      <path d=\"M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z\" />\n    </svg>\n  );\n}\n\nfunction ChevronDownIcon(props: React.SVGProps<SVGSVGElement>) {\n  return (\n    <svg viewBox=\"0 0 20 20\" fill=\"currentColor\" {...props}>\n      <path\n        fillRule=\"evenodd\"\n        d=\"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z\"\n        clipRule=\"evenodd\"\n      />\n    </svg>\n  );\n}\n\n// ─── Computed Rules Runner ─────────────────────────────────\n\nfunction ComputedRulesRunner({\n  rules,\n  control,\n  setValue,\n}: {\n  rules: ComputedRule[];\n  control: ReturnType<typeof useForm>['control'];\n  setValue: ReturnType<typeof useForm>['setValue'];\n}) {\n  const allWatchFields = [...new Set(rules.flatMap((r) => r.watch))];\n  const watchedValues = useWatch({ control, name: allWatchFields });\n\n  useEffect(() => {\n    const snapshot: Record<string, unknown> = {};\n    allWatchFields.forEach((field, idx) => { snapshot[field] = watchedValues[idx]; });\n    rules.forEach((rule) => {\n      const result = rule.compute(snapshot);\n      setValue(rule.targetField, result, { shouldDirty: false });\n    });\n  }, [watchedValues, rules, setValue, allWatchFields]);\n\n  return null;\n}\n\n// ─── Form Values Watcher ───────────────────────────────────\n\nfunction FormValuesWatcher({\n  control,\n  onChange,\n}: {\n  control: ReturnType<typeof useForm>['control'];\n  onChange: (values: Record<string, unknown>) => void;\n}) {\n  const values = useWatch({ control });\n  useEffect(() => {\n    const t = setTimeout(() => onChange(values as Record<string, unknown>), 100);\n    return () => clearTimeout(t);\n  }, [values, onChange]);\n  return null;\n}\n\n// ─── Server Rules Runner ───────────────────────────────────\n\nfunction ServerRulesRunner({\n  rules,\n  control,\n  setValue,\n  onEvaluate,\n  setLoadingFields,\n}: {\n  rules: ServerRuleConfig[];\n  control: ReturnType<typeof useForm>['control'];\n  setValue: ReturnType<typeof useForm>['setValue'];\n  onEvaluate: (ruleId: string, formData: Record<string, unknown>) => Promise<Partial<Record<string, unknown>>>;\n  setLoadingFields: React.Dispatch<React.SetStateAction<Set<string>>>;\n}) {\n  const allTriggerFields = useMemo(\n    () => [...new Set(rules.flatMap((r) => r.triggerFields))],\n    [rules],\n  );\n  const watched = useWatch({ control, name: allTriggerFields as [string, ...string[]] });\n  const initialized = useRef(false);\n  const timers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());\n  const generations = useRef<Map<string, number>>(new Map());\n\n  useEffect(() => {\n    const isInit = !initialized.current;\n    initialized.current = true;\n\n    const snapshot: Record<string, unknown> = {};\n    allTriggerFields.forEach((k, i) => { snapshot[k] = watched[i]; });\n\n    rules.forEach((rule) => {\n      if (isInit && (rule.triggerOn ?? 'change') !== 'always') return;\n      if (rule.condition && !evaluateCondition(rule.condition as FieldCondition, snapshot)) return;\n\n      const existing = timers.current.get(rule.ruleId);\n      if (existing) clearTimeout(existing);\n\n      const delay = rule.debounceMs ?? 300;\n      const timer = setTimeout(async () => {\n        const gen = (generations.current.get(rule.ruleId) ?? 0) + 1;\n        generations.current.set(rule.ruleId, gen);\n\n        setLoadingFields((prev) => {\n          const next = new Set(prev);\n          rule.targetFields.forEach((f) => next.add(f));\n          return next;\n        });\n\n        try {\n          const result = await onEvaluate(rule.ruleId, snapshot);\n          if (generations.current.get(rule.ruleId) !== gen) return;\n          Object.entries(result).forEach(([key, value]) => {\n            setValue(key, value, { shouldDirty: false });\n          });\n        } catch {\n          // Leave fields unchanged on error\n        } finally {\n          if (generations.current.get(rule.ruleId) === gen) {\n            setLoadingFields((prev) => {\n              const next = new Set(prev);\n              rule.targetFields.forEach((f) => next.delete(f));\n              return next;\n            });\n          }\n        }\n\n        timers.current.delete(rule.ruleId);\n      }, delay);\n\n      timers.current.set(rule.ruleId, timer);\n    });\n  }, [watched]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  useEffect(() => {\n    return () => { timers.current.forEach((t) => clearTimeout(t)); };\n  }, []);\n\n  return null;\n}\n\n// ─── Controlled Field Wrapper ──────────────────────────────\n\nfunction FieldRendererControlled({\n  field,\n  control,\n  setValue,\n  editable,\n  readOnly,\n  loading,\n  error,\n  isComputed,\n}: {\n  field: MasterDocumentFormModalProps['fields'][number];\n  control: ReturnType<typeof useForm>['control'];\n  setValue: ReturnType<typeof useForm>['setValue'];\n  editable: boolean;\n  readOnly: boolean;\n  loading?: boolean;\n  error?: FieldError;\n  isComputed: boolean;\n}) {\n  const { t } = useMasterDocumentTranslation();\n  const value = useWatch({ control, name: field.key });\n\n  return (\n    <div className=\"relative\">\n      <FieldRenderer\n        fieldDef={field}\n        value={value}\n        onChange={(v) => setValue(field.key, v, { shouldDirty: true })}\n        editable={editable}\n        readOnly={readOnly}\n        error={error}\n      />\n      {isComputed && (\n        <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary italic mt-0.5\">{t('master_document.lines.calculated')}</span>\n      )}\n      {loading && <FieldLoadingIndicator />}\n    </div>\n  );\n}\n\n// ─── Accordion Section ─────────────────────────────────────\n\nfunction AccordionSection({\n  section,\n  children,\n  hasFields,\n}: {\n  section: MasterDocumentFormModalSection;\n  children: React.ReactNode;\n  hasFields: boolean;\n}) {\n  const [open, setOpen] = useState(section.defaultOpen !== false);\n\n  if (!hasFields) return null;\n\n  if (!section.collapsible) {\n    return (\n      <div className=\"mb-5\">\n        <div className=\"flex items-center gap-2 mb-3 pb-2 border-b border-border-secondary dark:border-dark-border-primary\">\n          <span className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary\">\n            {section.label}\n          </span>\n        </div>\n        {children}\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"mb-4 border border-border-secondary dark:border-dark-border-primary rounded-lg overflow-hidden\">\n      <button\n        type=\"button\"\n        onClick={() => setOpen((prev) => !prev)}\n        className={clsx(\n          'w-full flex items-center justify-between px-4 py-3 text-left transition-colors duration-150',\n          'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n          'focus:outline-hidden focus:ring-2 focus:ring-inset focus:ring-primary-custom-400 dark:focus:ring-dark-border-custom',\n          open\n            ? 'bg-background-secondary dark:bg-dark-bg-secondary'\n            : 'bg-bg-primary dark:bg-dark-bg-primary',\n        )}\n        aria-expanded={open}\n      >\n        <span className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary\">\n          {section.label}\n        </span>\n        <ChevronDownIcon\n          className={clsx(\n            'w-4 h-4 text-content-secondary dark:text-dark-content-secondary transition-transform duration-200',\n            open ? 'rotate-180' : 'rotate-0',\n          )}\n        />\n      </button>\n\n      {open && (\n        <div className=\"px-4 py-4\">\n          {children}\n        </div>\n      )}\n    </div>\n  );\n}\n\n// ─── MasterDocumentFormModal ───────────────────────────────\n\n/**\n * MasterDocumentFormModal — modal para crear o editar una línea del documento.\n *\n * Soporta dos layouts:\n * - Sin `sections`: grid plano de campos (comportamiento original).\n * - Con `sections`: campos agrupados en secciones verticales. Cada sección puede\n *   ser flat (collapsible: false) o tipo acordeón expandible (collapsible: true).\n *\n * @example\n * ```tsx\n * <MasterDocumentFormModal\n *   open={open}\n *   onClose={onClose}\n *   onConfirm={handleSave}\n *   fields={lineFields}\n *   title=\"Nueva línea\"\n *   sections={[\n *     { key: \"item\",         label: \"Datos de la línea\", defaultOpen: true },\n *     { key: \"segmentacion\", label: \"Segmentación\",      defaultOpen: false, collapsible: true },\n *   ]}\n * />\n * ```\n */\nexport function MasterDocumentFormModal({\n  open,\n  onClose,\n  onConfirm,\n  onConfirmAndAddAnother,\n  fields,\n  initialData,\n  computedRules,\n  serverRules,\n  onEvaluateServerRule,\n  errors: externalErrors,\n  title,\n  confirmLabel,\n  cancelLabel,\n  docState,\n  columns = 2,\n  sections,\n  widgetSlot,\n  onFormValuesChange,\n  className,\n}: MasterDocumentFormModalProps) {\n  const { t } = useMasterDocumentTranslation();\n  const resolvedConfirmLabel = confirmLabel ?? t('master_document.chrome.confirm');\n  const resolvedCancelLabel = cancelLabel ?? t('master_document.chrome.cancel');\n  const sortedFields = [...fields].sort((a, b) => a.order - b.order);\n  const modalRef = useRef<HTMLDivElement>(null);\n  const [loadingFields, setLoadingFields] = useState<Set<string>>(new Set());\n\n  // Collect dependency fields for condition evaluation\n  const conditionDeps = useMemo(() => {\n    const keys = new Set<string>();\n    sortedFields.forEach((f) => {\n      if (f.visibleWhen) extractDependencyFields(f.visibleWhen as FieldCondition).forEach((k) => keys.add(k));\n      if (f.hiddenWhen) extractDependencyFields(f.hiddenWhen as FieldCondition).forEach((k) => keys.add(k));\n    });\n    return [...keys];\n  }, [sortedFields]);\n\n  const defaultValues: Record<string, unknown> = {};\n  fields.forEach((f) => {\n    defaultValues[f.key] = initialData?.[f.key] ?? f.defaultValue ?? '';\n  });\n\n  const { control, setValue, reset, handleSubmit } = useForm({ defaultValues });\n\n  const watchedConditionValues = useWatch({ control, name: conditionDeps as [string, ...string[]] });\n\n  const conditionSnapshot = useMemo(() => {\n    const snap: Record<string, unknown> = {};\n    conditionDeps.forEach((key, i) => { snap[key] = watchedConditionValues[i]; });\n    return snap;\n  }, [conditionDeps, watchedConditionValues]);\n\n  const visibleFields = useMemo(() => {\n    if (conditionDeps.length === 0) return sortedFields;\n    return sortedFields.filter((f) => {\n      if (f.visibleWhen && !evaluateCondition(f.visibleWhen as FieldCondition, conditionSnapshot)) return false;\n      if (f.hiddenWhen && evaluateCondition(f.hiddenWhen as FieldCondition, conditionSnapshot)) return false;\n      return true;\n    });\n  }, [sortedFields, conditionDeps.length, conditionSnapshot]);\n\n  const configuredSectionKeys = useMemo(\n    () => new Set(sections?.map((s) => s.key) ?? []),\n    [sections],\n  );\n\n  // Fields without a matching section key → rendered above sections\n  const commonFields = useMemo(\n    () => (sections ? visibleFields.filter((f) => !configuredSectionKeys.has(f.section)) : []),\n    [sections, visibleFields, configuredSectionKeys],\n  );\n\n  // Reset form when modal opens\n  const prevOpenRef = useRef(false);\n  useEffect(() => {\n    const justOpened = open && !prevOpenRef.current;\n    prevOpenRef.current = open;\n    if (!justOpened) return;\n\n    const values: Record<string, unknown> = {};\n    fields.forEach((f) => {\n      values[f.key] = initialData?.[f.key] ?? f.defaultValue ?? '';\n    });\n    reset(values);\n  }, [open, initialData, fields, reset]);\n\n  // Focus first editable field on open\n  useEffect(() => {\n    if (!open) return;\n    const timer = setTimeout(() => {\n      const first = modalRef.current?.querySelector<HTMLElement>(\n        'input:not([disabled]):not([readonly]), textarea:not([disabled]):not([readonly])',\n      );\n      first?.focus();\n    }, 80);\n    return () => clearTimeout(timer);\n  }, [open]);\n\n  // Close on Escape\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  const handleConfirm = useCallback(\n    (data: Record<string, unknown>) => { onConfirm(data); },\n    [onConfirm],\n  );\n\n  const handleConfirmAndAddAnother = useCallback(\n    (data: Record<string, unknown>) => {\n      onConfirmAndAddAnother!(data);\n      const emptyValues: Record<string, unknown> = {};\n      fields.forEach((f) => { emptyValues[f.key] = f.defaultValue ?? ''; });\n      reset(emptyValues);\n    },\n    [onConfirmAndAddAnother, fields, reset],\n  );\n\n  const computedTargets = new Set(computedRules?.map((r) => r.targetField) ?? []);\n\n  const isFieldEditable = useCallback(\n    (field: MasterDocumentFormModalProps['fields'][number]) => {\n      if (!field.editableOn || field.editableOn.length === 0) return false;\n      if (field.editableOn.includes('*')) return true;\n      if (!docState) return true;\n      return field.editableOn.includes(docState);\n    },\n    [docState],\n  );\n\n  const gridClass = columns === 1 ? 'grid-cols-1' : 'grid-cols-1 sm:grid-cols-2';\n\n  function renderField(field: MasterDocumentFormModalProps['fields'][number]) {\n    const isComputed = computedTargets.has(field.key);\n    const isLoading = loadingFields.has(field.key);\n    const editable = isFieldEditable(field) && !isComputed && !isLoading;\n    return (\n      <div\n        key={field.key}\n        className={clsx(field.span >= 2 && columns === 2 && 'sm:col-span-2')}\n      >\n        <FieldRendererControlled\n          field={field}\n          control={control}\n          setValue={setValue}\n          editable={editable}\n          readOnly={isComputed}\n          loading={isLoading}\n          error={externalErrors?.[field.key]}\n          isComputed={isComputed}\n        />\n      </div>\n    );\n  }\n\n  if (!open) return null;\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        onClick={onClose}\n        aria-hidden=\"true\"\n      />\n\n      {/* Modal */}\n      <div\n        className={clsx(\n          'fixed z-[301] bg-bg-primary rounded-2xl overflow-hidden',\n          'shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-h-[85vh]',\n          widgetSlot ? 'max-w-[1000px]' : 'max-w-[700px]',\n          'max-sm:top-auto max-sm:bottom-0 max-sm:left-0 max-sm:right-0 max-sm:translate-x-0 max-sm:translate-y-0',\n          'max-sm:w-full max-sm:max-w-none max-sm:rounded-b-none max-sm:max-h-[90vh]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          className,\n        )}\n        ref={modalRef}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={title}\n      >\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-b border-border-secondary dark:border-dark-border-primary\">\n          <h2 className=\"text-base font-bold text-content-primary dark:text-dark-content-primary\">\n            {title}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className=\"p-1.5 rounded-md hover:bg-background-secondary text-content-secondary transition-all duration-150 focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary dark:hover:bg-dark-bg-secondary\"\n            aria-label={t('master_document.chrome.close')}\n          >\n            <XIcon className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/* Body */}\n        <div\n          className={clsx('flex', widgetSlot ? 'flex-row' : 'flex-col')}\n          style={{ maxHeight: 'calc(85vh - 130px)' }}\n        >\n          <div className={clsx('overflow-y-auto px-6 py-5', widgetSlot ? 'flex-1 min-w-0' : 'w-full')}>\n            {computedRules && computedRules.length > 0 && (\n              <ComputedRulesRunner rules={computedRules} control={control} setValue={setValue} />\n            )}\n\n            {serverRules && serverRules.length > 0 && onEvaluateServerRule && (\n              <ServerRulesRunner\n                rules={serverRules}\n                control={control}\n                setValue={setValue}\n                onEvaluate={onEvaluateServerRule}\n                setLoadingFields={setLoadingFields}\n              />\n            )}\n\n            {onFormValuesChange && (\n              <FormValuesWatcher control={control} onChange={onFormValuesChange} />\n            )}\n\n            {/* ── Flat layout (no sections) ── */}\n            {!sections && (\n              <div className={clsx('grid gap-4', gridClass)}>\n                {visibleFields.map(renderField)}\n              </div>\n            )}\n\n            {/* ── Accordion layout (with sections) ── */}\n            {sections && (\n              <>\n                {/* Common fields (no matching section key) above sections */}\n                {commonFields.length > 0 && (\n                  <div className={clsx('grid gap-4 mb-5', gridClass)}>\n                    {commonFields.map(renderField)}\n                  </div>\n                )}\n\n                {sections.map((section) => {\n                  const sectionFields = visibleFields.filter((f) => f.section === section.key);\n                  return (\n                    <AccordionSection\n                      key={section.key}\n                      section={section}\n                      hasFields={sectionFields.length > 0}\n                    >\n                      <div className={clsx('grid gap-4', gridClass)}>\n                        {sectionFields.map(renderField)}\n                      </div>\n                    </AccordionSection>\n                  );\n                })}\n              </>\n            )}\n          </div>\n\n          {/* Widget sidebar */}\n          {widgetSlot && (\n            <div className=\"w-72 shrink-0 border-l border-border-secondary dark:border-dark-border-primary overflow-y-auto max-sm:hidden\">\n              {widgetSlot}\n            </div>\n          )}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-6 py-4 border-t border-border-secondary dark:border-dark-border-primary\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'text-content-tertiary hover:bg-background-secondary transition-all duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'dark:text-dark-content-secondary dark:hover:bg-dark-bg-secondary',\n            )}\n          >\n            {resolvedCancelLabel}\n          </button>\n\n          {onConfirmAndAddAnother && (\n            <button\n              type=\"button\"\n              onClick={handleSubmit(handleConfirmAndAddAnother)}\n              className={clsx(\n                'px-4 py-2 rounded-md text-sm font-semibold',\n                'border border-border-primary text-content-primary hover:bg-background-secondary transition-all duration-150',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n                'dark:border-dark-border-primary dark:text-dark-content-primary dark:hover:bg-dark-bg-secondary',\n                'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              )}\n            >\n              {t('master_document.lines.saveAndAddAnother')}\n            </button>\n          )}\n\n          <button\n            type=\"button\"\n            onClick={handleSubmit(handleConfirm)}\n            className={clsx(\n              'px-5 py-2 rounded-md text-sm font-semibold',\n              'bg-primary-inverse-background text-primary-inverse-content hover:bg-primary-custom-700 transition-all duration-150',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'min-h-[36px]',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-custom-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            {resolvedConfirmLabel}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { clsx } from 'clsx';\nimport type { GlobalDiscountControlProps } from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\n\n/**\n * Control de descuento global a nivel de documento.\n *\n * Permite al usuario aplicar un descuento en modo porcentaje (%) o monto fijo\n * ($). Muestra el equivalente calculado en la unidad complementaria (si el modo\n * es porcentaje, calcula el monto; si es monto, calcula el porcentaje). En modo\n * de solo lectura (`editable={false}`) suprime los controles y presenta el\n * valor formateado.\n *\n * @see docs/colors.md - Sistema de tokens de color\n * @see MasterDocument.types - GlobalDiscountControlProps\n *\n * @example\n * ```tsx\n * <GlobalDiscountControl\n *   data={{ mode: 'percentage', percentage: 5 }}\n *   onChange={(d) => setDiscount(d)}\n *   subtotal={1200000}\n *   formatCurrency={formatCurrency}   // de useMasterDocumentFormatters()\n * />\n * ```\n */\nexport function GlobalDiscountControl({\n  data,\n  onChange,\n  subtotal,\n  formatCurrency,\n  editable = true,\n  className,\n}: GlobalDiscountControlProps) {\n  const { t } = useMasterDocumentTranslation();\n  const isPercentage = data.mode === 'percentage';\n\n  const computedAmount = isPercentage\n    ? subtotal * ((data.percentage ?? 0) / 100)\n    : (data.amount ?? 0);\n\n  const computedPct = !isPercentage && subtotal > 0\n    ? ((data.amount ?? 0) / subtotal) * 100\n    : (data.percentage ?? 0);\n\n  return (\n    <div\n      className={clsx(\n        'flex items-center gap-3 px-4 py-2.5 rounded-xl',\n        'bg-bg-primary shadow-sm',\n        'dark:bg-dark-bg-primary dark:border dark:border-dark-border-primary',\n        className,\n      )}\n    >\n      {/* Label */}\n      <span className=\"text-xs font-semibold text-content-primary dark:text-dark-content-primary shrink-0\">\n        {t('master_document.discount.globalLabel')}\n      </span>\n\n      {/* Mode toggle */}\n      {editable && (\n        <div className=\"flex rounded-md border border-border-primary dark:border-dark-border-primary overflow-hidden shrink-0\">\n          <button\n            type=\"button\"\n            onClick={() => onChange({ mode: 'percentage', percentage: computedPct, amount: undefined })}\n            aria-label={t('master_document.discount.applyPercent')}\n            aria-pressed={isPercentage}\n            className={clsx(\n              'px-2.5 py-1 text-xs font-semibold transition-colors',\n              isPercentage\n                ? 'bg-primary-600 text-white dark:text-dark-content-inverse dark:bg-primary-500'\n                : 'bg-transparent text-content-secondary dark:text-dark-content-secondary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n            )}\n          >\n            %\n          </button>\n          <button\n            type=\"button\"\n            onClick={() => onChange({ mode: 'amount', percentage: undefined, amount: computedAmount })}\n            aria-label={t('master_document.discount.applyAmount')}\n            aria-pressed={!isPercentage}\n            className={clsx(\n              'px-2.5 py-1 text-xs font-semibold transition-colors',\n              !isPercentage\n                ? 'bg-primary-600 text-white dark:text-dark-content-inverse dark:bg-primary-500'\n                : 'bg-transparent text-content-secondary dark:text-dark-content-secondary hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n            )}\n          >\n            $\n          </button>\n        </div>\n      )}\n\n      {/* Input */}\n      {editable ? (\n        <div className=\"relative flex-1 max-w-[160px]\">\n          <input\n            type=\"number\"\n            step={isPercentage ? '0.01' : '1'}\n            min=\"0\"\n            max={isPercentage ? '100' : subtotal}\n            value={isPercentage ? (data.percentage ?? '') : (data.amount ?? '')}\n            aria-label={t('master_document.discount.valueAria')}\n            onChange={(e) => {\n              const val = e.target.value === '' ? undefined : Number(e.target.value);\n              if (isPercentage) {\n                onChange({ mode: 'percentage', percentage: val, amount: undefined });\n              } else {\n                onChange({ mode: 'amount', percentage: undefined, amount: val });\n              }\n            }}\n            className={clsx(\n              \"w-full text-xs tabular-nums font-semibold text-right\",\n              'px-2.5 py-1.5 rounded-md',\n              'border border-border-primary dark:border-dark-border-primary',\n              'bg-bg-primary dark:bg-dark-bg-secondary',\n              'text-content-primary dark:text-dark-content-primary',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              isPercentage ? 'pr-6' : 'pl-5',\n            )}\n          />\n          {isPercentage ? (\n            <span className=\"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-content-tertiary dark:text-dark-content-secondary\">\n              %\n            </span>\n          ) : (\n            <span className=\"absolute left-2 top-1/2 -translate-y-1/2 text-xs text-content-tertiary dark:text-dark-content-secondary\">\n              $\n            </span>\n          )}\n        </div>\n      ) : (\n        <span className=\"text-xs tabular-nums font-semibold text-content-primary dark:text-dark-content-primary\">\n          {isPercentage ? `${data.percentage ?? 0}%` : formatCurrency(data.amount ?? 0)}\n        </span>\n      )}\n\n      {/* Computed equivalent */}\n      <span className=\"text-xs text-content-tertiary dark:text-dark-content-secondary shrink-0 ml-auto\">\n        {isPercentage\n          ? formatCurrency(computedAmount)\n          : `${subtotal > 0 ? computedPct.toFixed(2) : '0.00'}%`\n        }\n      </span>\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport type {\n  AvailableSourceDocument,\n  CrossDocumentPanelProps,\n  CrossingDocumentType,\n} from './MasterDocument.types';\nimport { Loading } from './components/loading';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { useMasterDocumentFormatters } from './formatters';\nimport { inlineActionButton } from './inlineActions';\n\n// ─── Badge de signo \"ECD · +\" / \"DCD · −\" (Story 105-5.02) ──\nfunction SignBadge({ type }: { type: CrossingDocumentType }) {\n  const isEcd = type === 'ECD';\n  return (\n    <span\n      className={clsx(\n        'inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-xs font-bold',\n        isEcd\n          ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'\n          : 'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300',\n      )}\n    >\n      {type} · {isEcd ? '+' : '−'}\n    </span>\n  );\n}\n\n// ─── Fila de documento disponible ──────────────────────────\nfunction AvailableRow({\n  doc,\n  selected,\n  editable,\n  disabled,\n  onToggle,\n  formatCurrency,\n  lineCountText,\n}: {\n  doc: AvailableSourceDocument;\n  selected: boolean;\n  editable: boolean;\n  disabled: boolean;\n  onToggle: (id: string, selected: boolean) => void;\n  formatCurrency: (value: number) => string;\n  /** Devuelve la frase completa ya pluralizada, p. ej. \"3 líneas\". */\n  lineCountText: (count: number) => string;\n}) {\n  return (\n    <tr\n      className={clsx(\n        'border-t border-border-primary dark:border-dark-border-primary transition-colors',\n        selected && 'bg-primary-custom-50 dark:bg-dark-bg-custom/40',\n      )}\n    >\n      {editable && (\n        <td className=\"px-2 py-2 align-middle\">\n          <input\n            type=\"checkbox\"\n            checked={selected}\n            disabled={disabled}\n            onChange={(e) => onToggle(doc.id, e.target.checked)}\n            aria-label={`Seleccionar ${doc.classLabel} ${doc.number}`}\n            className=\"w-4 h-4 rounded border-border-primary dark:border-dark-border-primary accent-primary-custom-600 cursor-pointer disabled:cursor-not-allowed\"\n          />\n        </td>\n      )}\n      <td className=\"px-2 py-2 align-middle\">\n        <div className=\"flex items-center gap-2\">\n          <SignBadge type={doc.type} />\n          <span className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary\">\n            {doc.number}\n          </span>\n        </div>\n        <span className=\"block text-xs text-content-secondary dark:text-dark-content-secondary\">\n          {doc.classLabel}\n          {doc.date ? ` · ${doc.date}` : ''}\n          {doc.lineCount != null ? ` · ${lineCountText(doc.lineCount)}` : ''}\n        </span>\n      </td>\n      <td className=\"px-2 py-2 align-middle text-right text-sm font-mono text-content-primary dark:text-dark-content-primary whitespace-nowrap\">\n        {doc.crossingSign < 0 ? '−' : '+'}\n        {formatCurrency(doc.netTotal)}\n      </td>\n    </tr>\n  );\n}\n\n/**\n * CrossDocumentPanel — panel de cruce WHOLE-DOCUMENT (Épica 105-5).\n *\n * Selección de documentos ENTEROS (ECD/DCD) con badge de signo, subtotal corrido\n * `Σ(ECDs.net) − Σ(DCDs.net)` reactivo, acción \"Cruzar\" y, sobre los ya cruzados,\n * \"Desvincular\" por documento. En modo no editable se presenta como histórico\n * read-only (sin checkboxes ni acciones). Alimentado por {@link useCrossDocuments}.\n */\nexport function CrossDocumentPanel({\n  available,\n  selectedIds,\n  subtotal,\n  loading = false,\n  busy = false,\n  editable = false,\n  error,\n  onToggleSelect,\n  onCross,\n  onRefresh,\n  formatCurrency: formatCurrencyProp,\n  messages,\n  className,\n}: CrossDocumentPanelProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatCurrency: formatCurrencyDefault } = useMasterDocumentFormatters();\n  const formatCurrency = formatCurrencyProp ?? formatCurrencyDefault;\n  const selected = new Set(selectedIds);\n  const title = messages?.title ?? t('master_document.crossing.panelTitle');\n  const emptyAvailable = messages?.emptyAvailable ?? t('master_document.crossing.emptyAvailable');\n  const subtotalLabel = messages?.subtotalLabel ?? t('master_document.crossing.subtotalLabel');\n  const crossButton = messages?.crossButton ?? t('master_document.crossing.crossButton');\n  // El override del template sigue siendo una etiqueta suelta (contrato histórico),\n  // así que en ese camino se concatena como antes. Sin override, la clave con\n  // plural produce la frase completa y el orden lo decide la traducción.\n  const lineCountText = (count: number): string =>\n    messages?.lineCountLabel\n      ? `${count} ${messages.lineCountLabel}`\n      : t('master_document.crossing.lineCount', { count });\n\n  return (\n    <div\n      className={clsx(\n        'bg-bg-primary dark:bg-dark-bg-primary',\n        'border border-border-primary dark:border-dark-border-primary',\n        'rounded-xl p-3',\n        className,\n      )}\n    >\n      <div className=\"flex items-center justify-between mb-2\">\n        <span className=\"text-xs font-bold text-content-secondary dark:text-dark-content-secondary uppercase tracking-wide\">\n          {title}\n        </span>\n        {onRefresh && (\n          <button\n            type=\"button\"\n            onClick={onRefresh}\n            disabled={loading || busy}\n            className={inlineActionButton}\n          >\n            {t('master_document.chrome.refresh')}\n          </button>\n        )}\n      </div>\n\n      {error && (\n        <div className=\"mb-2 px-2.5 py-2 rounded-md text-xs bg-rose-50 text-rose-700 border border-rose-200 dark:bg-rose-900/30 dark:text-rose-300 dark:border-rose-800\">\n          {error}\n        </div>\n      )}\n\n      {loading ? (\n        <Loading size=\"md\" label={t('master_document.crossing.loading')} />\n      ) : available.length === 0 ? (\n        <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary py-2\">{emptyAvailable}</p>\n      ) : (\n        <table className=\"w-full text-left\">\n          <tbody>\n            {available.map((doc) => (\n              <AvailableRow\n                key={doc.id}\n                doc={doc}\n                selected={selected.has(doc.id)}\n                editable={editable}\n                disabled={busy}\n                onToggle={onToggleSelect}\n                formatCurrency={formatCurrency}\n                lineCountText={lineCountText}\n              />\n            ))}\n          </tbody>\n        </table>\n      )}\n\n      {/* Subtotal corrido + acción Cruzar (solo editable) */}\n      {editable && available.length > 0 && (\n        <div className=\"mt-3 pt-3 border-t border-border-primary dark:border-dark-border-primary flex items-center justify-between gap-3\">\n          <div className=\"flex flex-col\">\n            <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">{subtotalLabel}</span>\n            <span className=\"text-base font-bold font-mono text-content-primary dark:text-dark-content-primary\">\n              {formatCurrency(subtotal)}\n            </span>\n          </div>\n          <button\n            type=\"button\"\n            onClick={onCross}\n            disabled={busy || selectedIds.length === 0}\n            className={clsx(\n              'px-3 py-1.5 rounded-md text-sm font-medium transition-colors cursor-pointer',\n              'bg-primary-custom-600 text-white hover:bg-primary-custom-700',\n              'dark:bg-dark-bg-custom dark:text-dark-content-custom dark:hover:bg-dark-border-custom',\n              'disabled:opacity-50 disabled:cursor-not-allowed',\n            )}\n          >\n            {busy ? t('master_document.crossing.crossing') : `${crossButton}${selectedIds.length ? ` (${selectedIds.length})` : ''}`}\n          </button>\n        </div>\n      )}\n    </div>\n  );\n}\n","import { clsx } from 'clsx';\nimport type {\n  CrossedSourceDocument,\n  CrossingDocumentType,\n  SourceDocumentsFactBoxProps,\n} from './MasterDocument.types';\nimport { useMasterDocumentTranslation } from './i18n';\nimport { useMasterDocumentFormatters } from './formatters';\nimport { inlineActionButtonDanger } from './inlineActions';\n\nfunction SignBadge({ type }: { type: CrossingDocumentType }) {\n  const isEcd = type === 'ECD';\n  return (\n    <span\n      className={clsx(\n        'inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-xs font-bold',\n        isEcd\n          ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'\n          : 'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300',\n      )}\n    >\n      {type} · {isEcd ? '+' : '−'}\n    </span>\n  );\n}\n\n// ─── Badge de estado del padre (POSTED → INVOICED) ─────────\nfunction StateBadge({ state }: { state: string }) {\n  const upper = state.toUpperCase();\n  const isInvoiced = upper === 'INVOICED';\n  return (\n    <span\n      className={clsx(\n        'inline-flex items-center px-1.5 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wide',\n        isInvoiced\n          ? 'bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300'\n          : 'bg-bg-secondary text-content-secondary dark:bg-dark-bg-secondary dark:text-dark-content-secondary',\n      )}\n    >\n      {state}\n    </span>\n  );\n}\n\nfunction CrossedRow({\n  doc,\n  editable,\n  busy,\n  onUncross,\n  formatCurrency,\n  uncrossLabel,\n}: {\n  doc: CrossedSourceDocument;\n  editable: boolean;\n  busy: boolean;\n  onUncross?: (id: string) => void;\n  formatCurrency: (value: number) => string;\n  uncrossLabel: string;\n}) {\n  return (\n    <li className=\"flex items-start justify-between gap-2 py-2 border-t border-border-primary dark:border-dark-border-primary first:border-t-0\">\n      <div className=\"min-w-0\">\n        <div className=\"flex items-center gap-2 flex-wrap\">\n          <SignBadge type={doc.type} />\n          <span className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary truncate\">\n            {doc.number}\n          </span>\n          {doc.state && <StateBadge state={doc.state} />}\n        </div>\n        <span className=\"block text-xs text-content-secondary dark:text-dark-content-secondary\">\n          {doc.classLabel}\n        </span>\n      </div>\n      <div className=\"flex flex-col items-end gap-1 flex-shrink-0\">\n        <span className=\"text-sm font-mono text-content-primary dark:text-dark-content-primary whitespace-nowrap\">\n          {doc.crossingSign < 0 ? '−' : '+'}\n          {formatCurrency(doc.netTotal)}\n        </span>\n        {editable && onUncross && (\n          <button\n            type=\"button\"\n            onClick={() => onUncross(doc.id)}\n            disabled={busy}\n            className={inlineActionButtonDanger}\n          >\n            {uncrossLabel}\n          </button>\n        )}\n      </div>\n    </li>\n  );\n}\n\n/**\n * SourceDocumentsFactBox — widget FactBox \"Documentos origen\" (Épica 105-5,\n * Story 105-5.04). Lista los documentos padre YA cruzados con su badge de signo\n * (ECD·+/DCD·−), estado (POSTED→INVOICED) y, en modo editable, \"Desvincular\"\n * por documento. Pensado para registrarse como `children` de un\n * `FactBoxSectionConfig` (ADR-017).\n */\nexport function SourceDocumentsFactBox({\n  documents,\n  subtotal,\n  editable = false,\n  busy = false,\n  onUncross,\n  formatCurrency: formatCurrencyProp,\n  messages,\n  className,\n}: SourceDocumentsFactBoxProps) {\n  const { t } = useMasterDocumentTranslation();\n  const { formatCurrency: formatCurrencyDefault } = useMasterDocumentFormatters();\n  const formatCurrency = formatCurrencyProp ?? formatCurrencyDefault;\n  const emptyCrossed = messages?.emptyCrossed ?? t('master_document.crossing.emptyCrossed');\n  const uncrossLabel = messages?.uncross ?? t('master_document.crossing.uncross');\n  const subtotalLabel = messages?.subtotalLabel ?? t('master_document.crossing.subtotalLabel');\n\n  if (documents.length === 0) {\n    return (\n      <p className={clsx('text-sm text-content-secondary dark:text-dark-content-secondary px-1 py-2', className)}>\n        {emptyCrossed}\n      </p>\n    );\n  }\n\n  return (\n    <div className={className}>\n      <ul className=\"px-1\">\n        {documents.map((doc) => (\n          <CrossedRow\n            key={doc.id}\n            doc={doc}\n            editable={editable}\n            busy={busy}\n            onUncross={onUncross}\n            formatCurrency={formatCurrency}\n            uncrossLabel={uncrossLabel}\n          />\n        ))}\n      </ul>\n      {subtotal != null && (\n        <div className=\"mt-2 pt-2 px-1 border-t border-border-primary dark:border-dark-border-primary flex items-center justify-between\">\n          <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary\">{subtotalLabel}</span>\n          <span className=\"text-sm font-bold font-mono text-content-primary dark:text-dark-content-primary\">\n            {formatCurrency(subtotal)}\n          </span>\n        </div>\n      )}\n    </div>\n  );\n}\n","import { useState, useEffect, useCallback, useMemo } from 'react';\nimport type { CrossDocumentsTemplateConfig } from '../template/MasterDocumentTemplate.types';\nimport type {\n  AvailableSourceDocument,\n  CrossedSourceDocument,\n  CrossingDocumentType,\n} from '../MasterDocument.types';\nimport { resolveCrossingError } from './crossingFetch';\nimport { useMasterDocumentTranslation } from '../i18n';\nimport type { CrossingFetch } from './crossingFetch';\n\n// ─── Rutas canónicas (override vía template.crossDocuments.routes) ──\n// El consumidor normalmente remapea estas rutas a su backend vía\n// `adapter.genericFetch`. `{id}` se sustituye por el documentId.\nconst DEFAULT_ROUTES = {\n  available: '/api/v1/crossings/available-source-documents?document_id={id}',\n  crossed: '/api/v1/crossings/{id}/source-documents',\n  cross: '/api/v1/crossings/{id}/cross',\n  uncross: '/api/v1/crossings/{id}/uncross',\n} as const;\n\nfunction buildRoute(\n  template: string,\n  documentId: string,\n): string {\n  return template.replace('{id}', encodeURIComponent(documentId));\n}\n\n// ─── Normalización del sign (acepta number/string del backend) ─────\nfunction normalizeSign(raw: unknown): 1 | -1 {\n  const n = typeof raw === 'string' ? Number(raw) : (raw as number);\n  return Number.isFinite(n) && n < 0 ? -1 : 1;\n}\n\nfunction deriveType(\n  rawType: unknown,\n  sign: 1 | -1,\n): CrossingDocumentType {\n  if (typeof rawType === 'string') {\n    const upper = rawType.toUpperCase();\n    if (upper === 'ECD' || upper === 'DCD') return upper;\n  }\n  return sign < 0 ? 'DCD' : 'ECD';\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction mapAvailable(raw: any): AvailableSourceDocument {\n  const crossingSign = normalizeSign(raw.crossing_sign ?? raw.crossingSign);\n  const lineCountRaw = raw.line_count ?? raw.lineCount;\n  return {\n    id: String(raw.id ?? raw.document_id ?? raw.documentId),\n    number: String(raw.prefix_number ?? raw.number ?? raw.document_number ?? raw.documentNumber ?? ''),\n    type: deriveType(raw.type ?? raw.parent_class_code ?? raw.parentClassCode, crossingSign),\n    classLabel: String(raw.class_label ?? raw.classLabel ?? raw.parent_class_code ?? raw.parentClassCode ?? ''),\n    crossingSign,\n    netTotal: Number(raw.net_total ?? raw.netTotal ?? 0),\n    date: raw.date ?? raw.document_date ?? raw.documentDate ?? undefined,\n    lineCount: lineCountRaw != null ? Number(lineCountRaw) : undefined,\n    state: raw.state ?? undefined,\n  };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction mapCrossed(raw: any): CrossedSourceDocument {\n  const crossingSign = normalizeSign(raw.crossing_sign ?? raw.crossingSign);\n  return {\n    id: String(raw.id ?? raw.document_id ?? raw.documentId),\n    number: String(raw.prefix_number ?? raw.number ?? raw.document_number ?? raw.documentNumber ?? ''),\n    type: deriveType(raw.type ?? raw.parent_class_code ?? raw.parentClassCode, crossingSign),\n    classLabel: String(raw.class_label ?? raw.classLabel ?? raw.parent_class_code ?? raw.parentClassCode ?? ''),\n    crossingSign,\n    netTotal: Number(raw.net_total ?? raw.netTotal ?? 0),\n    state: raw.state ?? undefined,\n    date: raw.date ?? raw.document_date ?? raw.documentDate ?? undefined,\n  };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction toArray(payload: any, key: string): any[] {\n  if (Array.isArray(payload)) return payload;\n  return payload?.[key] ?? payload?.data ?? payload?.items ?? [];\n}\n\ninterface UseCrossDocumentsOptions {\n  config: CrossDocumentsTemplateConfig | undefined;\n  documentId: string | undefined;\n  docState: string;\n  /** Salida HTTP (enruta por `adapter.genericFetch`). Ver {@link createCrossingFetch}. */\n  crossingFetch: CrossingFetch;\n  /**\n   * ¿El usuario tiene el permiso (`requiresPermission`)? El kit no resuelve RBAC;\n   * el consumidor inyecta este booleano. Si se omite, se asume `true`.\n   */\n  canCross?: boolean;\n  /** Notifica al consumidor tras un cross/uncross exitoso (para invalidar detail/totals/FactBox). */\n  onCrossingChanged?: () => void;\n}\n\nexport interface CrossDocumentsState {\n  available: AvailableSourceDocument[];\n  crossed: CrossedSourceDocument[];\n  selectedIds: string[];\n  /** `Σ(ECDs.net) − Σ(DCDs.net)` de la selección actual. */\n  subtotal: number;\n  /** Subtotal consolidado de los documentos ya cruzados. */\n  crossedSubtotal: number;\n  loading: boolean;\n  busy: boolean;\n  /** Editable = estado en `crossOn` Y permiso concedido. */\n  editable: boolean;\n  error: string | undefined;\n}\n\nexport interface CrossDocumentsActions {\n  toggleSelect: (id: string, selected: boolean) => void;\n  cross: () => Promise<void>;\n  uncross: (sourceDocumentId: string) => Promise<void>;\n  refresh: () => void;\n  clearError: () => void;\n}\n\nfunction useCrossDocumentsInternal({\n  config,\n  documentId,\n  docState,\n  crossingFetch,\n  canCross = true,\n  onCrossingChanged,\n}: UseCrossDocumentsOptions): { state: CrossDocumentsState; actions: CrossDocumentsActions } {\n  // Traduce los errores que genera el kit; los que trae el backend pasan intactos.\n  const { t } = useMasterDocumentTranslation();\n  const [available, setAvailable] = useState<AvailableSourceDocument[]>([]);\n  const [crossed, setCrossed] = useState<CrossedSourceDocument[]>([]);\n  const [selectedIds, setSelectedIds] = useState<string[]>([]);\n  const [loading, setLoading] = useState(false);\n  const [busy, setBusy] = useState(false);\n  const [error, setError] = useState<string | undefined>(undefined);\n\n  const routes = useMemo(\n    () => ({ ...DEFAULT_ROUTES, ...(config?.routes ?? {}) }),\n    [config?.routes],\n  );\n\n  const editable = canCross && !!config && (config.crossOn?.includes(docState) ?? false);\n\n  // ── Fetch de disponibles + cruzados ──────────────────────\n  const fetchAll = useCallback(() => {\n    if (!config || !config.enabled || !documentId) return;\n    setLoading(true);\n    setError(undefined);\n    Promise.allSettled([\n      crossingFetch<unknown>('GET', buildRoute(routes.available, documentId)),\n      crossingFetch<unknown>('GET', buildRoute(routes.crossed, documentId)),\n    ])\n      .then(([availRes, crossedRes]) => {\n        if (availRes.status === 'fulfilled') {\n          setAvailable(toArray(availRes.value, 'documents').map(mapAvailable));\n        } else {\n          // Falla de disponibles SÍ es relevante para el usuario (no puede cruzar).\n          setError(resolveCrossingError(availRes.reason, t).message);\n        }\n        // El endpoint de cruzados puede no existir todavía (degradación suave): si\n        // falla, dejamos la lista vacía sin romper el panel de disponibles.\n        if (crossedRes.status === 'fulfilled') {\n          setCrossed(toArray(crossedRes.value, 'documents').map(mapCrossed));\n        }\n      })\n      .finally(() => setLoading(false));\n  }, [config, documentId, crossingFetch, routes.available, routes.crossed, t]);\n\n  useEffect(() => {\n    if (!config || !config.enabled || !documentId) return;\n    fetchAll();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [documentId, config]);\n\n  // ── Selección whole-document ─────────────────────────────\n  const toggleSelect = useCallback((id: string, selected: boolean) => {\n    setSelectedIds((prev) =>\n      selected ? [...prev.filter((x) => x !== id), id] : prev.filter((x) => x !== id),\n    );\n  }, []);\n\n  // ── Subtotal corrido Σ(ECD.net) − Σ(DCD.net) ─────────────\n  // Los montos viajan positivos; el signo solo agrega (no se remultiplica).\n  const subtotal = useMemo(() => {\n    const selected = new Set(selectedIds);\n    return available.reduce(\n      (acc, doc) => (selected.has(doc.id) ? acc + doc.crossingSign * doc.netTotal : acc),\n      0,\n    );\n  }, [available, selectedIds]);\n\n  const crossedSubtotal = useMemo(\n    () => crossed.reduce((acc, doc) => acc + doc.crossingSign * doc.netTotal, 0),\n    [crossed],\n  );\n\n  // ── Cruzar (todo-o-nada sobre la selección) ──────────────\n  const cross = useCallback(async () => {\n    if (!config || !documentId || selectedIds.length === 0) return;\n    setBusy(true);\n    setError(undefined);\n    try {\n      await crossingFetch('POST', buildRoute(routes.cross, documentId), {\n        source_document_ids: selectedIds,\n      });\n      setSelectedIds([]);\n      fetchAll();\n      onCrossingChanged?.();\n    } catch (err) {\n      setError(resolveCrossingError(err, t).message);\n    } finally {\n      setBusy(false);\n    }\n  }, [config, documentId, selectedIds, crossingFetch, routes.cross, fetchAll, onCrossingChanged, t]);\n\n  // ── Desvincular un documento ya cruzado ──────────────────\n  const uncross = useCallback(\n    async (sourceDocumentId: string) => {\n      if (!config || !documentId) return;\n      setBusy(true);\n      setError(undefined);\n      try {\n        await crossingFetch('POST', buildRoute(routes.uncross, documentId), {\n          source_document_id: sourceDocumentId,\n        });\n        fetchAll();\n        onCrossingChanged?.();\n      } catch (err) {\n        setError(resolveCrossingError(err, t).message);\n      } finally {\n        setBusy(false);\n      }\n    },\n    [config, documentId, crossingFetch, routes.uncross, fetchAll, onCrossingChanged, t],\n  );\n\n  const clearError = useCallback(() => setError(undefined), []);\n\n  const state: CrossDocumentsState = {\n    available,\n    crossed,\n    selectedIds,\n    subtotal,\n    crossedSubtotal,\n    loading,\n    busy,\n    editable,\n    error,\n  };\n\n  const actions: CrossDocumentsActions = {\n    toggleSelect,\n    cross,\n    uncross,\n    refresh: fetchAll,\n    clearError,\n  };\n\n  return { state, actions };\n}\n\n/**\n * Motor de cruce WHOLE-DOCUMENT (Épica 105-5). Devuelve `null` cuando\n * `config` está ausente o deshabilitado. Mantiene la misma forma que\n * {@link useCrossing} (per-línea) pero con el modelo documento-entero:\n * selección todo-o-nada, signo +/−, subtotal `Σ(ECD)−Σ(DCD)`, cruzar/desvincular.\n */\nexport function useCrossDocuments(\n  options: UseCrossDocumentsOptions,\n): { state: CrossDocumentsState; actions: CrossDocumentsActions } | null {\n  const result = useCrossDocumentsInternal(options);\n  if (!options.config || !options.config.enabled) return null;\n  return result;\n}\n","import { createTranslationHook } from '../i18nFactory';\nimport { TEXTO_COMUN_ES, TEXTO_COMUN_EN } from '../commonTexts';\nimport type { TranslateFn } from '../i18nFactory';\n\n/**\n * i18n del widget de Anticipos.\n *\n * Cumple CA-F8 (usa `useTranslation` de siesa-ui-kit) y CA-F9 (paridad ES/EN).\n * El motor de traducción del kit hace fallback al `key` cuando el host no ha\n * registrado las claves `advances.*`; por eso este módulo provee diccionarios\n * locales que se usan como respaldo según el idioma activo, garantizando texto\n * listo para usar sin depender de que el documento consumidor registre los recursos.\n *\n * Las claves siguen el formato plano (no anidado) que espera\n * `DefaultTranslationEngine`.\n */\n\nexport const ADVANCES_TRANSLATIONS_ES: Record<string, string> = {\n  'advances.panel.title': 'Anticipos aplicados',\n  'advances.panel.empty': 'No hay anticipos aplicados a este documento.',\n  'advances.panel.apply': 'Aplicar anticipo',\n  'advances.panel.remove': 'Quitar',\n  'advances.panel.removeAria': 'Quitar anticipo aplicado',\n  'advances.panel.available_one': '{count} saldo disponible',\n  'advances.panel.available_other': '{count} saldos disponibles',\n  'advances.panel.loading': 'Cargando anticipos…',\n  'advances.panel.loadError': 'No se pudieron cargar los anticipos.',\n  'advances.status.reserved': 'Reservado',\n  'advances.status.confirmed': 'Confirmado',\n  'advances.status.reversed': 'Reversado',\n  'advances.modal.title': 'Aplicar anticipo',\n  'advances.modal.balanceLabel': 'Saldo de anticipo',\n  'advances.modal.balancePlaceholder': 'Selecciona un saldo de anticipo',\n  'advances.modal.amountLabel': 'Monto a aplicar',\n  'advances.modal.availableLabel': 'Disponible',\n  'advances.modal.cancel': TEXTO_COMUN_ES.cancel,\n  'advances.modal.confirm': 'Aplicar anticipo',\n  'advances.modal.applying': 'Aplicando…',\n  'advances.error.amountPositive': 'El monto debe ser mayor a 0.',\n  'advances.error.amountExceeds': 'El monto supera el disponible del saldo.',\n  'advances.error.selectBalance': 'Selecciona un saldo de anticipo.',\n  'advances.error.generic': TEXTO_COMUN_ES.errorGeneric,\n  'advances.error.forbidden': TEXTO_COMUN_ES.errorForbidden,\n  'advances.toast.applied': 'Anticipo aplicado correctamente.',\n  'advances.toast.removed': 'Anticipo quitado correctamente.',\n};\n\nexport const ADVANCES_TRANSLATIONS_EN: Record<string, string> = {\n  'advances.panel.title': 'Applied advances',\n  'advances.panel.empty': 'No advances applied to this document.',\n  'advances.panel.apply': 'Apply advance',\n  'advances.panel.remove': 'Remove',\n  'advances.panel.removeAria': 'Remove applied advance',\n  'advances.panel.available_one': '{count} available balance',\n  'advances.panel.available_other': '{count} available balances',\n  'advances.panel.loading': 'Loading advances…',\n  'advances.panel.loadError': 'Could not load advances.',\n  'advances.status.reserved': 'Reserved',\n  'advances.status.confirmed': 'Confirmed',\n  'advances.status.reversed': 'Reversed',\n  'advances.modal.title': 'Apply advance',\n  'advances.modal.balanceLabel': 'Advance balance',\n  'advances.modal.balancePlaceholder': 'Select an advance balance',\n  'advances.modal.amountLabel': 'Amount to apply',\n  'advances.modal.availableLabel': 'Available',\n  'advances.modal.cancel': TEXTO_COMUN_EN.cancel,\n  'advances.modal.confirm': 'Apply advance',\n  'advances.modal.applying': 'Applying…',\n  'advances.error.amountPositive': 'The amount must be greater than 0.',\n  'advances.error.amountExceeds': 'The amount exceeds the balance available.',\n  'advances.error.selectBalance': 'Select an advance balance.',\n  'advances.error.generic': TEXTO_COMUN_EN.errorGeneric,\n  'advances.error.forbidden': TEXTO_COMUN_EN.errorForbidden,\n  'advances.toast.applied': 'Advance applied successfully.',\n  'advances.toast.removed': 'Advance removed successfully.',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const ADVANCES_TRANSLATIONS = {\n  es: ADVANCES_TRANSLATIONS_ES,\n  en: ADVANCES_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción con interpolación `{var}`. */\nexport type AdvancesT = TranslateFn;\n\n/**\n * Hook de traducción del widget.\n *\n * Usa `useTranslation` del kit; si la clave no está registrada en el host\n * (el motor devuelve la propia clave), cae al diccionario local del idioma activo.\n */\nexport const useAdvancesTranslation = createTranslationHook(ADVANCES_TRANSLATIONS);\n","import { Badge } from '../../Badge/Badge';\nimport type { BadgeColor } from '../../Badge/Badge.types';\nimport { useAdvancesTranslation } from './i18n';\nimport type { AdvanceApplicationStatus } from './types';\n\n/** Mapeo estado → color de Badge (§4.3). */\nconst STATUS_COLOR: Record<AdvanceApplicationStatus, BadgeColor> = {\n  RESERVED: 'blue',\n  CONFIRMED: 'green',\n  REVERSED: 'zinc',\n};\n\n/** Mapeo estado → clave i18n de la etiqueta. */\nconst STATUS_LABEL_KEY: Record<AdvanceApplicationStatus, string> = {\n  RESERVED: 'advances.status.reserved',\n  CONFIRMED: 'advances.status.confirmed',\n  REVERSED: 'advances.status.reversed',\n};\n\nexport interface AdvanceStatusBadgeProps {\n  status: AdvanceApplicationStatus;\n  /** Etiqueta provista por el backend (`statusLabel`); tiene prioridad si existe. */\n  statusLabel?: string | null;\n  /** Texto del tooltip (fecha correspondiente al estado). */\n  tooltip?: string;\n}\n\n/**\n * Badge de estado de una aplicación de anticipo.\n *\n * Reutiliza el componente `Badge` del kit (que ya incluye dark mode por tokens).\n * Colores: RESERVED azul, CONFIRMED verde, REVERSED gris (§4.3 / CA-F2).\n */\nexport function AdvanceStatusBadge({ status, statusLabel, tooltip }: AdvanceStatusBadgeProps) {\n  const { t } = useAdvancesTranslation();\n  const label = statusLabel?.trim() || t(STATUS_LABEL_KEY[status]);\n\n  return <Badge color={STATUS_COLOR[status]} label={label} title={tooltip} />;\n}\n","/**\n * Claves de caché de TanStack Query reconciliadas (INC-09 / CA-F7).\n *\n * - `available-advances`: saldos disponibles del proveedor (lo que el modal busca).\n * - `advance-applications`: aplicaciones ya aplicadas al documento (lo que el panel renderiza).\n *\n * No confundir ambas: son dos dominios distintos con dos claves distintas (R7).\n */\n\nexport const availableAdvancesQueryKey = (documentId: string) =>\n  ['available-advances', documentId] as const;\n\nexport const advanceApplicationsQueryKey = (documentId: string) =>\n  ['advance-applications', documentId] as const;\n","import { useQuery } from '@tanstack/react-query';\nimport { availableAdvancesQueryKey } from './keys';\nimport type { AdvancesHttpRequest, SupplierOpenBalanceDto } from '../types';\n\nexport interface UseAvailableAdvancesParams {\n  documentId: string;\n  /** Endpoint GET de saldos disponibles (`/documents/{id}/available-advances`). */\n  availableAdvancesEndpoint: string;\n  httpRequest: AdvancesHttpRequest;\n  enabled?: boolean;\n}\n\n/**\n * Lista los saldos de anticipo disponibles para el documento.\n *\n * Cache key: `['available-advances', documentId]`.\n * Array vacío (200) es un estado válido: el documento no tiene saldos.\n */\nexport function useAvailableAdvances({\n  documentId,\n  availableAdvancesEndpoint,\n  httpRequest,\n  enabled = true,\n}: UseAvailableAdvancesParams) {\n  return useQuery<SupplierOpenBalanceDto[]>({\n    queryKey: availableAdvancesQueryKey(documentId),\n    enabled: enabled && Boolean(documentId),\n    queryFn: async () => {\n      const data = await httpRequest<SupplierOpenBalanceDto[]>('GET', availableAdvancesEndpoint);\n      return data ?? [];\n    },\n  });\n}\n","import type { Fetcher } from '../../LookupField/services/api.types';\n\n/**\n * Tipos del widget AdvanceApplicationsPanel (FEAT-102-5) — sub-componente de\n * MasterDocument.\n *\n * Espejo TypeScript de los DTOs del backend de Anticipos (FEAT-102) más los\n * contratos de props del widget reutilizable. Se integra en una sección FactBox\n * de cualquier documento MasterDocument.\n *\n * @see docs/feat-102-5-anticipo-masterdocument-integration-spec.md\n */\n\n// ─── Estados del ciclo de vida ────────────────────────────────────────────\n\n/**\n * Estado de una aplicación de anticipo.\n * Orden monótono estricto: RESERVED → CONFIRMED → REVERSED (RB-4).\n */\nexport type AdvanceApplicationStatus = 'RESERVED' | 'CONFIRMED' | 'REVERSED';\n\n/**\n * Códigos enteros emitidos por el backend (`AdvanceApplicationStatus`):\n * Reserved=0, Confirmed=1, Reversed=2.\n */\nconst STATUS_BY_CODE: Record<number, AdvanceApplicationStatus> = {\n  0: 'RESERVED',\n  1: 'CONFIRMED',\n  2: 'REVERSED',\n};\n\n/**\n * Normaliza el `status` recibido del backend a la unión string del widget.\n *\n * Resuelve la discrepancia de contrato (§6.3 / R2 de la spec): el backend hoy\n * emite `status` como entero (0/1/2) + `statusLabel` en español, mientras que\n * el frontend trabaja con el enum string. Esta función acepta ambos formatos\n * de forma defensiva para evitar regresiones de render de badges.\n */\nexport function normalizeAdvanceStatus(\n  status: number | string | null | undefined,\n): AdvanceApplicationStatus {\n  if (typeof status === 'number') {\n    return STATUS_BY_CODE[status] ?? 'RESERVED';\n  }\n  if (typeof status === 'string') {\n    const upper = status.toUpperCase();\n    if (upper === 'RESERVED' || upper === 'CONFIRMED' || upper === 'REVERSED') {\n      return upper;\n    }\n  }\n  // Respuesta sin status (ej: 204 No Content tras editar) → fallback seguro.\n  return 'RESERVED';\n}\n\n// ─── DTOs ──────────────────────────────────────────────────────────────────\n\n/**\n * Saldo abierto de anticipo del proveedor (`supplier_open_balances`).\n * Solo se listan/buscan saldos `isActive=true` y `availableAmount > 0` (RB-8).\n */\nexport interface SupplierOpenBalanceDto {\n  id: string;\n  supplierId: string;\n  companyId: string;\n  currencyId: string;\n  originalAmount: number;\n  availableAmount: number;\n  sourceDocumentId?: string | null;\n  sourceDocumentReference?: string | null;\n  operationCenterId?: string | null;\n  businessUnitId?: string | null;\n  auxiliaryId?: string | null;\n  isActive: boolean;\n  rowVersion: number;\n}\n\n/**\n * Aplicación de anticipo contra un documento (`document_advance_applications`).\n * `status` ya viene normalizado a la unión string (ver {@link normalizeAdvanceApplication}).\n */\nexport interface DocumentAdvanceApplicationDto {\n  id: string;\n  documentId: string;\n  openBalanceId: string;\n  appliedAmount: number;\n  appliedAmountAlt?: number | null;\n  currencyId: string;\n  status: AdvanceApplicationStatus;\n  /** Etiqueta en español opcional provista por el backend (`statusLabel`). */\n  statusLabel?: string | null;\n  /** Referencia legible del saldo origen, si el backend la incluye (para mostrar). */\n  sourceDocumentReference?: string | null;\n  reservedAt: string;\n  confirmedAt?: string | null;\n  reversedAt?: string | null;\n  confirmedBy?: string | null;\n  reversedBy?: string | null;\n  notes?: string | null;\n  rowVersion: number;\n}\n\n/**\n * Forma cruda como puede llegar del backend: `status` int o string.\n * Se normaliza con {@link normalizeAdvanceApplication} antes de usarse en UI.\n */\nexport interface RawDocumentAdvanceApplicationDto\n  extends Omit<DocumentAdvanceApplicationDto, 'status'> {\n  status: number | AdvanceApplicationStatus;\n}\n\n/** Normaliza una aplicación cruda del backend al DTO de UI. */\nexport function normalizeAdvanceApplication(\n  raw: RawDocumentAdvanceApplicationDto,\n): DocumentAdvanceApplicationDto {\n  return {\n    ...(raw ?? ({} as RawDocumentAdvanceApplicationDto)),\n    status: normalizeAdvanceStatus(raw?.status),\n  };\n}\n\n/** Payload HTTP de reserva (lo que el consumidor expone en `POST /{id}/advances`). */\nexport interface CreateAdvanceApplicationRequest {\n  openBalanceId: string;\n  appliedAmount: number;\n}\n\n// ─── IO inyectada ────────────────────────────────────────────────────────\n\n/**\n * Cliente HTTP inyectado para las operaciones REST del widget.\n *\n * El kit no depende de `axios`; el documento consumidor inyecta su instancia\n * ya configurada (interceptores de auth/company) envuelta en esta firma.\n * Espeja el patrón `IMasterDocumentAdapter.genericFetch(method, path, body)`.\n *\n * Debe rechazar con un error que exponga `status` (número HTTP) para que el\n * widget pueda distinguir 422/409 (toast) de 403 (Info inline).\n */\nexport type AdvancesHttpRequest = <T = unknown>(\n  method: 'GET' | 'POST' | 'DELETE',\n  url: string,\n  body?: unknown,\n) => Promise<T>;\n\n/** Error normalizado que el widget interpreta para el manejo de UI. */\nexport interface AdvancesHttpError extends Error {\n  status?: number;\n}\n\n// ─── Props ─────────────────────────────────────────────────────────────────\n\n/**\n * Props del panel principal `AdvanceApplicationsPanel`.\n *\n * El widget es agnóstico del documento: recibe sus endpoints e IO por props,\n * lo que permite montarlo en cualquier MasterDocument (CA-I4 / CA-F4).\n */\nexport interface AdvanceApplicationsPanelProps {\n  /** UUID del documento (PK de `document_headers.id`), no el número legible. */\n  documentId: string;\n  /** Proveedor del documento (scope de saldos visibles, RB-7). */\n  supplierId: string;\n  /** Moneda del documento (para validar `CurrencyMismatch`, BV-AA-03). */\n  documentCurrencyId: string;\n  /**\n   * `true` solo cuando el documento está en DRAFT (RB-6). Cuando es `false`,\n   * los botones \"Aplicar anticipo\" y \"Quitar\" se eliminan del DOM (FD-04).\n   */\n  isEditable: boolean;\n  /** Endpoint POST para reservar: `/api/v1/documents/{id}/advances`. */\n  applyAdvanceEndpoint: string;\n  /**\n   * Endpoint base DELETE para quitar: `/api/v1/documents/{id}/advances`.\n   * El widget añade `/{applicationId}`.\n   */\n  removeAdvanceEndpoint: string;\n  /** Endpoint GET de saldos disponibles: `/api/v1/documents/{id}/available-advances`. */\n  availableAdvancesEndpoint: string;\n  /**\n   * Endpoint GET de aplicaciones del documento.\n   * Por defecto usa `applyAdvanceEndpoint` (misma ruta, verbo GET).\n   */\n  applicationsEndpoint?: string;\n  /** Cliente HTTP inyectado para las operaciones REST. */\n  httpRequest: AdvancesHttpRequest;\n  /**\n   * Fetcher del `LookupField` para la búsqueda server-side paginada de saldos\n   * (`POST /available-advances/search`, NFR-01). El consumidor lo enlaza al\n   * documento (la entidad debe exponer `Id` en PascalCase).\n   */\n  fetcher: Fetcher;\n  /** Nombre de entidad pasado al `fetcher`. @default 'available-advances' */\n  searchEntity?: string;\n  /**\n   * Formateador de montos. @default `formatAmount` de `useMasterDocumentFormatters` (idioma activo, 2 decimales).\n   * (El `currencyId` es un UUID, no un código ISO, por eso no se formatea como divisa.)\n   */\n  formatAmount?: (value: number) => string;\n  /** Clases CSS adicionales para el contenedor raíz. */\n  className?: string;\n}\n\n/** Props del modal de aplicación de anticipo. */\nexport interface ApplyAdvanceModalProps {\n  open: boolean;\n  documentId: string;\n  documentCurrencyId: string;\n  applyAdvanceEndpoint: string;\n  httpRequest: AdvancesHttpRequest;\n  /** Fetcher del `LookupField` (búsqueda server-side de saldos). */\n  fetcher: Fetcher;\n  searchEntity?: string;\n  formatAmount?: (value: number) => string;\n  onClose: () => void;\n}\n","import { useQuery } from '@tanstack/react-query';\nimport { advanceApplicationsQueryKey } from './keys';\nimport { normalizeAdvanceApplication } from '../types';\nimport type {\n  AdvancesHttpRequest,\n  DocumentAdvanceApplicationDto,\n  RawDocumentAdvanceApplicationDto,\n} from '../types';\n\nexport interface UseDocumentAdvanceApplicationsParams {\n  documentId: string;\n  /** Endpoint GET de aplicaciones del documento (`/documents/{id}/advances`). */\n  applicationsEndpoint: string;\n  httpRequest: AdvancesHttpRequest;\n  enabled?: boolean;\n}\n\n/**\n * Lista las aplicaciones de anticipo del documento (lo que el panel renderiza).\n *\n * Cache key: `['advance-applications', documentId]`.\n * Normaliza el `status` (int o string) del backend a la unión del widget.\n */\nexport function useDocumentAdvanceApplications({\n  documentId,\n  applicationsEndpoint,\n  httpRequest,\n  enabled = true,\n}: UseDocumentAdvanceApplicationsParams) {\n  return useQuery<DocumentAdvanceApplicationDto[]>({\n    queryKey: advanceApplicationsQueryKey(documentId),\n    enabled: enabled && Boolean(documentId),\n    queryFn: async () => {\n      const raw = await httpRequest<RawDocumentAdvanceApplicationDto[]>('GET', applicationsEndpoint);\n      return (raw ?? []).map(normalizeAdvanceApplication);\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { advanceApplicationsQueryKey, availableAdvancesQueryKey } from './keys';\nimport { normalizeAdvanceApplication } from '../types';\nimport type {\n  AdvancesHttpRequest,\n  CreateAdvanceApplicationRequest,\n  DocumentAdvanceApplicationDto,\n  RawDocumentAdvanceApplicationDto,\n} from '../types';\n\n/** Contador de ids optimistas (estable entre renders, único por sesión). */\nlet optimisticCounter = 0;\n\nexport interface UseApplyAdvanceParams {\n  documentId: string;\n  /** Endpoint POST de reserva (`/documents/{id}/advances`). */\n  applyAdvanceEndpoint: string;\n  httpRequest: AdvancesHttpRequest;\n}\n\nexport interface ApplyAdvanceInput {\n  openBalanceId: string;\n  appliedAmount: number;\n  /** Moneda del documento, para la fila optimista (opcional). */\n  currencyId?: string;\n  /** Referencia del saldo origen, para la fila optimista (opcional). */\n  sourceDocumentReference?: string | null;\n}\n\ninterface ApplyMutationContext {\n  previous?: DocumentAdvanceApplicationDto[];\n}\n\n/**\n * Reserva un anticipo (`POST /{id}/advances`) con optimistic update.\n *\n * - `onMutate`: agrega una fila `RESERVED` temporal al cache de aplicaciones.\n * - `onError`: hace rollback al snapshot previo (CA-F5).\n * - `onSettled`: invalida `['advance-applications']` y `['available-advances']` (CA-F7).\n */\nexport function useApplyAdvance({\n  documentId,\n  applyAdvanceEndpoint,\n  httpRequest,\n}: UseApplyAdvanceParams) {\n  const queryClient = useQueryClient();\n  const appsKey = advanceApplicationsQueryKey(documentId);\n  const availKey = availableAdvancesQueryKey(documentId);\n\n  return useMutation<DocumentAdvanceApplicationDto, Error, ApplyAdvanceInput, ApplyMutationContext>({\n    mutationFn: async (input) => {\n      const payload: CreateAdvanceApplicationRequest = {\n        openBalanceId: input.openBalanceId,\n        appliedAmount: input.appliedAmount,\n      };\n      const raw = await httpRequest<RawDocumentAdvanceApplicationDto>(\n        'POST',\n        applyAdvanceEndpoint,\n        payload,\n      );\n      return normalizeAdvanceApplication(raw);\n    },\n    onMutate: async (input) => {\n      await queryClient.cancelQueries({ queryKey: appsKey });\n      const previous = queryClient.getQueryData<DocumentAdvanceApplicationDto[]>(appsKey);\n\n      const optimistic: DocumentAdvanceApplicationDto = {\n        id: `optimistic-${optimisticCounter++}`,\n        documentId,\n        openBalanceId: input.openBalanceId,\n        appliedAmount: input.appliedAmount,\n        currencyId: input.currencyId ?? '',\n        status: 'RESERVED',\n        sourceDocumentReference: input.sourceDocumentReference ?? null,\n        reservedAt: new Date().toISOString(),\n        rowVersion: 0,\n      };\n\n      queryClient.setQueryData<DocumentAdvanceApplicationDto[]>(appsKey, (prev) => [\n        ...(prev ?? []),\n        optimistic,\n      ]);\n\n      return { previous };\n    },\n    onError: (_error, _input, context) => {\n      if (context?.previous !== undefined) {\n        queryClient.setQueryData(appsKey, context.previous);\n      }\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: appsKey });\n      queryClient.invalidateQueries({ queryKey: availKey });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { advanceApplicationsQueryKey, availableAdvancesQueryKey } from './keys';\nimport type { AdvancesHttpRequest, DocumentAdvanceApplicationDto } from '../types';\n\nexport interface UseRemoveAdvanceParams {\n  documentId: string;\n  /** Endpoint base DELETE (`/documents/{id}/advances`); se le añade `/{applicationId}`. */\n  removeAdvanceEndpoint: string;\n  httpRequest: AdvancesHttpRequest;\n}\n\ninterface RemoveMutationContext {\n  previous?: DocumentAdvanceApplicationDto[];\n}\n\n/**\n * Quita una aplicación `RESERVED` (`DELETE /{id}/advances/{applicationId}`).\n *\n * Solo aplica a filas `RESERVED` (RB-5); el backend responde 409 (BV-AA-07) si\n * la aplicación está `CONFIRMED`/`REVERSED`. Usa optimistic remove + rollback e\n * invalida ambas claves de caché.\n */\nexport function useRemoveAdvance({\n  documentId,\n  removeAdvanceEndpoint,\n  httpRequest,\n}: UseRemoveAdvanceParams) {\n  const queryClient = useQueryClient();\n  const appsKey = advanceApplicationsQueryKey(documentId);\n  const availKey = availableAdvancesQueryKey(documentId);\n\n  return useMutation<void, Error, string, RemoveMutationContext>({\n    mutationFn: async (applicationId) => {\n      await httpRequest<void>('DELETE', `${removeAdvanceEndpoint}/${applicationId}`);\n    },\n    onMutate: async (applicationId) => {\n      await queryClient.cancelQueries({ queryKey: appsKey });\n      const previous = queryClient.getQueryData<DocumentAdvanceApplicationDto[]>(appsKey);\n\n      queryClient.setQueryData<DocumentAdvanceApplicationDto[]>(appsKey, (prev) =>\n        (prev ?? []).filter((app) => app.id !== applicationId),\n      );\n\n      return { previous };\n    },\n    onError: (_error, _applicationId, context) => {\n      if (context?.previous !== undefined) {\n        queryClient.setQueryData(appsKey, context.previous);\n      }\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: appsKey });\n      queryClient.invalidateQueries({ queryKey: availKey });\n    },\n  });\n}\n","import { useEffect, useState } from 'react';\nimport { clsx } from 'clsx';\nimport { XMarkIcon } from '@heroicons/react/24/outline';\n\nimport { LookupField } from '../../LookupField';\nimport type { LookupRecord } from '../../LookupField';\nimport { Info } from '../../Info/Info';\nimport { toast } from '../../Toast';\nimport { useMasterDocumentFormatters } from '../formatters';\n\nimport { useAdvancesTranslation } from './i18n';\nimport { useApplyAdvance } from './hooks';\nimport type { ApplyAdvanceModalProps, AdvancesHttpError } from './types';\n\n/** Registro devuelto por la búsqueda server-side de saldos (Id en PascalCase). */\ninterface AdvanceBalanceLookupRecord extends LookupRecord {\n  sourceDocumentReference?: string | null;\n  availableAmount: number;\n  currencyId: string;\n}\n\n/**\n * Modal para aplicar (reservar) un anticipo contra el documento.\n *\n * - Selección de saldo vía `LookupField` server-side (NFR-01; debounce interno del componente).\n * - Valida monto `> 0` y `≤ availableAmount` del saldo seleccionado (BV-AA-01/02).\n * - En error 422/409 el modal NO se cierra y muestra el mensaje (CA-F5); 403 → `Info` inline (FD-06).\n *\n * Sigue el patrón visual de los modales de MasterDocument (overlay + diálogo centrado).\n */\nexport function ApplyAdvanceModal({\n  open,\n  documentId,\n  documentCurrencyId,\n  applyAdvanceEndpoint,\n  httpRequest,\n  fetcher,\n  searchEntity = 'available-advances',\n  formatAmount: formatAmountProp,\n  onClose,\n}: ApplyAdvanceModalProps) {\n  const { t } = useAdvancesTranslation();\n  const { formatAmount: defaultFormatAmount } = useMasterDocumentFormatters();\n  const formatAmount = formatAmountProp ?? defaultFormatAmount;\n  const applyMutation = useApplyAdvance({ documentId, applyAdvanceEndpoint, httpRequest });\n\n  const [selected, setSelected] = useState<AdvanceBalanceLookupRecord | null>(null);\n  const [amount, setAmount] = useState('');\n  const [validationError, setValidationError] = useState<string | null>(null);\n  const [forbidden, setForbidden] = useState(false);\n\n  // Reset al abrir\n  useEffect(() => {\n    if (open) {\n      setSelected(null);\n      setAmount('');\n      setValidationError(null);\n      setForbidden(false);\n    }\n  }, [open]);\n\n  // Esc para cerrar\n  useEffect(() => {\n    if (!open) return;\n    function handleKey(e: KeyboardEvent) {\n      if (e.key === 'Escape') onClose();\n    }\n    document.addEventListener('keydown', handleKey);\n    return () => document.removeEventListener('keydown', handleKey);\n  }, [open, onClose]);\n\n  if (!open) return null;\n\n  const numericAmount = Number(amount);\n  const available = selected?.availableAmount ?? 0;\n\n  function validate(): string | null {\n    if (!selected) return t('advances.error.selectBalance');\n    if (!Number.isFinite(numericAmount) || numericAmount <= 0) {\n      return t('advances.error.amountPositive');\n    }\n    if (numericAmount > available) return t('advances.error.amountExceeds');\n    return null;\n  }\n\n  function handleConfirm() {\n    const error = validate();\n    setValidationError(error);\n    if (error || !selected) return;\n\n    setForbidden(false);\n    applyMutation.mutate(\n      {\n        openBalanceId: selected.Id,\n        appliedAmount: numericAmount,\n        currencyId: selected.currencyId ?? documentCurrencyId,\n        sourceDocumentReference: selected.sourceDocumentReference ?? null,\n      },\n      {\n        onSuccess: () => {\n          toast.success(t('advances.toast.applied'));\n          onClose();\n        },\n        onError: (error) => {\n          const status = (error as AdvancesHttpError)?.status;\n          // 403 → Info inline; el modal permanece abierto (FD-06).\n          if (status === 403) {\n            setForbidden(true);\n            return;\n          }\n          // 422/409/otros → toast; el modal permanece abierto para corregir (CA-F5).\n          toast.error(error?.message || t('advances.error.generic'));\n        },\n      },\n    );\n  }\n\n  const isApplying = applyMutation.isPending;\n\n  return (\n    <>\n      {/* Overlay */}\n      <div\n        className=\"fixed inset-0 z-[300] bg-black/30 animate-[fadeIn_150ms_ease-out]\"\n        aria-hidden=\"true\"\n        onClick={onClose}\n      />\n\n      {/* Diálogo */}\n      <div\n        className={clsx(\n          'fixed z-[301] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',\n          'w-[calc(100%-32px)] max-w-[460px]',\n          'bg-bg-primary rounded-2xl shadow-lg',\n          'animate-[fadeIn_150ms_ease-out]',\n          'dark:bg-dark-bg-primary dark:shadow-none dark:border dark:border-dark-border-primary',\n          'flex flex-col max-h-[90vh]',\n        )}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby=\"apply-advance-modal-title\"\n      >\n        {/* Header */}\n        <div className=\"flex items-center justify-between px-5 pt-5 pb-3 shrink-0\">\n          <h2\n            id=\"apply-advance-modal-title\"\n            className=\"text-[15px] font-bold text-content-primary dark:text-dark-content-primary\"\n          >\n            {t('advances.modal.title')}\n          </h2>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'p-1.5 rounded-md transition-colors duration-150',\n              'hover:bg-background-secondary dark:hover:bg-dark-bg-secondary',\n              'text-content-secondary dark:text-dark-content-secondary',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n            aria-label={t('advances.modal.cancel')}\n          >\n            <XMarkIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n          </button>\n        </div>\n\n        {/* Body */}\n        <div className=\"flex flex-col gap-4 px-5 pb-4 overflow-y-auto min-h-0\">\n          {/* Selección de saldo (LookupField server-side) */}\n          <LookupField<AdvanceBalanceLookupRecord>\n            entity={searchEntity}\n            label={t('advances.modal.balanceLabel')}\n            placeholder={t('advances.modal.balancePlaceholder')}\n            fetcher={fetcher}\n            displayFields={['sourceDocumentReference', 'availableAmount']}\n            bindFields={['availableAmount', 'currencyId']}\n            value={selected?.Id ?? null}\n            onChange={(record) => {\n              setSelected(record);\n              setValidationError(null);\n            }}\n            required\n          />\n\n          {/* Disponible del saldo seleccionado */}\n          {selected && (\n            <p className=\"text-xs text-content-secondary dark:text-dark-content-secondary -mt-2\">\n              {t('advances.modal.availableLabel')}: {formatAmount(available)}\n            </p>\n          )}\n\n          {/* Monto a aplicar */}\n          <div className=\"flex flex-col gap-1.5\">\n            <label\n              htmlFor=\"apply-advance-amount\"\n              className=\"text-sm font-medium text-content-primary dark:text-dark-content-primary\"\n            >\n              {t('advances.modal.amountLabel')}\n            </label>\n            <input\n              id=\"apply-advance-amount\"\n              type=\"number\"\n              inputMode=\"decimal\"\n              min={0}\n              step=\"0.01\"\n              value={amount}\n              onChange={(e) => {\n                setAmount(e.target.value);\n                setValidationError(null);\n              }}\n              className={clsx(\n                'w-full px-3 py-2 text-sm rounded-lg',\n                'border bg-bg-primary dark:bg-dark-bg-secondary',\n                'text-content-primary dark:text-dark-content-primary',\n                'placeholder:text-content-tertiary dark:placeholder:text-dark-content-secondary',\n                'focus:outline-hidden focus:ring-2 focus:ring-primary-400 dark:focus:ring-dark-border-custom',\n                validationError\n                  ? 'border-red-400 dark:border-red-500'\n                  : 'border-border-primary dark:border-dark-border-primary',\n              )}\n            />\n          </div>\n\n          {/* Error de validación / negocio */}\n          {validationError && (\n            <p className=\"text-xs text-red-600 dark:text-red-400\" role=\"alert\">\n              {validationError}\n            </p>\n          )}\n\n          {/* 403 sin permiso */}\n          {forbidden && <Info color=\"red\" title={t('advances.error.forbidden')} />}\n        </div>\n\n        {/* Footer */}\n        <div className=\"flex items-center justify-end gap-3 px-5 py-4 border-t border-border-primary dark:border-dark-border-primary shrink-0\">\n          <button\n            type=\"button\"\n            onClick={onClose}\n            className={clsx(\n              'px-4 py-2 rounded-md text-sm font-semibold',\n              'border border-border-primary text-content-tertiary',\n              'hover:bg-background-secondary transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:border-dark-border-primary dark:text-dark-content-secondary',\n              'dark:hover:bg-dark-bg-secondary',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            {t('advances.modal.cancel')}\n          </button>\n          <button\n            type=\"button\"\n            onClick={handleConfirm}\n            disabled={isApplying}\n            className={clsx(\n              'px-5 py-2 rounded-md text-sm font-semibold',\n              'bg-primary-600 text-white',\n              'hover:bg-primary-700 transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'disabled:opacity-40 disabled:pointer-events-none',\n            )}\n          >\n            {isApplying ? t('advances.modal.applying') : t('advances.modal.confirm')}\n          </button>\n        </div>\n      </div>\n    </>\n  );\n}\n","import { useState } from 'react';\nimport { clsx } from 'clsx';\nimport { PlusIcon, TrashIcon } from '@heroicons/react/24/outline';\n\nimport { toast } from '../../Toast';\nimport { Info } from '../../Info/Info';\nimport { useMasterDocumentFormatters } from '../formatters';\n\nimport { AdvanceStatusBadge } from './AdvanceStatusBadge';\nimport { ApplyAdvanceModal } from './ApplyAdvanceModal';\nimport { Loading } from '../components/loading';\nimport { useAdvancesTranslation } from './i18n';\nimport {\n  useAvailableAdvances,\n  useDocumentAdvanceApplications,\n  useRemoveAdvance,\n} from './hooks';\nimport type {\n  AdvanceApplicationsPanelProps,\n  AdvancesHttpError,\n  DocumentAdvanceApplicationDto,\n} from './types';\n\n/**\n * Panel de aplicaciones de anticipo — sub-componente de MasterDocument (FEAT-102-5).\n *\n * Renderiza las aplicaciones de anticipo del documento (monto, referencia del\n * saldo origen, `Badge` de estado) y, cuando el documento es editable (DRAFT),\n * permite aplicar nuevos anticipos y quitar los `RESERVED`.\n *\n * Diseñado para montarse en una sección FactBox de cualquier documento\n * MasterDocument, inyectando sus endpoints e IO por props (CA-I1 / CA-I4).\n *\n * @example\n * ```tsx\n * <AdvanceApplicationsPanel\n *   documentId={docId}\n *   supplierId={supplierId}\n *   documentCurrencyId={currencyId}\n *   isEditable={docState === 'DRAFT'}\n *   applyAdvanceEndpoint={`/api/v1/documents/${docId}/advances`}\n *   removeAdvanceEndpoint={`/api/v1/documents/${docId}/advances`}\n *   availableAdvancesEndpoint={`/api/v1/documents/${docId}/available-advances`}\n *   httpRequest={httpRequest}\n *   fetcher={advancesFetcher}\n * />\n * ```\n */\nexport function AdvanceApplicationsPanel({\n  documentId,\n  documentCurrencyId,\n  isEditable,\n  applyAdvanceEndpoint,\n  removeAdvanceEndpoint,\n  availableAdvancesEndpoint,\n  applicationsEndpoint,\n  httpRequest,\n  fetcher,\n  searchEntity = 'available-advances',\n  formatAmount: formatAmountProp,\n  className,\n}: AdvanceApplicationsPanelProps) {\n  const { t } = useAdvancesTranslation();\n  const { formatAmount: defaultFormatAmount, formatDateTime } = useMasterDocumentFormatters();\n  const formatAmount = formatAmountProp ?? defaultFormatAmount;\n  const [modalOpen, setModalOpen] = useState(false);\n\n  /**\n   * `undefined` cuando no hay fecha o es inválida, para que\n   * `AdvanceStatusBadge` no muestre un tooltip vacío (preserva el\n   * comportamiento previo; `formatDateTime` del hook devolvería `'—'`).\n   */\n  function formatDate(iso?: string | null): string | undefined {\n    if (!iso) return undefined;\n    const date = new Date(iso);\n    if (Number.isNaN(date.getTime())) return undefined;\n    return formatDateTime(iso);\n  }\n\n  /** Selecciona la fecha del tooltip según el estado (§4.3). */\n  function tooltipDate(app: DocumentAdvanceApplicationDto): string | undefined {\n    switch (app.status) {\n      case 'CONFIRMED':\n        return formatDate(app.confirmedAt);\n      case 'REVERSED':\n        return formatDate(app.reversedAt);\n      default:\n        return formatDate(app.reservedAt);\n    }\n  }\n\n  const applicationsQuery = useDocumentAdvanceApplications({\n    documentId,\n    applicationsEndpoint: applicationsEndpoint ?? applyAdvanceEndpoint,\n    httpRequest,\n  });\n\n  // Saldos disponibles: alimenta el contador y se invalida tras aplicar/quitar.\n  const availableQuery = useAvailableAdvances({\n    documentId,\n    availableAdvancesEndpoint,\n    httpRequest,\n    enabled: isEditable,\n  });\n\n  const removeMutation = useRemoveAdvance({ documentId, removeAdvanceEndpoint, httpRequest });\n\n  const applications = applicationsQuery.data ?? [];\n  const availableCount = availableQuery.data?.length ?? 0;\n\n  function handleRemove(applicationId: string) {\n    removeMutation.mutate(applicationId, {\n      onSuccess: () => toast.success(t('advances.toast.removed')),\n      onError: (error) => {\n        const status = (error as AdvancesHttpError)?.status;\n        if (status === 403) {\n          toast.error(t('advances.error.forbidden'));\n          return;\n        }\n        toast.error(error?.message || t('advances.error.generic'));\n      },\n    });\n  }\n\n  return (\n    <section\n      className={clsx('flex flex-col gap-3', className)}\n      aria-label={t('advances.panel.title')}\n    >\n      {/* Header */}\n      <div className=\"flex items-center justify-between gap-2\">\n        <div className=\"flex items-baseline gap-2 min-w-0\">\n          <h3 className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary truncate\">\n            {t('advances.panel.title')}\n          </h3>\n          {isEditable && availableCount > 0 && (\n            <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary shrink-0\">\n              {t('advances.panel.available', { count: availableCount })}\n            </span>\n          )}\n        </div>\n\n        {/* Botón Aplicar — solo en DOM cuando isEditable (FD-04 / CA-F3) */}\n        {isEditable && (\n          <button\n            type=\"button\"\n            onClick={() => setModalOpen(true)}\n            className={clsx(\n              'inline-flex items-center gap-1.5 shrink-0',\n              'px-3 py-1.5 rounded-md text-xs font-semibold',\n              'bg-primary-600 text-white',\n              'hover:bg-primary-700 transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n            )}\n          >\n            <PlusIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n            {t('advances.panel.apply')}\n          </button>\n        )}\n      </div>\n\n      {/* Estados de carga / error */}\n      {applicationsQuery.isLoading ? (\n        <Loading size=\"md\" label={t('advances.panel.loading')} />\n      ) : applicationsQuery.isError ? (\n        <Info color=\"red\" title={t('advances.panel.loadError')} />\n      ) : applications.length === 0 ? (\n        <p className=\"text-sm text-content-secondary dark:text-dark-content-secondary py-3\">\n          {t('advances.panel.empty')}\n        </p>\n      ) : (\n        <ul className=\"flex flex-col gap-2\">\n          {applications.map((app) => {\n            const canRemove = isEditable && app.status === 'RESERVED';\n            return (\n              <li\n                key={app.id}\n                className={clsx(\n                  'flex items-center justify-between gap-3 px-3 py-2.5 rounded-xl',\n                  'border border-border-primary dark:border-dark-border-primary',\n                  'bg-bg-primary dark:bg-dark-bg-secondary',\n                )}\n              >\n                {/* Monto + referencia */}\n                <div className=\"flex flex-col min-w-0\">\n                  <span className=\"text-sm font-semibold text-content-primary dark:text-dark-content-primary\">\n                    {formatAmount(app.appliedAmount)}\n                  </span>\n                  <span className=\"text-xs text-content-secondary dark:text-dark-content-secondary truncate\">\n                    {app.sourceDocumentReference || app.openBalanceId}\n                  </span>\n                </div>\n\n                {/* Estado + acción */}\n                <div className=\"flex items-center gap-2 shrink-0\">\n                  <AdvanceStatusBadge\n                    status={app.status}\n                    statusLabel={app.statusLabel}\n                    tooltip={tooltipDate(app)}\n                  />\n                  {canRemove && (\n                    <button\n                      type=\"button\"\n                      onClick={() => handleRemove(app.id)}\n                      disabled={removeMutation.isPending}\n                      className={clsx(\n                        'inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium',\n                        'text-red-600 dark:text-red-400',\n                        'hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors duration-150',\n                        'focus:outline-hidden focus:ring-2 focus:ring-red-400 focus:ring-offset-2',\n                        'dark:focus:ring-offset-dark-bg-primary',\n                        'disabled:opacity-40 disabled:pointer-events-none',\n                      )}\n                      aria-label={t('advances.panel.removeAria')}\n                    >\n                      <TrashIcon className=\"w-3.5 h-3.5\" aria-hidden=\"true\" />\n                      {t('advances.panel.remove')}\n                    </button>\n                  )}\n                </div>\n              </li>\n            );\n          })}\n        </ul>\n      )}\n\n      {/* Modal de aplicación (solo se monta si isEditable) */}\n      {isEditable && (\n        <ApplyAdvanceModal\n          open={modalOpen}\n          documentId={documentId}\n          documentCurrencyId={documentCurrencyId}\n          applyAdvanceEndpoint={applyAdvanceEndpoint}\n          httpRequest={httpRequest}\n          fetcher={fetcher}\n          searchEntity={searchEntity}\n          formatAmount={formatAmount}\n          onClose={() => setModalOpen(false)}\n        />\n      )}\n    </section>\n  );\n}\n","import { createTranslationHook } from '../i18nFactory';\nimport { TEXTO_COMUN_ES, TEXTO_COMUN_EN } from '../commonTexts';\nimport type { TranslateFn } from '../i18nFactory';\n\n/**\n * i18n del widget de Cuotas (FEAT-105-7).\n *\n * Usa `useTranslation` de siesa-ui-kit vía `createTranslationHook`; si el host no\n * registró las claves `installments.*` (el motor devuelve la propia clave), cae al\n * diccionario local del idioma activo y, en último término, al español. Garantiza\n * español listo para usar sin depender de que el documento consumidor registre los\n * recursos. Las claves siguen el formato plano que espera `DefaultTranslationEngine`.\n */\n\nexport const INSTALLMENTS_TRANSLATIONS_ES: Record<string, string> = {\n  'installments.panel.title': 'Cuotas',\n  'installments.panel.empty': 'Este documento no tiene cuotas.',\n  // Sin uso: el panel muestra skeleton. Pendiente de confirmar con diseño.\n  // Deuda con dueño en docs/i18n-masterdocument-deuda.md (punto 2).\n  'installments.panel.loading': 'Cargando cuotas…',\n  'installments.panel.loadError': 'No se pudieron cargar las cuotas.',\n  'installments.panel.regenerate': 'Regenerar',\n  'installments.panel.regenerateAria': 'Regenerar el plan de cuotas',\n  'installments.column.number': 'Cuota',\n  'installments.column.dueDate': 'Vencimiento',\n  'installments.column.promptPaymentDate': 'Fecha pronto pago',\n  'installments.column.amount': 'Monto',\n  'installments.column.promptPaymentDiscount': 'Descuento PP',\n  'installments.column.flags': '',\n  'installments.badge.manual': 'Manual',\n  'installments.badge.manualTooltip': 'Valor automático: {amount}',\n  'installments.edit.amountAria': 'Editar monto de la cuota {number}',\n  'installments.modal.title': 'Regenerar cuotas',\n  'installments.modal.body': 'Se descartarán los ajustes manuales. ¿Continuar?',\n  'installments.modal.cancel': TEXTO_COMUN_ES.cancel,\n  'installments.modal.confirm': 'Regenerar',\n  'installments.error.amountPositive': 'El monto debe ser mayor o igual a 0.',\n  'installments.error.conflict': 'La cuota fue modificada por otro usuario. Se recargó el plan.',\n  'installments.error.forbidden': TEXTO_COMUN_ES.errorForbidden,\n  'installments.error.tooMany': 'El plan supera el máximo de 36 cuotas.',\n  'installments.error.generic': TEXTO_COMUN_ES.errorGeneric,\n  'installments.toast.updated': 'Cuota actualizada correctamente.',\n  'installments.toast.regenerated': 'Plan de cuotas regenerado.',\n};\n\nexport const INSTALLMENTS_TRANSLATIONS_EN: Record<string, string> = {\n  'installments.panel.title': 'Installments',\n  'installments.panel.empty': 'This document has no installments.',\n  'installments.panel.loading': 'Loading installments…',\n  'installments.panel.loadError': 'Could not load installments.',\n  'installments.panel.regenerate': 'Regenerate',\n  'installments.panel.regenerateAria': 'Regenerate the installment plan',\n  'installments.column.number': 'Installment',\n  'installments.column.dueDate': 'Due date',\n  'installments.column.promptPaymentDate': 'Prompt payment date',\n  'installments.column.amount': 'Amount',\n  'installments.column.promptPaymentDiscount': 'PP discount',\n  'installments.column.flags': '',\n  'installments.badge.manual': 'Manual',\n  'installments.badge.manualTooltip': 'Automatic value: {amount}',\n  'installments.edit.amountAria': 'Edit amount of installment {number}',\n  'installments.modal.title': 'Regenerate installments',\n  'installments.modal.body': 'Manual adjustments will be discarded. Continue?',\n  'installments.modal.cancel': TEXTO_COMUN_EN.cancel,\n  'installments.modal.confirm': 'Regenerate',\n  'installments.error.amountPositive': 'The amount must be greater than or equal to 0.',\n  'installments.error.conflict': 'The installment was modified by another user. The plan was reloaded.',\n  'installments.error.forbidden': TEXTO_COMUN_EN.errorForbidden,\n  'installments.error.tooMany': 'The plan exceeds the maximum of 36 installments.',\n  'installments.error.generic': TEXTO_COMUN_EN.errorGeneric,\n  'installments.toast.updated': 'Installment updated successfully.',\n  'installments.toast.regenerated': 'Installment plan regenerated.',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const INSTALLMENTS_TRANSLATIONS = {\n  es: INSTALLMENTS_TRANSLATIONS_ES,\n  en: INSTALLMENTS_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción con interpolación `{var}`. */\nexport type InstallmentsT = TranslateFn;\n\n/**\n * Hook de traducción del widget.\n *\n * Usa `useTranslation` del kit; si la clave no está registrada en el host\n * (el motor devuelve la propia clave), cae al diccionario local del idioma activo.\n */\nexport const useInstallmentsTranslation = createTranslationHook(INSTALLMENTS_TRANSLATIONS);\n","import { Badge } from '../../Badge/Badge';\nimport { useInstallmentsTranslation } from './i18n';\n\nexport interface InstallmentManualBadgeProps {\n  /** Valor auto-generado original (de `autoGeneratedSnapshot.amount`), ya formateado. */\n  autoAmountLabel?: string;\n}\n\n/**\n * Badge \"Manual\" de una cuota editada (FEAT-105-7.02).\n *\n * Reutiliza el `Badge` del kit (color `amber`, ADAPTACIÓN A3). El tooltip\n * (atributo `title` nativo, ADAPTACIÓN A2) muestra el valor automático original\n * cuando está disponible.\n */\nexport function InstallmentManualBadge({ autoAmountLabel }: InstallmentManualBadgeProps) {\n  const { t } = useInstallmentsTranslation();\n  const tooltip = autoAmountLabel\n    ? t('installments.badge.manualTooltip', { amount: autoAmountLabel })\n    : undefined;\n\n  return <Badge color=\"amber\" label={t('installments.badge.manual')} title={tooltip} />;\n}\n","import { AlertDialog } from '../../AlertDialog/AlertDialog';\nimport { useInstallmentsTranslation } from './i18n';\n\nexport interface RegenerateInstallmentsModalProps {\n  open: boolean;\n  /** Mutación en vuelo: bloquea los botones y muestra spinner en confirmar. */\n  isProcessing: boolean;\n  onConfirm: () => void;\n  onClose: () => void;\n}\n\n/**\n * Modal de confirmación de regeneración del plan de cuotas (FEAT-105-7.03).\n *\n * Envuelve el `AlertDialog` del kit (`type=\"warning\"`, ADAPTACIÓN A4) advirtiendo\n * que se descartarán los ajustes manuales.\n */\nexport function RegenerateInstallmentsModal({\n  open,\n  isProcessing,\n  onConfirm,\n  onClose,\n}: RegenerateInstallmentsModalProps) {\n  const { t } = useInstallmentsTranslation();\n\n  return (\n    <AlertDialog\n      isOpen={open}\n      type=\"warning\"\n      title={t('installments.modal.title')}\n      description={t('installments.modal.body')}\n      cancelText={t('installments.modal.cancel')}\n      confirmText={t('installments.modal.confirm')}\n      isProcess={isProcessing}\n      preventCloseOnOverlayClick\n      onCancel={onClose}\n      onConfirm={onConfirm}\n    />\n  );\n}\n","/**\n * Clave de caché de TanStack Query del plan de cuotas (FEAT-105-7).\n *\n * `document-installments`: cuotas del documento que la grilla renderiza. Se\n * invalida tras editar/regenerar para mantener la cabecera/totales consistentes.\n */\nexport const installmentsQueryKey = (documentId: string) =>\n  ['document-installments', documentId] as const;\n","/**\n * Tipos del widget InstallmentsPanel (FEAT-105-7) — sub-componente de\n * MasterDocument.\n *\n * Espejo TypeScript del DTO de cuotas del backend (`DocumentInstallmentDto`,\n * 105-6) más los contratos de props del widget reutilizable. Se integra en una\n * sección FactBox de cualquier documento MasterDocument (precedente:\n * AdvanceApplicationsPanel / SerialPanel).\n *\n * @see feat-105-7-cuotas-masterdocument-spec.md\n */\n\n// ─── DTOs ──────────────────────────────────────────────────────────────────\n\n/**\n * Snapshot auto-generado de la cuota (`auto_generated_snapshot`). Llega como\n * objeto JSON ya deserializado. El tooltip del badge \"Manual\" lee `amount`.\n */\nexport interface InstallmentAutoSnapshot {\n  /** Monto auto-generado original de la cuota (antes del ajuste manual). */\n  amount?: number;\n  [key: string]: unknown;\n}\n\n/**\n * Cuota del plan de pagos (TF2) — espejo de `DocumentInstallmentDto` (camelCase).\n * Tabla genérica `core.document_installments`, keyed por `documentId = FC.Id`.\n */\nexport interface InstallmentDto {\n  /** PK de la cuota. */\n  id: string;\n  /** FK al documento (FC). */\n  documentId: string;\n  /** Número de cuota 1-based. */\n  installmentNumber: number;\n  /** Fecha de vencimiento (`YYYY-MM-DD`). */\n  dueDate: string;\n  /** Monto de la cuota (moneda del documento). */\n  amount: number;\n  /** Moneda (UUID, no código ISO). */\n  currencyId?: string | null;\n  /** Cuota liquidada. */\n  isSettled: boolean;\n  /** Monto en moneda alterna. */\n  amountAlt?: number | null;\n  /** Fecha límite de pronto pago (única para todas las cuotas). */\n  promptPaymentDate?: string | null;\n  /** Descuento de pronto pago de la cuota. */\n  promptPaymentDiscount?: number | null;\n  /** Descuento de pronto pago en moneda alterna. */\n  promptPaymentDiscountAlt?: number | null;\n  /** `true` si la cuota fue editada manualmente. */\n  isManual: boolean;\n  /** Snapshot con los inputs auto-generados originales (incluye `amount`). */\n  autoGeneratedSnapshot?: InstallmentAutoSnapshot | null;\n  /** Versión de fila para concurrencia optimista. */\n  rowVersion: number;\n  /** Auditoría. */\n  createdAt?: string;\n  updatedAt?: string;\n}\n\n/**\n * Forma cruda como puede llegar del backend. `autoGeneratedSnapshot` puede venir\n * como objeto o como string JSON; se normaliza con {@link normalizeInstallment}.\n */\nexport interface RawInstallmentDto extends Omit<InstallmentDto, 'autoGeneratedSnapshot'> {\n  autoGeneratedSnapshot?: InstallmentAutoSnapshot | string | null;\n}\n\n/** Intenta parsear el snapshot a objeto, tolerando string JSON o `null`. */\nfunction normalizeSnapshot(\n  snapshot: InstallmentAutoSnapshot | string | null | undefined,\n): InstallmentAutoSnapshot | null {\n  if (snapshot == null) return null;\n  if (typeof snapshot === 'string') {\n    try {\n      return JSON.parse(snapshot) as InstallmentAutoSnapshot;\n    } catch {\n      return null;\n    }\n  }\n  return snapshot;\n}\n\n/** Normaliza una cuota cruda del backend al DTO de UI. */\nexport function normalizeInstallment(raw: RawInstallmentDto): InstallmentDto {\n  const base = (raw ?? {}) as RawInstallmentDto;\n  return {\n    ...base,\n    isManual: Boolean(base.isManual),\n    isSettled: Boolean(base.isSettled),\n    autoGeneratedSnapshot: normalizeSnapshot(base.autoGeneratedSnapshot),\n  };\n}\n\n/** Ordena las cuotas por `installmentNumber` ascendente (orden canónico de UI). */\nexport function sortInstallments(installments: InstallmentDto[]): InstallmentDto[] {\n  return [...installments].sort((a, b) => a.installmentNumber - b.installmentNumber);\n}\n\n/**\n * Payload del PUT de edición de una cuota (`UpdateSupplierInvoiceInstallmentDto`).\n * `id`/`installmentId` van en la ruta, nunca en el body.\n */\nexport interface ModifyInstallmentPayload {\n  /** Versión de fila requerida (concurrencia optimista). */\n  rowVersion: number;\n  /** Nuevo monto (>= 0). */\n  amount?: number;\n  /** Nueva fecha de vencimiento (`YYYY-MM-DD`). */\n  dueDate?: string;\n  /** Nueva fecha de pronto pago (`YYYY-MM-DD`). */\n  promptPaymentDate?: string;\n  /** Nuevo descuento de pronto pago (>= 0). */\n  promptPaymentDiscount?: number;\n}\n\n// ─── IO inyectada ────────────────────────────────────────────────────────\n\n/**\n * Cliente HTTP inyectado para las operaciones REST del widget.\n *\n * El kit no depende de `axios`; el documento consumidor inyecta su instancia\n * ya configurada (interceptores de auth/company) envuelta en esta firma.\n * Espeja el patrón `AdvancesHttpRequest` / `IMasterDocumentAdapter.genericFetch`.\n *\n * Debe rechazar con un error que exponga `status` (número HTTP) para que el\n * widget distinga 409 (conflicto) / 422 (validación) de 403 (sin permiso).\n */\nexport type InstallmentsHttpRequest = <T = unknown>(\n  method: 'GET' | 'PUT' | 'POST',\n  url: string,\n  body?: unknown,\n) => Promise<T>;\n\n/** Error normalizado que el widget interpreta para el manejo de UI. */\nexport interface InstallmentsHttpError extends Error {\n  status?: number;\n}\n\n// ─── Props ─────────────────────────────────────────────────────────────────\n\n/**\n * Props del panel principal `InstallmentsPanel`.\n *\n * El widget es agnóstico del documento: recibe sus endpoints e IO por props,\n * lo que permite montarlo en cualquier MasterDocument.\n */\nexport interface InstallmentsPanelProps {\n  /** UUID del documento (PK de `document_headers.id`), no el número legible. */\n  documentId: string;\n  /**\n   * `true` solo cuando el documento es editable (DRAFT). Cuando es `false`, la\n   * grilla es read-only y el botón \"Regenerar\" se elimina del DOM.\n   */\n  isEditable: boolean;\n  /**\n   * `true` si el usuario tiene el permiso `alter_installments`. Sin él la grilla\n   * es read-only (sin edición in-line ni botón \"Regenerar\"), incluso en DRAFT.\n   */\n  canAlter: boolean;\n  /**\n   * Endpoint GET para cargar el plan de cuotas (BRECHA G1 — la app decide la\n   * ruta concreta, p.ej. `/{id}/factbox/installments`). Si se omite, la grilla\n   * solo se puebla con la respuesta de editar/regenerar.\n   */\n  installmentsEndpoint?: string;\n  /**\n   * Endpoint base PUT de edición: `/{id}/installments`. El widget añade\n   * `/{installmentId}`.\n   */\n  modifyInstallmentEndpoint: string;\n  /** Endpoint POST de regeneración: `/{id}/installments/regenerate`. */\n  regenerateEndpoint: string;\n  /** Cliente HTTP inyectado para las operaciones REST. */\n  httpRequest: InstallmentsHttpRequest;\n  /**\n   * Datos iniciales del plan (opcional). Útil cuando la carga proviene de la\n   * sección FactBox (`dataSource: 'adapter'`) en vez de un GET dedicado.\n   */\n  initialInstallments?: InstallmentDto[];\n  /**\n   * Formateador de montos. @default `formatAmount` de `useMasterDocumentFormatters` (idioma activo, 2 decimales).\n   */\n  formatAmount?: (value: number) => string;\n  /**\n   * Formateador de fechas (`YYYY-MM-DD`). @default `formatDate` de `useMasterDocumentFormatters` (idioma activo, `dateStyle:'medium'`).\n   */\n  formatDate?: (value: string) => string;\n  /** Clases CSS adicionales para el contenedor raíz. */\n  className?: string;\n}\n","import { useQuery } from '@tanstack/react-query';\nimport { installmentsQueryKey } from './keys';\nimport { normalizeInstallment, sortInstallments } from '../types';\nimport type { InstallmentDto, InstallmentsHttpRequest, RawInstallmentDto } from '../types';\n\nexport interface UseInstallmentsParams {\n  documentId: string;\n  /**\n   * Endpoint GET del plan de cuotas (BRECHA G1). Si se omite, la query queda\n   * deshabilitada y la grilla se puebla solo con `initialData` / mutaciones.\n   */\n  installmentsEndpoint?: string;\n  httpRequest: InstallmentsHttpRequest;\n  /** Datos iniciales (p.ej. provenientes de la sección FactBox del adapter). */\n  initialData?: InstallmentDto[];\n  enabled?: boolean;\n}\n\n/**\n * Carga el plan de cuotas del documento (lo que la grilla renderiza).\n *\n * Cache key: `['document-installments', documentId]`. Normaliza el\n * `autoGeneratedSnapshot` (objeto o string JSON) y ordena por `installmentNumber`.\n */\nexport function useInstallments({\n  documentId,\n  installmentsEndpoint,\n  httpRequest,\n  initialData,\n  enabled = true,\n}: UseInstallmentsParams) {\n  return useQuery<InstallmentDto[]>({\n    queryKey: installmentsQueryKey(documentId),\n    enabled: enabled && Boolean(documentId) && Boolean(installmentsEndpoint),\n    initialData: initialData ? sortInstallments(initialData) : undefined,\n    queryFn: async () => {\n      const raw = await httpRequest<RawInstallmentDto[]>('GET', installmentsEndpoint!);\n      return sortInstallments((raw ?? []).map(normalizeInstallment));\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { installmentsQueryKey } from './keys';\nimport { normalizeInstallment, sortInstallments } from '../types';\nimport type {\n  InstallmentDto,\n  InstallmentsHttpRequest,\n  ModifyInstallmentPayload,\n  RawInstallmentDto,\n} from '../types';\n\nexport interface UseModifyInstallmentParams {\n  documentId: string;\n  /** Endpoint base PUT (`/{id}/installments`); se le añade `/{installmentId}`. */\n  modifyInstallmentEndpoint: string;\n  httpRequest: InstallmentsHttpRequest;\n}\n\nexport interface ModifyInstallmentInput {\n  installmentId: string;\n  payload: ModifyInstallmentPayload;\n}\n\ninterface ModifyMutationContext {\n  previous?: InstallmentDto[];\n}\n\n/**\n * Edita el monto (u otros campos) de una cuota\n * (`PUT /{id}/installments/{installmentId}`) con optimistic update.\n *\n * - `onMutate`: aplica el cambio a la fila y la marca `isManual = true`.\n * - `onError`: rollback al snapshot previo (el panel surfacea 409/422/403).\n * - `onSuccess`: reemplaza la fila con la respuesta del servidor (rowVersion++).\n * - `onSettled`: invalida `['document-installments', documentId]`.\n */\nexport function useModifyInstallment({\n  documentId,\n  modifyInstallmentEndpoint,\n  httpRequest,\n}: UseModifyInstallmentParams) {\n  const queryClient = useQueryClient();\n  const key = installmentsQueryKey(documentId);\n\n  return useMutation<InstallmentDto, Error, ModifyInstallmentInput, ModifyMutationContext>({\n    mutationFn: async ({ installmentId, payload }) => {\n      const raw = await httpRequest<RawInstallmentDto>(\n        'PUT',\n        `${modifyInstallmentEndpoint}/${installmentId}`,\n        payload,\n      );\n      return normalizeInstallment(raw);\n    },\n    onMutate: async ({ installmentId, payload }) => {\n      await queryClient.cancelQueries({ queryKey: key });\n      const previous = queryClient.getQueryData<InstallmentDto[]>(key);\n\n      queryClient.setQueryData<InstallmentDto[]>(key, (prev) =>\n        (prev ?? []).map((row) =>\n          row.id === installmentId\n            ? {\n                ...row,\n                amount: payload.amount ?? row.amount,\n                dueDate: payload.dueDate ?? row.dueDate,\n                promptPaymentDate: payload.promptPaymentDate ?? row.promptPaymentDate,\n                promptPaymentDiscount:\n                  payload.promptPaymentDiscount ?? row.promptPaymentDiscount,\n                isManual: true,\n              }\n            : row,\n        ),\n      );\n\n      return { previous };\n    },\n    onError: (_error, _input, context) => {\n      if (context?.previous !== undefined) {\n        queryClient.setQueryData(key, context.previous);\n      }\n    },\n    onSuccess: (updated) => {\n      queryClient.setQueryData<InstallmentDto[]>(key, (prev) =>\n        sortInstallments((prev ?? []).map((row) => (row.id === updated.id ? updated : row))),\n      );\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { installmentsQueryKey } from './keys';\nimport { normalizeInstallment, sortInstallments } from '../types';\nimport type { InstallmentDto, InstallmentsHttpRequest, RawInstallmentDto } from '../types';\n\nexport interface UseRegenerateInstallmentsParams {\n  documentId: string;\n  /** Endpoint POST de regeneración (`/{id}/installments/regenerate`). */\n  regenerateEndpoint: string;\n  httpRequest: InstallmentsHttpRequest;\n}\n\n/**\n * Regenera el plan completo (`POST /{id}/installments/regenerate`), descartando\n * todos los ajustes manuales.\n *\n * - `onSuccess`: siembra el cache con la lista regenerada (todas `isManual=false`).\n * - `onSettled`: invalida `['document-installments', documentId]`.\n *\n * El backend devuelve 422 (`INSTALLMENT_COUNT_EXCEEDED` > 36) — el panel lo surfacea.\n */\nexport function useRegenerateInstallments({\n  documentId,\n  regenerateEndpoint,\n  httpRequest,\n}: UseRegenerateInstallmentsParams) {\n  const queryClient = useQueryClient();\n  const key = installmentsQueryKey(documentId);\n\n  return useMutation<InstallmentDto[], Error, void>({\n    mutationFn: async () => {\n      const raw = await httpRequest<RawInstallmentDto[]>('POST', regenerateEndpoint, {});\n      return sortInstallments((raw ?? []).map(normalizeInstallment));\n    },\n    onSuccess: (regenerated) => {\n      queryClient.setQueryData<InstallmentDto[]>(key, regenerated);\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useState } from 'react';\nimport { clsx } from 'clsx';\nimport { ArrowPathIcon } from '@heroicons/react/24/outline';\n\nimport { toast } from '../../Toast';\nimport { Info } from '../../Info/Info';\nimport { Input } from '../../Input/Input';\nimport { Table } from '../../Table/Table';\nimport type { TableColumn } from '../../Table/Table.types';\nimport { useMasterDocumentFormatters } from '../formatters';\n\nimport { InstallmentManualBadge } from './InstallmentManualBadge';\nimport { RegenerateInstallmentsModal } from './RegenerateInstallmentsModal';\nimport { useInstallmentsTranslation } from './i18n';\nimport { useInstallments, useModifyInstallment, useRegenerateInstallments } from './hooks';\nimport type { InstallmentDto, InstallmentsHttpError, InstallmentsPanelProps } from './types';\n\nconst DASH = '—';\n\n/**\n * Panel de Cuotas (TF2) — sub-componente de MasterDocument (FEAT-105-7).\n *\n * Renderiza el plan de cuotas del documento en una grilla (número, vencimiento,\n * fecha de pronto pago, monto, descuento PP y badge \"Manual\"). Cuando el usuario\n * tiene el permiso `alter_installments` y el documento es editable (DRAFT):\n * permite editar el monto in-line (`PUT /{id}/installments/{installmentId}`) y\n * regenerar el plan completo (`POST /{id}/installments/regenerate`).\n *\n * Diseñado para montarse en una sección FactBox de cualquier documento\n * MasterDocument, inyectando sus endpoints e IO por props (precedente:\n * AdvanceApplicationsPanel / SerialPanel).\n *\n * @example\n * ```tsx\n * <InstallmentsPanel\n *   documentId={docId}\n *   isEditable={docState === 'DRAFT'}\n *   canAlter={permissions.includes(CORE_PERMISSIONS.SUPPLIER_INVOICES.ALTER_INSTALLMENTS)}\n *   installmentsEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/factbox/installments`}\n *   modifyInstallmentEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/installments`}\n *   regenerateEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/installments/regenerate`}\n *   httpRequest={httpRequest}\n * />\n * ```\n */\nexport function InstallmentsPanel({\n  documentId,\n  isEditable,\n  canAlter,\n  installmentsEndpoint,\n  modifyInstallmentEndpoint,\n  regenerateEndpoint,\n  httpRequest,\n  initialInstallments,\n  formatAmount: formatAmountProp,\n  formatDate: formatDateProp,\n  className,\n}: InstallmentsPanelProps) {\n  const { t } = useInstallmentsTranslation();\n  const { formatAmount: defaultFormatAmount, formatDate: defaultFormatDate } =\n    useMasterDocumentFormatters();\n  const formatAmount = formatAmountProp ?? defaultFormatAmount;\n  const formatDate = formatDateProp ?? defaultFormatDate;\n\n  /** La edición solo procede con permiso + documento editable (gating FE de G3). */\n  const editableNow = canAlter && isEditable;\n\n  const [modalOpen, setModalOpen] = useState(false);\n  const [editingId, setEditingId] = useState<string | null>(null);\n  const [editValue, setEditValue] = useState('');\n  const [pendingId, setPendingId] = useState<string | null>(null);\n\n  const installmentsQuery = useInstallments({\n    documentId,\n    installmentsEndpoint,\n    httpRequest,\n    initialData: initialInstallments,\n  });\n\n  const modifyMutation = useModifyInstallment({\n    documentId,\n    modifyInstallmentEndpoint,\n    httpRequest,\n  });\n\n  const regenerateMutation = useRegenerateInstallments({\n    documentId,\n    regenerateEndpoint,\n    httpRequest,\n  });\n\n  const installments = installmentsQuery.data ?? [];\n\n  function cancelEdit() {\n    setEditingId(null);\n    setEditValue('');\n  }\n\n  function startEdit(row: InstallmentDto) {\n    if (!editableNow || pendingId) return;\n    setEditingId(row.id);\n    setEditValue(String(row.amount ?? 0));\n  }\n\n  function reportError(error: unknown) {\n    const status = (error as InstallmentsHttpError)?.status;\n    if (status === 403) {\n      toast.error(t('installments.error.forbidden'));\n      return;\n    }\n    if (status === 409) {\n      toast.error(t('installments.error.conflict'));\n      return;\n    }\n    if (status === 422) {\n      toast.error(t('installments.error.tooMany'));\n      return;\n    }\n    toast.error((error as Error)?.message || t('installments.error.generic'));\n  }\n\n  function commitEdit(row: InstallmentDto) {\n    const next = Number(editValue);\n    cancelEdit();\n\n    // Sin cambio o valor inválido → no se muta.\n    if (editValue.trim() === '' || Number.isNaN(next) || next === row.amount) {\n      return;\n    }\n    if (next < 0) {\n      toast.error(t('installments.error.amountPositive'));\n      return;\n    }\n\n    setPendingId(row.id);\n    modifyMutation.mutate(\n      { installmentId: row.id, payload: { rowVersion: row.rowVersion, amount: next } },\n      {\n        onSuccess: () => toast.success(t('installments.toast.updated')),\n        onError: reportError,\n        onSettled: () => setPendingId(null),\n      },\n    );\n  }\n\n  function handleRegenerate() {\n    regenerateMutation.mutate(undefined, {\n      onSuccess: () => {\n        toast.success(t('installments.toast.regenerated'));\n        setModalOpen(false);\n      },\n      onError: reportError,\n    });\n  }\n\n  const columns: TableColumn<InstallmentDto>[] = [\n    {\n      header: t('installments.column.number'),\n      accessor: 'installmentNumber',\n      align: 'center',\n      width: '72px',\n    },\n    {\n      header: t('installments.column.dueDate'),\n      accessor: 'dueDate',\n      render: (value) => (value ? formatDate(value as string) : DASH),\n    },\n    {\n      header: t('installments.column.promptPaymentDate'),\n      accessor: 'promptPaymentDate',\n      render: (value) => (value ? formatDate(value as string) : DASH),\n    },\n    {\n      header: t('installments.column.amount'),\n      accessor: 'amount',\n      align: 'right',\n      render: (_value, row) => {\n        if (editingId === row.id) {\n          return (\n            <Input\n              type=\"number\"\n              min={0}\n              step=\"any\"\n              inputSize=\"xs\"\n              autoFocus\n              value={editValue}\n              aria-label={t('installments.edit.amountAria', { number: row.installmentNumber })}\n              onChange={(e) => setEditValue(e.target.value)}\n              onBlur={() => commitEdit(row)}\n              onKeyDown={(e) => {\n                if (e.key === 'Enter') {\n                  e.preventDefault();\n                  commitEdit(row);\n                } else if (e.key === 'Escape') {\n                  e.preventDefault();\n                  cancelEdit();\n                }\n              }}\n              className=\"w-28 ml-auto\"\n            />\n          );\n        }\n        return (\n          <span\n            className={clsx(\n              'inline-flex items-center gap-1.5 justify-end tabular-nums',\n              editableNow && !pendingId && 'cursor-pointer hover:underline',\n              pendingId === row.id && 'opacity-50',\n            )}\n            onDoubleClick={() => startEdit(row)}\n            title={editableNow ? t('installments.edit.amountAria', { number: row.installmentNumber }) : undefined}\n          >\n            {formatAmount(row.amount)}\n          </span>\n        );\n      },\n    },\n    {\n      header: t('installments.column.promptPaymentDiscount'),\n      accessor: 'promptPaymentDiscount',\n      align: 'right',\n      render: (value) =>\n        value == null ? DASH : <span className=\"tabular-nums\">{formatAmount(value as number)}</span>,\n    },\n    {\n      header: t('installments.column.flags'),\n      accessor: 'isManual',\n      align: 'center',\n      width: '84px',\n      render: (_value, row) =>\n        row.isManual ? (\n          <InstallmentManualBadge\n            autoAmountLabel={\n              typeof row.autoGeneratedSnapshot?.amount === 'number'\n                ? formatAmount(row.autoGeneratedSnapshot.amount)\n                : undefined\n            }\n          />\n        ) : null,\n    },\n  ];\n\n  return (\n    <section\n      className={clsx('flex flex-col gap-3', className)}\n      aria-label={t('installments.panel.title')}\n    >\n      {/* Header */}\n      <div className=\"flex items-center justify-between gap-2\">\n        <h3 className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary truncate\">\n          {t('installments.panel.title')}\n        </h3>\n\n        {/* Botón Regenerar — solo en DOM cuando editableNow (oculto, no deshabilitado) */}\n        {editableNow && (\n          <button\n            type=\"button\"\n            onClick={() => setModalOpen(true)}\n            disabled={regenerateMutation.isPending}\n            aria-label={t('installments.panel.regenerateAria')}\n            className={clsx(\n              'inline-flex items-center gap-1.5 shrink-0',\n              'px-3 py-1.5 rounded-md text-xs font-semibold',\n              'bg-primary-600 text-white',\n              'hover:bg-primary-700 transition-colors duration-150',\n              'focus:outline-hidden focus:ring-2 focus:ring-primary-400 focus:ring-offset-2',\n              'dark:bg-dark-bg-inverse dark:text-dark-content-inverse dark:hover:bg-dark-bg-inverse/90',\n              'dark:focus:ring-dark-border-custom dark:focus:ring-offset-dark-bg-primary',\n              'disabled:opacity-40 disabled:pointer-events-none',\n            )}\n          >\n            <ArrowPathIcon className=\"w-4 h-4\" aria-hidden=\"true\" />\n            {t('installments.panel.regenerate')}\n          </button>\n        )}\n      </div>\n\n      {/* Estados de carga / error / grilla */}\n      {installmentsQuery.isError ? (\n        <Info color=\"red\" title={t('installments.panel.loadError')} />\n      ) : (\n        <Table<InstallmentDto>\n          columns={columns}\n          data={installments}\n          variant=\"basic\"\n          fullWidth\n          showShadow={false}\n          loading={installmentsQuery.isLoading}\n          emptyMessage={t('installments.panel.empty')}\n        />\n      )}\n\n      {/* Modal de regeneración (solo se monta si editableNow) */}\n      {editableNow && (\n        <RegenerateInstallmentsModal\n          open={modalOpen}\n          isProcessing={regenerateMutation.isPending}\n          onConfirm={handleRegenerate}\n          onClose={() => setModalOpen(false)}\n        />\n      )}\n    </section>\n  );\n}\n","import { createTranslationHook } from '../i18nFactory';\nimport { TEXTO_COMUN_ES, TEXTO_COMUN_EN } from '../commonTexts';\nimport type { TranslateFn } from '../i18nFactory';\n\n/**\n * i18n del widget de Retenciones (FEAT-105-11).\n *\n * Usa `useTranslation` de siesa-ui-kit vía `createTranslationHook`; si el host no\n * registró las claves `withholdings.*` (el motor devuelve la propia clave), cae al\n * diccionario local del idioma activo y, en último término, al español. Garantiza\n * español listo para usar sin depender de que el documento consumidor registre los\n * recursos. Las claves siguen el formato plano que espera `DefaultTranslationEngine`.\n */\n\nexport const WITHHOLDINGS_TRANSLATIONS_ES: Record<string, string> = {\n  'withholdings.panel.title': 'Retenciones',\n  'withholdings.panel.empty': 'Este documento no tiene retenciones.',\n  // Sin uso: el panel muestra un skeleton en vez de texto. No se borra sin\n  // confirmar con diseño que el skeleton es definitivo.\n  // Deuda con dueño en docs/i18n-masterdocument-deuda.md (punto 2).\n  'withholdings.panel.loading': 'Cargando retenciones…',\n  'withholdings.panel.loadError': 'No se pudieron cargar las retenciones.',\n\n  'withholdings.column.class': 'Clase',\n  'withholdings.column.base': 'Base',\n  'withholdings.column.rate': 'Tasa',\n  'withholdings.column.total': 'Total',\n  'withholdings.column.action': 'Acción',\n  'withholdings.column.origin': 'Origen',\n\n  'withholdings.origin.manual': 'Manual',\n  'withholdings.origin.manipulated': 'Modificado',\n  'withholdings.origin.automatic': 'Automático',\n  'withholdings.origin.originalTooltip': 'Valor original: {value}',\n\n  'withholdings.action.1': 'Aumenta total',\n  'withholdings.action.2': 'Disminuye total',\n  'withholdings.action.3': 'Sin efecto en total',\n  'withholdings.action.4': 'Sin contabilizar',\n  // Guarda para valores que el backend pueda añadir fuera del rango 1..4: sin ella\n  // la celda renderizaba la clave cruda `withholdings.action.7`.\n  'withholdings.action.unknown': 'Acción no reconocida',\n\n  'withholdings.actions.add': TEXTO_COMUN_ES.add,\n  'withholdings.actions.edit': 'Modificar',\n  'withholdings.actions.delete': TEXTO_COMUN_ES.delete,\n  'withholdings.actions.recalculate': 'Recalcular',\n\n  'withholdings.add.title': 'Agregar retención',\n  'withholdings.add.class': 'Clase de retención',\n  'withholdings.add.classPlaceholder': 'Seleccione una clase',\n  'withholdings.add.key': 'Clave de retención',\n  'withholdings.add.keyPlaceholder': 'Seleccione una clave',\n  'withholdings.add.operationCenter': 'Centro de operación',\n  'withholdings.add.operationCenterPlaceholder': 'Seleccione un centro',\n  'withholdings.add.base': 'Base',\n  'withholdings.add.total': 'Valor retenido',\n  'withholdings.add.submit': TEXTO_COMUN_ES.add,\n  'withholdings.add.cancel': TEXTO_COMUN_ES.cancel,\n\n  'withholdings.edit.title': 'Modificar retención',\n  'withholdings.edit.base': 'Base',\n  'withholdings.edit.total': 'Valor retenido',\n  'withholdings.edit.action': 'Acción sobre el total',\n  'withholdings.edit.submit': TEXTO_COMUN_ES.save,\n  'withholdings.edit.cancel': TEXTO_COMUN_ES.cancel,\n\n  'withholdings.delete.title': 'Eliminar retención',\n  'withholdings.delete.body': 'Se eliminará esta retención manual. ¿Continuar?',\n  'withholdings.delete.confirm': TEXTO_COMUN_ES.delete,\n  'withholdings.delete.cancel': TEXTO_COMUN_ES.cancel,\n\n  'withholdings.recalculate.title': 'Recalcular retenciones',\n  'withholdings.recalculate.body':\n    'Se regenerarán las retenciones automáticas. Las manuales y las modificadas se preservan. ¿Continuar?',\n  'withholdings.recalculate.confirm': 'Recalcular',\n  'withholdings.recalculate.cancel': TEXTO_COMUN_ES.cancel,\n\n  'withholdings.validation.required': 'Campo requerido.',\n  'withholdings.validation.basePositive': 'La base debe ser mayor que 0.',\n  'withholdings.validation.totalPositive': 'El valor debe ser mayor que 0.',\n  'withholdings.validation.operationCenterRequired':\n    'El centro de operación es obligatorio para claves municipales.',\n\n  'withholdings.error.forbidden': TEXTO_COMUN_ES.errorForbidden,\n  'withholdings.error.conflict': 'Conflicto: la retención cambió o ya existe esa combinación.',\n  // ⚠️ Estas tres siguen sin conectar, a propósito y no por descuido.\n  // `reportError` discrimina por `status` HTTP, y las tres son sub-casos de\n  // negocio del MISMO código (409/422): \"modificada por otro usuario\",\n  // \"solo manuales\" y \"no es borrador\" son indistinguibles sin un `errorCode`.\n  // `WithholdingsHttpError` solo declara `status` y `detail`, así que conectarlas\n  // exigiría (a) extender el tipo con el `errorCode` del backend y (b) conocer\n  // sus valores reales — que no están en este repo. Inventarlos daría un mapeo\n  // que nunca se dispara y aparentaría cobertura.\n  // Mientras tanto el usuario ve el `detail` del backend, que llega traducido.\n  // Registrada con dueño en docs/i18n-masterdocument-deuda.md (punto 1).\n  'withholdings.error.concurrency':\n    'La retención fue modificada por otro usuario. Se recargó la lista.',\n  'withholdings.error.cannotDeleteAutomatic': 'Solo se pueden eliminar retenciones manuales.',\n  'withholdings.error.notDraft': 'El documento no está en estado borrador.',\n  'withholdings.error.validation': 'Revise los datos ingresados.',\n  'withholdings.error.notFound': 'Recurso no encontrado.',\n  'withholdings.error.liquitaxUnavailable': 'El servicio de liquidación no está disponible.',\n  'withholdings.error.generic': TEXTO_COMUN_ES.errorGeneric,\n  'withholdings.error.catalog': 'No se pudieron cargar los catálogos.',\n\n  'withholdings.toast.added': 'Retención agregada correctamente.',\n  'withholdings.toast.updated': 'Retención actualizada correctamente.',\n  'withholdings.toast.deleted': 'Retención eliminada correctamente.',\n  'withholdings.toast.recalculated': 'Retenciones recalculadas: {preserved} preservadas, {recalculated} regeneradas.',\n};\n\nexport const WITHHOLDINGS_TRANSLATIONS_EN: Record<string, string> = {\n  'withholdings.panel.title': 'Withholdings',\n  'withholdings.panel.empty': 'This document has no withholdings.',\n  'withholdings.panel.loading': 'Loading withholdings…',\n  'withholdings.panel.loadError': 'Could not load withholdings.',\n\n  'withholdings.column.class': 'Class',\n  'withholdings.column.base': 'Base',\n  'withholdings.column.rate': 'Rate',\n  'withholdings.column.total': 'Total',\n  'withholdings.column.action': 'Action',\n  'withholdings.column.origin': 'Origin',\n\n  'withholdings.origin.manual': 'Manual',\n  'withholdings.origin.manipulated': 'Modified',\n  'withholdings.origin.automatic': 'Automatic',\n  'withholdings.origin.originalTooltip': 'Original value: {value}',\n\n  'withholdings.action.1': 'Increases total',\n  'withholdings.action.2': 'Decreases total',\n  'withholdings.action.3': 'No effect on total',\n  'withholdings.action.4': 'Not accounted',\n  'withholdings.action.unknown': 'Unrecognized action',\n\n  'withholdings.actions.add': TEXTO_COMUN_EN.add,\n  'withholdings.actions.edit': 'Edit',\n  'withholdings.actions.delete': TEXTO_COMUN_EN.delete,\n  'withholdings.actions.recalculate': 'Recalculate',\n\n  'withholdings.add.title': 'Add withholding',\n  'withholdings.add.class': 'Withholding class',\n  'withholdings.add.classPlaceholder': 'Select a class',\n  'withholdings.add.key': 'Withholding key',\n  'withholdings.add.keyPlaceholder': 'Select a key',\n  'withholdings.add.operationCenter': 'Operation center',\n  'withholdings.add.operationCenterPlaceholder': 'Select a center',\n  'withholdings.add.base': 'Base',\n  'withholdings.add.total': 'Withheld value',\n  'withholdings.add.submit': TEXTO_COMUN_EN.add,\n  'withholdings.add.cancel': TEXTO_COMUN_EN.cancel,\n\n  'withholdings.edit.title': 'Edit withholding',\n  'withholdings.edit.base': 'Base',\n  'withholdings.edit.total': 'Withheld value',\n  'withholdings.edit.action': 'Action on total',\n  'withholdings.edit.submit': TEXTO_COMUN_EN.save,\n  'withholdings.edit.cancel': TEXTO_COMUN_EN.cancel,\n\n  'withholdings.delete.title': 'Delete withholding',\n  'withholdings.delete.body': 'This manual withholding will be deleted. Continue?',\n  'withholdings.delete.confirm': TEXTO_COMUN_EN.delete,\n  'withholdings.delete.cancel': TEXTO_COMUN_EN.cancel,\n\n  'withholdings.recalculate.title': 'Recalculate withholdings',\n  'withholdings.recalculate.body':\n    'Automatic withholdings will be regenerated. Manual and modified ones are preserved. Continue?',\n  'withholdings.recalculate.confirm': 'Recalculate',\n  'withholdings.recalculate.cancel': TEXTO_COMUN_EN.cancel,\n\n  'withholdings.validation.required': 'Required field.',\n  'withholdings.validation.basePositive': 'The base must be greater than 0.',\n  'withholdings.validation.totalPositive': 'The value must be greater than 0.',\n  'withholdings.validation.operationCenterRequired':\n    'The operation center is required for municipal keys.',\n\n  'withholdings.error.forbidden': TEXTO_COMUN_EN.errorForbidden,\n  'withholdings.error.conflict': 'Conflict: the withholding changed or that combination already exists.',\n  'withholdings.error.concurrency': 'The withholding was modified by another user. The list was reloaded.',\n  'withholdings.error.cannotDeleteAutomatic': 'Only manual withholdings can be deleted.',\n  'withholdings.error.notDraft': 'The document is not in draft state.',\n  'withholdings.error.validation': 'Check the entered data.',\n  'withholdings.error.notFound': 'Resource not found.',\n  'withholdings.error.liquitaxUnavailable': 'The settlement service is unavailable.',\n  'withholdings.error.generic': TEXTO_COMUN_EN.errorGeneric,\n  'withholdings.error.catalog': 'Could not load catalogs.',\n\n  'withholdings.toast.added': 'Withholding added successfully.',\n  'withholdings.toast.updated': 'Withholding updated successfully.',\n  'withholdings.toast.deleted': 'Withholding deleted successfully.',\n  'withholdings.toast.recalculated': 'Withholdings recalculated: {preserved} preserved, {recalculated} regenerated.',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const WITHHOLDINGS_TRANSLATIONS = {\n  es: WITHHOLDINGS_TRANSLATIONS_ES,\n  en: WITHHOLDINGS_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción con interpolación `{var}`. */\nexport type WithholdingsT = TranslateFn;\n\n/**\n * Hook de traducción del widget.\n *\n * Usa `useTranslation` del kit; si la clave no está registrada en el host\n * (el motor devuelve la propia clave), cae al diccionario local del idioma activo.\n */\nexport const useWithholdingsTranslation = createTranslationHook(WITHHOLDINGS_TRANSLATIONS);\n","import { Badge } from '../../Badge/Badge';\nimport type { BadgeColor } from '../../Badge/Badge.types';\nimport { useWithholdingsTranslation } from './i18n';\nimport type { WithholdingOrigin } from './types';\n\nexport interface WithholdingOriginBadgeProps {\n  /** Origen de la fila (derivado de `isManual`/`isManipulated`). */\n  origin: WithholdingOrigin;\n}\n\nconst ORIGIN_CONFIG: Record<WithholdingOrigin, { color: BadgeColor; labelKey: string }> = {\n  manual: { color: 'amber', labelKey: 'withholdings.origin.manual' },\n  manipulated: { color: 'violet', labelKey: 'withholdings.origin.manipulated' },\n  automatic: { color: 'zinc', labelKey: 'withholdings.origin.automatic' },\n};\n\n/**\n * Badge de origen de una retención (FEAT-105-11.01).\n *\n * - `manual` → \"Manual\" (amber)\n * - `manipulated` → \"Modificado\" (violet)\n * - `automatic` → \"Automático\" (zinc)\n *\n * Reutiliza el `Badge` del kit.\n */\nexport function WithholdingOriginBadge({ origin }: WithholdingOriginBadgeProps) {\n  const { t } = useWithholdingsTranslation();\n  const { color, labelKey } = ORIGIN_CONFIG[origin];\n  return <Badge color={color} label={t(labelKey)} />;\n}\n","import { useWithholdingsTranslation } from './i18n';\nimport type { WithholdingDto } from './types';\n\nexport interface WithholdingTotalCellProps {\n  row: WithholdingDto;\n  formatAmount: (value: number) => string;\n}\n\n/**\n * Celda del valor total de una retención (FEAT-105-11.01).\n *\n * Cuando la fila es manipulada y el backend expone `originalTotalValue` (GAP-2),\n * muestra el valor original del motor en un tooltip (atributo `title` nativo).\n * Si el BE aún no expone `original_*`, degrada a la celda simple sin tooltip.\n */\nexport function WithholdingTotalCell({ row, formatAmount }: WithholdingTotalCellProps) {\n  const { t } = useWithholdingsTranslation();\n\n  const hasOriginal = row.isManipulated && typeof row.originalTotalValue === 'number';\n  const tooltip = hasOriginal\n    ? t('withholdings.origin.originalTooltip', { value: formatAmount(row.originalTotalValue as number) })\n    : undefined;\n\n  return (\n    <span\n      className={`tabular-nums ${hasOriginal ? 'underline decoration-dotted underline-offset-2 cursor-help' : ''}`}\n      title={tooltip}\n    >\n      {formatAmount(row.totalValue)}\n    </span>\n  );\n}\n","import { PlusIcon, PencilSquareIcon, TrashIcon, ArrowPathIcon } from '@heroicons/react/24/outline';\nimport { Button } from '../../Button/Button';\nimport { useWithholdingsTranslation } from './i18n';\nimport type { WithholdingDto } from './types';\n\nexport interface WithholdingsActionBarProps {\n  /** Permiso de escritura (Agregar/Modificar/Eliminar). */\n  canWrite: boolean;\n  /** Permiso de recálculo (Recalcular). */\n  canRecalculate: boolean;\n  /** `true` si hay loaders de catálogo (habilita Agregar). */\n  hasCatalogs: boolean;\n  /** Fila seleccionada (habilita Modificar/Eliminar). */\n  selectedRow: WithholdingDto | null;\n  /** Alguna mutación en vuelo: deshabilita la barra. */\n  isBusy: boolean;\n  onAdd: () => void;\n  onEdit: () => void;\n  onDelete: () => void;\n  onRecalculate: () => void;\n}\n\n/**\n * Barra de acciones del panel de retenciones (FEAT-105-11.02).\n *\n * El padre solo monta esta barra cuando el documento es editable y el usuario\n * tiene algún permiso (gating de estado/permiso → la barra se oculta, no se\n * deshabilita). Aquí se gatea por permiso fino y por selección:\n * - Agregar: requiere `canWrite` + catálogos.\n * - Modificar: requiere `canWrite` + fila seleccionada.\n * - Eliminar: requiere `canWrite` + fila seleccionada **manual** (las\n *   automáticas/manipuladas devuelven 409).\n * - Recalcular: requiere `canRecalculate`.\n */\nexport function WithholdingsActionBar({\n  canWrite,\n  canRecalculate,\n  hasCatalogs,\n  selectedRow,\n  isBusy,\n  onAdd,\n  onEdit,\n  onDelete,\n  onRecalculate,\n}: WithholdingsActionBarProps) {\n  const { t } = useWithholdingsTranslation();\n\n  const hasSelection = Boolean(selectedRow);\n  const canDeleteSelected = hasSelection && Boolean(selectedRow?.isManual);\n\n  return (\n    <div className=\"flex flex-wrap items-center gap-2\">\n      {canWrite && hasCatalogs && (\n        <Button\n          type=\"default\"\n          size=\"sm\"\n          leftIcon={<PlusIcon className=\"w-4 h-4\" />}\n          disabled={isBusy}\n          onClick={onAdd}\n        >\n          {t('withholdings.actions.add')}\n        </Button>\n      )}\n\n      {canWrite && (\n        <Button\n          type=\"outline\"\n          size=\"sm\"\n          leftIcon={<PencilSquareIcon className=\"w-4 h-4\" />}\n          disabled={isBusy || !hasSelection}\n          onClick={onEdit}\n        >\n          {t('withholdings.actions.edit')}\n        </Button>\n      )}\n\n      {canWrite && (\n        <Button\n          type=\"outline\"\n          size=\"sm\"\n          leftIcon={<TrashIcon className=\"w-4 h-4\" />}\n          disabled={isBusy || !canDeleteSelected}\n          onClick={onDelete}\n        >\n          {t('withholdings.actions.delete')}\n        </Button>\n      )}\n\n      {canRecalculate && (\n        <Button\n          type=\"outline\"\n          size=\"sm\"\n          leftIcon={<ArrowPathIcon className=\"w-4 h-4\" />}\n          disabled={isBusy}\n          onClick={onRecalculate}\n          className=\"ml-auto\"\n        >\n          {t('withholdings.actions.recalculate')}\n        </Button>\n      )}\n    </div>\n  );\n}\n","import { Fragment, type ReactNode } from 'react';\nimport { Dialog, Transition } from '@headlessui/react';\nimport { Button } from '../../Button/Button';\n\nexport interface WithholdingFormDialogProps {\n  open: boolean;\n  title: string;\n  /** Cuerpo del formulario (campos). */\n  children: ReactNode;\n  submitLabel: string;\n  cancelLabel: string;\n  /** Mutación en vuelo: bloquea botones y muestra spinner en confirmar. */\n  isSubmitting: boolean;\n  /** Deshabilita el botón de enviar (p.ej. formulario inválido). */\n  submitDisabled?: boolean;\n  onSubmit: () => void;\n  onClose: () => void;\n}\n\n/**\n * Shell de diálogo con formulario para el panel de retenciones (Agregar/Modificar).\n *\n * Construido sobre el `Dialog` de Headless UI (mismo cimiento que `AlertDialog`),\n * porque `AlertDialog` no admite contenido de formulario (`children`). El submit\n * se dispara desde el `<form>` (Enter) y desde el botón principal.\n */\nexport function WithholdingFormDialog({\n  open,\n  title,\n  children,\n  submitLabel,\n  cancelLabel,\n  isSubmitting,\n  submitDisabled = false,\n  onSubmit,\n  onClose,\n}: WithholdingFormDialogProps) {\n  const handleClose = () => {\n    if (!isSubmitting) onClose();\n  };\n\n  return (\n    <Transition appear show={open} as={Fragment}>\n      <Dialog as=\"div\" open={open} className=\"relative z-50 text-left\" onClose={handleClose}>\n        <Transition.Child\n          as={Fragment}\n          enter=\"ease-out duration-300\"\n          enterFrom=\"opacity-0\"\n          enterTo=\"opacity-100\"\n          leave=\"ease-in duration-200\"\n          leaveFrom=\"opacity-100\"\n          leaveTo=\"opacity-0\"\n        >\n          <div className=\"fixed inset-0 bg-black/60 backdrop-blur-[2px] transition-opacity\" />\n        </Transition.Child>\n\n        <div className=\"fixed inset-0 z-10 overflow-y-auto\">\n          <div className=\"flex min-h-full items-center justify-center p-4 text-center sm:p-0\">\n            <Transition.Child\n              as={Fragment}\n              enter=\"ease-out duration-300\"\n              enterFrom=\"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95\"\n              enterTo=\"opacity-100 translate-y-0 sm:scale-100\"\n              leave=\"ease-in duration-200\"\n              leaveFrom=\"opacity-100 translate-y-0 sm:scale-100\"\n              leaveTo=\"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95\"\n            >\n              <Dialog.Panel className=\"w-full max-w-md bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-600 rounded-xl transform overflow-hidden text-left align-middle shadow-xl transition-all\">\n                <form\n                  onSubmit={(e) => {\n                    e.preventDefault();\n                    if (!submitDisabled && !isSubmitting) onSubmit();\n                  }}\n                  className=\"p-6 flex flex-col gap-4\"\n                >\n                  <Dialog.Title\n                    as=\"p\"\n                    className=\"text-sm leading-5 font-bold text-content-primary dark:text-dark-content-primary\"\n                  >\n                    {title}\n                  </Dialog.Title>\n\n                  <div className=\"flex flex-col gap-3\">{children}</div>\n\n                  <div className=\"flex flex-wrap items-center justify-end gap-3 mt-2\">\n                    <Button type=\"plain\" size=\"base\" onClick={handleClose} disabled={isSubmitting}>\n                      {cancelLabel}\n                    </Button>\n                    <Button\n                      type=\"default\"\n                      size=\"base\"\n                      htmlType=\"submit\"\n                      disabled={isSubmitting || submitDisabled}\n                    >\n                      <span className=\"flex items-center justify-center gap-2 whitespace-nowrap\">\n                        {submitLabel}\n                        {isSubmitting && (\n                          <svg\n                            className=\"animate-spin h-4 w-4 text-white shrink-0\"\n                            xmlns=\"http://www.w3.org/2000/svg\"\n                            fill=\"none\"\n                            viewBox=\"0 0 24 24\"\n                          >\n                            <circle\n                              className=\"opacity-25\"\n                              cx=\"12\"\n                              cy=\"12\"\n                              r=\"10\"\n                              stroke=\"currentColor\"\n                              strokeWidth=\"4\"\n                            />\n                            <path\n                              className=\"opacity-75\"\n                              fill=\"currentColor\"\n                              d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n                            />\n                          </svg>\n                        )}\n                      </span>\n                    </Button>\n                  </div>\n                </form>\n              </Dialog.Panel>\n            </Transition.Child>\n          </div>\n        </div>\n      </Dialog>\n    </Transition>\n  );\n}\n","/**\n * Claves de caché de TanStack Query del panel de retenciones (FEAT-105-11).\n *\n * `document-withholdings`: lista TF3 del documento que la grilla renderiza. Se\n * invalida tras agregar/modificar/eliminar/recalcular (los totales T1/TF4b cambian).\n * `withholding-classes` / `withholding-keys`: catálogos del modal Agregar.\n */\nexport const withholdingsQueryKey = (documentId: string) =>\n  ['document-withholdings', documentId] as const;\n\nexport const withholdingClassesQueryKey = () => ['withholding-classes'] as const;\n\nexport const withholdingKeysQueryKey = (classId: string) =>\n  ['withholding-keys', classId] as const;\n\nexport const withholdingOperationCentersQueryKey = () =>\n  ['withholding-operation-centers'] as const;\n","/**\n * Tipos del widget WithholdingsPanel (FEAT-105-11) — sub-componente de\n * MasterDocument.\n *\n * Espejo TypeScript del read-model de retenciones del backend (`WithholdingDto`,\n * 105-10) más los contratos de props del widget reutilizable. Las retenciones\n * (TF3, tabla genérica `document_header_withholdings`) son un child genérico de\n * documento: el mismo panel sirve para compras/ventas/inventario inyectando sus\n * endpoints e IO por props (precedente: InstallmentsPanel / AdvanceApplicationsPanel).\n *\n * @see feat-105-11-panel-retenciones-masterdocument-spec.md\n */\n\n// ─── DTOs ──────────────────────────────────────────────────────────────────\n\n/**\n * Acción de la retención sobre el total del documento.\n * 1=IncreasesTotal · 2=DecreasesTotal · 3=NoActionDocumentTotal · 4=NoActionNoAccounting.\n * En el PUT solo se admiten 1/2/3 (0 y 4 → 400).\n */\nexport type WithholdingAction = 1 | 2 | 3 | 4;\n\n/**\n * Retención (TF3) — espejo de `WithholdingDto` (camelCase). Tabla genérica\n * `document_header_withholdings`, keyed por `documentId = document_headers.id`.\n *\n * Origen de la fila (derivado de `isManual`/`isManipulated`):\n * - `isManual = true` → creada manualmente por el usuario (POST).\n * - `isManipulated = true` → automática del motor que el usuario editó (PUT).\n * - ambos `false` → automática \"pura\" del motor LEGO-13.\n * (Restricción DB: nunca ambos `true` a la vez.)\n */\nexport interface WithholdingDto {\n  /** PK de la retención. */\n  id: string;\n  /** FK al documento (header). */\n  documentId: string;\n  /** Clase de retención (UUID). El nombre legible es opcional (ver GAP-2). */\n  withholdingClassId: string;\n  /** Clave de retención (UUID). */\n  withholdingKeyId: string;\n  /** Código denormalizado de la clave (≤20). */\n  withholdingKeyCode: string;\n  /** Acción sobre el total (1|2|3|4). */\n  withholdingAction: WithholdingAction;\n  /** Base de cálculo (decimal 18,6). */\n  baseValue: number;\n  /** Valor retenido (decimal 18,6). */\n  totalValue: number;\n  /** Centro de operación (UUID) o null si la clave es de regionalidad nacional. */\n  operationCenterId: string | null;\n  /** Fila creada manualmente. */\n  isManual: boolean;\n  /** Fila automática editada por el usuario (con `original_*` congelado). */\n  isManipulated: boolean;\n  /** Retención provisional. */\n  isProvisional: boolean;\n  /** Autorretención. */\n  isSelfWithholding: boolean;\n  /** Versión de fila para concurrencia optimista. */\n  rowVersion: number;\n  /** Auditoría. */\n  createdByUserId?: string;\n  updatedByUserId?: string;\n\n  // ── Campos opcionales — solo presentes si el BE resuelve GAP-2 ──────────\n  /** Nombre legible de la clase (columna \"Clase\"). GAP-2: puede no venir. */\n  withholdingClassName?: string;\n  /** Tasa porcentual de la clave (columna \"Tasa\"). GAP-2: puede no venir. */\n  rate?: number | null;\n  /** Base original del motor antes de manipular (tooltip \"valor original\"). GAP-2. */\n  originalBaseValue?: number | null;\n  /** Valor original del motor antes de manipular (tooltip \"valor original\"). GAP-2. */\n  originalTotalValue?: number | null;\n}\n\n/**\n * Forma cruda como puede llegar del backend. Booleanos defensivos + acción\n * tolerante; se normaliza con {@link normalizeWithholding}.\n */\nexport interface RawWithholdingDto\n  extends Partial<Omit<WithholdingDto, 'id' | 'documentId' | 'withholdingAction'>> {\n  id: string;\n  documentId: string;\n  withholdingAction?: number | null;\n}\n\n/** Origen visual de una retención (badge de la columna \"Origen\"). */\nexport type WithholdingOrigin = 'manual' | 'manipulated' | 'automatic';\n\n/** Deriva el origen visual de una retención a partir de sus flags. */\nexport function getWithholdingOrigin(w: Pick<WithholdingDto, 'isManual' | 'isManipulated'>): WithholdingOrigin {\n  if (w.isManual) return 'manual';\n  if (w.isManipulated) return 'manipulated';\n  return 'automatic';\n}\n\nfunction coerceAction(value: number | null | undefined): WithholdingAction {\n  return value === 1 || value === 2 || value === 3 || value === 4 ? value : 3;\n}\n\n/** Normaliza una retención cruda del backend al DTO de UI. */\nexport function normalizeWithholding(raw: RawWithholdingDto): WithholdingDto {\n  const base = (raw ?? {}) as RawWithholdingDto;\n  return {\n    id: base.id,\n    documentId: base.documentId,\n    withholdingClassId: base.withholdingClassId ?? '',\n    withholdingKeyId: base.withholdingKeyId ?? '',\n    withholdingKeyCode: base.withholdingKeyCode ?? '',\n    withholdingAction: coerceAction(base.withholdingAction),\n    baseValue: Number(base.baseValue ?? 0),\n    totalValue: Number(base.totalValue ?? 0),\n    operationCenterId: base.operationCenterId ?? null,\n    isManual: Boolean(base.isManual),\n    isManipulated: Boolean(base.isManipulated),\n    isProvisional: Boolean(base.isProvisional),\n    isSelfWithholding: Boolean(base.isSelfWithholding),\n    rowVersion: Number(base.rowVersion ?? 0),\n    createdByUserId: base.createdByUserId,\n    updatedByUserId: base.updatedByUserId,\n    withholdingClassName: base.withholdingClassName,\n    rate: base.rate ?? null,\n    originalBaseValue: base.originalBaseValue ?? null,\n    originalTotalValue: base.originalTotalValue ?? null,\n  };\n}\n\n/**\n * Orden canónico de UI: manuales primero, luego manipuladas, luego automáticas;\n * dentro de cada grupo por código de clave. Estable y determinista.\n */\nexport function sortWithholdings(withholdings: WithholdingDto[]): WithholdingDto[] {\n  const rank = (w: WithholdingDto) => (w.isManual ? 0 : w.isManipulated ? 1 : 2);\n  return [...withholdings].sort(\n    (a, b) => rank(a) - rank(b) || a.withholdingKeyCode.localeCompare(b.withholdingKeyCode),\n  );\n}\n\n// ─── Payloads de escritura ─────────────────────────────────────────────────\n\n/**\n * Payload del POST de creación manual (`CreateWithholdingDto`).\n *\n * ⚠ Nomenclatura BE: el create usa `baseAmount` (NO `baseValue`). `withholdingAction`\n * NO se envía: el backend lo calcula desde una matriz de decisión.\n */\nexport interface CreateWithholdingPayload {\n  /** Clase de retención (UUID, requerido). */\n  withholdingClassId: string;\n  /** Clave de retención (UUID, requerido; debe pertenecer a la clase). */\n  withholdingKeyId: string;\n  /** Centro de operación (UUID); requerido si la clave es municipal, null si nacional. */\n  operationCenterId: string | null;\n  /** Base de cálculo (> 0). ⚠ `baseAmount`, no `baseValue`. */\n  baseAmount: number;\n  /** Valor retenido (> 0). */\n  totalValue: number;\n  /** Base en moneda alterna (opcional). */\n  baseAmountAlt?: number | null;\n  /** Valor en moneda alterna (opcional). */\n  totalValueAlt?: number | null;\n}\n\n/**\n * Payload del PUT de modificación (`UpdateWithholdingDto`).\n *\n * ⚠ Nomenclatura BE: el update usa `baseValue` (NO `baseAmount`). `withholdingAction`\n * sí se respeta (solo 1/2/3). `rowVersion` requerido (concurrencia).\n */\nexport interface ModifyWithholdingPayload {\n  /** Base de cálculo (> 0). */\n  baseValue: number;\n  /** Valor retenido (> 0). */\n  totalValue: number;\n  /** Base en moneda alterna (opcional). */\n  baseValueAlt?: number | null;\n  /** Valor en moneda alterna (opcional). */\n  totalValueAlt?: number | null;\n  /** Acción sobre el total (1|2|3; 0 y 4 → 400). */\n  withholdingAction: 1 | 2 | 3;\n  /** Versión de fila requerida (concurrencia optimista). */\n  rowVersion: number;\n}\n\n/** Resumen del recálculo (`RecalculateSummaryDto`). */\nexport interface RecalculateSummary {\n  /** Filas preservadas (manuales + manipuladas restauradas). */\n  preserved: number;\n  /** Filas automáticas regeneradas por el motor. */\n  recalculated: number;\n}\n\n/** Respuesta del recálculo (`RecalculateWithholdingsResponse`). */\nexport interface RecalculateWithholdingsResponse {\n  /** Set TF3 completo tras el recálculo. */\n  withholdings: WithholdingDto[];\n  summary: RecalculateSummary;\n}\n\n/**\n * Envelope de las mutaciones de child (ADR-011): POST/PUT devuelven\n * `{ child, header }`; DELETE devuelve `{ header }`. El `header` es el\n * `DocumentHeaderDto` (totales recalculados); el widget no lo tipa fuerte.\n */\nexport interface WithholdingChildEnvelope {\n  child: RawWithholdingDto;\n  header?: unknown;\n}\nexport interface WithholdingDeleteEnvelope {\n  header?: unknown;\n}\n\n// ─── IO inyectada ────────────────────────────────────────────────────────\n\n/**\n * Cliente HTTP inyectado para las operaciones REST del widget.\n *\n * El kit no depende de `axios`; el documento consumidor inyecta su instancia ya\n * configurada (interceptores de auth/company) envuelta en esta firma. Debe\n * rechazar con un error que exponga `status` (número HTTP) para que el widget\n * distinga 409 (conflicto/duplicado) / 422 (negocio) / 403 (sin permiso).\n */\nexport type WithholdingsHttpRequest = <T = unknown>(\n  method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n  url: string,\n  body?: unknown,\n) => Promise<T>;\n\n/** Error normalizado que el widget interpreta para el manejo de UI. */\nexport interface WithholdingsHttpError extends Error {\n  status?: number;\n  /** `ProblemDetails.detail` ya traducido por `Accept-Language` (si llega). */\n  detail?: string;\n}\n\n// ─── Catálogos (modal Agregar) ─────────────────────────────────────────────\n\n/** Opción de clase de retención para el `Select` del modal Agregar. */\nexport interface WithholdingClassOption {\n  id: string;\n  name: string;\n}\n\n/** Regionalidad de la clave: determina si el centro de operación es requerido. */\nexport type WithholdingKeyRegionality = 'national' | 'municipal';\n\n/** Opción de clave de retención (filtrada por clase) para el modal Agregar. */\nexport interface WithholdingKeyOption {\n  id: string;\n  code: string;\n  name: string;\n  /** Tasa porcentual (informativa). */\n  percentRate?: number | null;\n  /** Si es municipal, el centro de operación es obligatorio. @default 'national' */\n  regionality?: WithholdingKeyRegionality;\n}\n\n/** Opción de centro de operación para el modal Agregar. */\nexport interface WithholdingOperationCenterOption {\n  id: string;\n  name: string;\n}\n\n/**\n * Loaders de catálogo inyectados (decoplan el widget del transporte/rutas\n * concretas, que son específicos del host). Si se omite `catalogs`, el botón\n * \"Agregar\" no se muestra (Modificar/Eliminar/Recalcular siguen disponibles).\n */\nexport interface WithholdingsCatalogs {\n  /** Lista de clases de retención disponibles. */\n  loadClasses: () => Promise<WithholdingClassOption[]>;\n  /** Lista de claves de la clase seleccionada. */\n  loadKeys: (classId: string) => Promise<WithholdingKeyOption[]>;\n  /** Lista de centros de operación (solo si alguna clave es municipal). */\n  loadOperationCenters?: () => Promise<WithholdingOperationCenterOption[]>;\n}\n\n// ─── Props ─────────────────────────────────────────────────────────────────\n\n/**\n * Props del panel principal `WithholdingsPanel`.\n *\n * El widget es agnóstico del documento: recibe sus endpoints e IO por props,\n * lo que permite montarlo en cualquier MasterDocument (compras/ventas/inventario).\n */\nexport interface WithholdingsPanelProps {\n  /** UUID del documento (PK de `document_headers.id`), no el número legible. */\n  documentId: string;\n  /**\n   * `true` solo cuando el documento es editable (DRAFT). Cuando es `false`, la\n   * grilla es read-only y la barra de acciones se elimina del DOM.\n   */\n  isEditable: boolean;\n  /**\n   * `true` si el usuario tiene permiso de escritura de TF3\n   * (`commercial.core.withholdings.write`). Gatea Agregar/Modificar/Eliminar.\n   */\n  canWrite: boolean;\n  /**\n   * `true` si el usuario tiene permiso de recálculo\n   * (`commercial.core.supplier-invoices.modify_withholdings`). Gatea Recalcular.\n   */\n  canRecalculate: boolean;\n  /**\n   * Endpoint GET para cargar la lista TF3 (BRECHA G1/GAP-1 — el BE aún la expone\n   * como stub 501). Si se omite, la grilla solo se puebla con `initialWithholdings`\n   * y con las respuestas de las mutaciones.\n   */\n  withholdingsEndpoint?: string;\n  /**\n   * Endpoint base de child: `/{id}/withholdings`. El widget añade `/{childId}`\n   * para PUT/DELETE y `/recalculate` para el recálculo. POST va a la base.\n   */\n  withholdingsBaseEndpoint: string;\n  /** Cliente HTTP inyectado para las operaciones REST. */\n  httpRequest: WithholdingsHttpRequest;\n  /** Loaders de catálogo para el modal Agregar (opcional — ver {@link WithholdingsCatalogs}). */\n  catalogs?: WithholdingsCatalogs;\n  /**\n   * Datos iniciales (opcional). Útil cuando la carga proviene de la sección\n   * FactBox (`dataSource: 'adapter'`) en vez de un GET dedicado.\n   */\n  initialWithholdings?: WithholdingDto[];\n  /** Formateador de montos. @default `formatAmount` de `useMasterDocumentFormatters` (idioma activo, 2 decimales). */\n  formatAmount?: (value: number) => string;\n  /** Clases CSS adicionales para el contenedor raíz. */\n  className?: string;\n}\n","import { useQuery } from '@tanstack/react-query';\nimport { withholdingsQueryKey } from './keys';\nimport { normalizeWithholding, sortWithholdings } from '../types';\nimport type { WithholdingDto, WithholdingsHttpRequest, RawWithholdingDto } from '../types';\n\nexport interface UseWithholdingsParams {\n  documentId: string;\n  /**\n   * Endpoint GET de la lista TF3 (BRECHA G1/GAP-1). Si se omite, la query queda\n   * deshabilitada y la grilla se puebla solo con `initialData` / mutaciones.\n   */\n  withholdingsEndpoint?: string;\n  httpRequest: WithholdingsHttpRequest;\n  /** Datos iniciales (p.ej. provenientes de la sección FactBox del adapter). */\n  initialData?: WithholdingDto[];\n  enabled?: boolean;\n}\n\n/**\n * Carga la lista de retenciones (TF3) del documento (lo que la grilla renderiza).\n *\n * Cache key: `['document-withholdings', documentId]`. Normaliza cada fila y\n * aplica el orden canónico (manuales → manipuladas → automáticas).\n */\nexport function useWithholdings({\n  documentId,\n  withholdingsEndpoint,\n  httpRequest,\n  initialData,\n  enabled = true,\n}: UseWithholdingsParams) {\n  return useQuery<WithholdingDto[]>({\n    queryKey: withholdingsQueryKey(documentId),\n    enabled: enabled && Boolean(documentId) && Boolean(withholdingsEndpoint),\n    initialData: initialData ? sortWithholdings(initialData) : undefined,\n    queryFn: async () => {\n      const raw = await httpRequest<RawWithholdingDto[]>('GET', withholdingsEndpoint!);\n      return sortWithholdings((raw ?? []).map(normalizeWithholding));\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { withholdingsQueryKey } from './keys';\nimport { normalizeWithholding, sortWithholdings } from '../types';\nimport type {\n  CreateWithholdingPayload,\n  WithholdingChildEnvelope,\n  WithholdingDto,\n  WithholdingsHttpRequest,\n} from '../types';\n\nexport interface UseAddManualWithholdingParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/withholdings`). El POST va a esta ruta. */\n  withholdingsBaseEndpoint: string;\n  httpRequest: WithholdingsHttpRequest;\n}\n\n/**\n * Agrega una retención manual (`POST /{id}/withholdings`) → 201 `{child, header}`.\n *\n * `withholding_action` NO se envía: el backend lo calcula. La fila resultante\n * llega con `isManual = true`.\n *\n * - `onSuccess`: inserta la fila nueva en el cache.\n * - `onSettled`: invalida `['document-withholdings', documentId]` (totales cambian).\n */\nexport function useAddManualWithholding({\n  documentId,\n  withholdingsBaseEndpoint,\n  httpRequest,\n}: UseAddManualWithholdingParams) {\n  const queryClient = useQueryClient();\n  const key = withholdingsQueryKey(documentId);\n\n  return useMutation<WithholdingDto, Error, CreateWithholdingPayload>({\n    mutationFn: async (payload) => {\n      const res = await httpRequest<WithholdingChildEnvelope>(\n        'POST',\n        withholdingsBaseEndpoint,\n        payload,\n      );\n      return normalizeWithholding(res.child);\n    },\n    onSuccess: (created) => {\n      queryClient.setQueryData<WithholdingDto[]>(key, (prev) =>\n        sortWithholdings([...(prev ?? []).filter((row) => row.id !== created.id), created]),\n      );\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { withholdingsQueryKey } from './keys';\nimport { normalizeWithholding, sortWithholdings } from '../types';\nimport type {\n  ModifyWithholdingPayload,\n  WithholdingChildEnvelope,\n  WithholdingDto,\n  WithholdingsHttpRequest,\n} from '../types';\n\nexport interface UseModifyWithholdingParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/withholdings`); se le añade `/{childId}`. */\n  withholdingsBaseEndpoint: string;\n  httpRequest: WithholdingsHttpRequest;\n}\n\nexport interface ModifyWithholdingInput {\n  withholdingId: string;\n  payload: ModifyWithholdingPayload;\n}\n\ninterface ModifyMutationContext {\n  previous?: WithholdingDto[];\n}\n\n/**\n * Modifica una retención (`PUT /{id}/withholdings/{childId}`) → 200 `{child, header}`,\n * con optimistic update.\n *\n * - `onMutate`: aplica base/total/acción a la fila. Si era automática (no manual),\n *   la marca `isManipulated = true` (espejo del comportamiento del backend).\n * - `onError`: rollback al snapshot previo (el panel surfacea 409/422/403).\n * - `onSuccess`: reemplaza la fila con la respuesta del servidor (rowVersion++).\n * - `onSettled`: invalida `['document-withholdings', documentId]`.\n */\nexport function useModifyWithholding({\n  documentId,\n  withholdingsBaseEndpoint,\n  httpRequest,\n}: UseModifyWithholdingParams) {\n  const queryClient = useQueryClient();\n  const key = withholdingsQueryKey(documentId);\n\n  return useMutation<WithholdingDto, Error, ModifyWithholdingInput, ModifyMutationContext>({\n    mutationFn: async ({ withholdingId, payload }) => {\n      const res = await httpRequest<WithholdingChildEnvelope>(\n        'PUT',\n        `${withholdingsBaseEndpoint}/${withholdingId}`,\n        payload,\n      );\n      return normalizeWithholding(res.child);\n    },\n    onMutate: async ({ withholdingId, payload }) => {\n      await queryClient.cancelQueries({ queryKey: key });\n      const previous = queryClient.getQueryData<WithholdingDto[]>(key);\n\n      queryClient.setQueryData<WithholdingDto[]>(key, (prev) =>\n        (prev ?? []).map((row) =>\n          row.id === withholdingId\n            ? {\n                ...row,\n                baseValue: payload.baseValue,\n                totalValue: payload.totalValue,\n                withholdingAction: payload.withholdingAction,\n                // Editar una fila automática la convierte en manipulada.\n                isManipulated: row.isManual ? row.isManipulated : true,\n              }\n            : row,\n        ),\n      );\n\n      return { previous };\n    },\n    onError: (_error, _input, context) => {\n      if (context?.previous !== undefined) {\n        queryClient.setQueryData(key, context.previous);\n      }\n    },\n    onSuccess: (updated) => {\n      queryClient.setQueryData<WithholdingDto[]>(key, (prev) =>\n        sortWithholdings((prev ?? []).map((row) => (row.id === updated.id ? updated : row))),\n      );\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { withholdingsQueryKey } from './keys';\nimport type { WithholdingDto, WithholdingsHttpRequest } from '../types';\n\nexport interface UseDeleteWithholdingParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/withholdings`); se le añade `/{childId}`. */\n  withholdingsBaseEndpoint: string;\n  httpRequest: WithholdingsHttpRequest;\n}\n\n/**\n * Elimina una retención manual (`DELETE /{id}/withholdings/{childId}`) → 200 `{header}`.\n *\n * Solo las filas `isManual = true` son eliminables; el backend responde 409 sobre\n * automáticas/manipuladas (la UI ya deshabilita Eliminar en ese caso).\n *\n * - `onSuccess`: quita la fila del cache.\n * - `onSettled`: invalida `['document-withholdings', documentId]` (totales cambian).\n */\nexport function useDeleteWithholding({\n  documentId,\n  withholdingsBaseEndpoint,\n  httpRequest,\n}: UseDeleteWithholdingParams) {\n  const queryClient = useQueryClient();\n  const key = withholdingsQueryKey(documentId);\n\n  return useMutation<string, Error, string>({\n    mutationFn: async (withholdingId) => {\n      await httpRequest('DELETE', `${withholdingsBaseEndpoint}/${withholdingId}`);\n      return withholdingId;\n    },\n    onSuccess: (deletedId) => {\n      queryClient.setQueryData<WithholdingDto[]>(key, (prev) =>\n        (prev ?? []).filter((row) => row.id !== deletedId),\n      );\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { withholdingsQueryKey } from './keys';\nimport { normalizeWithholding, sortWithholdings } from '../types';\nimport type {\n  RawWithholdingDto,\n  RecalculateSummary,\n  RecalculateWithholdingsResponse,\n  WithholdingDto,\n  WithholdingsHttpRequest,\n} from '../types';\n\nexport interface UseRecalculateWithholdingsParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/withholdings`); se le añade `/recalculate`. */\n  withholdingsBaseEndpoint: string;\n  httpRequest: WithholdingsHttpRequest;\n}\n\ninterface RawRecalculateResponse {\n  withholdings?: RawWithholdingDto[];\n  summary?: Partial<RecalculateSummary>;\n}\n\n/**\n * Recalcula las retenciones (`POST /{id}/withholdings/recalculate`) → 200\n * `{ withholdings, summary }`.\n *\n * El motor (LEGO-13) borra las automáticas, preserva las manuales y restaura las\n * manipuladas con los valores del usuario. Devuelve `{ preserved, recalculated }`.\n *\n * - `onSuccess`: siembra el cache con el set TF3 completo regenerado.\n * - `onSettled`: invalida `['document-withholdings', documentId]`.\n */\nexport function useRecalculateWithholdings({\n  documentId,\n  withholdingsBaseEndpoint,\n  httpRequest,\n}: UseRecalculateWithholdingsParams) {\n  const queryClient = useQueryClient();\n  const key = withholdingsQueryKey(documentId);\n\n  return useMutation<RecalculateWithholdingsResponse, Error, void>({\n    mutationFn: async () => {\n      const res = await httpRequest<RawRecalculateResponse>(\n        'POST',\n        `${withholdingsBaseEndpoint}/recalculate`,\n      );\n      return {\n        withholdings: sortWithholdings((res.withholdings ?? []).map(normalizeWithholding)),\n        summary: {\n          preserved: Number(res.summary?.preserved ?? 0),\n          recalculated: Number(res.summary?.recalculated ?? 0),\n        },\n      };\n    },\n    onSuccess: (result) => {\n      queryClient.setQueryData<WithholdingDto[]>(key, result.withholdings);\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useQuery } from '@tanstack/react-query';\nimport {\n  withholdingClassesQueryKey,\n  withholdingKeysQueryKey,\n  withholdingOperationCentersQueryKey,\n} from './keys';\nimport type {\n  WithholdingClassOption,\n  WithholdingKeyOption,\n  WithholdingOperationCenterOption,\n  WithholdingsCatalogs,\n} from '../types';\n\nconst STALE_TIME = 5 * 60 * 1000; // los catálogos cambian poco (§7.4)\n\nexport interface UseWithholdingClassesParams {\n  catalogs?: Pick<WithholdingsCatalogs, 'loadClasses'>;\n  enabled?: boolean;\n}\n\n/** Carga las clases de retención para el `Select` del modal Agregar. */\nexport function useWithholdingClasses({ catalogs, enabled = true }: UseWithholdingClassesParams) {\n  return useQuery<WithholdingClassOption[]>({\n    queryKey: withholdingClassesQueryKey(),\n    enabled: enabled && Boolean(catalogs?.loadClasses),\n    staleTime: STALE_TIME,\n    queryFn: () => catalogs!.loadClasses(),\n  });\n}\n\nexport interface UseWithholdingKeysParams {\n  catalogs?: Pick<WithholdingsCatalogs, 'loadKeys'>;\n  /** Clase seleccionada; sin ella la query queda deshabilitada. */\n  classId: string | null;\n  enabled?: boolean;\n}\n\n/** Carga las claves de la clase seleccionada (filtradas por clase). */\nexport function useWithholdingKeys({ catalogs, classId, enabled = true }: UseWithholdingKeysParams) {\n  return useQuery<WithholdingKeyOption[]>({\n    queryKey: withholdingKeysQueryKey(classId ?? ''),\n    enabled: enabled && Boolean(catalogs?.loadKeys) && Boolean(classId),\n    staleTime: STALE_TIME,\n    queryFn: () => catalogs!.loadKeys(classId!),\n  });\n}\n\nexport interface UseWithholdingOperationCentersParams {\n  catalogs?: Pick<WithholdingsCatalogs, 'loadOperationCenters'>;\n  enabled?: boolean;\n}\n\n/** Carga los centros de operación (solo necesarios para claves municipales). */\nexport function useWithholdingOperationCenters({\n  catalogs,\n  enabled = true,\n}: UseWithholdingOperationCentersParams) {\n  return useQuery<WithholdingOperationCenterOption[]>({\n    queryKey: withholdingOperationCentersQueryKey(),\n    enabled: enabled && Boolean(catalogs?.loadOperationCenters),\n    staleTime: STALE_TIME,\n    queryFn: () => catalogs!.loadOperationCenters!(),\n  });\n}\n","import { useMemo, useState } from 'react';\nimport { Input } from '../../Input/Input';\nimport { Select } from '../../Select/Select';\nimport type { SelectOption } from '../../Select/Select.types';\nimport { WithholdingFormDialog } from './WithholdingFormDialog';\nimport { useWithholdingsTranslation } from './i18n';\nimport {\n  useWithholdingClasses,\n  useWithholdingKeys,\n  useWithholdingOperationCenters,\n} from './hooks';\nimport type { CreateWithholdingPayload, WithholdingsCatalogs, WithholdingKeyOption } from './types';\n\nexport interface WithholdingsAddModalProps {\n  open: boolean;\n  /** Loaders de catálogo (clase/clave/centro). */\n  catalogs: WithholdingsCatalogs;\n  /** Mutación en vuelo. */\n  isSubmitting: boolean;\n  onSubmit: (payload: CreateWithholdingPayload) => void;\n  onClose: () => void;\n}\n\n/**\n * Modal Agregar retención manual (FEAT-105-11.02).\n *\n * Captura clase/clave/centro (vía `Select` de catálogo) y base/valor. NO expone\n * `withholdingAction`: el backend lo calcula desde su matriz de decisión (GOTCHA\n * documentado en la spec §2.3). El centro de operación se exige solo si la clave\n * seleccionada es de regionalidad municipal.\n */\nexport function WithholdingsAddModal({\n  open,\n  catalogs,\n  isSubmitting,\n  onSubmit,\n  onClose,\n}: WithholdingsAddModalProps) {\n  const { t } = useWithholdingsTranslation();\n\n  const [classId, setClassId] = useState('');\n  const [keyId, setKeyId] = useState('');\n  const [operationCenterId, setOperationCenterId] = useState('');\n  const [base, setBase] = useState('');\n  const [total, setTotal] = useState('');\n  const [touched, setTouched] = useState(false);\n\n  const classesQuery = useWithholdingClasses({ catalogs, enabled: open });\n  const keysQuery = useWithholdingKeys({ catalogs, classId: classId || null, enabled: open });\n  const ocQuery = useWithholdingOperationCenters({ catalogs, enabled: open });\n\n  // Cualquiera de los tres catálogos que falle deja el formulario inservible:\n  // se avisa una sola vez en lugar de dejar los selects vacíos en silencio.\n  const catalogsFailed = classesQuery.isError || keysQuery.isError || ocQuery.isError;\n\n  const classOptions: SelectOption[] = useMemo(\n    () => (classesQuery.data ?? []).map((c) => ({ value: c.id, label: c.name })),\n    [classesQuery.data],\n  );\n  const keyOptions: SelectOption[] = useMemo(\n    () =>\n      (keysQuery.data ?? []).map((k) => ({\n        value: k.id,\n        label: k.code ? `${k.code} — ${k.name}` : k.name,\n      })),\n    [keysQuery.data],\n  );\n  const ocOptions: SelectOption[] = useMemo(\n    () => (ocQuery.data ?? []).map((o) => ({ value: o.id, label: o.name })),\n    [ocQuery.data],\n  );\n\n  const selectedKey: WithholdingKeyOption | undefined = useMemo(\n    () => (keysQuery.data ?? []).find((k) => k.id === keyId),\n    [keysQuery.data, keyId],\n  );\n  const ocRequired = selectedKey?.regionality === 'municipal';\n\n  const baseNum = Number(base);\n  const totalNum = Number(total);\n  const baseValid = base.trim() !== '' && !Number.isNaN(baseNum) && baseNum > 0;\n  const totalValid = total.trim() !== '' && !Number.isNaN(totalNum) && totalNum > 0;\n  const ocValid = !ocRequired || Boolean(operationCenterId);\n  const formValid = Boolean(classId) && Boolean(keyId) && baseValid && totalValid && ocValid;\n\n  function reset() {\n    setClassId('');\n    setKeyId('');\n    setOperationCenterId('');\n    setBase('');\n    setTotal('');\n    setTouched(false);\n  }\n\n  function handleClose() {\n    reset();\n    onClose();\n  }\n\n  function handleSubmit() {\n    setTouched(true);\n    if (!formValid) return;\n    onSubmit({\n      withholdingClassId: classId,\n      withholdingKeyId: keyId,\n      operationCenterId: ocRequired ? operationCenterId : null,\n      baseAmount: baseNum,\n      totalValue: totalNum,\n    });\n  }\n\n  return (\n    <WithholdingFormDialog\n      open={open}\n      title={t('withholdings.add.title')}\n      submitLabel={t('withholdings.add.submit')}\n      cancelLabel={t('withholdings.add.cancel')}\n      isSubmitting={isSubmitting}\n      submitDisabled={!formValid}\n      onSubmit={handleSubmit}\n      onClose={handleClose}\n    >\n      {/* Los tres catálogos se cargaban sin mirar `isError`: si el backend fallaba,\n          el usuario veía selects vacíos y sin explicación. `withholdings.error.catalog`\n          existía en el catálogo pero no estaba conectada a nada. */}\n      {catalogsFailed && (\n        <p\n          role=\"alert\"\n          className=\"mb-3 rounded-md bg-error-bg px-3 py-2 text-sm text-error-content\"\n        >\n          {t('withholdings.error.catalog')}\n        </p>\n      )}\n      <Select\n        label={t('withholdings.add.class')}\n        placeholder={t('withholdings.add.classPlaceholder')}\n        options={classOptions}\n        value={classId}\n        required\n        error={touched && !classId}\n        errorMessage={touched && !classId ? t('withholdings.validation.required') : undefined}\n        onChange={(v) => {\n          setClassId(String(v));\n          // Cambiar la clase invalida la clave y el centro seleccionados.\n          setKeyId('');\n          setOperationCenterId('');\n        }}\n      />\n\n      <Select\n        label={t('withholdings.add.key')}\n        placeholder={t('withholdings.add.keyPlaceholder')}\n        options={keyOptions}\n        value={keyId}\n        required\n        disabled={!classId || keysQuery.isLoading}\n        error={touched && !keyId}\n        errorMessage={touched && !keyId ? t('withholdings.validation.required') : undefined}\n        onChange={(v) => {\n          setKeyId(String(v));\n          setOperationCenterId('');\n        }}\n      />\n\n      {ocRequired && (\n        <Select\n          label={t('withholdings.add.operationCenter')}\n          placeholder={t('withholdings.add.operationCenterPlaceholder')}\n          options={ocOptions}\n          value={operationCenterId}\n          required\n          error={touched && !operationCenterId}\n          errorMessage={\n            touched && !operationCenterId\n              ? t('withholdings.validation.operationCenterRequired')\n              : undefined\n          }\n          onChange={(v) => setOperationCenterId(String(v))}\n        />\n      )}\n\n      <Input\n        label={t('withholdings.add.base')}\n        type=\"number\"\n        min={0}\n        step=\"any\"\n        inputMode=\"decimal\"\n        value={base}\n        error={touched && !baseValid}\n        errorMessage={touched && !baseValid ? t('withholdings.validation.basePositive') : undefined}\n        onChange={(e) => setBase(e.target.value)}\n      />\n\n      <Input\n        label={t('withholdings.add.total')}\n        type=\"number\"\n        min={0}\n        step=\"any\"\n        inputMode=\"decimal\"\n        value={total}\n        error={touched && !totalValid}\n        errorMessage={touched && !totalValid ? t('withholdings.validation.totalPositive') : undefined}\n        onChange={(e) => setTotal(e.target.value)}\n      />\n    </WithholdingFormDialog>\n  );\n}\n","import { useEffect, useState } from 'react';\nimport { Input } from '../../Input/Input';\nimport { Select } from '../../Select/Select';\nimport type { SelectOption } from '../../Select/Select.types';\nimport { WithholdingFormDialog } from './WithholdingFormDialog';\nimport { useWithholdingsTranslation } from './i18n';\nimport type { ModifyWithholdingPayload, WithholdingDto } from './types';\n\nexport interface WithholdingsEditModalProps {\n  open: boolean;\n  /** Fila a editar (provee valores iniciales y `rowVersion`). */\n  row: WithholdingDto | null;\n  /** Mutación en vuelo. */\n  isSubmitting: boolean;\n  onSubmit: (payload: ModifyWithholdingPayload) => void;\n  onClose: () => void;\n}\n\n/**\n * Modal Modificar retención (FEAT-105-11.02).\n *\n * Pre-poblado con la fila seleccionada. Edita base/valor y la acción (1/2/3; el\n * backend rechaza 0/4). `rowVersion` viaja oculto en el payload para la\n * concurrencia optimista (un 409 → la lista se recarga).\n */\nexport function WithholdingsEditModal({\n  open,\n  row,\n  isSubmitting,\n  onSubmit,\n  onClose,\n}: WithholdingsEditModalProps) {\n  const { t } = useWithholdingsTranslation();\n\n  const [base, setBase] = useState('');\n  const [total, setTotal] = useState('');\n  const [action, setAction] = useState<1 | 2 | 3>(1);\n  const [touched, setTouched] = useState(false);\n\n  // Re-sembrar el formulario cuando cambia la fila / se abre el modal.\n  useEffect(() => {\n    if (open && row) {\n      setBase(String(row.baseValue ?? ''));\n      setTotal(String(row.totalValue ?? ''));\n      setAction(row.withholdingAction === 2 ? 2 : row.withholdingAction === 3 ? 3 : 1);\n      setTouched(false);\n    }\n  }, [open, row]);\n\n  const actionOptions: SelectOption[] = [\n    { value: 1, label: t('withholdings.action.1') },\n    { value: 2, label: t('withholdings.action.2') },\n    { value: 3, label: t('withholdings.action.3') },\n  ];\n\n  const baseNum = Number(base);\n  const totalNum = Number(total);\n  const baseValid = base.trim() !== '' && !Number.isNaN(baseNum) && baseNum > 0;\n  const totalValid = total.trim() !== '' && !Number.isNaN(totalNum) && totalNum > 0;\n  const formValid = baseValid && totalValid;\n\n  function handleSubmit() {\n    setTouched(true);\n    if (!formValid || !row) return;\n    onSubmit({\n      baseValue: baseNum,\n      totalValue: totalNum,\n      withholdingAction: action,\n      rowVersion: row.rowVersion,\n    });\n  }\n\n  return (\n    <WithholdingFormDialog\n      open={open}\n      title={t('withholdings.edit.title')}\n      submitLabel={t('withholdings.edit.submit')}\n      cancelLabel={t('withholdings.edit.cancel')}\n      isSubmitting={isSubmitting}\n      submitDisabled={!formValid}\n      onSubmit={handleSubmit}\n      onClose={onClose}\n    >\n      <Input\n        label={t('withholdings.edit.base')}\n        type=\"number\"\n        min={0}\n        step=\"any\"\n        inputMode=\"decimal\"\n        value={base}\n        error={touched && !baseValid}\n        errorMessage={touched && !baseValid ? t('withholdings.validation.basePositive') : undefined}\n        onChange={(e) => setBase(e.target.value)}\n      />\n\n      <Input\n        label={t('withholdings.edit.total')}\n        type=\"number\"\n        min={0}\n        step=\"any\"\n        inputMode=\"decimal\"\n        value={total}\n        error={touched && !totalValid}\n        errorMessage={touched && !totalValid ? t('withholdings.validation.totalPositive') : undefined}\n        onChange={(e) => setTotal(e.target.value)}\n      />\n\n      <Select\n        label={t('withholdings.edit.action')}\n        options={actionOptions}\n        value={action}\n        onChange={(v) => setAction(Number(v) as 1 | 2 | 3)}\n      />\n    </WithholdingFormDialog>\n  );\n}\n","import { AlertDialog } from '../../AlertDialog/AlertDialog';\n\nexport interface WithholdingsConfirmModalProps {\n  open: boolean;\n  /** Título del diálogo. */\n  title: string;\n  /** Cuerpo / descripción. */\n  body: string;\n  /** Texto del botón de confirmación. */\n  confirmLabel: string;\n  /** Texto del botón de cancelar. */\n  cancelLabel: string;\n  /** `warning` para Recalcular, `danger` para Eliminar. @default 'warning' */\n  type?: 'warning' | 'danger';\n  /** Mutación en vuelo: bloquea botones y muestra spinner. */\n  isLoading: boolean;\n  onConfirm: () => void;\n  onClose: () => void;\n}\n\n/**\n * Modal de confirmación genérico del panel de retenciones (FEAT-105-11.03).\n *\n * Envuelve el `AlertDialog` del kit; sirve para Recalcular (`warning`) y para\n * Eliminar (`danger`). Reutilizable por cualquier acción que requiera confirmar.\n */\nexport function WithholdingsConfirmModal({\n  open,\n  title,\n  body,\n  confirmLabel,\n  cancelLabel,\n  type = 'warning',\n  isLoading,\n  onConfirm,\n  onClose,\n}: WithholdingsConfirmModalProps) {\n  return (\n    <AlertDialog\n      isOpen={open}\n      type={type}\n      title={title}\n      description={body}\n      cancelText={cancelLabel}\n      confirmText={confirmLabel}\n      isProcess={isLoading}\n      preventCloseOnOverlayClick\n      onCancel={onClose}\n      onConfirm={onConfirm}\n    />\n  );\n}\n","import { useEffect, useState } from 'react';\nimport { clsx } from 'clsx';\n\nimport { toast } from '../../Toast';\nimport { Info } from '../../Info/Info';\nimport { Table } from '../../Table/Table';\nimport type { TableColumn } from '../../Table/Table.types';\nimport { useMasterDocumentFormatters } from '../formatters';\n\nimport { WithholdingOriginBadge } from './WithholdingOriginBadge';\nimport { WithholdingTotalCell } from './WithholdingTotalCell';\nimport { WithholdingsActionBar } from './WithholdingsActionBar';\nimport { WithholdingsAddModal } from './WithholdingsAddModal';\nimport { WithholdingsEditModal } from './WithholdingsEditModal';\nimport { WithholdingsConfirmModal } from './WithholdingsConfirmModal';\nimport { useWithholdingsTranslation } from './i18n';\nimport {\n  useWithholdings,\n  useAddManualWithholding,\n  useModifyWithholding,\n  useDeleteWithholding,\n  useRecalculateWithholdings,\n} from './hooks';\nimport { getWithholdingOrigin } from './types';\nimport type {\n  CreateWithholdingPayload,\n  ModifyWithholdingPayload,\n  WithholdingDto,\n  WithholdingsHttpError,\n  WithholdingsPanelProps,\n} from './types';\n\nconst DASH = '—';\n\ntype ConfirmKind = 'delete' | 'recalculate' | null;\n\n/**\n * Panel de Retenciones (TF3) — sub-componente de MasterDocument (FEAT-105-11).\n *\n * Renderiza la grilla TF3 del documento (Clase, Base, Tasa, Total, Acción y badge\n * de Origen). Cuando el usuario tiene permiso y el documento es editable (DRAFT)\n * muestra la barra de acciones: Agregar (POST), Modificar (PUT con `rowVersion`),\n * Eliminar (DELETE, solo manuales) y Recalcular (POST recalculate, preserva\n * manuales/manipuladas). Sin permiso o fuera de DRAFT la barra se oculta y la\n * grilla queda read-only.\n *\n * Diseñado para montarse en una sección FactBox de cualquier documento\n * MasterDocument, inyectando endpoints, IO y catálogos por props (precedente:\n * InstallmentsPanel).\n *\n * @example\n * ```tsx\n * <WithholdingsPanel\n *   documentId={docId}\n *   isEditable={docState === 'DRAFT'}\n *   canWrite={permissions.includes(CORE_PERMISSIONS.WITHHOLDINGS.WRITE)}\n *   canRecalculate={permissions.includes(CORE_PERMISSIONS.SUPPLIER_INVOICES.MODIFY_WITHHOLDINGS)}\n *   withholdingsEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/withholdings`}\n *   withholdingsBaseEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/withholdings`}\n *   httpRequest={httpRequest}\n *   catalogs={catalogs}\n * />\n * ```\n */\nexport function WithholdingsPanel({\n  documentId,\n  isEditable,\n  canWrite,\n  canRecalculate,\n  withholdingsEndpoint,\n  withholdingsBaseEndpoint,\n  httpRequest,\n  catalogs,\n  initialWithholdings,\n  formatAmount: formatAmountProp,\n  className,\n}: WithholdingsPanelProps) {\n  const { t } = useWithholdingsTranslation();\n  const { formatAmount: defaultFormatAmount } = useMasterDocumentFormatters();\n  const formatAmount = formatAmountProp ?? defaultFormatAmount;\n\n  const [selectedId, setSelectedId] = useState<string | null>(null);\n  const [addOpen, setAddOpen] = useState(false);\n  const [editOpen, setEditOpen] = useState(false);\n  const [confirm, setConfirm] = useState<ConfirmKind>(null);\n\n  const withholdingsQuery = useWithholdings({\n    documentId,\n    withholdingsEndpoint,\n    httpRequest,\n    initialData: initialWithholdings,\n  });\n\n  const addMutation = useAddManualWithholding({ documentId, withholdingsBaseEndpoint, httpRequest });\n  const modifyMutation = useModifyWithholding({ documentId, withholdingsBaseEndpoint, httpRequest });\n  const deleteMutation = useDeleteWithholding({ documentId, withholdingsBaseEndpoint, httpRequest });\n  const recalcMutation = useRecalculateWithholdings({\n    documentId,\n    withholdingsBaseEndpoint,\n    httpRequest,\n  });\n\n  const withholdings = withholdingsQuery.data ?? [];\n  const selectedRow = withholdings.find((w) => w.id === selectedId) ?? null;\n\n  // Si la fila seleccionada desaparece tras un refresco, limpiar la selección.\n  useEffect(() => {\n    if (selectedId && !(withholdingsQuery.data ?? []).some((w) => w.id === selectedId)) {\n      setSelectedId(null);\n    }\n  }, [withholdingsQuery.data, selectedId]);\n\n  const isBusy =\n    addMutation.isPending ||\n    modifyMutation.isPending ||\n    deleteMutation.isPending ||\n    recalcMutation.isPending;\n\n  /** La barra se muestra solo en DRAFT y con algún permiso (oculta, no deshabilitada). */\n  const showActionBar = isEditable && (canWrite || canRecalculate);\n\n  function reportError(error: unknown) {\n    const err = error as WithholdingsHttpError;\n    const detail = err?.detail;\n    switch (err?.status) {\n      case 403:\n        toast.error(t('withholdings.error.forbidden'));\n        return;\n      case 404:\n        toast.error(detail || t('withholdings.error.notFound'));\n        return;\n      case 409:\n        toast.error(detail || t('withholdings.error.conflict'));\n        return;\n      case 422:\n        toast.error(detail || t('withholdings.error.validation'));\n        return;\n      case 503:\n        toast.error(t('withholdings.error.liquitaxUnavailable'));\n        return;\n      default:\n        toast.error(detail || err?.message || t('withholdings.error.generic'));\n    }\n  }\n\n  function handleAdd(payload: CreateWithholdingPayload) {\n    addMutation.mutate(payload, {\n      onSuccess: () => {\n        toast.success(t('withholdings.toast.added'));\n        setAddOpen(false);\n      },\n      onError: reportError,\n    });\n  }\n\n  function handleEdit(payload: ModifyWithholdingPayload) {\n    if (!selectedRow) return;\n    modifyMutation.mutate(\n      { withholdingId: selectedRow.id, payload },\n      {\n        onSuccess: () => {\n          toast.success(t('withholdings.toast.updated'));\n          setEditOpen(false);\n        },\n        onError: reportError,\n      },\n    );\n  }\n\n  function handleDelete() {\n    if (!selectedRow) return;\n    deleteMutation.mutate(selectedRow.id, {\n      onSuccess: () => {\n        toast.success(t('withholdings.toast.deleted'));\n        setConfirm(null);\n        setSelectedId(null);\n      },\n      onError: reportError,\n    });\n  }\n\n  function handleRecalculate() {\n    recalcMutation.mutate(undefined, {\n      onSuccess: (result) => {\n        toast.success(\n          t('withholdings.toast.recalculated', {\n            preserved: result.summary.preserved,\n            recalculated: result.summary.recalculated,\n          }),\n        );\n        setConfirm(null);\n      },\n      onError: reportError,\n    });\n  }\n\n  const columns: TableColumn<WithholdingDto>[] = [\n    {\n      header: t('withholdings.column.class'),\n      accessor: 'withholdingClassName',\n      render: (_value, row) => row.withholdingClassName || row.withholdingKeyCode || DASH,\n    },\n    {\n      header: t('withholdings.column.base'),\n      accessor: 'baseValue',\n      align: 'right',\n      render: (value) => <span className=\"tabular-nums\">{formatAmount(value as number)}</span>,\n    },\n    {\n      header: t('withholdings.column.rate'),\n      accessor: 'rate',\n      align: 'right',\n      width: '72px',\n      render: (value) => (value == null ? DASH : <span className=\"tabular-nums\">{`${value}%`}</span>),\n    },\n    {\n      header: t('withholdings.column.total'),\n      accessor: 'totalValue',\n      align: 'right',\n      render: (_value, row) => <WithholdingTotalCell row={row} formatAmount={formatAmount} />,\n    },\n    {\n      header: t('withholdings.column.action'),\n      accessor: 'withholdingAction',\n      align: 'center',\n      render: (value) => {\n        // El rango declarado es 1..4; cualquier otro valor del backend caeria en\n        // la clave cruda, asi que se degrada a un texto legible.\n        const clave = `withholdings.action.${value as number}`;\n        const texto = t(clave);\n        return texto === clave ? t('withholdings.action.unknown') : texto;\n      },\n    },\n    {\n      header: t('withholdings.column.origin'),\n      accessor: 'isManual',\n      align: 'center',\n      width: '110px',\n      render: (_value, row) => <WithholdingOriginBadge origin={getWithholdingOrigin(row)} />,\n    },\n  ];\n\n  return (\n    <section\n      className={clsx('flex flex-col gap-3', className)}\n      aria-label={t('withholdings.panel.title')}\n    >\n      {/* Header */}\n      <div className=\"flex items-center justify-between gap-2\">\n        <h3 className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary truncate\">\n          {t('withholdings.panel.title')}\n        </h3>\n      </div>\n\n      {/* Barra de acciones (solo DRAFT + permiso) */}\n      {showActionBar && (\n        <WithholdingsActionBar\n          canWrite={canWrite}\n          canRecalculate={canRecalculate}\n          hasCatalogs={Boolean(catalogs)}\n          selectedRow={selectedRow}\n          isBusy={isBusy}\n          onAdd={() => setAddOpen(true)}\n          onEdit={() => selectedRow && setEditOpen(true)}\n          onDelete={() => selectedRow && setConfirm('delete')}\n          onRecalculate={() => setConfirm('recalculate')}\n        />\n      )}\n\n      {/* Estados de carga / error / grilla */}\n      {withholdingsQuery.isError ? (\n        <Info color=\"red\" title={t('withholdings.panel.loadError')} />\n      ) : (\n        <Table<WithholdingDto>\n          columns={columns}\n          data={withholdings}\n          variant=\"basic\"\n          fullWidth\n          showShadow={false}\n          loading={withholdingsQuery.isLoading}\n          emptyMessage={t('withholdings.panel.empty')}\n          onRowClick={\n            showActionBar && canWrite\n              ? (row) => setSelectedId((prev) => (prev === row.id ? null : row.id))\n              : undefined\n          }\n          isRowSelected={(row) => row.id === selectedId}\n        />\n      )}\n\n      {/* Modal Agregar (solo con permiso + catálogos) */}\n      {showActionBar && canWrite && catalogs && (\n        <WithholdingsAddModal\n          open={addOpen}\n          catalogs={catalogs}\n          isSubmitting={addMutation.isPending}\n          onSubmit={handleAdd}\n          onClose={() => setAddOpen(false)}\n        />\n      )}\n\n      {/* Modal Modificar */}\n      {showActionBar && canWrite && (\n        <WithholdingsEditModal\n          open={editOpen}\n          row={selectedRow}\n          isSubmitting={modifyMutation.isPending}\n          onSubmit={handleEdit}\n          onClose={() => setEditOpen(false)}\n        />\n      )}\n\n      {/* Confirmación Eliminar */}\n      <WithholdingsConfirmModal\n        open={confirm === 'delete'}\n        type=\"danger\"\n        title={t('withholdings.delete.title')}\n        body={t('withholdings.delete.body')}\n        confirmLabel={t('withholdings.delete.confirm')}\n        cancelLabel={t('withholdings.delete.cancel')}\n        isLoading={deleteMutation.isPending}\n        onConfirm={handleDelete}\n        onClose={() => setConfirm(null)}\n      />\n\n      {/* Confirmación Recalcular */}\n      <WithholdingsConfirmModal\n        open={confirm === 'recalculate'}\n        type=\"warning\"\n        title={t('withholdings.recalculate.title')}\n        body={t('withholdings.recalculate.body')}\n        confirmLabel={t('withholdings.recalculate.confirm')}\n        cancelLabel={t('withholdings.recalculate.cancel')}\n        isLoading={recalcMutation.isPending}\n        onConfirm={handleRecalculate}\n        onClose={() => setConfirm(null)}\n      />\n    </section>\n  );\n}\n","import { createTranslationHook } from '../i18nFactory';\nimport { TEXTO_COMUN_ES, TEXTO_COMUN_EN } from '../commonTexts';\nimport type { TranslateFn } from '../i18nFactory';\n\n/**\n * i18n del widget de Instrumento Financiero (FEAT-105-17).\n *\n * Usa `useTranslation` de siesa-ui-kit vía `createTranslationHook`; si el host no\n * registró las claves `financial_instrument.*` (el motor devuelve la propia clave),\n * cae al diccionario local del idioma activo y, en último término, al español.\n * Garantiza texto listo para usar sin depender de que el documento consumidor\n * registre los recursos. Las claves siguen el formato plano que espera\n * `DefaultTranslationEngine`.\n */\n\nexport const FINANCIAL_INSTRUMENT_TRANSLATIONS_ES: Record<string, string> = {\n  'financial_instrument.panel.title': 'Instrumento financiero',\n  'financial_instrument.panel.loading': 'Cargando instrumento financiero…',\n  'financial_instrument.panel.loadError': 'No se pudo cargar el instrumento financiero.',\n  'financial_instrument.panel.readonly': 'Instrumento financiero (solo lectura)',\n\n  'financial_instrument.field.type': 'Tipo de instrumento',\n  'financial_instrument.field.typePlaceholder': 'Seleccione un tipo',\n  'financial_instrument.field.number': 'Número',\n  'financial_instrument.field.numberPlaceholder': 'Número del instrumento',\n  'financial_instrument.field.issueDate': 'Fecha de emisión',\n  'financial_instrument.field.dueDate': 'Fecha de vencimiento',\n  'financial_instrument.field.beneficiary': 'Beneficiario',\n  'financial_instrument.field.beneficiaryPlaceholder': 'Nombre del beneficiario',\n  'financial_instrument.field.amount': 'Monto',\n  'financial_instrument.field.amountAlt': 'Monto (moneda alterna)',\n\n  'financial_instrument.actions.create': TEXTO_COMUN_ES.save,\n  'financial_instrument.actions.update': 'Guardar cambios',\n  'financial_instrument.actions.delete': TEXTO_COMUN_ES.delete,\n\n  'financial_instrument.delete.title': 'Eliminar instrumento financiero',\n  'financial_instrument.delete.body':\n    'Se desactivará el instrumento financiero actual. Podrá capturar uno nuevo después. ¿Continuar?',\n  'financial_instrument.delete.confirm': TEXTO_COMUN_ES.delete,\n  'financial_instrument.delete.cancel': TEXTO_COMUN_ES.cancel,\n\n  'financial_instrument.validation.required': 'Campo requerido.',\n  'financial_instrument.validation.amountPositive': 'El monto debe ser mayor que 0.',\n  'financial_instrument.validation.dueDateBeforeIssue':\n    'La fecha de vencimiento debe ser igual o posterior a la fecha de emisión.',\n\n  'financial_instrument.error.forbidden': TEXTO_COMUN_ES.errorForbidden,\n  // Sin uso: el 409 se maneja en FinancialInstrumentPanel.tsx pero con el `detail`\n  // del backend. Igual que en Retenciones, distinguir el sub-caso exigiria un\n  // `errorCode` que el tipo de error no declara.\n  'financial_instrument.error.conflict': 'Ya existe un instrumento financiero activo para este documento.',\n  'financial_instrument.error.concurrency':\n    'El instrumento fue modificado por otro usuario. Se recargaron los datos.',\n  'financial_instrument.error.validation': 'Revise los datos ingresados.',\n  'financial_instrument.error.notFound': 'Recurso no encontrado.',\n  'financial_instrument.error.generic': TEXTO_COMUN_ES.errorGeneric,\n\n  'financial_instrument.toast.created': 'Instrumento financiero creado correctamente.',\n  'financial_instrument.toast.updated': 'Instrumento financiero actualizado correctamente.',\n  'financial_instrument.toast.deleted': 'Instrumento financiero eliminado correctamente.',\n\n  'financial_instrument.factbox.title': 'Instrumento financiero',\n  'financial_instrument.factbox.pending': 'Pendiente de captura',\n  'financial_instrument.factbox.number': 'N° {number}',\n  'financial_instrument.factbox.due': 'Vence {date}',\n};\n\nexport const FINANCIAL_INSTRUMENT_TRANSLATIONS_EN: Record<string, string> = {\n  'financial_instrument.panel.title': 'Financial instrument',\n  'financial_instrument.panel.loading': 'Loading financial instrument…',\n  'financial_instrument.panel.loadError': 'Could not load the financial instrument.',\n  'financial_instrument.panel.readonly': 'Financial instrument (read-only)',\n\n  'financial_instrument.field.type': 'Instrument type',\n  'financial_instrument.field.typePlaceholder': 'Select a type',\n  'financial_instrument.field.number': 'Number',\n  'financial_instrument.field.numberPlaceholder': 'Instrument number',\n  'financial_instrument.field.issueDate': 'Issue date',\n  'financial_instrument.field.dueDate': 'Due date',\n  'financial_instrument.field.beneficiary': 'Beneficiary',\n  'financial_instrument.field.beneficiaryPlaceholder': 'Beneficiary name',\n  'financial_instrument.field.amount': 'Amount',\n  'financial_instrument.field.amountAlt': 'Amount (alternate currency)',\n\n  'financial_instrument.actions.create': TEXTO_COMUN_EN.save,\n  'financial_instrument.actions.update': 'Save changes',\n  'financial_instrument.actions.delete': TEXTO_COMUN_EN.delete,\n\n  'financial_instrument.delete.title': 'Delete financial instrument',\n  'financial_instrument.delete.body':\n    'The current financial instrument will be deactivated. You can capture a new one afterwards. Continue?',\n  'financial_instrument.delete.confirm': TEXTO_COMUN_EN.delete,\n  'financial_instrument.delete.cancel': TEXTO_COMUN_EN.cancel,\n\n  'financial_instrument.validation.required': 'Required field.',\n  'financial_instrument.validation.amountPositive': 'The amount must be greater than 0.',\n  'financial_instrument.validation.dueDateBeforeIssue':\n    'The due date must be equal to or later than the issue date.',\n\n  'financial_instrument.error.forbidden': TEXTO_COMUN_EN.errorForbidden,\n  'financial_instrument.error.conflict': 'An active financial instrument already exists for this document.',\n  'financial_instrument.error.concurrency':\n    'The instrument was modified by another user. The data was reloaded.',\n  'financial_instrument.error.validation': 'Check the entered data.',\n  'financial_instrument.error.notFound': 'Resource not found.',\n  'financial_instrument.error.generic': TEXTO_COMUN_EN.errorGeneric,\n\n  'financial_instrument.toast.created': 'Financial instrument created successfully.',\n  'financial_instrument.toast.updated': 'Financial instrument updated successfully.',\n  'financial_instrument.toast.deleted': 'Financial instrument deleted successfully.',\n\n  'financial_instrument.factbox.title': 'Financial instrument',\n  'financial_instrument.factbox.pending': 'Pending capture',\n  'financial_instrument.factbox.number': 'No. {number}',\n  'financial_instrument.factbox.due': 'Due {date}',\n};\n\n/** Diccionarios de respaldo por idioma, listos para registrar en el host si se desea. */\nexport const FINANCIAL_INSTRUMENT_TRANSLATIONS = {\n  es: FINANCIAL_INSTRUMENT_TRANSLATIONS_ES,\n  en: FINANCIAL_INSTRUMENT_TRANSLATIONS_EN,\n} as const;\n\n/** Función de traducción con interpolación `{var}`. */\nexport type FinancialInstrumentT = TranslateFn;\n\n/**\n * Hook de traducción del widget.\n *\n * Usa `useTranslation` del kit; si la clave no está registrada en el host\n * (el motor devuelve la propia clave), cae al diccionario local del idioma activo.\n */\nexport const useFinancialInstrumentTranslation = createTranslationHook(\n  FINANCIAL_INSTRUMENT_TRANSLATIONS,\n);\n","import { useMemo } from 'react';\nimport { Badge } from '../../Badge/Badge';\nimport { Select } from '../../Select/Select';\nimport type { SelectOption } from '../../Select/Select.types';\nimport { useFinancialInstrumentTranslation } from './i18n';\nimport type { InstrumentTypeOption } from './types';\n\nexport interface InstrumentTypeFieldProps {\n  /** Valor seleccionado (UUID del tipo). */\n  value: string;\n  /** Tipos de instrumento disponibles (catálogo GAP-2). */\n  options: InstrumentTypeOption[];\n  /**\n   * `true` si el usuario tiene `change_default_financial_instrument`: el campo es\n   * un `Select` editable. Sin el permiso (o sin catálogo) cae a chip read-only\n   * con el nombre del tipo (FR-84 / 105-17.02).\n   */\n  canChangeDefaultType: boolean;\n  /** Nombre legible del tipo seleccionado (default de la condición — GAP-3/GAP-4). */\n  selectedTypeName?: string;\n  /** El catálogo se está cargando. */\n  isLoading?: boolean;\n  /** Marca el error de \"requerido\" (formulario tocado y sin valor). */\n  error?: boolean;\n  /** Deshabilita el `Select` (documento read-only). */\n  disabled?: boolean;\n  onChange: (value: string) => void;\n}\n\nconst DASH = '—';\n\n/**\n * Campo \"Tipo de instrumento\" (105-17.02).\n *\n * Con `change_default_financial_instrument` y catálogo disponible: `Select` de\n * tipos activos. Sin el permiso (o sin catálogo — GAP-2): chip read-only con el\n * nombre del tipo default; el valor igual viaja en el submit del formulario.\n */\nexport function InstrumentTypeField({\n  value,\n  options,\n  canChangeDefaultType,\n  selectedTypeName,\n  isLoading = false,\n  error = false,\n  disabled = false,\n  onChange,\n}: InstrumentTypeFieldProps) {\n  const { t } = useFinancialInstrumentTranslation();\n\n  const selectOptions: SelectOption[] = useMemo(\n    () => options.map((o) => ({ value: o.id, label: o.name })),\n    [options],\n  );\n\n  // Nombre a mostrar en el chip read-only: el explícito, o el del catálogo.\n  const readonlyName =\n    selectedTypeName || options.find((o) => o.id === value)?.name || DASH;\n\n  if (canChangeDefaultType && options.length > 0) {\n    return (\n      <Select\n        label={t('financial_instrument.field.type')}\n        placeholder={t('financial_instrument.field.typePlaceholder')}\n        options={selectOptions}\n        value={value}\n        required\n        disabled={disabled || isLoading}\n        error={error}\n        errorMessage={error ? t('financial_instrument.validation.required') : undefined}\n        onChange={(v) => onChange(String(v))}\n      />\n    );\n  }\n\n  return (\n    <div className=\"flex flex-col gap-1\">\n      <span className=\"text-xs font-medium text-content-secondary dark:text-dark-content-secondary\">\n        {t('financial_instrument.field.type')}\n      </span>\n      <div>\n        <Badge color=\"zinc\" label={readonlyName} />\n      </div>\n    </div>\n  );\n}\n","import { useEffect, useState } from 'react';\nimport { Input } from '../../Input/Input';\nimport { Button } from '../../Button/Button';\nimport { InstrumentTypeField } from './InstrumentTypeField';\nimport { useFinancialInstrumentTranslation } from './i18n';\nimport type {\n  CreateFinancialInstrumentPayload,\n  FinancialInstrumentDto,\n  InstrumentTypeOption,\n} from './types';\n\nexport interface FinancialInstrumentFormProps {\n  /** IF activo a editar, o `null` en modo crear. */\n  instrument: FinancialInstrumentDto | null;\n  /** `true` si el documento es editable (DRAFT) y el usuario puede capturar. */\n  canEdit: boolean;\n  /** `true` si el usuario tiene `change_default_financial_instrument`. */\n  canChangeDefaultType: boolean;\n  /** Tipos de instrumento disponibles (catálogo GAP-2). */\n  instrumentTypes: InstrumentTypeOption[];\n  /** El catálogo de tipos se está cargando. */\n  typesLoading?: boolean;\n  /** Tipo default sugerido por la condición de pago (GAP-3) — pre-puebla al crear. */\n  defaultInstrumentTypeId?: string;\n  /** Nombre del tipo default (GAP-3/GAP-4) para el chip read-only. */\n  defaultInstrumentTypeName?: string;\n  /** Guardado en vuelo (POST/PUT). */\n  isSaving: boolean;\n  /** Borrado en vuelo (DELETE). */\n  isDeleting: boolean;\n  onSubmit: (values: CreateFinancialInstrumentPayload) => void;\n  onDelete: () => void;\n}\n\ninterface FormState {\n  instrumentTypeId: string;\n  instrumentNumber: string;\n  issueDate: string;\n  dueDate: string;\n  beneficiaryName: string;\n  amount: string;\n  amountAlt: string;\n}\n\nconst EMPTY: FormState = {\n  instrumentTypeId: '',\n  instrumentNumber: '',\n  issueDate: '',\n  dueDate: '',\n  beneficiaryName: '',\n  amount: '',\n  amountAlt: '',\n};\n\n/**\n * Formulario de captura/edición del Instrumento Financiero (105-17.01/02).\n *\n * 7 campos: tipo (chip o `Select` según permiso), número, fechas de emisión y\n * vencimiento, beneficiario y montos. Crea (POST) cuando no hay IF; edita (PUT)\n * cuando lo hay. Validación estructural inmediata (6 requeridos + `dueDate ≥\n * issueDate` + `amount > 0`); el backend es la autoridad final. Fuera de DRAFT o\n * sin permiso el formulario es read-only (sin botones).\n */\nexport function FinancialInstrumentForm({\n  instrument,\n  canEdit,\n  canChangeDefaultType,\n  instrumentTypes,\n  typesLoading = false,\n  defaultInstrumentTypeId,\n  defaultInstrumentTypeName,\n  isSaving,\n  isDeleting,\n  onSubmit,\n  onDelete,\n}: FinancialInstrumentFormProps) {\n  const { t } = useFinancialInstrumentTranslation();\n\n  const isCreate = !instrument;\n  const [form, setForm] = useState<FormState>(EMPTY);\n  const [touched, setTouched] = useState(false);\n\n  // Re-sembrar cuando cambia el IF (carga / refresco). En modo crear, el tipo\n  // arranca en el default sugerido por la condición de pago (GAP-3).\n  useEffect(() => {\n    if (instrument) {\n      setForm({\n        instrumentTypeId: instrument.instrumentTypeId,\n        instrumentNumber: instrument.instrumentNumber,\n        issueDate: instrument.issueDate,\n        dueDate: instrument.dueDate,\n        beneficiaryName: instrument.beneficiaryName,\n        amount: String(instrument.amount ?? ''),\n        amountAlt: instrument.amountAlt == null ? '' : String(instrument.amountAlt),\n      });\n    } else {\n      setForm({ ...EMPTY, instrumentTypeId: defaultInstrumentTypeId ?? '' });\n    }\n    setTouched(false);\n  }, [instrument, defaultInstrumentTypeId]);\n\n  const set = <K extends keyof FormState>(field: K, value: FormState[K]) =>\n    setForm((prev) => ({ ...prev, [field]: value }));\n\n  const amountNum = Number(form.amount);\n  const amountAltNum = Number(form.amountAlt);\n\n  const typeValid = form.instrumentTypeId.trim() !== '';\n  const numberValid = form.instrumentNumber.trim() !== '';\n  const issueValid = form.issueDate.trim() !== '';\n  const dueValid = form.dueDate.trim() !== '';\n  const beneficiaryValid = form.beneficiaryName.trim() !== '';\n  const amountValid = form.amount.trim() !== '' && !Number.isNaN(amountNum) && amountNum > 0;\n  // Comparación lexicográfica válida para fechas ISO (YYYY-MM-DD).\n  const dueAfterIssue = !issueValid || !dueValid || form.dueDate >= form.issueDate;\n  const amountAltValid =\n    form.amountAlt.trim() === '' || (!Number.isNaN(amountAltNum) && amountAltNum > 0);\n\n  const formValid =\n    typeValid &&\n    numberValid &&\n    issueValid &&\n    dueValid &&\n    beneficiaryValid &&\n    amountValid &&\n    dueAfterIssue &&\n    amountAltValid;\n\n  function handleSubmit() {\n    setTouched(true);\n    if (!formValid) return;\n    onSubmit({\n      instrumentTypeId: form.instrumentTypeId,\n      instrumentNumber: form.instrumentNumber.trim(),\n      issueDate: form.issueDate,\n      dueDate: form.dueDate,\n      beneficiaryName: form.beneficiaryName.trim(),\n      amount: amountNum,\n      amountAlt: form.amountAlt.trim() === '' ? null : amountAltNum,\n    });\n  }\n\n  const ro = !canEdit;\n  const busy = isSaving || isDeleting;\n\n  return (\n    <form\n      onSubmit={(e) => {\n        e.preventDefault();\n        if (canEdit && !busy) handleSubmit();\n      }}\n      className=\"flex flex-col gap-3\"\n    >\n      <InstrumentTypeField\n        value={form.instrumentTypeId}\n        options={instrumentTypes}\n        canChangeDefaultType={canChangeDefaultType && !ro}\n        selectedTypeName={instrument?.instrumentTypeName ?? defaultInstrumentTypeName}\n        isLoading={typesLoading}\n        error={touched && !typeValid}\n        disabled={ro || busy}\n        onChange={(v) => set('instrumentTypeId', v)}\n      />\n\n      <Input\n        label={t('financial_instrument.field.number')}\n        placeholder={t('financial_instrument.field.numberPlaceholder')}\n        maxLength={100}\n        value={form.instrumentNumber}\n        disabled={ro || busy}\n        error={touched && !numberValid}\n        errorMessage={touched && !numberValid ? t('financial_instrument.validation.required') : undefined}\n        onChange={(e) => set('instrumentNumber', e.target.value)}\n      />\n\n      <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-3\">\n        <Input\n          label={t('financial_instrument.field.issueDate')}\n          type=\"date\"\n          value={form.issueDate}\n          disabled={ro || busy}\n          error={touched && !issueValid}\n          errorMessage={touched && !issueValid ? t('financial_instrument.validation.required') : undefined}\n          onChange={(e) => set('issueDate', e.target.value)}\n        />\n\n        <Input\n          label={t('financial_instrument.field.dueDate')}\n          type=\"date\"\n          min={form.issueDate || undefined}\n          value={form.dueDate}\n          disabled={ro || busy}\n          error={touched && (!dueValid || !dueAfterIssue)}\n          errorMessage={\n            touched && !dueValid\n              ? t('financial_instrument.validation.required')\n              : touched && !dueAfterIssue\n                ? t('financial_instrument.validation.dueDateBeforeIssue')\n                : undefined\n          }\n          onChange={(e) => set('dueDate', e.target.value)}\n        />\n      </div>\n\n      <Input\n        label={t('financial_instrument.field.beneficiary')}\n        placeholder={t('financial_instrument.field.beneficiaryPlaceholder')}\n        maxLength={255}\n        value={form.beneficiaryName}\n        disabled={ro || busy}\n        error={touched && !beneficiaryValid}\n        errorMessage={\n          touched && !beneficiaryValid ? t('financial_instrument.validation.required') : undefined\n        }\n        onChange={(e) => set('beneficiaryName', e.target.value)}\n      />\n\n      <div className=\"grid grid-cols-1 sm:grid-cols-2 gap-3\">\n        <Input\n          label={t('financial_instrument.field.amount')}\n          type=\"number\"\n          min={0}\n          step=\"any\"\n          inputMode=\"decimal\"\n          value={form.amount}\n          disabled={ro || busy}\n          error={touched && !amountValid}\n          errorMessage={\n            touched && !amountValid ? t('financial_instrument.validation.amountPositive') : undefined\n          }\n          onChange={(e) => set('amount', e.target.value)}\n        />\n\n        <Input\n          label={t('financial_instrument.field.amountAlt')}\n          type=\"number\"\n          min={0}\n          step=\"any\"\n          inputMode=\"decimal\"\n          value={form.amountAlt}\n          disabled={ro || busy}\n          error={touched && !amountAltValid}\n          errorMessage={\n            touched && !amountAltValid ? t('financial_instrument.validation.amountPositive') : undefined\n          }\n          onChange={(e) => set('amountAlt', e.target.value)}\n        />\n      </div>\n\n      {canEdit && (\n        <div className=\"flex flex-wrap items-center justify-end gap-3 mt-1\">\n          {!isCreate && (\n            <Button\n              type=\"plain\"\n              size=\"base\"\n              htmlType=\"button\"\n              onClick={(e) => {\n                // SBC-3953 — defensa en profundidad: Eliminar NUNCA debe enviar un\n                // formulario. `htmlType=\"button\"` ya lo garantiza (default del kit),\n                // y esto neutraliza además cualquier submit que pudiera burbujear\n                // hacia un `<form>` ancestro del host. Solo abre el flujo de borrado.\n                e.preventDefault();\n                e.stopPropagation();\n                onDelete();\n              }}\n              disabled={busy}\n            >\n              <span className=\"text-red-600 dark:text-red-400\">\n                {t('financial_instrument.actions.delete')}\n              </span>\n            </Button>\n          )}\n          <Button\n            type=\"default\"\n            size=\"base\"\n            htmlType=\"submit\"\n            disabled={busy || !formValid}\n          >\n            <span className=\"flex items-center justify-center gap-2 whitespace-nowrap\">\n              {isCreate\n                ? t('financial_instrument.actions.create')\n                : t('financial_instrument.actions.update')}\n              {isSaving && (\n                <svg\n                  className=\"animate-spin h-4 w-4 text-white shrink-0\"\n                  xmlns=\"http://www.w3.org/2000/svg\"\n                  fill=\"none\"\n                  viewBox=\"0 0 24 24\"\n                >\n                  <circle\n                    className=\"opacity-25\"\n                    cx=\"12\"\n                    cy=\"12\"\n                    r=\"10\"\n                    stroke=\"currentColor\"\n                    strokeWidth=\"4\"\n                  />\n                  <path\n                    className=\"opacity-75\"\n                    fill=\"currentColor\"\n                    d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n                  />\n                </svg>\n              )}\n            </span>\n          </Button>\n        </div>\n      )}\n    </form>\n  );\n}\n","import { AlertDialog } from '../../AlertDialog/AlertDialog';\n\nexport interface FinancialInstrumentConfirmModalProps {\n  open: boolean;\n  /** Título del diálogo. */\n  title: string;\n  /** Cuerpo / descripción. */\n  body: string;\n  /** Texto del botón de confirmación. */\n  confirmLabel: string;\n  /** Texto del botón de cancelar. */\n  cancelLabel: string;\n  /** Mutación en vuelo: bloquea botones y muestra spinner. */\n  isLoading: boolean;\n  onConfirm: () => void;\n  onClose: () => void;\n}\n\n/**\n * Modal de confirmación de borrado del Instrumento Financiero (105-17).\n *\n * Envuelve el `AlertDialog` del kit (variante `danger`); el borrado es lógico\n * (soft-delete) y libera el slot para capturar uno nuevo.\n */\nexport function FinancialInstrumentConfirmModal({\n  open,\n  title,\n  body,\n  confirmLabel,\n  cancelLabel,\n  isLoading,\n  onConfirm,\n  onClose,\n}: FinancialInstrumentConfirmModalProps) {\n  return (\n    <AlertDialog\n      isOpen={open}\n      type=\"danger\"\n      title={title}\n      description={body}\n      cancelText={cancelLabel}\n      confirmText={confirmLabel}\n      isProcess={isLoading}\n      preventCloseOnOverlayClick\n      onCancel={onClose}\n      onConfirm={onConfirm}\n    />\n  );\n}\n","/**\n * Claves de caché de TanStack Query del panel de Instrumento Financiero (FEAT-105-17).\n *\n * `financial-instrument`: el IF activo del documento (o `null` si no hay). Se\n * invalida tras crear/actualizar/eliminar.\n * `instrument-types`: catálogo de tipos de instrumento (GAP-2), independiente del\n * documento y cacheado con `staleTime` largo (cambia poco).\n */\nexport const financialInstrumentQueryKey = (documentId: string) =>\n  ['financial-instrument', documentId] as const;\n\nexport const instrumentTypesQueryKey = () => ['instrument-types'] as const;\n","/**\n * Tipos del widget FinancialInstrumentPanel (FEAT-105-17) — sub-componente de\n * MasterDocument.\n *\n * Espejo TypeScript del read-model de Instrumento Financiero (IF) del backend\n * (`SupplierInvoiceFinancialInstrumentDto`, épica 105-16) más los contratos de\n * props del widget reutilizable. El IF es un registro netamente documental\n * (cheque/pagaré/letra) asociado a una Factura de Proveedor: NO contabiliza ni\n * emite eventos. Cardinalidad **máximo un IF activo por documento**; el borrado\n * es lógico (`isActive = false`). El mismo panel sirve para cualquier documento\n * MasterDocument inyectando sus endpoints e IO por props (precedente:\n * InstallmentsPanel / WithholdingsPanel).\n *\n * @see feat-105-17-instrumento-financiero-masterdocument-spec.md\n */\n\n// ─── DTOs ──────────────────────────────────────────────────────────────────\n\n/**\n * Instrumento Financiero — espejo de `SupplierInvoiceFinancialInstrumentDto`\n * (camelCase). Tabla dedicada `core.supplier_invoice_financial_instruments`,\n * keyed por `documentId = document_headers.id`.\n */\nexport interface FinancialInstrumentDto {\n  /** PK del instrumento. */\n  id: string;\n  /** FK al documento (header). */\n  documentId: string;\n  /** Tipo de instrumento (UUID). El nombre legible es opcional (ver GAP-2/GAP-4). */\n  instrumentTypeId: string;\n  /** Número del instrumento (≤100). */\n  instrumentNumber: string;\n  /** Fecha de emisión (YYYY-MM-DD). */\n  issueDate: string;\n  /** Fecha de vencimiento (YYYY-MM-DD, ≥ issueDate). */\n  dueDate: string;\n  /** Nombre del beneficiario (≤255). */\n  beneficiaryName: string;\n  /** Monto (> 0). */\n  amount: number;\n  /** Monto en moneda alterna (opcional). */\n  amountAlt: number | null;\n  /** Instrumento activo (soft-delete: `false` lo desactiva). */\n  isActive: boolean;\n  /** Versión de fila para concurrencia optimista. */\n  rowVersion: number;\n  /** Auditoría. */\n  createdAt?: string;\n  createdByUserId?: string;\n  updatedAt?: string;\n  updatedByUserId?: string;\n\n  // ── Campo opcional — solo presente si el BE resuelve GAP-2/GAP-4 ──────────\n  /** Nombre legible del tipo (FactBox y chip default). GAP-4: puede no venir. */\n  instrumentTypeName?: string;\n}\n\n/**\n * Forma cruda como puede llegar del backend. Números/booleanos defensivos; se\n * normaliza con {@link normalizeFinancialInstrument}.\n */\nexport interface RawFinancialInstrumentDto\n  extends Partial<Omit<FinancialInstrumentDto, 'id' | 'documentId'>> {\n  id: string;\n  documentId: string;\n}\n\n/** Normaliza un IF crudo del backend al DTO de UI. */\nexport function normalizeFinancialInstrument(raw: RawFinancialInstrumentDto): FinancialInstrumentDto {\n  const base = (raw ?? {}) as RawFinancialInstrumentDto;\n  return {\n    id: base.id,\n    documentId: base.documentId,\n    instrumentTypeId: base.instrumentTypeId ?? '',\n    instrumentNumber: base.instrumentNumber ?? '',\n    issueDate: base.issueDate ?? '',\n    dueDate: base.dueDate ?? '',\n    beneficiaryName: base.beneficiaryName ?? '',\n    amount: Number(base.amount ?? 0),\n    amountAlt: base.amountAlt == null ? null : Number(base.amountAlt),\n    isActive: base.isActive == null ? true : Boolean(base.isActive),\n    rowVersion: Number(base.rowVersion ?? 0),\n    createdAt: base.createdAt,\n    createdByUserId: base.createdByUserId,\n    updatedAt: base.updatedAt,\n    updatedByUserId: base.updatedByUserId,\n    instrumentTypeName: base.instrumentTypeName,\n  };\n}\n\n// ─── Payloads de escritura ─────────────────────────────────────────────────\n\n/** Payload del POST de creación (`CreateFinancialInstrumentDto`). */\nexport interface CreateFinancialInstrumentPayload {\n  /** Tipo de instrumento (UUID, requerido). */\n  instrumentTypeId: string;\n  /** Número del instrumento (requerido, ≤100). */\n  instrumentNumber: string;\n  /** Fecha de emisión (requerida, YYYY-MM-DD). */\n  issueDate: string;\n  /** Fecha de vencimiento (requerida, ≥ issueDate). */\n  dueDate: string;\n  /** Nombre del beneficiario (requerido, ≤255). */\n  beneficiaryName: string;\n  /** Monto (> 0). */\n  amount: number;\n  /** Monto en moneda alterna (opcional). */\n  amountAlt?: number | null;\n}\n\n/**\n * Payload del PUT de modificación (`UpdateFinancialInstrumentDto`) — igual que\n * crear **+** `rowVersion` (requerido ≠ 0, concurrencia optimista).\n */\nexport interface UpdateFinancialInstrumentPayload extends CreateFinancialInstrumentPayload {\n  /** Versión de fila requerida (concurrencia optimista). */\n  rowVersion: number;\n}\n\n// ─── IO inyectada ────────────────────────────────────────────────────────\n\n/**\n * Cliente HTTP inyectado para las operaciones REST del widget.\n *\n * El kit no depende de `axios`; el documento consumidor inyecta su instancia ya\n * configurada (interceptores de auth/company) envuelta en esta firma. Debe\n * rechazar con un error que exponga `status` (número HTTP) para que el widget\n * distinga 409 (concurrencia) / 422 (negocio) / 403 (sin permiso) / 404.\n */\nexport type FinancialInstrumentHttpRequest = <T = unknown>(\n  method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n  url: string,\n  body?: unknown,\n) => Promise<T>;\n\n/** Error normalizado que el widget interpreta para el manejo de UI. */\nexport interface FinancialInstrumentHttpError extends Error {\n  status?: number;\n  /** `ProblemDetails.detail` ya traducido por `Accept-Language` (si llega). */\n  detail?: string;\n}\n\n// ─── Catálogo de tipos de instrumento (GAP-2) ──────────────────────────────\n\n/** Opción de tipo de instrumento para el `Select` del campo tipo. */\nexport interface InstrumentTypeOption {\n  id: string;\n  name: string;\n}\n\n/**\n * Loaders de catálogo inyectados (decoplan el widget del transporte/rutas\n * concretas, que son específicos del host).\n *\n * GAP-2: el catálogo de tipos de instrumento aún NO existe en Core. Mientras no\n * exista, se omite `catalogs`: el campo tipo cae a chip read-only con el default\n * de la condición de pago (o \"—\").\n */\nexport interface FinancialInstrumentCatalogs {\n  /** Lista de tipos de instrumento activos. */\n  loadInstrumentTypes: () => Promise<InstrumentTypeOption[]>;\n}\n\n// ─── Props ─────────────────────────────────────────────────────────────────\n\n/**\n * Props del panel principal `FinancialInstrumentPanel`.\n *\n * El widget es agnóstico del documento: recibe sus endpoints e IO por props,\n * lo que permite montarlo en cualquier MasterDocument.\n */\nexport interface FinancialInstrumentPanelProps {\n  /** UUID del documento (PK de `document_headers.id`), no el número legible. */\n  documentId: string;\n  /**\n   * `true` solo cuando el documento es editable (DRAFT). Cuando es `false`, el\n   * formulario es read-only y los botones Guardar/Eliminar se eliminan del DOM.\n   */\n  isEditable: boolean;\n  /**\n   * `true` si el usuario tiene `capture_financial_instrument`. Gatea\n   * Guardar (crear/editar) y Eliminar.\n   */\n  canCapture: boolean;\n  /**\n   * `true` si el usuario tiene `change_default_financial_instrument`. Con él, el\n   * tipo es un `Select`; sin él, queda fijo en el default y se muestra como chip\n   * read-only (FR-84 / 105-17.02).\n   */\n  canChangeDefaultType: boolean;\n  /**\n   * Endpoint GET del IF activo (BRECHA GAP-1 — el BE aún no lo expone). Si se\n   * omite, el formulario solo se puebla con `initialInstrument` y con las\n   * respuestas de las mutaciones (no puede arrancar en modo edición tras recarga).\n   */\n  financialInstrumentEndpoint?: string;\n  /**\n   * Endpoint base de child: `/{id}/financial-instrument`. El POST va a la base;\n   * el widget añade `/{fiId}` para PUT/DELETE.\n   */\n  financialInstrumentBaseEndpoint: string;\n  /** Cliente HTTP inyectado para las operaciones REST. */\n  httpRequest: FinancialInstrumentHttpRequest;\n  /** Loaders de catálogo de tipos (opcional — GAP-2). */\n  catalogs?: FinancialInstrumentCatalogs;\n  /**\n   * Tipo de instrumento default sugerido por la condición de pago (GAP-3). Se usa\n   * para pre-poblar el campo tipo al crear y para el chip read-only.\n   */\n  defaultInstrumentTypeId?: string;\n  /** Nombre del tipo default (GAP-3/GAP-4) para el chip read-only. */\n  defaultInstrumentTypeName?: string;\n  /**\n   * Datos iniciales (opcional). Útil cuando la carga proviene de la sección\n   * FactBox (`dataSource: 'adapter'`) en vez de un GET dedicado.\n   */\n  initialInstrument?: FinancialInstrumentDto | null;\n  /** Clases CSS adicionales para el contenedor raíz. */\n  className?: string;\n}\n","import { useQuery } from '@tanstack/react-query';\nimport { financialInstrumentQueryKey } from './keys';\nimport { normalizeFinancialInstrument } from '../types';\nimport type {\n  FinancialInstrumentDto,\n  FinancialInstrumentHttpRequest,\n  RawFinancialInstrumentDto,\n} from '../types';\n\nexport interface UseFinancialInstrumentParams {\n  documentId: string;\n  /**\n   * Endpoint GET del IF activo (BRECHA GAP-1 — el BE aún no lo expone). Si se\n   * omite, la query queda deshabilitada y el formulario se puebla solo con\n   * `initialData` / mutaciones.\n   */\n  financialInstrumentEndpoint?: string;\n  httpRequest: FinancialInstrumentHttpRequest;\n  /** Datos iniciales (p.ej. provenientes de la sección FactBox del adapter). */\n  initialData?: FinancialInstrumentDto | null;\n  enabled?: boolean;\n}\n\n/**\n * Carga el Instrumento Financiero activo del documento (o `null` si no hay).\n *\n * Cache key: `['financial-instrument', documentId]`. El backend puede responder\n * con `204`/cuerpo vacío/`404` cuando no hay IF activo: cualquiera de esos casos\n * se normaliza a `null` para que el panel decida crear-vs-editar.\n */\nexport function useFinancialInstrument({\n  documentId,\n  financialInstrumentEndpoint,\n  httpRequest,\n  initialData,\n  enabled = true,\n}: UseFinancialInstrumentParams) {\n  return useQuery<FinancialInstrumentDto | null>({\n    queryKey: financialInstrumentQueryKey(documentId),\n    enabled: enabled && Boolean(documentId) && Boolean(financialInstrumentEndpoint),\n    initialData: initialData ?? undefined,\n    queryFn: async () => {\n      try {\n        const raw = await httpRequest<RawFinancialInstrumentDto | null>(\n          'GET',\n          financialInstrumentEndpoint!,\n        );\n        return raw && raw.id ? normalizeFinancialInstrument(raw) : null;\n      } catch (error) {\n        // \"Sin IF activo\" se modela como 404 → null (no es un error de carga).\n        if ((error as { status?: number })?.status === 404) return null;\n        throw error;\n      }\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { financialInstrumentQueryKey } from './keys';\nimport { normalizeFinancialInstrument } from '../types';\nimport type {\n  CreateFinancialInstrumentPayload,\n  FinancialInstrumentDto,\n  FinancialInstrumentHttpRequest,\n  RawFinancialInstrumentDto,\n} from '../types';\n\nexport interface UseCreateFinancialInstrumentParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/financial-instrument`). El POST va a esta ruta. */\n  financialInstrumentBaseEndpoint: string;\n  httpRequest: FinancialInstrumentHttpRequest;\n}\n\n/**\n * Crea el Instrumento Financiero (`POST /{id}/financial-instrument`) → 201 + DTO.\n *\n * El backend devuelve el DTO directamente (sin envelope `{child, header}`: el IF\n * es child de tabla propia, no child LEGO de `DocumentCore`). Un 2º IF activo →\n * 422 (BV-S07), que el panel surfacea.\n *\n * - `onSuccess`: siembra el IF en el cache.\n * - `onSettled`: invalida `['financial-instrument', documentId]`.\n */\nexport function useCreateFinancialInstrument({\n  documentId,\n  financialInstrumentBaseEndpoint,\n  httpRequest,\n}: UseCreateFinancialInstrumentParams) {\n  const queryClient = useQueryClient();\n  const key = financialInstrumentQueryKey(documentId);\n\n  return useMutation<FinancialInstrumentDto, Error, CreateFinancialInstrumentPayload>({\n    mutationFn: async (payload) => {\n      const res = await httpRequest<RawFinancialInstrumentDto>(\n        'POST',\n        financialInstrumentBaseEndpoint,\n        payload,\n      );\n      return normalizeFinancialInstrument(res);\n    },\n    onSuccess: (created) => {\n      queryClient.setQueryData<FinancialInstrumentDto | null>(key, created);\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { financialInstrumentQueryKey } from './keys';\nimport { normalizeFinancialInstrument } from '../types';\nimport type {\n  FinancialInstrumentDto,\n  FinancialInstrumentHttpRequest,\n  RawFinancialInstrumentDto,\n  UpdateFinancialInstrumentPayload,\n} from '../types';\n\nexport interface UseUpdateFinancialInstrumentParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/financial-instrument`); se le añade `/{fiId}`. */\n  financialInstrumentBaseEndpoint: string;\n  httpRequest: FinancialInstrumentHttpRequest;\n}\n\nexport interface UpdateFinancialInstrumentInput {\n  financialInstrumentId: string;\n  payload: UpdateFinancialInstrumentPayload;\n}\n\n/**\n * Modifica el Instrumento Financiero (`PUT /{id}/financial-instrument/{fiId}`) →\n * 200 + DTO. `rowVersion` viaja en el payload (concurrencia optimista); un 409 →\n * el panel surfacea y recarga. Cambiar el tipo sin permiso → 422 (FR-84).\n *\n * - `onSuccess`: reemplaza el IF en el cache (rowVersion incrementado).\n * - `onSettled`: invalida `['financial-instrument', documentId]`.\n */\nexport function useUpdateFinancialInstrument({\n  documentId,\n  financialInstrumentBaseEndpoint,\n  httpRequest,\n}: UseUpdateFinancialInstrumentParams) {\n  const queryClient = useQueryClient();\n  const key = financialInstrumentQueryKey(documentId);\n\n  return useMutation<FinancialInstrumentDto, Error, UpdateFinancialInstrumentInput>({\n    mutationFn: async ({ financialInstrumentId, payload }) => {\n      const res = await httpRequest<RawFinancialInstrumentDto>(\n        'PUT',\n        `${financialInstrumentBaseEndpoint}/${financialInstrumentId}`,\n        payload,\n      );\n      return normalizeFinancialInstrument(res);\n    },\n    onSuccess: (updated) => {\n      queryClient.setQueryData<FinancialInstrumentDto | null>(key, updated);\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { financialInstrumentQueryKey } from './keys';\nimport type { FinancialInstrumentDto, FinancialInstrumentHttpRequest } from '../types';\n\nexport interface UseDeleteFinancialInstrumentParams {\n  documentId: string;\n  /** Endpoint base de child (`/{id}/financial-instrument`); se le añade `/{fiId}`. */\n  financialInstrumentBaseEndpoint: string;\n  httpRequest: FinancialInstrumentHttpRequest;\n}\n\n/**\n * Desactiva el Instrumento Financiero activo\n * (`DELETE /{id}/financial-instrument/{fiId}`) → 204 No Content (sin envelope —\n * divergencia consciente de ADR-011, ver spec §4.3). Es un soft-delete\n * (`isActive = false`) que libera el slot para capturar uno nuevo.\n *\n * - `onSuccess`: limpia el IF del cache (vuelve a modo crear).\n * - `onSettled`: invalida `['financial-instrument', documentId]`.\n */\nexport function useDeleteFinancialInstrument({\n  documentId,\n  financialInstrumentBaseEndpoint,\n  httpRequest,\n}: UseDeleteFinancialInstrumentParams) {\n  const queryClient = useQueryClient();\n  const key = financialInstrumentQueryKey(documentId);\n\n  return useMutation<string, Error, string>({\n    mutationFn: async (financialInstrumentId) => {\n      await httpRequest('DELETE', `${financialInstrumentBaseEndpoint}/${financialInstrumentId}`);\n      return financialInstrumentId;\n    },\n    onSuccess: () => {\n      queryClient.setQueryData<FinancialInstrumentDto | null>(key, null);\n    },\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: key });\n    },\n  });\n}\n","import { useQuery } from '@tanstack/react-query';\nimport { instrumentTypesQueryKey } from './keys';\nimport type { FinancialInstrumentCatalogs, InstrumentTypeOption } from '../types';\n\nconst STALE_TIME = 5 * 60 * 1000; // los catálogos cambian poco (§7.4)\n\nexport interface UseInstrumentTypesParams {\n  catalogs?: Pick<FinancialInstrumentCatalogs, 'loadInstrumentTypes'>;\n  enabled?: boolean;\n}\n\n/**\n * Carga los tipos de instrumento activos para el `Select` del campo tipo\n * (105-17.02). GAP-2: mientras el catálogo no exista en Core, se omite `catalogs`\n * y la query queda deshabilitada (el campo cae a chip read-only con el default).\n */\nexport function useInstrumentTypes({ catalogs, enabled = true }: UseInstrumentTypesParams) {\n  return useQuery<InstrumentTypeOption[]>({\n    queryKey: instrumentTypesQueryKey(),\n    enabled: enabled && Boolean(catalogs?.loadInstrumentTypes),\n    staleTime: STALE_TIME,\n    queryFn: () => catalogs!.loadInstrumentTypes(),\n  });\n}\n","import { useState } from 'react';\nimport { clsx } from 'clsx';\n\nimport { toast } from '../../Toast';\nimport { Info } from '../../Info/Info';\n\nimport { FinancialInstrumentForm } from './FinancialInstrumentForm';\nimport { FinancialInstrumentConfirmModal } from './FinancialInstrumentConfirmModal';\nimport { Loading } from '../components/loading';\nimport { useFinancialInstrumentTranslation } from './i18n';\nimport {\n  useFinancialInstrument,\n  useCreateFinancialInstrument,\n  useUpdateFinancialInstrument,\n  useDeleteFinancialInstrument,\n  useInstrumentTypes,\n} from './hooks';\nimport type {\n  CreateFinancialInstrumentPayload,\n  FinancialInstrumentHttpError,\n  FinancialInstrumentPanelProps,\n} from './types';\n\n/**\n * Panel de Instrumento Financiero (IF) — sub-componente de MasterDocument\n * (FEAT-105-17).\n *\n * Captura/edita/elimina el único IF activo (cheque, pagaré, letra) asociado a un\n * documento. Sin IF → modo crear (POST); con IF → modo editar pre-poblado (PUT\n * con `rowVersion`); Eliminar → soft-delete (libera el slot). Fuera de DRAFT o\n * sin `capture_financial_instrument` el formulario queda read-only. El campo tipo\n * es editable solo con `change_default_financial_instrument` (FR-84).\n *\n * Diseñado para montarse en una sección/FactBox de cualquier documento\n * MasterDocument inyectando endpoints, IO y catálogo por props (precedente:\n * InstallmentsPanel / WithholdingsPanel).\n *\n * @example\n * ```tsx\n * <FinancialInstrumentPanel\n *   documentId={docId}\n *   isEditable={docState === 'DRAFT'}\n *   canCapture={permissions.includes(CORE_PERMISSIONS.SUPPLIER_INVOICES.CAPTURE_FINANCIAL_INSTRUMENT)}\n *   canChangeDefaultType={permissions.includes(CORE_PERMISSIONS.SUPPLIER_INVOICES.CHANGE_DEFAULT_FINANCIAL_INSTRUMENT)}\n *   financialInstrumentEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/financial-instrument`}\n *   financialInstrumentBaseEndpoint={`/api/v1/purchases/supplier-invoices/${docId}/financial-instrument`}\n *   httpRequest={httpRequest}\n *   catalogs={catalogs}\n * />\n * ```\n */\nexport function FinancialInstrumentPanel({\n  documentId,\n  isEditable,\n  canCapture,\n  canChangeDefaultType,\n  financialInstrumentEndpoint,\n  financialInstrumentBaseEndpoint,\n  httpRequest,\n  catalogs,\n  defaultInstrumentTypeId,\n  defaultInstrumentTypeName,\n  initialInstrument,\n  className,\n}: FinancialInstrumentPanelProps) {\n  const { t } = useFinancialInstrumentTranslation();\n\n  const [confirmOpen, setConfirmOpen] = useState(false);\n\n  const instrumentQuery = useFinancialInstrument({\n    documentId,\n    financialInstrumentEndpoint,\n    httpRequest,\n    initialData: initialInstrument,\n  });\n  const typesQuery = useInstrumentTypes({ catalogs, enabled: canChangeDefaultType });\n\n  const createMutation = useCreateFinancialInstrument({\n    documentId,\n    financialInstrumentBaseEndpoint,\n    httpRequest,\n  });\n  const updateMutation = useUpdateFinancialInstrument({\n    documentId,\n    financialInstrumentBaseEndpoint,\n    httpRequest,\n  });\n  const deleteMutation = useDeleteFinancialInstrument({\n    documentId,\n    financialInstrumentBaseEndpoint,\n    httpRequest,\n  });\n\n  const instrument = instrumentQuery.data ?? null;\n  const canEdit = isEditable && canCapture;\n\n  function reportError(error: unknown) {\n    const err = error as FinancialInstrumentHttpError;\n    const detail = err?.detail;\n    switch (err?.status) {\n      case 403:\n        toast.error(t('financial_instrument.error.forbidden'));\n        return;\n      case 404:\n        toast.error(detail || t('financial_instrument.error.notFound'));\n        return;\n      case 409:\n        toast.error(detail || t('financial_instrument.error.concurrency'));\n        return;\n      case 422:\n        toast.error(detail || t('financial_instrument.error.validation'));\n        return;\n      default:\n        toast.error(detail || err?.message || t('financial_instrument.error.generic'));\n    }\n  }\n\n  function handleSubmit(values: CreateFinancialInstrumentPayload) {\n    if (instrument) {\n      updateMutation.mutate(\n        {\n          financialInstrumentId: instrument.id,\n          payload: { ...values, rowVersion: instrument.rowVersion },\n        },\n        {\n          onSuccess: () => toast.success(t('financial_instrument.toast.updated')),\n          onError: reportError,\n        },\n      );\n    } else {\n      createMutation.mutate(values, {\n        onSuccess: () => toast.success(t('financial_instrument.toast.created')),\n        onError: reportError,\n      });\n    }\n  }\n\n  function handleDelete() {\n    if (!instrument) return;\n    deleteMutation.mutate(instrument.id, {\n      onSuccess: () => {\n        toast.success(t('financial_instrument.toast.deleted'));\n        setConfirmOpen(false);\n      },\n      onError: (error) => {\n        reportError(error);\n        setConfirmOpen(false);\n      },\n    });\n  }\n\n  return (\n    <section\n      className={clsx('flex flex-col gap-3', className)}\n      aria-label={t('financial_instrument.panel.title')}\n    >\n      <div className=\"flex items-center justify-between gap-2\">\n        <h3 className=\"text-sm font-bold text-content-primary dark:text-dark-content-primary truncate\">\n          {canEdit\n            ? t('financial_instrument.panel.title')\n            : t('financial_instrument.panel.readonly')}\n        </h3>\n      </div>\n\n      {instrumentQuery.isError ? (\n        <Info color=\"red\" title={t('financial_instrument.panel.loadError')} />\n      ) : instrumentQuery.isLoading ? (\n        <Loading size=\"md\" label={t('financial_instrument.panel.loading')} />\n      ) : (\n        <FinancialInstrumentForm\n          instrument={instrument}\n          canEdit={canEdit}\n          canChangeDefaultType={canChangeDefaultType}\n          instrumentTypes={typesQuery.data ?? []}\n          typesLoading={typesQuery.isLoading}\n          defaultInstrumentTypeId={defaultInstrumentTypeId}\n          defaultInstrumentTypeName={defaultInstrumentTypeName}\n          isSaving={createMutation.isPending || updateMutation.isPending}\n          isDeleting={deleteMutation.isPending}\n          onSubmit={handleSubmit}\n          onDelete={() => setConfirmOpen(true)}\n        />\n      )}\n\n      <FinancialInstrumentConfirmModal\n        open={confirmOpen}\n        title={t('financial_instrument.delete.title')}\n        body={t('financial_instrument.delete.body')}\n        confirmLabel={t('financial_instrument.delete.confirm')}\n        cancelLabel={t('financial_instrument.delete.cancel')}\n        isLoading={deleteMutation.isPending}\n        onConfirm={handleDelete}\n        onClose={() => setConfirmOpen(false)}\n      />\n    </section>\n  );\n}\n","import { createFormatters } from '../formatters';\n\n/**\n * Formateadores por defecto del panel de Instrumento Financiero. El consumidor\n * puede sobrescribirlos por props (`formatAmount` / `formatDate`).\n *\n * Son funciones puras (no pueden usar el hook `useMasterDocumentFormatters`),\n * por eso reciben el `locale` como parámetro opcional en vez de resolverlo\n * ellas mismas; el componente que las consume debe pasarle el `locale` del\n * idioma activo (`useMasterDocumentFormatters().locale`).\n */\n\n/** Monto con 2 decimales, según el `locale` dado. */\nexport const defaultFormatAmount = (value: number, locale: string = 'es-CO'): string =>\n  createFormatters(locale).formatAmount(value);\n\n/**\n * Fecha (`YYYY-MM-DD` o cualquier valor que `Intl` entienda) según el `locale`\n * dado: `15/07/2026` en español, `Jul 15, 2026` en inglés.\n *\n * Antes construía `dd/MM/yyyy` por partes, justificándolo con que ese formato\n * \"no varía con el idioma\". Eso era precisamente el defecto: `01/09/2026` se lee\n * como 1 de septiembre en español y como 9 de enero en inglés, así que la cadena\n * fija no es neutra, es ambigua. Dejaba además a dos paneles del mismo feature\n * con dos comportamientos, porque `InstallmentsPanel` sí usa el hook de\n * formateadores.\n *\n * El motivo real de la construcción manual era el desfase de zona horaria\n * (`new Date('YYYY-MM-DD')` interpreta UTC y al oeste de Greenwich retrocede un\n * día); `createFormatters` ya lo resuelve parseando la fecha en horario local.\n *\n * Ante fecha ausente o inválida devuelve el guion largo del resto del kit —antes\n * devolvía cadena vacía o el valor crudo—, para que el FactBox no muestre un\n * \"Vence\" sin nada detrás.\n */\nexport const defaultFormatDate = (isoDate: string, locale: string = 'es-CO'): string =>\n  createFormatters(locale).formatDate(isoDate);\n","import { clsx } from 'clsx';\nimport { Card, CardContent } from '../../Card/Card';\nimport { Badge } from '../../Badge/Badge';\nimport { useMasterDocumentFormatters } from '../formatters';\nimport { useFinancialInstrumentTranslation } from './i18n';\nimport { defaultFormatAmount, defaultFormatDate } from './format';\nimport type { FinancialInstrumentDto } from './types';\n\nexport interface FinancialInstrumentFactBoxProps {\n  /** IF activo del documento, o `null` si no hay. */\n  instrument: FinancialInstrumentDto | null;\n  /**\n   * `true` si la condición de pago exige IF (`requires_financial_instrument`).\n   * Cuando es `true` y no hay IF, muestra el placeholder \"Pendiente de captura\"\n   * (105-17.03 — AUDIT-NOTE: la épica pedía ocultar; confirmar con PO). Cuando es\n   * `false` y no hay IF, el widget no renderiza nada (zero footprint).\n   */\n  requiresInstrument?: boolean;\n  /** Formateador de montos. @default `defaultFormatAmount` (idioma activo, 2 decimales). */\n  formatAmount?: (value: number) => string;\n  /** Formateador de fechas YYYY-MM-DD. @default formato medio del idioma activo. */\n  formatDate?: (isoDate: string) => string;\n  /** Clases CSS adicionales. */\n  className?: string;\n}\n\nconst DASH = '—';\n\n/**\n * Widget de resumen del Instrumento Financiero para el FactBox (105-17.03).\n *\n * Read-only. Con IF activo muestra `{tipo} · N° {número} · {monto} · Vence\n * {fecha}`. Sin IF y con `requiresInstrument` muestra \"Pendiente de captura\". Sin\n * IF y sin requerimiento, no renderiza nada (zero footprint).\n */\nexport function FinancialInstrumentFactBox({\n  instrument,\n  requiresInstrument = false,\n  formatAmount: formatAmountProp,\n  formatDate: formatDateProp,\n  className,\n}: FinancialInstrumentFactBoxProps) {\n  const { t } = useFinancialInstrumentTranslation();\n  const { locale } = useMasterDocumentFormatters();\n  const formatAmount = formatAmountProp ?? ((value: number) => defaultFormatAmount(value, locale));\n  const formatDate = formatDateProp ?? ((iso: string) => defaultFormatDate(iso, locale));\n\n  // Zero footprint: sin IF y sin requerimiento → nada.\n  if (!instrument && !requiresInstrument) return null;\n\n  const title = t('financial_instrument.factbox.title');\n\n  if (!instrument) {\n    return (\n      <Card className={clsx('w-full', className)}>\n        <CardContent className=\"flex flex-col gap-1.5 py-3\">\n          <span className=\"text-xs font-bold text-content-secondary dark:text-dark-content-secondary uppercase tracking-wide\">\n            {title}\n          </span>\n          <Badge color=\"amber\" label={t('financial_instrument.factbox.pending')} />\n        </CardContent>\n      </Card>\n    );\n  }\n\n  const typeName = instrument.instrumentTypeName || DASH;\n\n  return (\n    <Card className={clsx('w-full', className)}>\n      <CardContent className=\"flex flex-col gap-1.5 py-3\">\n        <span className=\"text-xs font-bold text-content-secondary dark:text-dark-content-secondary uppercase tracking-wide\">\n          {title}\n        </span>\n        <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-content-primary dark:text-dark-content-primary\">\n          <span className=\"font-medium\">{typeName}</span>\n          <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">·</span>\n          <span>{t('financial_instrument.factbox.number', { number: instrument.instrumentNumber })}</span>\n          <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">·</span>\n          <span className=\"tabular-nums font-medium\">{formatAmount(instrument.amount)}</span>\n          <span className=\"text-content-tertiary dark:text-dark-content-tertiary\">·</span>\n          <span className=\"text-content-secondary dark:text-dark-content-secondary\">\n            {t('financial_instrument.factbox.due', { date: formatDate(instrument.dueDate) })}\n          </span>\n        </div>\n      </CardContent>\n    </Card>\n  );\n}\n","import { createTranslationHook, type TranslationDictionaries } from '../components/MasterDocument/i18nFactory';\n\n/**\n * Traducciones del modulo Dashboard.\n *\n * ⚠️ Ninguna cadena de este diccionario puede nombrar un producto ni un modulo de negocio: el kit\n * lo consumen Comercial, Financiero y Nomina. Todo lo que sea vocabulario del host —titulo,\n * modulos, categorias— viaja por props, no por aqui. Habia dos que si lo hacian (\"Dashboard\n * Comercial\" y \"Cargando perfil comercial\"): se generalizaron, y el titulo paso a ser una prop.\n *\n * <b>Por qué con diccionarios locales y no sólo con el catálogo del host.</b> El motor i18n del kit\n * devuelve la CLAVE CRUDA cuando no encuentra una traducción, así que un host que no haya sembrado\n * `dashboard.*` en su `/langs` vería `dashboard.chrome.loading` en pantalla — peor que el español\n * que había antes de traducir nada. `createTranslationHook` resuelve en cascada y deja el\n * diccionario `es` como último recurso, de modo que **traducir no puede empeorar la pantalla de\n * ningún host**.\n *\n * Es el mismo mecanismo que usan `MasterDocument` y sus paneles, que son los módulos de nivel\n * pantalla del kit. Los dos componentes que usan `react-i18next` directo (`FormCacheSelector`,\n * `LookupField`) son controles pequeños y autocontenidos, otra especie.\n *\n * <b>Precedencia:</b> motor del host en el idioma activo → diccionario local del idioma activo →\n * motor con su fallback → diccionario `es`.\n */\nconst TRADUCCIONES: TranslationDictionaries = {\n  es: {\n    // ── Chrome de la pantalla ──\n    'dashboard.chrome.loading': 'Cargando tu tablero...',\n    'dashboard.chrome.loadError': 'No se pudo cargar el dashboard',\n    'dashboard.chrome.retry': 'Reintentar',\n    // Agrupa los widgets cuya categoria no declaro el host. Antes era el literal 'Otros',\n    // que se pintaba igual en ingles porque nunca pasaba por aqui.\n    'dashboard.category.uncategorized': 'Otros',\n    'dashboard.chrome.title': 'Tablero de indicadores',\n    'dashboard.chrome.viewCascade': 'Vista Cascada',\n    'dashboard.chrome.viewTabs': 'Vista Pestañas',\n    'dashboard.chrome.viewBoard': 'Tablero único',\n    'dashboard.chrome.saving': 'Guardando...',\n    'dashboard.chrome.edit': 'Editar',\n    'dashboard.chrome.editModeHint': 'Modo edición activo — arrastra y redimensiona los widgets. Cierra el panel para salir.',\n    'dashboard.chrome.emptyHint': 'Aún no tienes indicadores en tu tablero. Usa «Editar» para agregarlos desde el catálogo.',\n    'dashboard.presentation.enter': 'Modo presentación',\n    'dashboard.presentation.exit': 'Salir de presentación',\n    'dashboard.presentation.rotate': 'Rotar',\n\n    // ── Selector de compañía ──\n    'dashboard.company.placeholder': 'Seleccionar compañía',\n    'dashboard.company.search': 'Buscar compañía...',\n    'dashboard.company.noMatches': 'Ninguna compañía coincide',\n    'dashboard.company.enabled': 'Habilitado',\n    'dashboard.company.notEnabled': 'No habilitado',\n    'dashboard.company.notAvailable': 'No disponible',\n    'dashboard.chrome.empty': 'Dashboard Vacío',\n\n    // ── Acciones sobre un widget ──\n    'dashboard.widget.refresh': 'Actualizar datos',\n    'dashboard.widget.maximize': 'Maximizar widget',\n    'dashboard.widget.minimize': 'Minimizar',\n    'dashboard.widget.remove': 'Quitar del dashboard',\n    'dashboard.widget.noData': 'Sin datos disponibles',\n    'dashboard.widget.unavailable': 'no disponible o archivo no encontrado.',\n    'dashboard.widget.justNow': 'justo ahora',\n    'dashboard.widget.agoMinutes': 'hace {n} min',\n    'dashboard.widget.agoHours': 'hace {n} h',\n    'dashboard.widget.highVolume': 'Este widget procesa {count} registros. El rendimiento puede verse afectado.',\n\n    // ── KPI: la referencia del delta se deriva del periodo, nunca se escribe a mano ──\n    'dashboard.kpi.vsPreviousDay': 'vs. ayer',\n    'dashboard.kpi.vsPreviousWeek': 'vs. semana anterior',\n    'dashboard.kpi.vsPreviousMonth': 'vs. mes anterior',\n    'dashboard.kpi.trendUp': 'Subió',\n    'dashboard.kpi.trendDown': 'Bajó',\n    // La etiqueta del cuerpo cuando el KPI agrega varios registros: dice QUÉ se hizo con ellos.\n    'dashboard.kpi.aggregatedLabel': '{agg} ({count} registros)',\n    'dashboard.kpi.aggSum': 'Total',\n    'dashboard.kpi.aggAverage': 'Promedio',\n    'dashboard.kpi.aggCount': 'Conteo',\n    'dashboard.kpi.aggMin': 'Mínimo',\n    'dashboard.kpi.aggMax': 'Máximo',\n    'dashboard.kpi.aggLast': 'Último',\n\n    // ── Gráficos ──\n    'dashboard.chart.others': 'Otros',\n    'dashboard.chart.total': 'Total',\n\n    // ── Tabla ──\n    'dashboard.table.rowCount': '{count} registros',\n    'dashboard.table.yes': 'Sí',\n    'dashboard.table.no': 'No',\n    'dashboard.table.expandForMore': 'Ampliar para ver más columnas',\n\n    // ── Confirmaciones ──\n    'dashboard.confirm.removeBody': 'Podrás volver a agregarlo desde el catálogo.',\n    'dashboard.confirm.removeQuestion': '¿Quitar este widget de tu tablero?',\n    'dashboard.confirm.removeAction': 'Quitar',\n    'dashboard.confirm.deleteTitle': 'Eliminar widget',\n    'dashboard.confirm.deleteBody': 'Esta acción no se puede deshacer.',\n    'dashboard.confirm.cancel': 'Cancelar',\n\n    // ── Catálogo ──\n    'dashboard.catalog.title': 'Catálogo de Indicadores',\n    'dashboard.catalog.search': 'Buscar indicador...',\n    'dashboard.catalog.empty': 'No se encontraron indicadores.',\n    'dashboard.catalog.deleteWidget': 'Eliminar widget del catálogo',\n\n    // ── Diálogo de acceso por widget (F5-bis) ──\n    //\n    // ⚠️ Ninguna de estas cadenas nombra un módulo de negocio ni un permiso concreto: los códigos de\n    // los nombres de los módulos son vocabulario del HOST y viajan por el adaptador.\n    'dashboard.builder.open': 'Crear un indicador',\n    'dashboard.builder.openExternal': 'Crear un indicador o conectar un API externo',\n    // 🔴 Marco POSITIVO en toda la ventana: el verbo es siempre «ver» y el sujeto siempre\n    // «indicador». Ni «restringir», ni «cerrar», ni «widget» — tres palabras que decian lo mismo de\n    // tres maneras, y dos de ellas en negativo.\n    'dashboard.access.dialogTitle': 'Quién ve este indicador',\n    'dashboard.access.close': 'Cerrar',\n    'dashboard.access.searchPeople': 'Buscar una persona por nombre o correo...',\n    'dashboard.access.pickModule': 'Elegir un módulo...',\n    'dashboard.access.searchPermissions': 'Buscar un permiso por nombre o código...',\n    'dashboard.access.noPermissionMatch': 'Ningún permiso tuyo coincide. Solo puedes conceder por un permiso que tú tengas.',\n    'dashboard.access.permissionOwnScope': 'Solo aparecen los permisos que tú tienes: no se puede conceder por uno ajeno.',\n    'dashboard.access.subjectIdPlaceholder': 'Identificador de quien recibe el acceso',\n    'dashboard.access.subject.user': 'Una persona',\n    'dashboard.access.subject.permission': 'Un permiso',\n    'dashboard.access.subject.module': 'Un módulo',\n    'dashboard.access.level': 'Nivel',\n    'dashboard.access.level.viewer': 'Puede ver',\n    'dashboard.access.level.editor': 'Puede editar',\n    'dashboard.access.level.owner': 'Puede administrar',\n    'dashboard.access.expiry': 'Vencimiento',\n    'dashboard.access.expiryDefault': 'Con el vencimiento por defecto',\n    'dashboard.access.expiryDefaultDays': 'Vence en {days} días',\n    'dashboard.access.expiryDate': 'Vence en una fecha',\n    'dashboard.access.expiryNever': 'Sin vencimiento',\n    'dashboard.access.expiresOn': 'Vence el {date}',\n    'dashboard.access.grant': 'Dar acceso',\n    'dashboard.access.currentAccess': 'Con acceso',\n    'dashboard.access.noneYet': 'Nadie más tiene acceso a este indicador.',\n    'dashboard.access.revoke': 'Quitar el acceso',\n    'dashboard.access.loading': 'Cargando...',\n    'dashboard.access.inert': 'sin efecto',\n    'dashboard.access.grantInert': 'El acceso quedó guardado, pero a esta persona NO le va a aparecer: le falta un permiso de más arriba. Concédeselo donde se administran los permisos — no le quites el requisito al indicador.',\n    'dashboard.access.visibility': 'Quién lo alcanza',\n    'dashboard.access.needsPublish': 'Abrirlo a un módulo entero requiere el permiso de publicar.',\n    // ── 🔴 F5 · UNA sola pregunta: ¿quién ve este indicador? ──\n    //\n    // Hubo una segunda —la sensibilidad— y se retiró el 2026-09-14, de la pantalla y del modelo.\n    // Se parecía a ésta («las dos quitan gente») y se comportaba al revés, y la única señal de esa\n    // diferencia eran tres palabras en una columna.\n    // La casilla. Quitados los radios, lo que queda es binario — y un binario se dice con un check.\n    'dashboard.access.restrictedCheck': 'Limitar quién lo ve',\n    'dashboard.access.restrictedCheckOn': 'Elige abajo quién lo ve.',\n    // Las dos formas de cerrarlo. Son dos visibilidades distintas del modelo, asi que son\n    // EXCLUYENTES — radios, no casillas.\n    // 🔴 NEUTRO A PROPOSITO, y este es el sitio donde mas cuesta serlo.\n    //\n    // Aqui habia dos pares de claves —`scopeOwner`/`scopeAdmins`— y el dialogo elegia entre ellos\n    // con `widget.propietario_id`, o sea aplicando una regla del HOST: «privado SIN dueño lo ven los\n    // administradores». Eso es `esPersonal` de Comercial, y el kit lo consumen tres productos.\n    //\n    // Ahora hay UNA clave neutra y el host la corrige por `describeVisibility`. El texto del kit\n    // describe el ESTADO y no promete quien entra — que es lo unico que el kit puede afirmar.\n    'dashboard.access.scopeClosed': 'Cerrado',\n    'dashboard.access.scopeClosedHint': 'No aparece para nadie por esta vía.',\n    'dashboard.access.scopeUsers': 'Personas específicas',\n    'dashboard.access.scopeUsersHint': 'Solo quienes figuren en la lista.',\n    // ⚠️ Aqui estaba `adminsAlways`: «quienes administran {vertical} lo ven siempre». Se retiro del\n    // diccionario a proposito — no es copy, es una AFIRMACION sobre el modelo del host. La escribe\n    // el host por `describeAlwaysSee`, y sin respuesta la nota no se pinta.\n    'dashboard.access.noChanges': 'Sin cambios',\n    // El motor pluraliza por SUFIJO y con `count` numerico. Sin `_other`, «2 cambios» caia a la\n    // clave base y se leia igual que el singular.\n    'dashboard.access.pendingChanges_one': '1 cambio sin guardar',\n    'dashboard.access.pendingChanges_other': '{count} cambios sin guardar',\n    'dashboard.access.pickSomeoneFirst': 'Elige primero a una persona de la lista.',\n    'dashboard.access.cancel': 'Cancelar',\n    'dashboard.access.saveChanges': 'Guardar cambios',\n    // 🔴 Se pinta en el TOAST, no en la ventana: la ventana ya se cerró cuando esto se lee. Neutro a\n    // proposito —«el acceso», no «la vertical»— porque el kit no sabe a quien alcanza el indicador.\n    'dashboard.access.savedOk': 'Se guardó quién ve este indicador.',\n    'dashboard.access.saveFailedSome':\n      'Se guardó lo demás, pero esto quedó sin aplicar: {quienes}. Vuelve a intentarlo.',\n    // 🔴 Sin la palabra «vertical», que es vocabulario de Comercial —y este diccionario tiene\n    // prohibido nombrar un modulo de negocio, lo dice su propio encabezado—. `{alcance}` lo llena el\n    // host con la etiqueta que use: «Ventas», «Tesorería», «Nómina».\n    'dashboard.access.restrictedCheckOff': 'Sin marcar, lo ven todos los que alcanza el indicador.',\n    'dashboard.access.restrictedCheckOffNamed': 'Sin marcar, lo ve todo {alcance}.',\n    'dashboard.access.restrictedNeedsPublish':\n      'Para quitar la restricción hace falta poder abrir el indicador a un colectivo, que es otro acto.',\n    'dashboard.access.audienceToday': 'Hoy lo ve:',\n    'dashboard.access.add': 'Añadir',\n    'dashboard.access.save': 'Guardar',\n    'dashboard.access.saving': 'Guardando...',\n\n    // ── Personalización ──\n    'dashboard.customize.visualization': 'Visualización',\n    'dashboard.customize.name': 'Nombre del Widget',\n    'dashboard.customize.category': 'Categoría',\n    'dashboard.customize.width': 'Ancho por defecto',\n    'dashboard.customize.widthSmall': 'Pequeño (3 cols)',\n    'dashboard.customize.widthMedium': 'Mediano (6 cols)',\n    'dashboard.customize.widthFull': 'Ancho Total (12 cols)',\n    'dashboard.customize.refresh': 'Frecuencia de actualización',\n\n    // ── Mapeo de campos ──\n    'dashboard.fields.chartFields': 'Campos del gráfico',\n    'dashboard.fields.groupBy': 'Agrupar por',\n    'dashboard.fields.available': 'Campos disponibles del endpoint',\n\n    // -- Widget Builder --\n    'dashboard.builder.step1.title': 'Conexión a Datos',\n    'dashboard.builder.step1.subtitle': 'Selecciona un indicador del catálogo o conecta tu propia API.',\n    'dashboard.builder.step1.catalog': 'Catálogo de indicadores',\n    'dashboard.builder.step1.manual': 'URL manual / Siesa',\n    'dashboard.builder.step1.ready': 'Listo para continuar',\n    'dashboard.builder.step1.external': 'Servicio Externo — las credenciales del usuario no se propagan a esta API.',\n    'dashboard.builder.step1.method': 'Método',\n    'dashboard.builder.step1.url': 'URL del Endpoint',\n    'dashboard.builder.step1.headersTitle': 'Headers y Body',\n    'dashboard.builder.step1.customHeaders': 'Headers personalizados',\n    'dashboard.builder.step1.error': 'Error:',\n    'dashboard.builder.step1.performance': 'Rendimiento:',\n\n    'dashboard.builder.step2.title': 'Mapeo de Datos',\n    'dashboard.builder.step2.subtitle': 'Indica cómo se relacionan los campos del JSON con la visualización seleccionada.',\n    'dashboard.builder.step2.noData': 'No hay datos disponibles. Vuelve al paso anterior y prueba la conexión primero.',\n    'dashboard.builder.step2.aggregation': 'Tipo de agregación',\n    'dashboard.builder.step2.axisXLabels': 'Eje X — Etiquetas',\n    'dashboard.builder.step2.axisXTime': 'Eje X — Etiquetas / Tiempo',\n    'dashboard.builder.step2.axisYValues': 'Eje Y — Valores',\n    'dashboard.builder.step2.categoryField': 'Campo de categorías',\n    'dashboard.builder.step2.valuesField': 'Campo de valores',\n    'dashboard.builder.step2.availableColumns': 'Columnas disponibles',\n    'dashboard.builder.step2.allAssigned': 'Todas asignadas',\n    'dashboard.builder.step2.selectedColumns': 'Columnas seleccionadas (orden)',\n    'dashboard.builder.step2.dragHint': 'Arrastra o haz click para agregar',\n    'dashboard.builder.step2.direction': 'Dirección',\n    'dashboard.builder.step2.asc': 'Ascendente',\n    'dashboard.builder.step2.desc': 'Descendente',\n    'dashboard.builder.step2.autoMapping': 'Mapeo automático detectado',\n\n    'dashboard.builder.step3.title': 'Tipo de Presentación',\n    'dashboard.builder.step3.subtitle': 'Elige cómo se va a visualizar el indicador en el dashboard.',\n\n    'dashboard.builder.step4.title': 'Apariencia y Dimensiones',\n    'dashboard.builder.step4.description': 'Descripción corta (opcional)',\n    'dashboard.builder.step4.preview': 'Vista previa',\n    'dashboard.builder.step4.noRefresh': 'Sin auto-refresh',\n    'dashboard.builder.step4.every30s': 'Cada 30 segundos',\n    'dashboard.builder.step4.every1m': 'Cada 1 minuto',\n    'dashboard.builder.step4.every2m': 'Cada 2 minutos',\n    'dashboard.builder.step4.every5m': 'Cada 5 minutos',\n    'dashboard.builder.step4.every10m': 'Cada 10 minutos',\n    'dashboard.builder.step4.every30m': 'Cada 30 minutos',\n\n    'dashboard.builder.step5.title': 'Publicación y Permisos',\n    'dashboard.builder.step5.private': 'Widget Privado (Solo yo)',\n    'dashboard.builder.step5.privateHint': 'Solo tú podrás ver este widget en tu catálogo personal.',\n    'dashboard.builder.step5.public': 'Widget Público (Corporativo)',\n    'dashboard.builder.step2.valueFieldLabel': 'Campo de valor',\n    'dashboard.builder.step2.detectedValue': 'Campo valor:',\n    'dashboard.builder.step2.detectedDate': 'Campo fecha:',\n    'dashboard.builder.step1.searchIndicator': 'Buscar indicador...',\n    'dashboard.builder.step4.namePlaceholder': 'Ej. Tasa de Conversión B2B',\n    // 🔴 F3 — el rotulo dice la VERDAD. «Publico» a secas sugiere «todo el mundo», y nunca fue\n    // cierto: siempre fue «todo el mundo DE ESTE GRUPO». Se conserva la clave `public` porque es lo\n    // que se pinta cuando la categoria no declara grupo, que es un estado distinto.\n    //\n    // ⚠️ SIN la palabra «vertical», que es vocabulario de Comercial (`DashboardVertical` de Core) y\n    // este diccionario tiene prohibido nombrar un modulo de negocio —lo dice su propio encabezado—.\n    // `{alcance}` lo llena el host con SU etiqueta: «Ventas», «Tesoreria», «Nomina».\n    'dashboard.builder.step5.publicIn': 'Público en {alcance}',\n    'dashboard.builder.step5.publicInHint':\n      'Sale de la categoría «{alcance}»: no se pregunta aparte, y así no pueden discrepar.',\n    'dashboard.builder.step5.noScopeHint':\n      'Esta categoría no declara a qué grupo pertenece, así que no hay dónde publicar. Elige otra categoría en el paso anterior.',\n    'dashboard.builder.step5.toEveryone': 'A todos los de {alcance}',\n    'dashboard.builder.step5.toPeople': 'Solo a estas personas',\n    'dashboard.builder.step5.noSearch':\n      'Este host no tiene buscador de personas. Se puede repartir después, desde el diálogo de acceso.',\n    'dashboard.builder.step5.searchPerson': 'Buscar persona…',\n    'dashboard.builder.step5.removePerson': 'Quitar a {persona}',\n    'dashboard.builder.step5.noPeopleYet':\n      'Sin nadie en la lista, el indicador se crea restringido y sin acceso para nadie — ni siquiera para ti. Agrega al menos una persona, o elige «A todos los de {alcance}».',\n    'dashboard.builder.step5.ceilingWarning':\n      'Solo alcanza a quien ya tenga {alcance}: el acceso se guarda igual para los demás, y queda sin efecto.',\n    // 🔴 F4 — las tres llamadas no tienen transaccion, asi que el final a medias TIENE NOMBRE. El\n    // peor caso es un indicador creado, restringido y sin nadie dentro: invisible hasta para su\n    // autor, y sin ningun error que lo delate.\n    'dashboard.builder.step5.partialNobody':\n      'El indicador «{nombre}» se creó y quedó restringido, pero NO se pudo dar acceso a nadie: ahora mismo no lo ve nadie, ni tú. Ábrelo en el diálogo de acceso para repartirlo.',\n    'dashboard.builder.step5.partialSome':\n      'El indicador «{nombre}» se creó y quedó restringido. Entraron: {ok}. NO entraron: {fallidos}. Ábrelo en el diálogo de acceso para completar el reparto.',\n    'dashboard.builder.step5.partialNotRestricted':\n      'El indicador «{nombre}» se creó, pero NO se pudo restringir, así que sigue privado para ti y nadie más lo ve. Ábrelo en el diálogo de acceso para repartirlo.',\n    'dashboard.builder.step5.openAccessDialog': 'Abrir el diálogo de acceso',\n    'dashboard.builder.step5.dismissPartial': 'Entendido, lo dejo así por ahora',\n    'dashboard.widget.emptyData': 'Sin datos',\n    'dashboard.widget.imageUnavailable': 'Imagen no disponible',\n  },\n\n  en: {\n    'dashboard.chrome.loading': 'Loading your dashboard...',\n    'dashboard.chrome.loadError': 'The dashboard could not be loaded',\n    'dashboard.chrome.retry': 'Retry',\n    'dashboard.category.uncategorized': 'Other',\n    'dashboard.chrome.title': 'KPI dashboard',\n    'dashboard.chrome.viewCascade': 'Cascade view',\n    'dashboard.chrome.viewTabs': 'Tab view',\n    'dashboard.chrome.viewBoard': 'Single board',\n    'dashboard.chrome.saving': 'Saving...',\n    'dashboard.chrome.edit': 'Edit',\n    'dashboard.chrome.editModeHint': 'Edit mode on — drag and resize the widgets. Close the panel to exit.',\n    'dashboard.chrome.emptyHint': 'You have no indicators on your dashboard yet. Use \"Edit\" to add them from the catalog.',\n    'dashboard.presentation.enter': 'Presentation mode',\n    'dashboard.presentation.exit': 'Exit presentation',\n    'dashboard.presentation.rotate': 'Rotate',\n\n    'dashboard.company.placeholder': 'Select company',\n    'dashboard.company.search': 'Search company...',\n    'dashboard.company.noMatches': 'No company matches',\n    'dashboard.company.enabled': 'Enabled',\n    'dashboard.company.notEnabled': 'Not enabled',\n    'dashboard.company.notAvailable': 'Not available',\n    'dashboard.chrome.empty': 'Empty dashboard',\n\n    'dashboard.widget.refresh': 'Refresh data',\n    'dashboard.widget.maximize': 'Maximize widget',\n    'dashboard.widget.minimize': 'Minimize',\n    'dashboard.widget.remove': 'Remove from dashboard',\n    'dashboard.widget.noData': 'No data available',\n    'dashboard.widget.unavailable': 'unavailable or file not found.',\n    'dashboard.widget.justNow': 'just now',\n    'dashboard.widget.agoMinutes': '{n} min ago',\n    'dashboard.widget.agoHours': '{n} h ago',\n    'dashboard.widget.highVolume': 'This widget processes {count} records. Performance may be affected.',\n\n    'dashboard.kpi.vsPreviousDay': 'vs. yesterday',\n    'dashboard.kpi.vsPreviousWeek': 'vs. previous week',\n    'dashboard.kpi.vsPreviousMonth': 'vs. previous month',\n    'dashboard.kpi.trendUp': 'Up',\n    'dashboard.kpi.trendDown': 'Down',\n    'dashboard.kpi.aggregatedLabel': '{agg} ({count} records)',\n    'dashboard.kpi.aggSum': 'Total',\n    'dashboard.kpi.aggAverage': 'Average',\n    'dashboard.kpi.aggCount': 'Count',\n    'dashboard.kpi.aggMin': 'Minimum',\n    'dashboard.kpi.aggMax': 'Maximum',\n    'dashboard.kpi.aggLast': 'Latest',\n\n    'dashboard.chart.others': 'Other',\n    'dashboard.chart.total': 'Total',\n\n    'dashboard.table.rowCount': '{count} records',\n    'dashboard.table.yes': 'Yes',\n    'dashboard.table.no': 'No',\n    'dashboard.table.expandForMore': 'Expand to see more columns',\n\n    'dashboard.confirm.removeBody': 'You can add it back from the catalog.',\n    'dashboard.confirm.removeQuestion': 'Remove this widget from your dashboard?',\n    'dashboard.confirm.removeAction': 'Remove',\n    'dashboard.confirm.deleteTitle': 'Delete widget',\n    'dashboard.confirm.deleteBody': 'This cannot be undone.',\n    'dashboard.confirm.cancel': 'Cancel',\n\n    'dashboard.catalog.title': 'Indicator catalog',\n    'dashboard.catalog.search': 'Search indicator...',\n    'dashboard.catalog.empty': 'No indicators found.',\n    'dashboard.catalog.deleteWidget': 'Delete widget from catalog',\n\n    // ── Widget access dialog (F5-bis) ──\n    'dashboard.builder.open': 'Create an indicator',\n    'dashboard.builder.openExternal': 'Create an indicator or connect an external API',\n    'dashboard.access.dialogTitle': 'Who sees this widget',\n    'dashboard.access.close': 'Close',\n    'dashboard.access.searchPeople': 'Search a person by name or email...',\n    'dashboard.access.pickModule': 'Pick a module...',\n    'dashboard.access.searchPermissions': 'Search a permission by name or code...',\n    'dashboard.access.noPermissionMatch': 'None of your permissions match. You can only grant through a permission you hold.',\n    'dashboard.access.permissionOwnScope': \"Only permissions you hold are listed: you cannot grant through someone else's.\",\n    'dashboard.access.subjectIdPlaceholder': 'Identifier of the access recipient',\n    'dashboard.access.subject.user': 'A person',\n    'dashboard.access.subject.permission': 'A permission',\n    'dashboard.access.subject.module': 'A module',\n    'dashboard.access.level': 'Level',\n    'dashboard.access.level.viewer': 'Can view',\n    'dashboard.access.level.editor': 'Can edit',\n    'dashboard.access.level.owner': 'Can manage',\n    'dashboard.access.expiry': 'Expiry',\n    'dashboard.access.expiryDefault': 'With the default expiry',\n    'dashboard.access.expiryDefaultDays': 'Expires in {days} days',\n    'dashboard.access.expiryDate': 'Expires on a date',\n    'dashboard.access.expiryNever': 'Never expires',\n    'dashboard.access.expiresOn': 'Expires on {date}',\n    'dashboard.access.grant': 'Give access',\n    'dashboard.access.currentAccess': 'With access',\n    'dashboard.access.noneYet': 'Nobody else has access to this widget.',\n    'dashboard.access.revoke': 'Remove access',\n    'dashboard.access.loading': 'Loading...',\n    'dashboard.access.inert': 'no effect',\n    'dashboard.access.grantInert': 'Access was saved, but this person will NOT see the widget: they are missing a higher-level permission. Grant it where permissions are managed — do not drop the widget requirement.',\n    'dashboard.access.visibility': 'Who can reach it',\n    'dashboard.access.needsPublish': 'Opening it to a whole module requires the publish permission.',\n    'dashboard.access.restrictedCheck': 'Limit who sees it',\n    'dashboard.access.restrictedCheckOn': 'Choose below who sees it.',\n    'dashboard.access.scopeClosed': 'Closed',\n    'dashboard.access.scopeClosedHint': 'It does not show up for anyone through this route.',\n    'dashboard.access.scopeUsers': 'Specific people',\n    'dashboard.access.scopeUsersHint': 'Only those on the list.',\n    'dashboard.access.noChanges': 'No changes',\n    'dashboard.access.pendingChanges_one': '1 unsaved change',\n    'dashboard.access.pendingChanges_other': '{count} unsaved changes',\n    'dashboard.access.pickSomeoneFirst': 'Pick a person from the list first.',\n    'dashboard.access.cancel': 'Cancel',\n    'dashboard.access.saveChanges': 'Save changes',\n    'dashboard.access.savedOk': 'Saved who sees this widget.',\n    'dashboard.access.saveFailedSome':\n      'Everything else was saved, but this was left unapplied: {quienes}. Try again.',\n    'dashboard.access.restrictedCheckOff': 'Unticked, everyone the widget reaches sees it.',\n    'dashboard.access.restrictedCheckOffNamed': 'Unticked, all of {alcance} sees it.',\n    'dashboard.access.restrictedNeedsPublish':\n      'Removing the restriction requires being able to open the widget to a group, which is another act.',\n    'dashboard.access.audienceToday': 'Today it is seen by:',\n    'dashboard.access.add': 'Add',\n    'dashboard.access.save': 'Save',\n    'dashboard.access.saving': 'Saving...',\n\n    'dashboard.customize.visualization': 'Visualization',\n    'dashboard.customize.name': 'Widget name',\n    'dashboard.customize.category': 'Category',\n    'dashboard.customize.width': 'Default width',\n    'dashboard.customize.widthSmall': 'Small (3 cols)',\n    'dashboard.customize.widthMedium': 'Medium (6 cols)',\n    'dashboard.customize.widthFull': 'Full width (12 cols)',\n    'dashboard.customize.refresh': 'Refresh interval',\n\n    'dashboard.fields.chartFields': 'Chart fields',\n    'dashboard.fields.groupBy': 'Group by',\n    'dashboard.fields.available': 'Available endpoint fields',\n\n    // -- Widget Builder --\n    'dashboard.builder.step1.title': 'Data connection',\n    'dashboard.builder.step1.subtitle': 'Pick an indicator from the catalog or connect your own API.',\n    'dashboard.builder.step1.catalog': 'Indicator catalog',\n    'dashboard.builder.step1.manual': 'Manual URL / Siesa',\n    'dashboard.builder.step1.ready': 'Ready to continue',\n    'dashboard.builder.step1.external': 'External service - user credentials are not forwarded to this API.',\n    'dashboard.builder.step1.method': 'Method',\n    'dashboard.builder.step1.url': 'Endpoint URL',\n    'dashboard.builder.step1.headersTitle': 'Headers and body',\n    'dashboard.builder.step1.customHeaders': 'Custom headers',\n    'dashboard.builder.step1.error': 'Error:',\n    'dashboard.builder.step1.performance': 'Performance:',\n\n    'dashboard.builder.step2.title': 'Data mapping',\n    'dashboard.builder.step2.subtitle': 'Tell us how the JSON fields map to the chosen visualization.',\n    'dashboard.builder.step2.noData': 'No data available. Go back and test the connection first.',\n    'dashboard.builder.step2.aggregation': 'Aggregation',\n    'dashboard.builder.step2.axisXLabels': 'X axis - Labels',\n    'dashboard.builder.step2.axisXTime': 'X axis - Labels / Time',\n    'dashboard.builder.step2.axisYValues': 'Y axis - Values',\n    'dashboard.builder.step2.categoryField': 'Category field',\n    'dashboard.builder.step2.valuesField': 'Values field',\n    'dashboard.builder.step2.availableColumns': 'Available columns',\n    'dashboard.builder.step2.allAssigned': 'All assigned',\n    'dashboard.builder.step2.selectedColumns': 'Selected columns (order)',\n    'dashboard.builder.step2.dragHint': 'Drag or click to add',\n    'dashboard.builder.step2.direction': 'Direction',\n    'dashboard.builder.step2.asc': 'Ascending',\n    'dashboard.builder.step2.desc': 'Descending',\n    'dashboard.builder.step2.autoMapping': 'Automatic mapping detected',\n\n    'dashboard.builder.step3.title': 'Presentation type',\n    'dashboard.builder.step3.subtitle': 'Choose how the indicator will be displayed on the dashboard.',\n\n    'dashboard.builder.step4.title': 'Appearance and size',\n    'dashboard.builder.step4.description': 'Short description (optional)',\n    'dashboard.builder.step4.preview': 'Preview',\n    'dashboard.builder.step4.noRefresh': 'No auto-refresh',\n    'dashboard.builder.step4.every30s': 'Every 30 seconds',\n    'dashboard.builder.step4.every1m': 'Every minute',\n    'dashboard.builder.step4.every2m': 'Every 2 minutes',\n    'dashboard.builder.step4.every5m': 'Every 5 minutes',\n    'dashboard.builder.step4.every10m': 'Every 10 minutes',\n    'dashboard.builder.step4.every30m': 'Every 30 minutes',\n\n    'dashboard.builder.step5.title': 'Publishing and permissions',\n    'dashboard.builder.step5.private': 'Private widget (only me)',\n    'dashboard.builder.step5.privateHint': 'Only you will see this widget in your personal catalog.',\n    'dashboard.builder.step5.public': 'Public widget (corporate)',\n    'dashboard.builder.step2.valueFieldLabel': 'Value field',\n    'dashboard.builder.step2.detectedValue': 'Value field:',\n    'dashboard.builder.step2.detectedDate': 'Date field:',\n    'dashboard.builder.step1.searchIndicator': 'Search indicator...',\n    'dashboard.builder.step4.namePlaceholder': 'e.g. B2B conversion rate',\n    'dashboard.builder.step5.publicIn': 'Public in {alcance}',\n    'dashboard.builder.step5.publicInHint':\n      'It comes from the «{alcance}» category: it is not asked separately, so the two cannot disagree.',\n    'dashboard.builder.step5.noScopeHint':\n      'This category does not declare which group it belongs to, so there is nowhere to publish. Pick another category in the previous step.',\n    'dashboard.builder.step5.toEveryone': 'To everyone in {alcance}',\n    'dashboard.builder.step5.toPeople': 'Only to these people',\n    'dashboard.builder.step5.noSearch':\n      'This host has no people search. You can share later, from the access dialog.',\n    'dashboard.builder.step5.searchPerson': 'Search person…',\n    'dashboard.builder.step5.removePerson': 'Remove {persona}',\n    'dashboard.builder.step5.noPeopleYet':\n      'With nobody on the list, the widget is created restricted and reachable by no one — not even you. Add at least one person, or choose «To everyone in {alcance}».',\n    'dashboard.builder.step5.ceilingWarning':\n      'It only reaches people who already have {alcance}: the access is still stored for the others, with no effect.',\n    'dashboard.builder.step5.partialNobody':\n      'Widget «{nombre}» was created and restricted, but access could NOT be granted to anyone: right now nobody can see it, not even you. Open it in the access dialog to share it.',\n    'dashboard.builder.step5.partialSome':\n      'Widget «{nombre}» was created and restricted. Granted: {ok}. NOT granted: {fallidos}. Open it in the access dialog to finish sharing.',\n    'dashboard.builder.step5.partialNotRestricted':\n      'Widget «{nombre}» was created, but could NOT be restricted, so it stays private to you and nobody else sees it. Open it in the access dialog to share it.',\n    'dashboard.builder.step5.openAccessDialog': 'Open the access dialog',\n    'dashboard.builder.step5.dismissPartial': 'Understood, leave it like this for now',\n    'dashboard.widget.emptyData': 'No data',\n    'dashboard.widget.imageUnavailable': 'Image unavailable',\n  },\n};\n\n/** Hook de traducción del módulo. Ver la nota de arriba sobre la cascada de resolución. */\nexport const useDashboardTranslation = createTranslationHook(TRADUCCIONES);\n\n/** Expuesto para tests: permite afirmar que `es` y `en` tienen exactamente las mismas claves. */\nexport const DASHBOARD_TRANSLATIONS = TRADUCCIONES;\n","import React, { useEffect, useRef, useState } from 'react';\nimport { Building2, Globe, ChevronDown, Check } from 'lucide-react';\nimport { useDashboardTranslation } from '../i18n';\n\n/**\n * Selector de compañía del tablero de indicadores.\n *\n * <b>Es una copia deliberada del de MasterCrud, no una abstracción compartida.</b>\n * Ese es el patrón del kit: `MasterCrud` tiene el suyo, `MasterPatternView` tiene\n * otro (`toolbar/CompanySelector`) y `MasterDocument` monta el propio. Cada módulo\n * necesita props distintas —aquí hace falta buscador y opciones deshabilitadas con\n * motivo, que los maestros no piden— y factorizarlos en uno solo obligaría a tocar\n * un componente del que dependen los maestros para servir a una pantalla nueva.\n *\n * <b>El aspecto es idéntico al de Ítems, a propósito.</b> Mismo chip azul de marca, mismo icono\n * contextual —globo cuando el alcance es Global, edificio cuando es una compañía—, mismo panel\n * con divisor, mismo check azul en la activa. Un usuario que cambia de compañía en Ítems y luego\n * en el tablero tiene que estar haciendo el mismo gesto sobre el mismo control.\n *\n * <b>Los colores salen de la escala `primary-*` del kit, no de hexadecimales.</b> El chip usaba\n * siete literales y seis de ellos ERAN esos tokens (`#93d1fd` = `primary-300`,\n * `#1355b7` = `primary-800`, `#dbeefe` = `primary-100`, `#3c9bf6` = `primary-500`,\n * `#0e79fd` = `primary-600`), mientras su propia variante oscura ya los nombraba. La regla del\n * módulo (`index.css`) es que ningún componente del tablero declare un hexadecimal; este control\n * es del ERP y no una tarjeta del tablero, así que su excepción es usar `primary-*` en vez de\n * `--dash-*` — no cablear el valor.\n *\n * Lo que este añade y los maestros no tienen:\n *\n *  - <b>Buscador</b>, porque un tablero de dirección se consulta en organizaciones\n *    con muchas compañías y un panel sin filtro deja de ser usable.\n *  - <b>Opciones deshabilitadas con su motivo</b>, para `Global`: en un maestro\n *    significa \"registro que aplica a todas\"; en un tablero significaría consolidar\n *    varias compañías, que es otra operación — y sumar cifras en monedas distintas\n *    da un número creíble y sin significado.\n */\n\nexport interface DashboardCompany {\n  uuid: string;\n  name: string;\n  code?: string | null;\n  /** Si el usuario la tiene habilitada. `undefined` oculta la pill de estado. */\n  enabled?: boolean;\n}\n\n/** El uuid con el que los maestros representan el alcance Global. Mismo convenio. */\nexport const GLOBAL_UUID = '000';\n\n/** A partir de cuántas compañías aparece el buscador solo. */\nexport const SEARCH_THRESHOLD = 8;\n\nexport interface DashboardCompanySelectorProps {\n  companies: DashboardCompany[];\n  selectedCompanyId?: string | null;\n  onCompanyChange: (company: DashboardCompany) => void;\n  /**\n   * Opciones visibles pero no elegibles, con el motivo como tooltip.\n   * `{ '000': 'Las compañías habilitadas manejan monedas distintas' }`\n   *\n   * <b>Se muestran en vez de ocultarse.</b> Quien conoce una opción de otra pantalla\n   * y no la encuentra aquí asume que falta o que algo se rompió; verla apagada con\n   * su motivo le dice que existe y por qué hoy no aplica.\n   */\n  optionDisabledReasons?: Record<string, string>;\n  /** `'auto'` enciende el buscador a partir de {@link SEARCH_THRESHOLD} compañías. */\n  searchable?: boolean | 'auto';\n  disabled?: boolean;\n  className?: string;\n}\n\nexport const DashboardCompanySelector: React.FC<DashboardCompanySelectorProps> = ({\n  companies,\n  selectedCompanyId,\n  onCompanyChange,\n  optionDisabledReasons,\n  searchable = 'auto',\n  disabled = false,\n  className = '',\n}) => {\n  const { t } = useDashboardTranslation();\n  const [open, setOpen] = useState(false);\n  const [query, setQuery] = useState('');\n  const rootRef = useRef<HTMLDivElement>(null);\n  const searchRef = useRef<HTMLInputElement>(null);\n\n  useEffect(() => {\n    if (!open) {\n      // Se limpia al cerrar: reabrir con el filtro de la vez anterior puesto\n      // parecería una lista incompleta.\n      setQuery('');\n      return;\n    }\n    // Autofocus: quien abre el panel para buscar ya sabe qué va a teclear.\n    searchRef.current?.focus();\n\n    const onDocClick = (e: MouseEvent) => {\n      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);\n    };\n    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };\n    document.addEventListener('mousedown', onDocClick);\n    document.addEventListener('keydown', onKey);\n    return () => {\n      document.removeEventListener('mousedown', onDocClick);\n      document.removeEventListener('keydown', onKey);\n    };\n  }, [open]);\n\n  if (!companies.length) return null;\n\n  const selected = companies.find(c => String(c.uuid) === String(selectedCompanyId));\n  const isGlobal = !selected || String(selected.uuid) === GLOBAL_UUID;\n  const ContextIcon = isGlobal ? Globe : Building2;\n  const chipLabel = selected?.name ?? t('dashboard.company.placeholder');\n\n  /** Filtra por nombre Y por código: quien conoce el código lo teclea antes que el nombre. */\n  const matches = (c: DashboardCompany) => {\n    const needle = query.trim().toLowerCase();\n    if (!needle) return true;\n    return String(c.name ?? '').toLowerCase().includes(needle)\n      || String(c.code ?? '').toLowerCase().includes(needle);\n  };\n\n  const visible = companies.filter(matches);\n  const globals = visible.filter(c => String(c.uuid) === GLOBAL_UUID);\n  const reales = visible.filter(c => String(c.uuid) !== GLOBAL_UUID);\n\n  const showSearch = searchable === true\n    || (searchable === 'auto' && companies.length >= SEARCH_THRESHOLD);\n\n  // Mismo chip que el maestro de Ítems, literalmente: azul de marca, no tokens del\n  // tablero. Es un control del ERP, no una tarjeta del tablero, y tiene que leerse\n  // igual en las dos pantallas.\n  const chipClasses = [\n    'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold leading-none select-none transition-colors',\n    'bg-primary-50 dark:bg-primary-900/20 border border-primary-300 dark:border-primary-800 text-primary-800 dark:text-primary-300',\n    disabled\n      ? 'opacity-60 cursor-not-allowed'\n      : 'cursor-pointer hover:bg-primary-100 dark:hover:bg-primary-900/40 hover:border-primary-500',\n  ].join(' ');\n\n  const renderOption = (company: DashboardCompany) => {\n    const optIsGlobal = String(company.uuid) === GLOBAL_UUID;\n    const OptIcon = optIsGlobal ? Globe : Building2;\n    const active = String(company.uuid) === String(selectedCompanyId);\n    const reason = optionDisabledReasons?.[String(company.uuid)];\n\n    return (\n      <button\n        key={company.uuid}\n        type=\"button\"\n        role=\"menuitem\"\n        disabled={!!reason}\n        title={reason}\n        onClick={() => { if (reason) return; onCompanyChange(company); setOpen(false); }}\n        className={`w-full flex items-center gap-2 px-3 py-2 text-xs transition-colors ${\n          reason ? 'opacity-50 cursor-not-allowed' : 'hover:bg-[var(--dash-surface-page)]'\n        }`}\n        style={{ color: 'var(--dash-text-primary)' }}\n        data-testid={`company-option-${company.uuid}`}\n      >\n        <span className=\"w-3 flex-shrink-0 text-primary-600\">\n          {active && <Check className=\"w-3 h-3\" />}\n        </span>\n        <span className=\"flex-shrink-0 text-primary-800 dark:text-primary-300\">\n          <OptIcon className=\"w-3.5 h-3.5\" />\n        </span>\n        <span className=\"font-medium truncate min-w-0\" title={company.name}>{company.name}</span>\n\n        <span className=\"ml-auto flex items-center gap-2 flex-shrink-0\">\n          {!optIsGlobal && company.code != null && (\n            <span style={{ color: 'var(--dash-text-muted)', fontVariantNumeric: 'tabular-nums' }}>\n              {company.code}\n            </span>\n          )}\n          {reason ? (\n            <span className=\"text-[11px]\" style={{ color: 'var(--dash-text-muted)' }}>\n              {t('dashboard.company.notAvailable')}\n            </span>\n          ) : !optIsGlobal && company.enabled !== undefined && (\n            company.enabled ? (\n              <span className=\"inline-flex items-center gap-1 text-[11px] font-semibold\" style={{ color: 'var(--dash-success)' }}>\n                <Check className=\"w-3 h-3\" />{t('dashboard.company.enabled')}\n              </span>\n            ) : (\n              <span className=\"inline-flex items-center gap-1 text-[11px]\" style={{ color: 'var(--dash-text-muted)' }}>\n                <span className=\"inline-block w-3 h-3 rounded-full border border-current\" />\n                {t('dashboard.company.notEnabled')}\n              </span>\n            )\n          )}\n        </span>\n      </button>\n    );\n  };\n\n  return (\n    <div className={`relative inline-block ${className}`} ref={rootRef} data-testid=\"dashboard-company-selector\">\n      <button\n        type=\"button\"\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        disabled={disabled}\n        onClick={() => setOpen(v => !v)}\n        className={chipClasses}\n      >\n        <span className=\"flex-shrink-0\"><ContextIcon className=\"w-3.5 h-3.5 flex-shrink-0\" /></span>\n        <span className=\"max-w-[180px] truncate\" title={chipLabel}>{chipLabel}</span>\n        <ChevronDown className={`w-3 h-3 flex-shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />\n      </button>\n\n      {open && (\n        <div\n          role=\"menu\"\n          className=\"absolute left-0 top-full mt-1 z-50 min-w-[300px] max-w-[420px] max-h-[320px] overflow-y-auto rounded-lg shadow-md py-1 border\"\n          style={{ background: 'var(--dash-surface-card)', borderColor: 'var(--dash-border)' }}\n        >\n          {showSearch && (\n            <div className=\"px-2 pb-1\">\n              <input\n                ref={searchRef}\n                type=\"text\"\n                value={query}\n                onChange={e => setQuery(e.target.value)}\n                placeholder={t('dashboard.company.search')}\n                aria-label={t('dashboard.company.search')}\n                className=\"w-full px-2 py-1.5 text-xs rounded border bg-transparent outline-none focus:border-primary-500\"\n                style={{ borderColor: 'var(--dash-border)', color: 'var(--dash-text-primary)' }}\n                data-testid=\"company-search\"\n              />\n            </div>\n          )}\n\n          {visible.length === 0 && (\n            <p className=\"px-3 py-3 text-xs text-center\" style={{ color: 'var(--dash-text-muted)' }}>\n              {t('dashboard.company.noMatches')}\n            </p>\n          )}\n\n          {globals.map(renderOption)}\n          {globals.length > 0 && reales.length > 0 && (\n            <hr className=\"my-1\" style={{ borderColor: 'var(--dash-border)' }} />\n          )}\n          {reales.map(renderOption)}\n        </div>\n      )}\n    </div>\n  );\n};\n","import type { WidgetDefinition, DashboardFetcher, AllowedInternalRoutes, DataSourceOption } from '../types';\n\n/**\n * GET /api/dashboard/widgets\n * Devuelve el catálogo de widgets filtrado por el rol del usuario (vía JWT en el host).\n */\nexport const getCatalogWidgets = async (\n  fetcher: DashboardFetcher\n): Promise<WidgetDefinition[]> => {\n  return fetcher<WidgetDefinition[]>('/api/dashboard/widgets', { method: 'GET' });\n};\n\n/**\n * POST /api/dashboard/widgets\n * Registra un widget creado desde el Widget Builder.\n */\nexport const createWidget = async (\n  newWidget: Omit<WidgetDefinition, 'version'>,\n  fetcher: DashboardFetcher\n): Promise<WidgetDefinition> => {\n  return fetcher<WidgetDefinition>('/api/dashboard/widgets', {\n    method: 'POST',\n    body: newWidget,\n  });\n};\n\n/**\n * PATCH /api/dashboard/widgets/:widgetId\n * Actualiza un widget existente (campos parciales).\n */\nexport const updateWidget = async (\n  widgetId: string,\n  patch: Partial<WidgetDefinition>,\n  fetcher: DashboardFetcher\n): Promise<WidgetDefinition> => {\n  return fetcher<WidgetDefinition>(`/api/dashboard/widgets/${widgetId}`, {\n    method: 'PATCH',\n    body: patch,\n  });\n};\n\n/**\n * DELETE /api/dashboard/widgets/:widgetId\n * Elimina un widget del catalogo (requiere rol admin).\n */\nexport const deleteWidget = async (\n  widgetId: string,\n  fetcher: DashboardFetcher\n): Promise<{ deleted: boolean }> => {\n  return fetcher<{ deleted: boolean }>(`/api/dashboard/widgets/${widgetId}`, {\n    method: 'DELETE',\n  });\n};\n\n/**\n * GET /api/dashboard/widgets/allowed-internal-routes\n * Retorna la configuracion publica del whitelist para el Widget Builder.\n */\nexport const getAllowedInternalRoutes = async (\n  fetcher: DashboardFetcher\n): Promise<AllowedInternalRoutes> => {\n  return fetcher<AllowedInternalRoutes>('/api/dashboard/widgets/allowed-internal-routes', { method: 'GET' });\n};\n\n/**\n * GET /api/dashboard/widgets/data-sources\n * Retorna el catalogo de fuentes internas filtrado por roles del usuario.\n */\nexport const getDataSources = async (\n  fetcher: DashboardFetcher\n): Promise<DataSourceOption[]> => {\n  return fetcher<DataSourceOption[]>('/api/dashboard/widgets/data-sources', { method: 'GET' });\n};\n","import type { LayoutUpdatePayload, UserWidgetPreference, DashboardFetcher } from '../types';\n\n/**\n * GET /api/dashboard/layout\n * Carga el layout guardado para el usuario autenticado.\n */\nexport const getUserLayout = async (\n  userId: string,\n  fetcher: DashboardFetcher\n): Promise<UserWidgetPreference[]> => {\n  return fetcher<UserWidgetPreference[]>('/api/dashboard/layout', { method: 'GET' });\n};\n\n/**\n * PUT /api/dashboard/layout\n * Reemplaza el layout completo del usuario (llamado con debounce 800ms).\n */\nexport const saveUserLayout = async (\n  payload: LayoutUpdatePayload,\n  fetcher: DashboardFetcher\n): Promise<{ success: boolean }> => {\n  return fetcher<{ success: boolean }>('/api/dashboard/layout', {\n    method: 'PUT',\n    body: payload,\n  });\n};\n","class t{constructor(t,e){this.operator=t,this.value=e,Object.defineProperty(this,\"t\",{writable:!0})}get notes(){return this.t}addNote(t){this.t=this.t||[],this.t.push(t)}}class e extends t{}class r extends e{constructor(t,e){if(!Array.isArray(e))throw new Error(`\"${t}\" operator expects to receive an array of conditions`);super(t,e)}}const n=\"__itself__\";class o extends t{constructor(t,e,r){super(t,r),this.field=e}}const s=new e(\"__null__\",null),i=Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);function c(t,e){return e instanceof r&&e.operator===t}function u(t,e){return 1===e.length?e[0]:new r(t,function t(e,r,n){const o=n||[];for(let n=0,s=r.length;n<s;n++){const s=r[n];c(e,s)?t(e,s.value,o):o.push(s)}return o}(t,e))}const a=t=>t,h=()=>Object.create(null),f=Object.defineProperty(h(),\"__@type@__\",{value:\"ignore value\"});function l(t,e,r=!1){if(!t||t&&t.constructor!==Object)return!1;for(const n in t){if(i(t,n)&&i(e,n)&&(!r||t[n]!==f))return!0}return!1}function d(t){const e=[];for(const r in t)i(t,r)&&t[r]!==f&&e.push(r);return e}function p(t,e){e!==s&&t.push(e)}const w=t=>u(\"and\",t),b=t=>u(\"or\",t),O={compound(t,e,n){const o=(Array.isArray(e)?e:[e]).map(t=>n.parse(t));return new r(t.name,o)},field:(t,e,r)=>new o(t.name,r.field,e),document:(t,r)=>new e(t.name,r)};class j{constructor(t,e=h()){this.o=void 0,this.s=void 0,this.i=void 0,this.u=void 0,this.h=void 0,this.parse=this.parse.bind(this),this.u={operatorToConditionName:e.operatorToConditionName||a,defaultOperatorName:e.defaultOperatorName||\"eq\",mergeFinalConditions:e.mergeFinalConditions||w},this.o=Object.keys(t).reduce((e,r)=>(e[r]=Object.assign({name:this.u.operatorToConditionName(r)},t[r]),e),{}),this.s=Object.assign({},e.fieldContext,{field:\"\",query:{},parse:this.parse,hasOperators:t=>l(t,this.o,e.useIgnoreValue)}),this.i=Object.assign({},e.documentContext,{parse:this.parse,query:{}}),this.h=e.useIgnoreValue?d:Object.keys}setParse(t){this.parse=t,this.s.parse=t,this.i.parse=t}parseField(t,e,r,n){const o=this.o[e];if(!o)throw new Error(`Unsupported operator \"${e}\"`);if(\"field\"!==o.type)throw new Error(`Unexpected ${o.type} operator \"${e}\" at field level`);return this.s.field=t,this.s.query=n,this.parseInstruction(o,r,this.s)}parseInstruction(t,e,r){\"function\"==typeof t.validate&&t.validate(t,e);return(t.parse||O[t.type])(t,e,r)}parseFieldOperators(t,e){const r=[],n=this.h(e);for(let o=0,s=n.length;o<s;o++){const s=n[o];if(!this.o[s])throw new Error(`Field query for \"${t}\" may contain only operators or a plain object as a value`);p(r,this.parseField(t,s,e[s],e))}return r}parse(t){const e=[],r=this.h(t);this.i.query=t;for(let n=0,o=r.length;n<o;n++){const o=r[n],s=t[o],i=this.o[o];if(i){if(\"document\"!==i.type&&\"compound\"!==i.type)throw new Error(`Cannot use parsing instruction for operator \"${o}\" in \"document\" context as it is supposed to be used in  \"${i.type}\" context`);p(e,this.parseInstruction(i,s,this.i))}else this.s.hasOperators(s)?e.push(...this.parseFieldOperators(o,s)):p(e,this.parseField(o,this.u.defaultOperatorName,s,t))}return this.u.mergeFinalConditions(e)}}function _(t,e){const r=t[e];if(\"function\"!=typeof r)throw new Error(`Unable to interpret \"${e}\" condition. Did you forget to register interpreter for it?`);return r}function y(t){return t.operator}function m(t,e){const r=e,n=r&&r.getInterpreterName||y;let o;switch(r?r.numberOfArguments:0){case 1:o=e=>{const o=n(e,r);return _(t,o)(e,s)};break;case 3:o=(e,o,i)=>{const c=n(e,r);return _(t,c)(e,o,i,s)};break;default:o=(e,o)=>{const i=n(e,r);return _(t,i)(e,o,s)}}const s=Object.assign({},r,{interpret:o});return s.interpret}function v(t,e){return(r,...n)=>{const o=t(r,...n),s=e.bind(null,o);return s.ast=o,s}}const x=j.prototype.parseInstruction;export{r as CompoundCondition,t as Condition,e as DocumentCondition,o as FieldCondition,n as ITSELF,s as NULL_CONDITION,j as ObjectQueryParser,w as buildAnd,b as buildOr,m as createInterpreter,v as createTranslatorFactory,O as defaultInstructionParsers,l as hasOperators,a as identity,f as ignoreValue,c as isCompound,h as object,u as optimizedCompoundCondition,x as parseInstruction};\n//# sourceMappingURL=index.mjs.map\n","import{optimizedCompoundCondition as e,FieldCondition as t,CompoundCondition as r,ITSELF as o,NULL_CONDITION as a,ObjectQueryParser as n,buildAnd as i}from\"@ucast/core\";export{defaultInstructionParsers as defaultParsers}from\"@ucast/core\";function s(e,t){if(!Array.isArray(t))throw new Error(`\"${e.name}\" expects value to be an array`)}function p(e,t){if(s(e,t),!t.length)throw new Error(`\"${e.name}\" expects to have at least one element in array`)}const l=e=>(t,r)=>{if(typeof r!==e)throw new Error(`\"${t.name}\" expects value to be a \"${e}\"`)},c={type:\"compound\",validate:p,parse(t,r,{parse:o}){const a=r.map(e=>o(e));return e(t.name,a)}},f=c,d={type:\"compound\",validate:p},u={type:\"field\",validate(e,t){if(!(t&&(t instanceof RegExp||t.constructor===Object)))throw new Error(`\"${e.name}\" expects to receive either regular expression or object of field operators`)},parse(e,o,a){const n=o instanceof RegExp?new t(\"regex\",a.field,o):a.parse(o,a);return new r(e.name,[n])}},$={type:\"field\",validate(e,t){if(!t||t.constructor!==Object)throw new Error(`\"${e.name}\" expects to receive an object with nested query or field level operators`)},parse(e,r,{parse:a,field:n,hasOperators:i}){const s=i(r)?a(r,{field:o}):a(r);return new t(e.name,n,s)}},w={type:\"field\",validate:l(\"number\")},y={type:\"field\",validate:s},x=y,v=y,h={type:\"field\",validate(e,t){if(!Array.isArray(t)||2!==t.length)throw new Error(`\"${e.name}\" expects an array with 2 numeric elements`)}},m={type:\"field\",validate:l(\"boolean\")},g={type:\"field\",validate:function(e,t){if(!(\"string\"==typeof t||\"number\"==typeof t||t instanceof Date))throw new Error(`\"${e.name}\" expects value to be comparable (i.e., string, number or date)`)}},b=g,E=b,j=b,O={type:\"field\"},R=O,_={type:\"field\",validate(e,t){if(!(t instanceof RegExp)&&\"string\"!=typeof t)throw new Error(`\"${e.name}\" expects value to be a regular expression or a string that represents regular expression`)},parse(e,r,o){const a=\"string\"==typeof r?new RegExp(r,o.query.$options||\"\"):r;return new t(e.name,o.field,a)}},q={type:\"field\",parse:()=>a},A={type:\"document\",validate:l(\"function\")};var N=Object.freeze({__proto__:null,$and:c,$or:f,$nor:d,$not:u,$elemMatch:$,$size:w,$in:y,$nin:x,$all:v,$mod:h,$exists:m,$gte:g,$gt:b,$lt:E,$lte:j,$eq:O,$ne:R,$regex:_,$options:q,$where:A});class P extends n{constructor(e){super(e,{defaultOperatorName:\"$eq\",operatorToConditionName:e=>e.slice(1)})}parse(e,t){return t&&t.field?i(this.parseFieldOperators(t.field,e)):super.parse(e)}}const z=N;export{v as $all,c as $and,$ as $elemMatch,O as $eq,m as $exists,b as $gt,g as $gte,y as $in,E as $lt,j as $lte,h as $mod,R as $ne,x as $nin,d as $nor,u as $not,q as $options,f as $or,_ as $regex,w as $size,A as $where,P as MongoQueryParser,z as allParsingInstructions};\n//# sourceMappingURL=index.mjs.map\n","import{ITSELF as r,createInterpreter as t}from\"@ucast/core\";function e(r,t,e){for(let n=0,o=r.length;n<o;n++)if(0===e(r[n],t))return!0;return!1}function n(r,t){return Array.isArray(r)&&Number.isNaN(Number(t))}function o(r,t,e){if(!n(r,t))return e(r,t);let o=[];for(let n=0;n<r.length;n++){const u=e(r[n],t);void 0!==u&&(o=o.concat(u))}return o}function u(r){return(t,e,n)=>{const o=n.get(e,t.field);return Array.isArray(o)?o.some(e=>r(t,e,n)):r(t,o,n)}}const c=Object.hasOwn||Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty),i=(r,t)=>r[t];function f(r,t,e){const n=t.lastIndexOf(\".\");return-1===n?[r,t]:[e(r,t.slice(0,n)),t.slice(n+1)]}function s(t,e,n=i){if(e===r)return t;if(!t)throw new Error(`Unable to get field \"${e}\" out of ${String(t)}.`);return function(r,t,e){if(-1===t.indexOf(\".\"))return o(r,t,e);const n=t.split(\".\");let u=r;for(let r=0,t=n.length;r<t;r++)if(u=o(u,n[r],e),!u||\"object\"!=typeof u)return r<t-1?void 0:u;return u}(t,e,n)}function a(r){return(t,e)=>s(t,e,r)}function l(r,t){return r===t?0:r>t?1:-1}function p(r,e={}){return t(r,Object.assign({get:s,compare:l},e))}const g=(r,t,{interpret:e})=>r.value.some(r=>e(r,t)),b=(r,t,e)=>!g(r,t,e),m=(r,t,{interpret:e})=>r.value.every(r=>e(r,t)),y=(r,t,{interpret:e})=>!e(r.value[0],t),j=(r,t,{compare:n,get:o})=>{const u=o(t,r.field);return Array.isArray(u)&&!Array.isArray(r.value)?e(u,r.value,n):0===n(u,r.value)},A=(r,t,e)=>!j(r,t,e),d=u((r,t,e)=>{const n=e.compare(t,r.value);return 0===n||-1===n}),O=u((r,t,e)=>-1===e.compare(t,r.value)),h=u((r,t,e)=>1===e.compare(t,r.value)),v=u((r,t,e)=>{const n=e.compare(t,r.value);return 0===n||1===n}),w=(t,e,{get:o})=>{if(t.field===r)return void 0!==e;const[u,i]=f(e,t.field,o),s=r=>null==r?Boolean(r)===t.value:c(r,i)===t.value;return n(u,i)?u.some(s):s(u)},_=u((r,t)=>\"number\"==typeof t&&t%r.value[0]===r.value[1]),x=(t,e,{get:o})=>{const[u,c]=f(e,t.field,o),i=r=>{const e=o(r,c);return Array.isArray(e)&&e.length===t.value};return t.field!==r&&n(u,c)?u.some(i):i(u)},N=u((r,t)=>\"string\"==typeof t&&r.value.test(t)),$=u((r,t,{compare:n})=>e(r.value,t,n)),q=(r,t,e)=>!$(r,t,e),z=(r,t,{compare:n,get:o})=>{const u=o(t,r.field);return Array.isArray(u)&&r.value.every(r=>e(u,r,n))},B=(r,t,{interpret:e,get:n})=>{const o=n(t,r.field);return Array.isArray(o)&&o.some(t=>e(r.value,t))},E=(r,t)=>r.value.call(t);var M=Object.freeze({__proto__:null,or:g,nor:b,and:m,not:y,eq:j,ne:A,lte:d,lt:O,gt:h,gte:v,exists:w,mod:_,size:x,regex:N,within:$,nin:q,all:z,elemMatch:B,where:E});const S=Object.assign({},M,{in:$}),U=p(S);export{z as all,S as allInterpreters,m as and,l as compare,a as createGetter,p as createJsInterpreter,B as elemMatch,j as eq,w as exists,s as getObjectField,f as getObjectFieldCursor,h as gt,v as gte,U as interpret,O as lt,d as lte,_ as mod,A as ne,q as nin,b as nor,y as not,g as or,N as regex,x as size,E as where,$ as within};\n//# sourceMappingURL=index.mjs.map\n","import{createTranslatorFactory as o,ITSELF as t}from\"@ucast/core\";export*from\"@ucast/core\";import{MongoQueryParser as e,allParsingInstructions as r,defaultParsers as c}from\"@ucast/mongo\";export*from\"@ucast/mongo\";import{createJsInterpreter as n,allInterpreters as f,compare as s}from\"@ucast/js\";export*from\"@ucast/js\";function i(o){return null===o||\"object\"!=typeof o?o:o instanceof Date?o.getTime():o&&\"function\"==typeof o.toJSON?o.toJSON():o}const m=(o,t)=>s(i(o),i(t));function p(r,c,f){const s=new e(r),i=n(c,Object.assign({compare:m},f));if(f&&f.forPrimitives){const o={field:t},e=s.parse;s.setParse(t=>e(t,o))}return o(s.parse,i)}const u=p(r,f),a=p([\"$and\",\"$or\"].reduce((o,t)=>(o[t]=Object.assign({},o[t],{type:\"field\"}),o),Object.assign({},r,{$nor:Object.assign({},r.$nor,{type:\"field\",parse:c.compound})})),f,{forPrimitives:!0}),j=u;export{p as createFactory,j as filter,u as guard,a as squire};\n//# sourceMappingURL=index.mjs.map\n","import{createFactory as t,$exists as i,$elemMatch as e,$options as s,$regex as n,$size as r,$all as o,$nin as c,$in as u,$gte as h,$gt as l,$lte as f,$lt as a,$ne as d,$eq as y,and as p,exists as b,elemMatch as w,regex as g,size as $,all as A,nin as m,within as M,gte as j,gt as E,lte as x,lt as v,ne as _,eq as F}from\"@ucast/mongo2js\";const O=Object.hasOwn||((t,i)=>Object.prototype.hasOwnProperty.call(t,i));function C(t){return Array.isArray(t)?t:[t]}const R=\"__caslSubjectType__\";function P(t,i){if(i)if(!O(i,R))Object.defineProperty(i,R,{value:t});else if(t!==i[R])throw new Error(`Trying to cast object to subject type ${t} but previously it was casted to ${i[R]}`);return i}const S=t=>{const i=typeof t;return i===\"string\"||i===\"function\"};const T=t=>t.modelName||t.name;function z(t){return typeof t===\"string\"?t:T(t)}function B(t){if(O(t,R))return t[R];return T(t.constructor)}const q={function:t=>t.constructor,string:B};function D(t,i,e){let s=C(i);let n=0;while(n<s.length){const i=s[n++];if(O(t,i))s=e(s,t[i])}return s}function Y(t,i){if(typeof i===\"string\"&&t.indexOf(i)!==-1)return i;for(let e=0;e<i.length;e++)if(t.indexOf(i[e])!==-1)return i[e];return null}const k=(t,i)=>t.concat(i);function L(t,i){if(i in t)throw new Error(`Cannot use \"${i}\" as an alias because it's reserved action.`);const e=Object.keys(t);const s=(t,e)=>{const s=Y(t,e);if(s)throw new Error(`Detected cycle ${s} -> ${t.join(\", \")}`);const n=typeof e===\"string\"&&e===i||t.indexOf(i)!==-1||Array.isArray(e)&&e.indexOf(i)!==-1;if(n)throw new Error(`Cannot make an alias to \"${i}\" because this is reserved action`);return t.concat(e)};for(let i=0;i<e.length;i++)D(t,e[i],s)}function U(t,i){if(!i||i.skipValidate!==false)L(t,i&&i.anyAction||\"manage\");return i=>D(t,i,k)}function G(t,i,e){for(let s=e;s<i.length;s++)t.push(i[s])}function H(t,i){if(!t||!t.length)return i||[];if(!i||!i.length)return t||[];let e=0;let s=0;const n=[];while(e<t.length&&s<i.length)if(t[e].priority<i[s].priority){n.push(t[e]);e++}else if(t[e].priority>i[s].priority){n.push(i[s]);s++}else{n.push(t[e]);e++;s++}G(n,t,e);G(n,i,s);return n}function I(t,i,e){let s=t.get(i);if(!s){s=e();t.set(i,s)}return s}const J=t=>t;function K(t,i){let e;for(let s=0;s<t.length;s++){const n=i(t[s]);if(e&&n)e.push(t[s]);if(!n)e??=t.slice(0,s)}return e||t}function N(t,i){if(Array.isArray(t.fields)&&!t.fields.length)throw new Error(\"`rawRule.fields` cannot be an empty array. https://bit.ly/390miLa\");if(t.fields&&!i.fieldMatcher)throw new Error('You need to pass \"fieldMatcher\" option in order to restrict access by fields');if(t.conditions&&!i.conditionsMatcher)throw new Error('You need to pass \"conditionsMatcher\" option in order to restrict access by conditions')}class Q{constructor(t,i,e=0){N(t,i);this.action=i.resolveAction(t.action);this.subject=t.subject;this.inverted=!!t.inverted;this.conditions=t.conditions;this.reason=t.reason;this.origin=t;this.fields=t.fields?C(t.fields):void 0;this.priority=e;this.t=i}i(){if(this.conditions&&!this.o)this.o=this.t.conditionsMatcher(this.conditions);return this.o}get ast(){const t=this.i();return t?t.ast:void 0}matchesConditions(t){if(!this.conditions)return true;if(!t||S(t))return!this.inverted;const i=this.i();return i(t)}matchesField(t){if(!this.fields)return true;if(!t)return!this.inverted;if(!this.u)this.u=this.t.fieldMatcher(this.fields);return this.u(t)}}function V(t,i){const e={value:t,prev:i,next:null};if(i)i.next=e;return e}function W(t){if(t.next)t.next.prev=t.prev;if(t.prev)t.prev.next=t.next;t.next=t.prev=null}const X=()=>({rules:[],merged:false});const Z=()=>new Map;class tt{constructor(t=[],i={}){this.h=false;this.l=new Map;this.p={conditionsMatcher:i.conditionsMatcher,fieldMatcher:i.fieldMatcher,resolveAction:i.resolveAction||J};this.$=i.anyAction||\"manage\";this.A=i.anySubjectType||\"all\";this.m=t;this.M=!!i.detectSubjectType;this.j=i.detectSubjectType||B;this.v(t)}get rules(){return this.m}detectSubjectType(t){if(S(t))return t;if(!t)return this.A;return this.j(t)}update(t){const i={rules:t,ability:this,target:this};this._(\"update\",i);this.m=t;this.v(t);this._(\"updated\",i);return this}v(t){const i=new Map;let e;for(let s=t.length-1;s>=0;s--){const n=t.length-s-1;const r=new Q(t[s],this.p,n);const o=C(r.action);const c=C(r.subject||this.A);if(!this.h&&r.fields)this.h=true;for(let t=0;t<c.length;t++){const s=I(i,c[t],Z);if(e===void 0)e=typeof c[t];if(typeof c[t]!==e&&e!==\"mixed\")e=\"mixed\";for(let t=0;t<o.length;t++)I(s,o[t],X).rules.push(r)}}this.l=i;if(e!==\"mixed\"&&!this.M){const t=q[e]||q.string;this.j=t}}possibleRulesFor(t,i=this.A){if(!S(i))throw new Error('\"possibleRulesFor\" accepts only subject types (i.e., string or class) as the 2nd parameter');const e=I(this.l,i,Z);const s=I(e,t,X);if(s.merged)return s.rules;const n=t!==this.$&&e.has(this.$)?e.get(this.$).rules:void 0;let r=H(s.rules,n);if(i!==this.A)r=H(r,this.possibleRulesFor(t,this.A));s.rules=r;s.merged=true;return r}rulesFor(t,i,e){const s=this.possibleRulesFor(t,i);if(e&&typeof e!==\"string\")throw new Error(\"The 3rd, `field` parameter is expected to be a string. See https://stalniy.github.io/casl/en/api/casl-ability#can-of-pure-ability for details\");if(!this.h)return s;return K(s,t=>t.matchesField(e))}actionsFor(t){if(!S(t))throw new Error('\"actionsFor\" accepts only subject types (i.e., string or class) as a parameter');const i=new Set;const e=this.l.get(t);if(e)Array.from(e.keys()).forEach(t=>i.add(t));const s=t!==this.A?this.l.get(this.A):void 0;if(s)Array.from(s.keys()).forEach(t=>i.add(t));return Array.from(i)}on(t,i){this.F=this.F||new Map;const e=this.F;const s=e.get(t)||null;const n=V(i,s);e.set(t,n);return()=>{const i=e.get(t);if(!n.next&&!n.prev&&i===n)e.delete(t);else if(n===i)e.set(t,n.prev);W(n)}}_(t,i){if(!this.F)return;let e=this.F.get(t)||null;const s=[];while(e!==null){s.push(e.value);e=e.prev}for(let t=0;t<s.length;t++)s[t](i)}}class PureAbility extends tt{can(t,i,e){const s=this.relevantRuleFor(t,i,e);return!!s&&!s.inverted}relevantRuleFor(t,i,e){const s=this.detectSubjectType(i);const n=this.rulesFor(t,s,e);for(let t=0,e=n.length;t<e;t++)if(n[t].matchesConditions(i))return n[t];return null}cannot(t,i,e){return!this.can(t,i,e)}}const it={$eq:y,$ne:d,$lt:a,$lte:f,$gt:l,$gte:h,$in:u,$nin:c,$all:o,$size:r,$regex:n,$options:s,$elemMatch:e,$exists:i};const et={eq:F,ne:_,lt:v,lte:x,gt:E,gte:j,in:M,nin:m,all:A,size:$,regex:g,elemMatch:w,exists:b,and:p};const st=(i,e,s)=>t(Object.assign({},it,i),Object.assign({},et,e),s);const nt=t(it,et);const rt=/[-/\\\\^$+?.()|[\\]{}]/g;const ot=/\\.?\\*+\\.?/g;const ct=/\\*+/;const ut=/\\./g;function ht(t,i,e){const s=e[0]===\"*\"||t[0]===\".\"&&t[t.length-1]===\".\"?\"+\":\"*\";const n=t.indexOf(\"**\")===-1?\"[^.]\":\".\";const r=t.replace(ut,\"\\\\$&\").replace(ct,n+s);return i+t.length===e.length?`(?:${r})?`:r}function lt(t,i,e){if(t===\".\"&&(e[i-1]===\"*\"||e[i+1]===\"*\"))return t;return`\\\\${t}`}function ft(t){const i=t.map(t=>t.replace(rt,lt).replace(ot,ht));const e=i.length>1?`(?:${i.join(\"|\")})`:i[0];return new RegExp(`^${e}$`)}const at=t=>{let i;return e=>{if(typeof i===\"undefined\")i=t.every(t=>t.indexOf(\"*\")===-1)?null:ft(t);return i===null?t.indexOf(e)!==-1:i.test(e)}};class Ability extends PureAbility{constructor(t=[],i={}){super(t,Object.assign({conditionsMatcher:nt,fieldMatcher:at},i))}}function createMongoAbility(t=[],i={}){return new PureAbility(t,Object.assign({conditionsMatcher:nt,fieldMatcher:at},i))}function isAbilityClass(t){return t.prototype!==void 0&&typeof t.prototype.possibleRulesFor===\"function\"}class dt{constructor(t){this.O=t}because(t){this.O.reason=t;return this}}class AbilityBuilder{constructor(t){this.rules=[];this.C=t;this.can=(t,i,e,s)=>this.R(t,i,e,s,false);this.cannot=(t,i,e,s)=>this.R(t,i,e,s,true);this.build=t=>isAbilityClass(this.C)?new this.C(this.rules,t):this.C(this.rules,t)}R(t,i,e,s,n){const r={action:t};if(n)r.inverted=n;if(i){r.subject=i;if(Array.isArray(e)||typeof e===\"string\")r.fields=e;else if(typeof e!==\"undefined\")r.conditions=e;if(typeof s!==\"undefined\")r.conditions=s}this.rules.push(r);return new dt(r)}}function defineAbility(t,i){const e=new AbilityBuilder(createMongoAbility);const s=t(e.can,e.cannot);if(s&&typeof s.then===\"function\")return s.then(()=>e.build(i));return e.build(i)}const yt=t=>`Cannot execute \"${t.action}\" on \"${t.subjectType}\"`;const pt=function t(i){this.message=i};pt.prototype=Object.create(Error.prototype);class ForbiddenError extends pt{static setDefaultMessage(t){this.P=typeof t===\"string\"?()=>t:t}static from(t){return new this(t)}constructor(t){super(\"\");this.ability=t;if(typeof Error.captureStackTrace===\"function\"){this.name=\"ForbiddenError\";Error.captureStackTrace(this,this.constructor)}}setMessage(t){this.message=t;return this}throwUnlessCan(t,i,e){const s=this.unlessCan(t,i,e);if(s)throw s}unlessCan(t,i,e){const s=this.ability.relevantRuleFor(t,i,e);if(s&&!s.inverted)return;this.action=t;this.subject=i;this.subjectType=z(this.ability.detectSubjectType(i));this.field=e;const n=s?s.reason:\"\";this.message=this.message||n||this.constructor.P(this);return this}}ForbiddenError.P=yt;var bt=Object.freeze({__proto__:null});export{Ability,AbilityBuilder,ForbiddenError,PureAbility,st as buildMongoQueryMatcher,U as createAliasResolver,createMongoAbility,defineAbility,B as detectSubjectType,at as fieldPatternMatcher,yt as getDefaultErrorMessage,bt as hkt,nt as mongoQueryMatcher,P as subject,C as wrapArray};\n//# sourceMappingURL=index.mjs.map\n","import { Ability, AbilityBuilder } from '@casl/ability';\nimport type { WidgetDefinition, WidgetPermissions } from './types';\n\ntype Actions = 'view' | 'create' | 'delete';\ntype Subjects = 'Widget' | 'Dashboard' | 'all';\nexport type DashboardAbility = Ability<[Actions, Subjects]>;\n\nexport function createDashboardAbility(userRoles: string[]): DashboardAbility {\n  const { can, build } = new AbilityBuilder<DashboardAbility>(Ability);\n\n  if (userRoles.length > 0) {\n    can('view', 'Dashboard');\n    can('view', 'Widget');\n  }\n\n  if (userRoles.includes('admin')) {\n    can('create', 'Widget');\n    can('delete', 'Widget');\n  }\n\n  return build();\n}\n\n/**\n * @deprecated Solo como respaldo de `resolveWidgetPermissions` para hosts cuyo backend no evalua\n * acceso por instancia. **No llamarla directamente para decidir si un widget se ve**: cruza roles\n * con `Array.includes`, o sea un OR, y por tanto puede *ensanchar* lo que el servidor ya restringio\n * por ACL. Se conserva exportada porque es API publica del kit desde el primer release.\n */\nexport function canUserViewWidget(userRoles: string[], widgetRoles: string[]): boolean {\n  if (widgetRoles.length === 0) return true;\n  return userRoles.some(role => widgetRoles.includes(role));\n}\n\n/** Lo que el widget del catalogo necesita traer para resolver sus verbos. */\ntype WidgetAccessShape = Pick<WidgetDefinition, 'permissions' | 'roles_permitidos' | 'propietario_id'>;\n\n/** El contexto del usuario, que **solo** se usa cuando el servidor no dijo nada. */\nexport interface WidgetPermissionsFallback {\n  userRoles: string[];\n  /** Si el usuario administra el catalogo. En el kit venia de `userRoles.includes('admin')`. */\n  isAdmin: boolean;\n}\n\n/**\n * Los cuatro verbos del usuario sobre un widget, **con el servidor primero**.\n *\n * ## Por que existe\n *\n * El kit tenia dos criterios de acceso corriendo a la vez: el backend filtraba el catalogo por su\n * regla de instancia (ACL ∩ RBAC) y el kit lo volvia a filtrar por su cuenta con\n * `canUserViewWidget(userRoles, roles_permitidos)`. Ese segundo filtro es un OR de roles, asi que\n * podia hacer dos cosas, las dos malas:\n *\n * - **Esconder** un widget que el servidor si concedio — el caso de compartir una instancia con una\n *   persona que no tiene el modulo del widget: el backend lo manda en el catalogo, el kit lo tira\n *   por no cruzar roles, y la persona con quien se compartio no lo ve nunca. Sin error ni log.\n * - **Mostrar** acciones que el servidor va a rechazar, porque `isAdmin` era global: el boton de\n *   borrar aparecia para todo widget con dueño, sin importar la ACL de esa fila.\n *\n * ## La regla\n *\n * Si el widget trae `permissions`, se usan **tal cual y sin mezclar**: son la decision del servidor,\n * que ya compuso capacidad (RBAC) ∩ grant de instancia (ACL). Ni se amplian con `isAdmin` ni se\n * recortan con los roles — cualquiera de las dos cosas reintroduce el segundo criterio.\n *\n * Si no los trae, se cae al comportamiento historico. Eso es lo que mantiene funcionando a un host\n * con backend viejo, y es deliberado que el respaldo sea *identico* a lo de antes y no algo mas\n * seguro: cerrar por defecto aqui vaciaria el catalogo de esos hosts en una subida de version de\n * parche.\n */\nexport function resolveWidgetPermissions(\n  widget: WidgetAccessShape,\n  fallback: WidgetPermissionsFallback,\n): WidgetPermissions {\n  if (widget.permissions) return widget.permissions;\n\n  // Un widget sin dueño es sembrado: el catalogo del tenant lo comparte todo el mundo y borrarlo\n  // no tiene papelera. Es la misma condicion que el panel evaluaba como `!isSeed && isAdmin`.\n  const esSembrado = !widget.propietario_id;\n\n  return {\n    can_view: canUserViewWidget(fallback.userRoles, widget.roles_permitidos ?? []),\n    can_edit: fallback.isAdmin,\n    can_delete: fallback.isAdmin && !esSembrado,\n    // Compartir por instancia no existia antes de que el servidor lo resolviera: sin `permissions`\n    // no hay a quien preguntar, y afirmarlo pintaria un dialogo contra un API que el host no tiene.\n    can_share: false,\n    // La exposicion la movia el administrador -y solo el: el backend forzaba privado a los demas al\n    // crear-, asi que el respaldo es `isAdmin` a secas.\n    can_publish: fallback.isAdmin,\n  };\n}\n","import { useState, useEffect } from 'react';\nimport type { WidgetDefinition, UserWidgetPreference, DashboardPeriod, DashboardFetcher } from '../types';\nimport { getCatalogWidgets } from '../api/dashboardCatalog';\nimport { getUserLayout } from '../api/dashboardLayout';\nimport { resolveWidgetPermissions } from '../ability';\n\ninterface UseWidgetEngineProps {\n  userId: string;\n  userRoles: string[];\n  fetcher: DashboardFetcher;\n  /**\n   * Si el usuario administra el catalogo. **Solo se usa como respaldo** cuando el backend no manda\n   * `permissions` en el DTO del widget. Ver `resolveWidgetPermissions`.\n   */\n  isAdmin?: boolean;\n}\n\n/**\n * Motor central de orquestación.\n * Obtiene el Catálogo de Widgets disponibles para el usuario y el Layout guardado.\n * Gestiona el estado global de la vista (periodo de fecha actual y modo de edición).\n */\nexport const useWidgetEngine = ({ userId, userRoles, fetcher, isAdmin = false }: UseWidgetEngineProps) => {\n  const [catalog, setCatalog] = useState<WidgetDefinition[]>([]);\n  const [initialLayout, setInitialLayout] = useState<UserWidgetPreference[]>([]);\n  \n  // Estado de la UI\n  const [isLoading, setIsLoading] = useState(true);\n  const [initError, setInitError] = useState<string | null>(null);\n  const [isEditMode, setIsEditMode] = useState(false);\n  const [period, setPeriod] = useState<DashboardPeriod>('Mes');\n\n  // Inicialización (Traer catálogo y preferencias)\n  useEffect(() => {\n    let isMounted = true;\n\n    const initEngine = async () => {\n      setIsLoading(true);\n      try {\n        // Ejecutamos ambas peticiones en paralelo\n        const [catalogData, layoutData] = await Promise.all([\n          getCatalogWidgets(fetcher),\n          getUserLayout(userId, fetcher)\n        ]);\n\n        if (isMounted) {\n          /**\n           * El catalogo llega YA filtrado por el servidor cuando el host evalua acceso por\n           * instancia, y entonces `can_view` es siempre `true` en lo que llega: este filtro no\n           * quita nada y esta bien que no quite nada. Lo que importa es que ya **no** se aplica el\n           * OR de roles encima, que era lo que escondia un widget compartido con alguien que no\n           * tiene su modulo. Sin `permissions`, el respaldo reproduce el filtro historico.\n           */\n          setCatalog(\n            catalogData.filter(w => resolveWidgetPermissions(w, { userRoles, isAdmin }).can_view),\n          );\n          setInitialLayout(layoutData);\n        }\n      } catch (e) {\n        const message = e instanceof Error ? e.message : 'Error desconocido al cargar el dashboard';\n        console.error('[KPI Dashboard] Error al inicializar el motor de widgets:', e);\n        if (isMounted) setInitError(message);\n      } finally {\n        if (isMounted) {\n          setIsLoading(false);\n        }\n      }\n    };\n\n    initEngine();\n\n    return () => {\n      isMounted = false;\n    };\n  }, [userId, fetcher]);\n\n  const toggleEditMode = () => setIsEditMode(prev => !prev);\n  \n  const handlePeriodChange = (newPeriod: DashboardPeriod) => {\n    setPeriod(newPeriod);\n    // Cambiar este estado forzará un re-render en cascada a los componentes,\n    // inyectando el nuevo 'period' en sus props y forzando a TanStack Query a buscar nuevos datos.\n  };\n\n  /**\n   * Helper para obtener la definición completa de un widget dado su ID\n   */\n  const getWidgetDefinition = (widgetId: string): WidgetDefinition | undefined => {\n    return catalog.find(w => w.widget_id === widgetId);\n  };\n\n  /**\n   * Agrega un widget recién creado (via Builder) al catálogo local\n   * sin necesidad de refetch completo desde el backend.\n   */\n  const addToCatalog = (widget: WidgetDefinition) => {\n    setCatalog(prev => [...prev, widget]);\n  };\n\n  /**\n   * Actualiza un widget existente en el catálogo local (tras edición via Builder).\n   */\n  const updateInCatalog = (updated: WidgetDefinition) => {\n    setCatalog(prev => prev.map(w => w.widget_id === updated.widget_id ? updated : w));\n  };\n\n  /**\n   * Elimina un widget del catálogo local (tras DELETE en backend).\n   */\n  const removeFromCatalog = (widgetId: string) => {\n    setCatalog(prev => prev.filter(w => w.widget_id !== widgetId));\n  };\n\n  return {\n    catalog,\n    initialLayout,\n    isLoading,\n    initError,\n    // UI State\n    isEditMode,\n    toggleEditMode,\n    period,\n    setPeriod: handlePeriodChange,\n    // Helpers\n    getWidgetDefinition,\n    addToCatalog,\n    updateInCatalog,\n    removeFromCatalog,\n  };\n};\n","import { useState, useEffect, useRef } from 'react';\nimport type { UserWidgetPreferenceBase } from '../types';\n\ninterface UseOptimisticLayoutProps<TPreference extends UserWidgetPreferenceBase> {\n  initialLayout: TPreference[];\n  saveLayout: (layout: TPreference[]) => Promise<void>;\n  debounceMs?: number;\n  /** Clave de localStorage para persistir el layout como respaldo local */\n  storageKey?: string;\n}\n\n/** Lee el layout desde localStorage. Devuelve null si no hay nada o el JSON está corrupto. */\nfunction readFromStorage<T>(key: string): T[] | null {\n  try {\n    const raw = localStorage.getItem(key);\n    if (!raw) return null;\n    const parsed = JSON.parse(raw) as T[];\n    return Array.isArray(parsed) && parsed.length > 0 ? parsed : null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Hook genérico responsable de mantener el estado local del Grid y sincronizarlo\n * con un callback de guardado (saveLayout) aplicando un debounce estricto.\n * Si se provee `storageKey`, persiste el layout en localStorage como respaldo ante\n * cierres de pestaña antes de que complete el debounce.\n */\nexport const useOptimisticLayout = <TPreference extends UserWidgetPreferenceBase>({\n  initialLayout,\n  saveLayout,\n  debounceMs = 800,\n  storageKey\n}: UseOptimisticLayoutProps<TPreference>) => {\n  const [layout, setLayout] = useState<TPreference[]>(() => {\n    if (storageKey) {\n      const saved = readFromStorage<TPreference>(storageKey);\n      if (saved) return saved;\n    }\n    return initialLayout;\n  });\n  const [isSaving, setIsSaving] = useState(false);\n\n  // Sincronizar layout local cuando initialLayout cambia (ej: cambio de usuario/roles)\n  const prevInitialRef = useRef(initialLayout);\n  useEffect(() => {\n    if (JSON.stringify(prevInitialRef.current) !== JSON.stringify(initialLayout)) {\n      prevInitialRef.current = initialLayout;\n      setLayout(initialLayout);\n    }\n  }, [initialLayout]);\n\n  // useRef para mantener una copia fresca del layout sin disparar re-renders en el efecto\n  const layoutToSaveRef = useRef<TPreference[]>(layout);\n  // Flag para omitir el guardado en el montaje inicial\n  const isFirstRender = useRef(true);\n\n  useEffect(() => {\n    layoutToSaveRef.current = layout;\n  }, [layout]);\n\n  // Persistencia en localStorage ante cada cambio (respaldo local inmediato)\n  useEffect(() => {\n    if (!storageKey) return;\n    try {\n      localStorage.setItem(storageKey, JSON.stringify(layout));\n    } catch {\n      // Ignorar errores de cuota\n    }\n  }, [layout, storageKey]);\n\n  // Debounce → REST (omite el primer render para no guardar en montaje)\n  useEffect(() => {\n    if (isFirstRender.current) {\n      isFirstRender.current = false;\n      return;\n    }\n\n    const timer = setTimeout(async () => {\n      setIsSaving(true);\n      try {\n        await saveLayout(layoutToSaveRef.current);\n      } catch (error) {\n        console.error('Error auto-guardando layout:', error);\n      } finally {\n        setIsSaving(false);\n      }\n    }, debounceMs);\n\n    return () => {\n      clearTimeout(timer);\n    };\n  }, [layout, debounceMs, saveLayout]);\n\n  /**\n   * Actualiza el estado local inmediatamente (Optimistic UI)\n   */\n  const updateLayout = (newLayout: TPreference[]) => {\n    setLayout(newLayout);\n  };\n\n  return {\n    layout,\n    updateLayout,\n    isSaving\n  };\n};\n","import { useCallback } from 'react';\nimport type { UserWidgetPreference, LayoutUpdatePayload, DashboardPeriod, DashboardFetcher } from '../types';\nimport { saveUserLayout } from '../api/dashboardLayout';\nimport { useOptimisticLayout } from '../../components/DashboardEngine/hooks/useOptimisticLayout';\n\ninterface UseDashboardLayoutProps {\n  userId: string;\n  initialLayout: UserWidgetPreference[];\n  period: DashboardPeriod;\n  fetcher: DashboardFetcher;\n}\n\nexport const useDashboardLayout = ({ userId, initialLayout, period, fetcher }: UseDashboardLayoutProps) => {\n  const saveLayout = useCallback(async (currentLayout: UserWidgetPreference[]) => {\n    const payload: LayoutUpdatePayload = {\n      userId,\n      period,\n      layout: currentLayout\n    };\n    await saveUserLayout(payload, fetcher);\n  }, [userId, period, fetcher]);\n\n  return useOptimisticLayout<UserWidgetPreference>({\n    initialLayout,\n    saveLayout,\n    debounceMs: 800,\n    storageKey: `dashboard_layout_${userId}`\n  });\n};\n","// src/core/calculate.ts\nfunction calcGridColWidth(positionParams) {\n  const { margin, containerPadding, containerWidth, cols } = positionParams;\n  return (containerWidth - margin[0] * (cols - 1) - containerPadding[0] * 2) / cols;\n}\nfunction calcGridItemWHPx(gridUnits, colOrRowSize, marginPx) {\n  if (!Number.isFinite(gridUnits)) return gridUnits;\n  return Math.round(\n    colOrRowSize * gridUnits + Math.max(0, gridUnits - 1) * marginPx\n  );\n}\nfunction calcGridItemPosition(positionParams, x, y, w, h, dragPosition, resizePosition) {\n  const { margin, containerPadding, rowHeight } = positionParams;\n  const colWidth = calcGridColWidth(positionParams);\n  let width;\n  let height;\n  let top;\n  let left;\n  if (resizePosition) {\n    width = Math.round(resizePosition.width);\n    height = Math.round(resizePosition.height);\n  } else {\n    width = calcGridItemWHPx(w, colWidth, margin[0]);\n    height = calcGridItemWHPx(h, rowHeight, margin[1]);\n  }\n  if (dragPosition) {\n    top = Math.round(dragPosition.top);\n    left = Math.round(dragPosition.left);\n  } else if (resizePosition) {\n    top = Math.round(resizePosition.top);\n    left = Math.round(resizePosition.left);\n  } else {\n    top = Math.round((rowHeight + margin[1]) * y + containerPadding[1]);\n    left = Math.round((colWidth + margin[0]) * x + containerPadding[0]);\n  }\n  if (!dragPosition && !resizePosition) {\n    if (Number.isFinite(w)) {\n      const siblingLeft = Math.round(\n        (colWidth + margin[0]) * (x + w) + containerPadding[0]\n      );\n      const actualMarginRight = siblingLeft - left - width;\n      if (actualMarginRight !== margin[0]) {\n        width += actualMarginRight - margin[0];\n      }\n    }\n    if (Number.isFinite(h)) {\n      const siblingTop = Math.round(\n        (rowHeight + margin[1]) * (y + h) + containerPadding[1]\n      );\n      const actualMarginBottom = siblingTop - top - height;\n      if (actualMarginBottom !== margin[1]) {\n        height += actualMarginBottom - margin[1];\n      }\n    }\n  }\n  return { top, left, width, height };\n}\nfunction calcXY(positionParams, top, left, w, h) {\n  const { margin, containerPadding, cols, rowHeight, maxRows } = positionParams;\n  const colWidth = calcGridColWidth(positionParams);\n  let x = Math.round((left - containerPadding[0]) / (colWidth + margin[0]));\n  let y = Math.round((top - containerPadding[1]) / (rowHeight + margin[1]));\n  x = clamp(x, 0, cols - w);\n  y = clamp(y, 0, maxRows - h);\n  return { x, y };\n}\nfunction calcXYRaw(positionParams, top, left) {\n  const { margin, containerPadding, rowHeight } = positionParams;\n  const colWidth = calcGridColWidth(positionParams);\n  const x = Math.round((left - containerPadding[0]) / (colWidth + margin[0]));\n  const y = Math.round((top - containerPadding[1]) / (rowHeight + margin[1]));\n  return { x, y };\n}\nfunction calcWH(positionParams, width, height, x, y, handle) {\n  const { margin, maxRows, cols, rowHeight } = positionParams;\n  const colWidth = calcGridColWidth(positionParams);\n  const w = Math.round((width + margin[0]) / (colWidth + margin[0]));\n  const h = Math.round((height + margin[1]) / (rowHeight + margin[1]));\n  let _w = clamp(w, 0, cols - x);\n  let _h = clamp(h, 0, maxRows - y);\n  if (handle === \"sw\" || handle === \"w\" || handle === \"nw\") {\n    _w = clamp(w, 0, cols);\n  }\n  if (handle === \"nw\" || handle === \"n\" || handle === \"ne\") {\n    _h = clamp(h, 0, maxRows);\n  }\n  return { w: _w, h: _h };\n}\nfunction calcWHRaw(positionParams, width, height) {\n  const { margin, rowHeight } = positionParams;\n  const colWidth = calcGridColWidth(positionParams);\n  const w = Math.max(\n    1,\n    Math.round((width + margin[0]) / (colWidth + margin[0]))\n  );\n  const h = Math.max(\n    1,\n    Math.round((height + margin[1]) / (rowHeight + margin[1]))\n  );\n  return { w, h };\n}\nfunction clamp(num, lowerBound, upperBound) {\n  return Math.max(Math.min(num, upperBound), lowerBound);\n}\nfunction calcGridCellDimensions(config) {\n  const {\n    width,\n    cols,\n    rowHeight,\n    margin = [10, 10],\n    containerPadding\n  } = config;\n  const padding = containerPadding ?? margin;\n  const cellWidth = (width - padding[0] * 2 - margin[0] * (cols - 1)) / cols;\n  const cellHeight = rowHeight;\n  return {\n    cellWidth,\n    cellHeight,\n    offsetX: padding[0],\n    offsetY: padding[1],\n    gapX: margin[0],\n    gapY: margin[1],\n    cols,\n    containerWidth: width\n  };\n}\n\n// src/core/collision.ts\nfunction collides(l1, l2) {\n  if (l1.i === l2.i) return false;\n  if (l1.x + l1.w <= l2.x) return false;\n  if (l1.x >= l2.x + l2.w) return false;\n  if (l1.y + l1.h <= l2.y) return false;\n  if (l1.y >= l2.y + l2.h) return false;\n  return true;\n}\nfunction getFirstCollision(layout, layoutItem) {\n  for (let i = 0; i < layout.length; i++) {\n    const item = layout[i];\n    if (item !== void 0 && collides(item, layoutItem)) {\n      return item;\n    }\n  }\n  return void 0;\n}\nfunction getAllCollisions(layout, layoutItem) {\n  return layout.filter((l) => collides(l, layoutItem));\n}\n\n// src/core/sort.ts\nfunction sortLayoutItems(layout, compactType) {\n  if (compactType === \"horizontal\") {\n    return sortLayoutItemsByColRow(layout);\n  }\n  if (compactType === \"vertical\") {\n    return sortLayoutItemsByRowCol(layout);\n  }\n  if (compactType === \"wrap\") {\n    return sortLayoutItemsByRowCol(layout);\n  }\n  return [...layout];\n}\nfunction sortLayoutItemsByRowCol(layout) {\n  return [...layout].sort((a, b) => {\n    if (a.y !== b.y) {\n      return a.y - b.y;\n    }\n    return a.x - b.x;\n  });\n}\nfunction sortLayoutItemsByColRow(layout) {\n  return [...layout].sort((a, b) => {\n    if (a.x !== b.x) {\n      return a.x - b.x;\n    }\n    return a.y - b.y;\n  });\n}\n\n// src/core/layout.ts\nfunction bottom(layout) {\n  let max = 0;\n  for (let i = 0; i < layout.length; i++) {\n    const item = layout[i];\n    if (item !== void 0) {\n      const bottomY = item.y + item.h;\n      if (bottomY > max) max = bottomY;\n    }\n  }\n  return max;\n}\nfunction getLayoutItem(layout, id) {\n  for (let i = 0; i < layout.length; i++) {\n    const item = layout[i];\n    if (item !== void 0 && item.i === id) {\n      return item;\n    }\n  }\n  return void 0;\n}\nfunction getStatics(layout) {\n  return layout.filter((l) => l.static === true);\n}\nfunction cloneLayoutItem(layoutItem) {\n  return {\n    i: layoutItem.i,\n    x: layoutItem.x,\n    y: layoutItem.y,\n    w: layoutItem.w,\n    h: layoutItem.h,\n    minW: layoutItem.minW,\n    maxW: layoutItem.maxW,\n    minH: layoutItem.minH,\n    maxH: layoutItem.maxH,\n    moved: Boolean(layoutItem.moved),\n    static: Boolean(layoutItem.static),\n    isDraggable: layoutItem.isDraggable,\n    isResizable: layoutItem.isResizable,\n    resizeHandles: layoutItem.resizeHandles,\n    constraints: layoutItem.constraints,\n    isBounded: layoutItem.isBounded\n  };\n}\nfunction cloneLayout(layout) {\n  const newLayout = new Array(layout.length);\n  for (let i = 0; i < layout.length; i++) {\n    const item = layout[i];\n    if (item !== void 0) {\n      newLayout[i] = cloneLayoutItem(item);\n    }\n  }\n  return newLayout;\n}\nfunction modifyLayout(layout, layoutItem) {\n  const newLayout = new Array(layout.length);\n  for (let i = 0; i < layout.length; i++) {\n    const item = layout[i];\n    if (item !== void 0) {\n      if (layoutItem.i === item.i) {\n        newLayout[i] = layoutItem;\n      } else {\n        newLayout[i] = item;\n      }\n    }\n  }\n  return newLayout;\n}\nfunction withLayoutItem(layout, itemKey, cb) {\n  let item = getLayoutItem(layout, itemKey);\n  if (!item) {\n    return [[...layout], null];\n  }\n  item = cb(cloneLayoutItem(item));\n  const newLayout = modifyLayout(layout, item);\n  return [newLayout, item];\n}\nfunction correctBounds(layout, bounds) {\n  const collidesWith = getStatics(layout);\n  for (let i = 0; i < layout.length; i++) {\n    const l = layout[i];\n    if (l === void 0) continue;\n    if (l.x + l.w > bounds.cols) {\n      l.x = bounds.cols - l.w;\n    }\n    if (l.x < 0) {\n      l.x = 0;\n      l.w = bounds.cols;\n    }\n    if (!l.static) {\n      collidesWith.push(l);\n    } else {\n      while (getFirstCollision(collidesWith, l)) {\n        l.y++;\n      }\n    }\n  }\n  return layout;\n}\nfunction moveElement(layout, l, x, y, isUserAction, preventCollision, compactType, cols, allowOverlap) {\n  if (l.static && l.isDraggable !== true) {\n    return [...layout];\n  }\n  if (l.y === y && l.x === x) {\n    return [...layout];\n  }\n  const oldX = l.x;\n  const oldY = l.y;\n  if (typeof x === \"number\") l.x = x;\n  if (typeof y === \"number\") l.y = y;\n  l.moved = true;\n  let sorted = sortLayoutItems(layout, compactType);\n  const movingUp = compactType === \"vertical\" && typeof y === \"number\" ? oldY >= y : compactType === \"horizontal\" && typeof x === \"number\" ? oldX >= x : false;\n  if (movingUp) {\n    sorted = sorted.reverse();\n  }\n  const collisions = getAllCollisions(sorted, l);\n  const hasCollisions = collisions.length > 0;\n  if (hasCollisions && allowOverlap) {\n    return cloneLayout(layout);\n  }\n  if (hasCollisions && preventCollision) {\n    l.x = oldX;\n    l.y = oldY;\n    l.moved = false;\n    return layout;\n  }\n  let resultLayout = [...layout];\n  for (let i = 0; i < collisions.length; i++) {\n    const collision = collisions[i];\n    if (collision === void 0) continue;\n    if (collision.moved) continue;\n    if (collision.static) {\n      resultLayout = moveElementAwayFromCollision(\n        resultLayout,\n        collision,\n        l,\n        isUserAction,\n        compactType);\n    } else {\n      resultLayout = moveElementAwayFromCollision(\n        resultLayout,\n        l,\n        collision,\n        isUserAction,\n        compactType);\n    }\n  }\n  return resultLayout;\n}\nfunction moveElementAwayFromCollision(layout, collidesWith, itemToMove, isUserAction, compactType, cols) {\n  const compactH = compactType === \"horizontal\";\n  const compactV = compactType === \"vertical\";\n  const preventCollision = collidesWith.static;\n  if (isUserAction) {\n    isUserAction = false;\n    const fakeItem = {\n      x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,\n      y: compactV ? Math.max(collidesWith.y - itemToMove.h, 0) : itemToMove.y,\n      w: itemToMove.w,\n      h: itemToMove.h,\n      i: \"-1\"\n    };\n    const firstCollision = getFirstCollision(layout, fakeItem);\n    const collisionNorth = firstCollision !== void 0 && firstCollision.y + firstCollision.h > collidesWith.y;\n    const collisionWest = firstCollision !== void 0 && collidesWith.x + collidesWith.w > firstCollision.x;\n    if (!firstCollision) {\n      return moveElement(\n        layout,\n        itemToMove,\n        compactH ? fakeItem.x : void 0,\n        compactV ? fakeItem.y : void 0,\n        isUserAction,\n        preventCollision,\n        compactType);\n    }\n    if (collisionNorth && compactV) {\n      return moveElement(\n        layout,\n        itemToMove,\n        void 0,\n        itemToMove.y + 1,\n        isUserAction,\n        preventCollision,\n        compactType);\n    }\n    if (collisionNorth && compactType === null) {\n      collidesWith.y = itemToMove.y;\n      itemToMove.y = itemToMove.y + itemToMove.h;\n      return [...layout];\n    }\n    if (collisionWest && compactH) {\n      return moveElement(\n        layout,\n        collidesWith,\n        itemToMove.x,\n        void 0,\n        isUserAction,\n        preventCollision,\n        compactType);\n    }\n  }\n  const newX = compactH ? itemToMove.x + 1 : void 0;\n  const newY = compactV ? itemToMove.y + 1 : void 0;\n  if (newX === void 0 && newY === void 0) {\n    return [...layout];\n  }\n  return moveElement(\n    layout,\n    itemToMove,\n    newX,\n    newY,\n    isUserAction,\n    preventCollision,\n    compactType);\n}\nfunction validateLayout(layout, contextName = \"Layout\") {\n  const requiredProps = [\"x\", \"y\", \"w\", \"h\"];\n  if (!Array.isArray(layout)) {\n    throw new Error(`${contextName} must be an array!`);\n  }\n  for (let i = 0; i < layout.length; i++) {\n    const item = layout[i];\n    if (item === void 0) continue;\n    for (const key of requiredProps) {\n      const value = item[key];\n      if (typeof value !== \"number\" || Number.isNaN(value)) {\n        throw new Error(\n          `ReactGridLayout: ${contextName}[${i}].${key} must be a number! Received: ${String(value)} (${typeof value})`\n        );\n      }\n    }\n    if (item.i !== void 0 && typeof item.i !== \"string\") {\n      throw new Error(\n        `ReactGridLayout: ${contextName}[${i}].i must be a string! Received: ${String(item.i)} (${typeof item.i})`\n      );\n    }\n  }\n}\n\nexport { bottom, calcGridCellDimensions, calcGridColWidth, calcGridItemPosition, calcGridItemWHPx, calcWH, calcWHRaw, calcXY, calcXYRaw, clamp, cloneLayout, cloneLayoutItem, collides, correctBounds, getAllCollisions, getFirstCollision, getLayoutItem, getStatics, modifyLayout, moveElement, moveElementAwayFromCollision, sortLayoutItems, sortLayoutItemsByColRow, sortLayoutItemsByRowCol, validateLayout, withLayoutItem };\n","import { getStatics, collides, getFirstCollision, bottom, sortLayoutItemsByRowCol, cloneLayoutItem, sortLayoutItemsByColRow, cloneLayout, correctBounds } from './chunk-76RTO6EO.mjs';\n\n// src/core/constraints.ts\nfunction clamp(value, min, max) {\n  return Math.max(min, Math.min(max, value));\n}\nvar gridBounds = {\n  name: \"gridBounds\",\n  constrainPosition(item, x, y, { cols, maxRows }) {\n    return {\n      x: clamp(x, 0, Math.max(0, cols - item.w)),\n      y: clamp(y, 0, Math.max(0, maxRows - item.h))\n    };\n  },\n  constrainSize(item, w, h, handle, { cols, maxRows }) {\n    const maxW = handle === \"w\" || handle === \"nw\" || handle === \"sw\" ? item.x + item.w : cols - item.x;\n    const maxH = handle === \"n\" || handle === \"nw\" || handle === \"ne\" ? item.y + item.h : maxRows - item.y;\n    return {\n      w: clamp(w, 1, Math.max(1, maxW)),\n      h: clamp(h, 1, Math.max(1, maxH))\n    };\n  }\n};\nvar minMaxSize = {\n  name: \"minMaxSize\",\n  constrainSize(item, w, h) {\n    return {\n      w: clamp(w, item.minW ?? 1, item.maxW ?? Infinity),\n      h: clamp(h, item.minH ?? 1, item.maxH ?? Infinity)\n    };\n  }\n};\nvar containerBounds = {\n  name: \"containerBounds\",\n  constrainPosition(item, x, y, { cols, maxRows, containerHeight, rowHeight, margin }) {\n    const visibleRows = containerHeight > 0 ? Math.floor((containerHeight + margin[1]) / (rowHeight + margin[1])) : maxRows;\n    return {\n      x: clamp(x, 0, Math.max(0, cols - item.w)),\n      y: clamp(y, 0, Math.max(0, visibleRows - item.h))\n    };\n  }\n};\nvar boundedX = {\n  name: \"boundedX\",\n  constrainPosition(item, x, y, { cols }) {\n    return {\n      x: clamp(x, 0, Math.max(0, cols - item.w)),\n      y\n    };\n  }\n};\nvar boundedY = {\n  name: \"boundedY\",\n  constrainPosition(item, x, y, { maxRows }) {\n    return {\n      x,\n      y: clamp(y, 0, Math.max(0, maxRows - item.h))\n    };\n  }\n};\nfunction aspectRatio(ratio) {\n  return {\n    name: `aspectRatio(${ratio})`,\n    constrainSize(_item, w, _h, _handle, context) {\n      const { cols, containerWidth, rowHeight, margin } = context;\n      const colWidth = (containerWidth - margin[0] * (cols - 1)) / cols;\n      const pixelWidth = colWidth * w + margin[0] * Math.max(0, w - 1);\n      const pixelHeight = pixelWidth / ratio;\n      const h = Math.max(\n        1,\n        Math.round((pixelHeight + margin[1]) / (rowHeight + margin[1]))\n      );\n      return { w, h };\n    }\n  };\n}\nfunction snapToGrid(stepX, stepY = stepX) {\n  if (stepX <= 0 || stepY <= 0) {\n    throw new Error(\n      `snapToGrid: step values must be positive (got stepX=${stepX}, stepY=${stepY})`\n    );\n  }\n  return {\n    name: `snapToGrid(${stepX}, ${stepY})`,\n    constrainPosition(_item, x, y) {\n      return {\n        x: Math.round(x / stepX) * stepX,\n        y: Math.round(y / stepY) * stepY\n      };\n    }\n  };\n}\nfunction minSize(minW, minH) {\n  return {\n    name: `minSize(${minW}, ${minH})`,\n    constrainSize(_item, w, h) {\n      return {\n        w: Math.max(minW, w),\n        h: Math.max(minH, h)\n      };\n    }\n  };\n}\nfunction maxSize(maxW, maxH) {\n  return {\n    name: `maxSize(${maxW}, ${maxH})`,\n    constrainSize(_item, w, h) {\n      return {\n        w: Math.min(maxW, w),\n        h: Math.min(maxH, h)\n      };\n    }\n  };\n}\nvar defaultConstraints = [gridBounds, minMaxSize];\nfunction applyPositionConstraints(constraints, item, x, y, context) {\n  let result = { x, y };\n  for (const constraint of constraints) {\n    if (constraint.constrainPosition) {\n      result = constraint.constrainPosition(item, result.x, result.y, context);\n    }\n  }\n  if (item.constraints) {\n    for (const constraint of item.constraints) {\n      if (constraint.constrainPosition) {\n        result = constraint.constrainPosition(\n          item,\n          result.x,\n          result.y,\n          context\n        );\n      }\n    }\n  }\n  return result;\n}\nfunction applySizeConstraints(constraints, item, w, h, handle, context) {\n  let result = { w, h };\n  for (const constraint of constraints) {\n    if (constraint.constrainSize) {\n      result = constraint.constrainSize(\n        item,\n        result.w,\n        result.h,\n        handle,\n        context\n      );\n    }\n  }\n  if (item.constraints) {\n    for (const constraint of item.constraints) {\n      if (constraint.constrainSize) {\n        result = constraint.constrainSize(\n          item,\n          result.w,\n          result.h,\n          handle,\n          context\n        );\n      }\n    }\n  }\n  return result;\n}\n\n// src/core/position.ts\nfunction setTransform({\n  top,\n  left,\n  width,\n  height\n}) {\n  const translate = `translate(${left}px,${top}px)`;\n  return {\n    transform: translate,\n    WebkitTransform: translate,\n    MozTransform: translate,\n    msTransform: translate,\n    OTransform: translate,\n    width: `${width}px`,\n    height: `${height}px`,\n    position: \"absolute\"\n  };\n}\nfunction setTopLeft({\n  top,\n  left,\n  width,\n  height\n}) {\n  return {\n    top: `${top}px`,\n    left: `${left}px`,\n    width: `${width}px`,\n    height: `${height}px`,\n    position: \"absolute\"\n  };\n}\nfunction perc(num) {\n  return num * 100 + \"%\";\n}\nfunction constrainWidth(left, currentWidth, newWidth, containerWidth) {\n  return left + newWidth > containerWidth ? currentWidth : newWidth;\n}\nfunction constrainHeight(top, currentHeight, newHeight) {\n  return top < 0 ? currentHeight : newHeight;\n}\nfunction constrainLeft(left) {\n  return Math.max(0, left);\n}\nfunction constrainTop(top) {\n  return Math.max(0, top);\n}\nvar resizeNorth = (currentSize, newSize, _containerWidth) => {\n  const { left, height, width } = newSize;\n  const top = currentSize.top - (height - currentSize.height);\n  return {\n    left,\n    width,\n    height: constrainHeight(top, currentSize.height, height),\n    top: constrainTop(top)\n  };\n};\nvar resizeEast = (currentSize, newSize, containerWidth) => {\n  const { top, left, height, width } = newSize;\n  return {\n    top,\n    height,\n    width: constrainWidth(\n      currentSize.left,\n      currentSize.width,\n      width,\n      containerWidth\n    ),\n    left: constrainLeft(left)\n  };\n};\nvar resizeWest = (currentSize, newSize, _containerWidth) => {\n  const { top, height, width } = newSize;\n  const left = currentSize.left + currentSize.width - width;\n  if (left < 0) {\n    return {\n      height,\n      width: currentSize.left + currentSize.width,\n      top: constrainTop(top),\n      left: 0\n    };\n  }\n  return {\n    height,\n    width,\n    top: constrainTop(top),\n    left\n  };\n};\nvar resizeSouth = (currentSize, newSize, _containerWidth) => {\n  const { top, left, height, width } = newSize;\n  return {\n    width,\n    left,\n    height: constrainHeight(top, currentSize.height, height),\n    top: constrainTop(top)\n  };\n};\nvar resizeNorthEast = (currentSize, newSize, containerWidth) => resizeNorth(\n  currentSize,\n  resizeEast(currentSize, newSize, containerWidth));\nvar resizeNorthWest = (currentSize, newSize, containerWidth) => resizeNorth(\n  currentSize,\n  resizeWest(currentSize, newSize));\nvar resizeSouthEast = (currentSize, newSize, containerWidth) => resizeSouth(\n  currentSize,\n  resizeEast(currentSize, newSize, containerWidth));\nvar resizeSouthWest = (currentSize, newSize, containerWidth) => resizeSouth(\n  currentSize,\n  resizeWest(currentSize, newSize));\nvar resizeHandlerMap = {\n  n: resizeNorth,\n  ne: resizeNorthEast,\n  e: resizeEast,\n  se: resizeSouthEast,\n  s: resizeSouth,\n  sw: resizeSouthWest,\n  w: resizeWest,\n  nw: resizeNorthWest\n};\nfunction resizeItemInDirection(direction, currentSize, newSize, containerWidth) {\n  const handler = resizeHandlerMap[direction];\n  if (!handler) {\n    return newSize;\n  }\n  return handler(currentSize, { ...currentSize, ...newSize }, containerWidth);\n}\nvar transformStrategy = {\n  type: \"transform\",\n  scale: 1,\n  calcStyle(pos) {\n    return setTransform(pos);\n  }\n};\nvar absoluteStrategy = {\n  type: \"absolute\",\n  scale: 1,\n  calcStyle(pos) {\n    return setTopLeft(pos);\n  }\n};\nfunction createScaledStrategy(scale) {\n  return {\n    type: \"transform\",\n    scale,\n    calcStyle(pos) {\n      return setTransform(pos);\n    },\n    calcDragPosition(clientX, clientY, offsetX, offsetY) {\n      return {\n        left: (clientX - offsetX) / scale,\n        top: (clientY - offsetY) / scale\n      };\n    }\n  };\n}\nvar defaultPositionStrategy = transformStrategy;\n\n// src/core/types.ts\nvar defaultGridConfig = {\n  cols: 12,\n  rowHeight: 150,\n  margin: [10, 10],\n  containerPadding: null,\n  maxRows: Infinity\n};\nvar defaultDragConfig = {\n  enabled: true,\n  bounded: false,\n  threshold: 3\n};\nvar defaultResizeConfig = {\n  enabled: true,\n  handles: [\"se\"]\n};\nvar defaultDropConfig = {\n  enabled: false,\n  defaultItem: { w: 1, h: 1 }\n};\n\n// src/core/compactors.ts\nfunction resolveCompactionCollision(layout, item, moveToCoord, axis, hasStatics) {\n  const sizeProp = axis === \"x\" ? \"w\" : \"h\";\n  item[axis] += 1;\n  const itemIndex = layout.findIndex((l) => l.i === item.i);\n  const layoutHasStatics = hasStatics ?? getStatics(layout).length > 0;\n  for (let i = itemIndex + 1; i < layout.length; i++) {\n    const otherItem = layout[i];\n    if (otherItem === void 0) continue;\n    if (otherItem.static) continue;\n    if (!layoutHasStatics && otherItem.y > item.y + item.h) break;\n    if (collides(item, otherItem)) {\n      resolveCompactionCollision(\n        layout,\n        otherItem,\n        moveToCoord + item[sizeProp],\n        axis,\n        layoutHasStatics\n      );\n    }\n  }\n  item[axis] = moveToCoord;\n}\nfunction compactItemVertical(compareWith, l, fullLayout, maxY) {\n  l.x = Math.max(l.x, 0);\n  l.y = Math.max(l.y, 0);\n  l.y = Math.min(maxY, l.y);\n  while (l.y > 0 && !getFirstCollision(compareWith, l)) {\n    l.y--;\n  }\n  let collision;\n  while ((collision = getFirstCollision(compareWith, l)) !== void 0) {\n    resolveCompactionCollision(fullLayout, l, collision.y + collision.h, \"y\");\n  }\n  l.y = Math.max(l.y, 0);\n  return l;\n}\nfunction compactItemHorizontal(compareWith, l, cols, fullLayout) {\n  l.x = Math.max(l.x, 0);\n  l.y = Math.max(l.y, 0);\n  while (l.x > 0 && !getFirstCollision(compareWith, l)) {\n    l.x--;\n  }\n  let collision;\n  while ((collision = getFirstCollision(compareWith, l)) !== void 0) {\n    resolveCompactionCollision(fullLayout, l, collision.x + collision.w, \"x\");\n    if (l.x + l.w > cols) {\n      l.x = cols - l.w;\n      l.y++;\n      while (l.x > 0 && !getFirstCollision(compareWith, l)) {\n        l.x--;\n      }\n    }\n  }\n  l.x = Math.max(l.x, 0);\n  return l;\n}\nvar verticalCompactor = {\n  type: \"vertical\",\n  allowOverlap: false,\n  compact(layout, _cols) {\n    const compareWith = getStatics(layout);\n    let maxY = bottom(compareWith);\n    const sorted = sortLayoutItemsByRowCol(layout);\n    const out = new Array(layout.length);\n    for (let i = 0; i < sorted.length; i++) {\n      const sortedItem = sorted[i];\n      if (sortedItem === void 0) continue;\n      let l = cloneLayoutItem(sortedItem);\n      if (!l.static) {\n        l = compactItemVertical(compareWith, l, sorted, maxY);\n        maxY = Math.max(maxY, l.y + l.h);\n        compareWith.push(l);\n      }\n      const originalIndex = layout.indexOf(sortedItem);\n      out[originalIndex] = l;\n      l.moved = false;\n    }\n    return out;\n  }\n};\nvar horizontalCompactor = {\n  type: \"horizontal\",\n  allowOverlap: false,\n  compact(layout, cols) {\n    const compareWith = getStatics(layout);\n    const sorted = sortLayoutItemsByColRow(layout);\n    const out = new Array(layout.length);\n    for (let i = 0; i < sorted.length; i++) {\n      const sortedItem = sorted[i];\n      if (sortedItem === void 0) continue;\n      let l = cloneLayoutItem(sortedItem);\n      if (!l.static) {\n        l = compactItemHorizontal(compareWith, l, cols, sorted);\n        compareWith.push(l);\n      }\n      const originalIndex = layout.indexOf(sortedItem);\n      out[originalIndex] = l;\n      l.moved = false;\n    }\n    return out;\n  }\n};\nvar noCompactor = {\n  type: null,\n  allowOverlap: false,\n  compact(layout, _cols) {\n    return cloneLayout(layout);\n  }\n};\nvar verticalOverlapCompactor = {\n  ...verticalCompactor,\n  allowOverlap: true,\n  compact(layout, _cols) {\n    return cloneLayout(layout);\n  }\n};\nvar horizontalOverlapCompactor = {\n  ...horizontalCompactor,\n  allowOverlap: true,\n  compact(layout, _cols) {\n    return cloneLayout(layout);\n  }\n};\nvar noOverlapCompactor = {\n  ...noCompactor,\n  allowOverlap: true\n};\nfunction getCompactor(compactType, allowOverlap = false, preventCollision = false) {\n  let baseCompactor;\n  if (allowOverlap) {\n    if (compactType === \"vertical\") baseCompactor = verticalOverlapCompactor;\n    else if (compactType === \"horizontal\")\n      baseCompactor = horizontalOverlapCompactor;\n    else baseCompactor = noOverlapCompactor;\n  } else {\n    if (compactType === \"vertical\") baseCompactor = verticalCompactor;\n    else if (compactType === \"horizontal\") baseCompactor = horizontalCompactor;\n    else baseCompactor = noCompactor;\n  }\n  if (preventCollision) {\n    return { ...baseCompactor, preventCollision };\n  }\n  return baseCompactor;\n}\n\n// src/core/responsive.ts\nfunction sortBreakpoints(breakpoints) {\n  const keys = Object.keys(breakpoints);\n  return keys.sort((a, b) => breakpoints[a] - breakpoints[b]);\n}\nfunction getBreakpointFromWidth(breakpoints, width) {\n  const sorted = sortBreakpoints(breakpoints);\n  let matching = sorted[0];\n  if (matching === void 0) {\n    throw new Error(\"No breakpoints defined\");\n  }\n  for (let i = 1; i < sorted.length; i++) {\n    const breakpointName = sorted[i];\n    if (breakpointName === void 0) continue;\n    const breakpointWidth = breakpoints[breakpointName];\n    if (width > breakpointWidth) {\n      matching = breakpointName;\n    }\n  }\n  return matching;\n}\nfunction getColsFromBreakpoint(breakpoint, cols) {\n  const colCount = cols[breakpoint];\n  if (colCount === void 0) {\n    throw new Error(\n      `ResponsiveReactGridLayout: \\`cols\\` entry for breakpoint ${String(breakpoint)} is missing!`\n    );\n  }\n  return colCount;\n}\nfunction findOrGenerateResponsiveLayout(layouts, breakpoints, breakpoint, lastBreakpoint, cols, compactTypeOrCompactor) {\n  const existingLayout = layouts[breakpoint];\n  if (existingLayout) {\n    return cloneLayout(existingLayout);\n  }\n  let layout = layouts[lastBreakpoint];\n  const breakpointsSorted = sortBreakpoints(breakpoints);\n  const breakpointsAbove = breakpointsSorted.slice(\n    breakpointsSorted.indexOf(breakpoint)\n  );\n  for (let i = 0; i < breakpointsAbove.length; i++) {\n    const b = breakpointsAbove[i];\n    if (b === void 0) continue;\n    const layoutForBreakpoint = layouts[b];\n    if (layoutForBreakpoint) {\n      layout = layoutForBreakpoint;\n      break;\n    }\n  }\n  const clonedLayout = cloneLayout(layout || []);\n  const corrected = correctBounds(clonedLayout, { cols });\n  const compactor = typeof compactTypeOrCompactor === \"object\" && compactTypeOrCompactor !== null ? compactTypeOrCompactor : getCompactor(compactTypeOrCompactor);\n  return compactor.compact(corrected, cols);\n}\nfunction getIndentationValue(value, breakpoint) {\n  if (Array.isArray(value)) {\n    return value;\n  }\n  const breakpointMap = value;\n  const breakpointValue = breakpointMap[breakpoint];\n  if (breakpointValue !== void 0) {\n    return breakpointValue;\n  }\n  const keys = Object.keys(breakpointMap);\n  for (const key of keys) {\n    const v = breakpointMap[key];\n    if (v !== void 0) {\n      return v;\n    }\n  }\n  return [10, 10];\n}\n\nexport { absoluteStrategy, applyPositionConstraints, applySizeConstraints, aspectRatio, boundedX, boundedY, compactItemHorizontal, compactItemVertical, containerBounds, createScaledStrategy, defaultConstraints, defaultDragConfig, defaultDropConfig, defaultGridConfig, defaultPositionStrategy, defaultResizeConfig, findOrGenerateResponsiveLayout, getBreakpointFromWidth, getColsFromBreakpoint, getCompactor, getIndentationValue, gridBounds, horizontalCompactor, horizontalOverlapCompactor, maxSize, minMaxSize, minSize, noCompactor, noOverlapCompactor, perc, resizeItemInDirection, resolveCompactionCollision, setTopLeft, setTransform, snapToGrid, sortBreakpoints, transformStrategy, verticalCompactor, verticalOverlapCompactor };\n","/**\r\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\r\n * use inside the built comparator.\r\n */\r\nfunction createDefaultIsNestedEqual(comparator) {\r\n    return function isEqual(a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, meta) {\r\n        return comparator(a, b, meta);\r\n    };\r\n}\r\n/**\r\n * Wrap the provided `areItemsEqual` method to manage the circular cache, allowing\r\n * for circular references to be safely included in the comparison without creating\r\n * stack overflows.\r\n */\r\nfunction createIsCircular(areItemsEqual) {\r\n    return function isCircular(a, b, isEqual, cache) {\r\n        if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\r\n            return areItemsEqual(a, b, isEqual, cache);\r\n        }\r\n        var cachedA = cache.get(a);\r\n        var cachedB = cache.get(b);\r\n        if (cachedA && cachedB) {\r\n            return cachedA === b && cachedB === a;\r\n        }\r\n        cache.set(a, b);\r\n        cache.set(b, a);\r\n        var result = areItemsEqual(a, b, isEqual, cache);\r\n        cache.delete(a);\r\n        cache.delete(b);\r\n        return result;\r\n    };\r\n}\r\n/**\r\n * Targeted shallow merge of two objects.\r\n *\r\n * @NOTE\r\n * This exists as a tinier compiled version of the `__assign` helper that\r\n * `tsc` injects in case of `Object.assign` not being present.\r\n */\r\nfunction merge(a, b) {\r\n    var merged = {};\r\n    for (var key in a) {\r\n        merged[key] = a[key];\r\n    }\r\n    for (var key in b) {\r\n        merged[key] = b[key];\r\n    }\r\n    return merged;\r\n}\r\n/**\r\n * Whether the value is a plain object.\r\n *\r\n * @NOTE\r\n * This is a same-realm compariosn only.\r\n */\r\nfunction isPlainObject(value) {\r\n    return value.constructor === Object || value.constructor == null;\r\n}\r\n/**\r\n * When the value is `Promise`-like, aka \"then-able\".\r\n */\r\nfunction isPromiseLike(value) {\r\n    return typeof value.then === 'function';\r\n}\r\n/**\r\n * Whether the values passed are strictly equal or both NaN.\r\n */\r\nfunction sameValueZeroEqual(a, b) {\r\n    return a === b || (a !== a && b !== b);\r\n}\n\nvar ARGUMENTS_TAG = '[object Arguments]';\r\nvar BOOLEAN_TAG = '[object Boolean]';\r\nvar DATE_TAG = '[object Date]';\r\nvar REG_EXP_TAG = '[object RegExp]';\r\nvar MAP_TAG = '[object Map]';\r\nvar NUMBER_TAG = '[object Number]';\r\nvar OBJECT_TAG = '[object Object]';\r\nvar SET_TAG = '[object Set]';\r\nvar STRING_TAG = '[object String]';\r\nvar toString = Object.prototype.toString;\r\nfunction createComparator(_a) {\r\n    var areArraysEqual = _a.areArraysEqual, areDatesEqual = _a.areDatesEqual, areMapsEqual = _a.areMapsEqual, areObjectsEqual = _a.areObjectsEqual, areRegExpsEqual = _a.areRegExpsEqual, areSetsEqual = _a.areSetsEqual, createIsNestedEqual = _a.createIsNestedEqual;\r\n    var isEqual = createIsNestedEqual(comparator);\r\n    /**\r\n     * compare the value of the two objects and return true if they are equivalent in values\r\n     */\r\n    function comparator(a, b, meta) {\r\n        // If the items are strictly equal, no need to do a value comparison.\r\n        if (a === b) {\r\n            return true;\r\n        }\r\n        // If the items are not non-nullish objects, then the only possibility\r\n        // of them being equal but not strictly is if they are both `NaN`. Since\r\n        // `NaN` is uniquely not equal to itself, we can use self-comparison of\r\n        // both objects, which is faster than `isNaN()`.\r\n        if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\r\n            return a !== a && b !== b;\r\n        }\r\n        // Checks are listed in order of commonality of use-case:\r\n        //   1. Common complex object types (plain object, array)\r\n        //   2. Common data values (date, regexp)\r\n        //   3. Less-common complex object types (map, set)\r\n        //   4. Less-common data values (promise, primitive wrappers)\r\n        // Inherently this is both subjective and assumptive, however\r\n        // when reviewing comparable libraries in the wild this order\r\n        // appears to be generally consistent.\r\n        // `isPlainObject` only checks against the object's own realm. Cross-realm\r\n        // comparisons are rare, and will be handled in the ultimate fallback, so\r\n        // we can avoid the `toString.call()` cost unless necessary.\r\n        if (isPlainObject(a) && isPlainObject(b)) {\r\n            return areObjectsEqual(a, b, isEqual, meta);\r\n        }\r\n        // `isArray()` works on subclasses and is cross-realm, so we can again avoid\r\n        // the `toString.call()` cost unless necessary by just checking if either\r\n        // and then both are arrays.\r\n        var aArray = Array.isArray(a);\r\n        var bArray = Array.isArray(b);\r\n        if (aArray || bArray) {\r\n            return aArray === bArray && areArraysEqual(a, b, isEqual, meta);\r\n        }\r\n        // Since this is a custom object, use the classic `toString.call()` to get its\r\n        // type. This is reasonably performant in modern environments like v8 and\r\n        // SpiderMonkey, and allows for cross-realm comparison when other checks like\r\n        // `instanceof` do not.\r\n        var aTag = toString.call(a);\r\n        if (aTag !== toString.call(b)) {\r\n            return false;\r\n        }\r\n        if (aTag === DATE_TAG) {\r\n            // `getTime()` showed better results compared to alternatives like `valueOf()`\r\n            // or the unary `+` operator.\r\n            return areDatesEqual(a, b, isEqual, meta);\r\n        }\r\n        if (aTag === REG_EXP_TAG) {\r\n            return areRegExpsEqual(a, b, isEqual, meta);\r\n        }\r\n        if (aTag === MAP_TAG) {\r\n            return areMapsEqual(a, b, isEqual, meta);\r\n        }\r\n        if (aTag === SET_TAG) {\r\n            return areSetsEqual(a, b, isEqual, meta);\r\n        }\r\n        // If a simple object tag, then we can prioritize a simple object comparison because\r\n        // it is likely a custom class. If an arguments tag, it should be treated as a standard\r\n        // object.\r\n        if (aTag === OBJECT_TAG || aTag === ARGUMENTS_TAG) {\r\n            // The exception for value comparison is `Promise`-like contracts. These should be\r\n            // treated the same as standard `Promise` objects, which means strict equality.\r\n            return isPromiseLike(a) || isPromiseLike(b)\r\n                ? false\r\n                : areObjectsEqual(a, b, isEqual, meta);\r\n        }\r\n        // As the penultimate fallback, check if the values passed are primitive wrappers. This\r\n        // is very rare in modern JS, which is why it is deprioritized compared to all other object\r\n        // types.\r\n        if (aTag === BOOLEAN_TAG || aTag === NUMBER_TAG || aTag === STRING_TAG) {\r\n            return sameValueZeroEqual(a.valueOf(), b.valueOf());\r\n        }\r\n        // If not matching any tags that require a specific type of comparison, then we hard-code false because\r\n        // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\r\n        //   - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\r\n        //     comparison that can be made.\r\n        //   - For types that can be introspected, but rarely have requirements to be compared\r\n        //     (`ArrayBuffer`, `DataView`, etc.), the cost is avoided to prioritize the common\r\n        //     use-cases (may be included in a future release, if requested enough).\r\n        //   - For types that can be introspected but do not have an objective definition of what\r\n        //     equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\r\n        // In all cases, these decisions should be reevaluated based on changes to the language and\r\n        // common development practices.\r\n        return false;\r\n    }\r\n    return comparator;\r\n}\n\n/**\r\n * Whether the arrays are equal in value.\r\n */\r\nfunction areArraysEqual(a, b, isEqual, meta) {\r\n    var index = a.length;\r\n    if (b.length !== index) {\r\n        return false;\r\n    }\r\n    // Decrementing `while` showed faster results than either incrementing or\r\n    // decrementing `for` loop and than an incrementing `while` loop. Declarative\r\n    // methods like `some` / `every` were not used to avoid incurring the garbage\r\n    // cost of anonymous callbacks.\r\n    while (index-- > 0) {\r\n        if (!isEqual(a[index], b[index], index, index, a, b, meta)) {\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n/**\r\n * Whether the arrays are equal in value, including circular references.\r\n */\r\nvar areArraysEqualCircular = createIsCircular(areArraysEqual);\n\n/**\r\n * Whether the dates passed are equal in value.\r\n *\r\n * @NOTE\r\n * This is a standalone function instead of done inline in the comparator\r\n * to allow for overrides.\r\n */\r\nfunction areDatesEqual(a, b) {\r\n    return sameValueZeroEqual(a.valueOf(), b.valueOf());\r\n}\n\n/**\r\n * Whether the `Map`s are equal in value.\r\n */\r\nfunction areMapsEqual(a, b, isEqual, meta) {\r\n    var isValueEqual = a.size === b.size;\r\n    if (!isValueEqual) {\r\n        return false;\r\n    }\r\n    if (!a.size) {\r\n        return true;\r\n    }\r\n    // The use of `forEach()` is to avoid the transpilation cost of `for...of` comparisons, and\r\n    // the inability to control the performance of the resulting code. It also avoids excessive\r\n    // iteration compared to doing comparisons of `keys()` and `values()`. As a result, though,\r\n    // we cannot short-circuit the iterations; bookkeeping must be done to short-circuit the\r\n    // equality checks themselves.\r\n    var matchedIndices = {};\r\n    var indexA = 0;\r\n    a.forEach(function (aValue, aKey) {\r\n        if (!isValueEqual) {\r\n            return;\r\n        }\r\n        var hasMatch = false;\r\n        var matchIndexB = 0;\r\n        b.forEach(function (bValue, bKey) {\r\n            if (!hasMatch &&\r\n                !matchedIndices[matchIndexB] &&\r\n                (hasMatch =\r\n                    isEqual(aKey, bKey, indexA, matchIndexB, a, b, meta) &&\r\n                        isEqual(aValue, bValue, aKey, bKey, a, b, meta))) {\r\n                matchedIndices[matchIndexB] = true;\r\n            }\r\n            matchIndexB++;\r\n        });\r\n        indexA++;\r\n        isValueEqual = hasMatch;\r\n    });\r\n    return isValueEqual;\r\n}\r\n/**\r\n * Whether the `Map`s are equal in value, including circular references.\r\n */\r\nvar areMapsEqualCircular = createIsCircular(areMapsEqual);\n\nvar OWNER = '_owner';\r\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\r\n/**\r\n * Whether the objects are equal in value.\r\n */\r\nfunction areObjectsEqual(a, b, isEqual, meta) {\r\n    var keysA = Object.keys(a);\r\n    var index = keysA.length;\r\n    if (Object.keys(b).length !== index) {\r\n        return false;\r\n    }\r\n    var key;\r\n    // Decrementing `while` showed faster results than either incrementing or\r\n    // decrementing `for` loop and than an incrementing `while` loop. Declarative\r\n    // methods like `some` / `every` were not used to avoid incurring the garbage\r\n    // cost of anonymous callbacks.\r\n    while (index-- > 0) {\r\n        key = keysA[index];\r\n        if (key === OWNER) {\r\n            var reactElementA = !!a.$$typeof;\r\n            var reactElementB = !!b.$$typeof;\r\n            if ((reactElementA || reactElementB) && reactElementA !== reactElementB) {\r\n                return false;\r\n            }\r\n        }\r\n        if (!hasOwnProperty.call(b, key) ||\r\n            !isEqual(a[key], b[key], key, key, a, b, meta)) {\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n/**\r\n * Whether the objects are equal in value, including circular references.\r\n */\r\nvar areObjectsEqualCircular = createIsCircular(areObjectsEqual);\n\n/**\r\n * Whether the regexps passed are equal in value.\r\n *\r\n * @NOTE\r\n * This is a standalone function instead of done inline in the comparator\r\n * to allow for overrides. An example of this would be supporting a\r\n * pre-ES2015 environment where the `flags` property is not available.\r\n */\r\nfunction areRegExpsEqual(a, b) {\r\n    return a.source === b.source && a.flags === b.flags;\r\n}\n\n/**\r\n * Whether the `Set`s are equal in value.\r\n */\r\nfunction areSetsEqual(a, b, isEqual, meta) {\r\n    var isValueEqual = a.size === b.size;\r\n    if (!isValueEqual) {\r\n        return false;\r\n    }\r\n    if (!a.size) {\r\n        return true;\r\n    }\r\n    // The use of `forEach()` is to avoid the transpilation cost of `for...of` comparisons, and\r\n    // the inability to control the performance of the resulting code. It also avoids excessive\r\n    // iteration compared to doing comparisons of `keys()` and `values()`. As a result, though,\r\n    // we cannot short-circuit the iterations; bookkeeping must be done to short-circuit the\r\n    // equality checks themselves.\r\n    var matchedIndices = {};\r\n    a.forEach(function (aValue, aKey) {\r\n        if (!isValueEqual) {\r\n            return;\r\n        }\r\n        var hasMatch = false;\r\n        var matchIndex = 0;\r\n        b.forEach(function (bValue, bKey) {\r\n            if (!hasMatch &&\r\n                !matchedIndices[matchIndex] &&\r\n                (hasMatch = isEqual(aValue, bValue, aKey, bKey, a, b, meta))) {\r\n                matchedIndices[matchIndex] = true;\r\n            }\r\n            matchIndex++;\r\n        });\r\n        isValueEqual = hasMatch;\r\n    });\r\n    return isValueEqual;\r\n}\r\n/**\r\n * Whether the `Set`s are equal in value, including circular references.\r\n */\r\nvar areSetsEqualCircular = createIsCircular(areSetsEqual);\n\nvar DEFAULT_CONFIG = Object.freeze({\r\n    areArraysEqual: areArraysEqual,\r\n    areDatesEqual: areDatesEqual,\r\n    areMapsEqual: areMapsEqual,\r\n    areObjectsEqual: areObjectsEqual,\r\n    areRegExpsEqual: areRegExpsEqual,\r\n    areSetsEqual: areSetsEqual,\r\n    createIsNestedEqual: createDefaultIsNestedEqual,\r\n});\r\nvar DEFAULT_CIRCULAR_CONFIG = Object.freeze({\r\n    areArraysEqual: areArraysEqualCircular,\r\n    areDatesEqual: areDatesEqual,\r\n    areMapsEqual: areMapsEqualCircular,\r\n    areObjectsEqual: areObjectsEqualCircular,\r\n    areRegExpsEqual: areRegExpsEqual,\r\n    areSetsEqual: areSetsEqualCircular,\r\n    createIsNestedEqual: createDefaultIsNestedEqual,\r\n});\r\nvar isDeepEqual = createComparator(DEFAULT_CONFIG);\r\n/**\r\n * Whether the items passed are deeply-equal in value.\r\n */\r\nfunction deepEqual(a, b) {\r\n    return isDeepEqual(a, b, undefined);\r\n}\r\nvar isShallowEqual = createComparator(merge(DEFAULT_CONFIG, { createIsNestedEqual: function () { return sameValueZeroEqual; } }));\r\n/**\r\n * Whether the items passed are shallowly-equal in value.\r\n */\r\nfunction shallowEqual(a, b) {\r\n    return isShallowEqual(a, b, undefined);\r\n}\r\nvar isCircularDeepEqual = createComparator(DEFAULT_CIRCULAR_CONFIG);\r\n/**\r\n * Whether the items passed are deeply-equal in value, including circular references.\r\n */\r\nfunction circularDeepEqual(a, b) {\r\n    return isCircularDeepEqual(a, b, new WeakMap());\r\n}\r\nvar isCircularShallowEqual = createComparator(merge(DEFAULT_CIRCULAR_CONFIG, {\r\n    createIsNestedEqual: function () { return sameValueZeroEqual; },\r\n}));\r\n/**\r\n * Whether the items passed are shallowly-equal in value, including circular references.\r\n */\r\nfunction circularShallowEqual(a, b) {\r\n    return isCircularShallowEqual(a, b, new WeakMap());\r\n}\r\n/**\r\n * Create a custom equality comparison method.\r\n *\r\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\r\n * where the standard methods are not performant enough, but can also be used to provide\r\n * support for legacy environments that do not support expected features like\r\n * `RegExp.prototype.flags` out of the box.\r\n */\r\nfunction createCustomEqual(getComparatorOptions) {\r\n    return createComparator(merge(DEFAULT_CONFIG, getComparatorOptions(DEFAULT_CONFIG)));\r\n}\r\n/**\r\n * Create a custom equality comparison method that handles circular references. This is very\r\n * similar to `createCustomEqual`, with the only difference being that `meta` expects to be\r\n * populated with a `WeakMap`-like contract.\r\n *\r\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\r\n * where the standard methods are not performant enough, but can also be used to provide\r\n * support for legacy environments that do not support expected features like\r\n * `WeakMap` out of the box.\r\n */\r\nfunction createCustomCircularEqual(getComparatorOptions) {\r\n    var comparator = createComparator(merge(DEFAULT_CIRCULAR_CONFIG, getComparatorOptions(DEFAULT_CIRCULAR_CONFIG)));\r\n    return (function (a, b, meta) {\r\n        if (meta === void 0) { meta = new WeakMap(); }\r\n        return comparator(a, b, meta);\r\n    });\r\n}\n\nexport { circularDeepEqual, circularShallowEqual, createCustomCircularEqual, createCustomEqual, deepEqual, sameValueZeroEqual, shallowEqual };\n//# sourceMappingURL=fast-equals.esm.js.map\n","function r(e){var o,t,f=\"\";if(\"string\"==typeof e||\"number\"==typeof e)f+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var n=e.length;for(o=0;o<n;o++)e[o]&&(t=r(e[o]))&&(f&&(f+=\" \"),f+=t)}else for(t in e)e[t]&&(f&&(f+=\" \"),f+=t);return f}function e(){for(var e,o,t=0,f=\"\",n=arguments.length;t<n;t++)(e=arguments[t])&&(o=r(e))&&(f&&(f+=\" \"),f+=o);return f}module.exports=e,module.exports.clsx=e;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.dontSetMe = dontSetMe;\nexports.findInArray = findInArray;\nexports.int = int;\nexports.isFunction = isFunction;\nexports.isNum = isNum;\n// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc\nfunction findInArray(array /*: Array<any> | TouchList*/, callback /*: Function*/) /*: any*/{\n  for (let i = 0, length = array.length; i < length; i++) {\n    if (callback.apply(callback, [array[i], i, array])) return array[i];\n  }\n}\nfunction isFunction(func /*: any*/) /*: boolean %checks*/{\n  // $FlowIgnore[method-unbinding]\n  return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';\n}\nfunction isNum(num /*: any*/) /*: boolean %checks*/{\n  return typeof num === 'number' && !isNaN(num);\n}\nfunction int(a /*: string*/) /*: number*/{\n  return parseInt(a, 10);\n}\nfunction dontSetMe(props /*: Object*/, propName /*: string*/, componentName /*: string*/) /*: ?Error*/{\n  if (props[propName]) {\n    return new Error(`Invalid prop ${propName} passed to ${componentName} - do not set this, set it on the child.`);\n  }\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.browserPrefixToKey = browserPrefixToKey;\nexports.browserPrefixToStyle = browserPrefixToStyle;\nexports.default = void 0;\nexports.getPrefix = getPrefix;\nconst prefixes = ['Moz', 'Webkit', 'O', 'ms'];\nfunction getPrefix() /*: string*/{\n  let prop /*: string*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transform';\n  // Ensure we're running in an environment where there is actually a global\n  // `window` obj\n  if (typeof window === 'undefined') return '';\n\n  // If we're in a pseudo-browser server-side environment, this access\n  // path may not exist, so bail out if it doesn't.\n  const style = window.document?.documentElement?.style;\n  if (!style) return '';\n  if (prop in style) return '';\n  for (let i = 0; i < prefixes.length; i++) {\n    if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];\n  }\n  return '';\n}\nfunction browserPrefixToKey(prop /*: string*/, prefix /*: string*/) /*: string*/{\n  return prefix ? `${prefix}${kebabToTitleCase(prop)}` : prop;\n}\nfunction browserPrefixToStyle(prop /*: string*/, prefix /*: string*/) /*: string*/{\n  return prefix ? `-${prefix.toLowerCase()}-${prop}` : prop;\n}\nfunction kebabToTitleCase(str /*: string*/) /*: string*/{\n  let out = '';\n  let shouldCapitalize = true;\n  for (let i = 0; i < str.length; i++) {\n    if (shouldCapitalize) {\n      out += str[i].toUpperCase();\n      shouldCapitalize = false;\n    } else if (str[i] === '-') {\n      shouldCapitalize = true;\n    } else {\n      out += str[i];\n    }\n  }\n  return out;\n}\n\n// Default export is the prefix itself, like 'Moz', 'Webkit', etc\n// Note that you may have to re-test for certain things; for instance, Chrome 50\n// can handle unprefixed `transform`, but not unprefixed `user-select`\nvar _default = exports.default = (getPrefix() /*: string*/);","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.addClassName = addClassName;\nexports.addEvent = addEvent;\nexports.addUserSelectStyles = addUserSelectStyles;\nexports.createCSSTransform = createCSSTransform;\nexports.createSVGTransform = createSVGTransform;\nexports.getTouch = getTouch;\nexports.getTouchIdentifier = getTouchIdentifier;\nexports.getTranslation = getTranslation;\nexports.innerHeight = innerHeight;\nexports.innerWidth = innerWidth;\nexports.matchesSelector = matchesSelector;\nexports.matchesSelectorAndParentsTo = matchesSelectorAndParentsTo;\nexports.offsetXYFromParent = offsetXYFromParent;\nexports.outerHeight = outerHeight;\nexports.outerWidth = outerWidth;\nexports.removeClassName = removeClassName;\nexports.removeEvent = removeEvent;\nexports.scheduleRemoveUserSelectStyles = scheduleRemoveUserSelectStyles;\nvar _shims = require(\"./shims\");\nvar _getPrefix = _interopRequireWildcard(require(\"./getPrefix\"));\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) \"default\" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }\n/*:: import type {ControlPosition, PositionOffsetControlPosition, MouseTouchEvent} from './types';*/\nlet matchesSelectorFunc = '';\nfunction matchesSelector(el /*: Node*/, selector /*: string*/) /*: boolean*/{\n  if (!matchesSelectorFunc) {\n    matchesSelectorFunc = (0, _shims.findInArray)(['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'], function (method) {\n      // $FlowIgnore: Doesn't think elements are indexable\n      return (0, _shims.isFunction)(el[method]);\n    });\n  }\n\n  // Might not be found entirely (not an Element?) - in that case, bail\n  // $FlowIgnore: Doesn't think elements are indexable\n  if (!(0, _shims.isFunction)(el[matchesSelectorFunc])) return false;\n\n  // $FlowIgnore: Doesn't think elements are indexable\n  return el[matchesSelectorFunc](selector);\n}\n\n// Works up the tree to the draggable itself attempting to match selector.\nfunction matchesSelectorAndParentsTo(el /*: Node*/, selector /*: string*/, baseNode /*: Node*/) /*: boolean*/{\n  let node = el;\n  do {\n    if (matchesSelector(node, selector)) return true;\n    if (node === baseNode) return false;\n    // $FlowIgnore[incompatible-type]\n    node = node.parentNode;\n  } while (node);\n  return false;\n}\nfunction addEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/, inputOptions /*: Object*/) /*: void*/{\n  if (!el) return;\n  const options = {\n    capture: true,\n    ...inputOptions\n  };\n  // $FlowIgnore[method-unbinding]\n  if (el.addEventListener) {\n    el.addEventListener(event, handler, options);\n  } else if (el.attachEvent) {\n    el.attachEvent('on' + event, handler);\n  } else {\n    // $FlowIgnore: Doesn't think elements are indexable\n    el['on' + event] = handler;\n  }\n}\nfunction removeEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/, inputOptions /*: Object*/) /*: void*/{\n  if (!el) return;\n  const options = {\n    capture: true,\n    ...inputOptions\n  };\n  // $FlowIgnore[method-unbinding]\n  if (el.removeEventListener) {\n    el.removeEventListener(event, handler, options);\n  } else if (el.detachEvent) {\n    el.detachEvent('on' + event, handler);\n  } else {\n    // $FlowIgnore: Doesn't think elements are indexable\n    el['on' + event] = null;\n  }\n}\nfunction outerHeight(node /*: HTMLElement*/) /*: number*/{\n  // This is deliberately excluding margin for our calculations, since we are using\n  // offsetTop which is including margin. See getBoundPosition\n  let height = node.clientHeight;\n  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n  height += (0, _shims.int)(computedStyle.borderTopWidth);\n  height += (0, _shims.int)(computedStyle.borderBottomWidth);\n  return height;\n}\nfunction outerWidth(node /*: HTMLElement*/) /*: number*/{\n  // This is deliberately excluding margin for our calculations, since we are using\n  // offsetLeft which is including margin. See getBoundPosition\n  let width = node.clientWidth;\n  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n  width += (0, _shims.int)(computedStyle.borderLeftWidth);\n  width += (0, _shims.int)(computedStyle.borderRightWidth);\n  return width;\n}\nfunction innerHeight(node /*: HTMLElement*/) /*: number*/{\n  let height = node.clientHeight;\n  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n  height -= (0, _shims.int)(computedStyle.paddingTop);\n  height -= (0, _shims.int)(computedStyle.paddingBottom);\n  return height;\n}\nfunction innerWidth(node /*: HTMLElement*/) /*: number*/{\n  let width = node.clientWidth;\n  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n  width -= (0, _shims.int)(computedStyle.paddingLeft);\n  width -= (0, _shims.int)(computedStyle.paddingRight);\n  return width;\n}\n/*:: interface EventWithOffset {\n  clientX: number, clientY: number\n}*/\n// Get from offsetParent\nfunction offsetXYFromParent(evt /*: EventWithOffset*/, offsetParent /*: HTMLElement*/, scale /*: number*/) /*: ControlPosition*/{\n  const isBody = offsetParent === offsetParent.ownerDocument.body;\n  const offsetParentRect = isBody ? {\n    left: 0,\n    top: 0\n  } : offsetParent.getBoundingClientRect();\n  const x = (evt.clientX + offsetParent.scrollLeft - offsetParentRect.left) / scale;\n  const y = (evt.clientY + offsetParent.scrollTop - offsetParentRect.top) / scale;\n  return {\n    x,\n    y\n  };\n}\nfunction createCSSTransform(controlPos /*: ControlPosition*/, positionOffset /*: PositionOffsetControlPosition*/) /*: Object*/{\n  const translation = getTranslation(controlPos, positionOffset, 'px');\n  return {\n    [(0, _getPrefix.browserPrefixToKey)('transform', _getPrefix.default)]: translation\n  };\n}\nfunction createSVGTransform(controlPos /*: ControlPosition*/, positionOffset /*: PositionOffsetControlPosition*/) /*: string*/{\n  const translation = getTranslation(controlPos, positionOffset, '');\n  return translation;\n}\nfunction getTranslation(_ref /*:: */, positionOffset /*: PositionOffsetControlPosition*/, unitSuffix /*: string*/) /*: string*/{\n  let {\n    x,\n    y\n  } /*: ControlPosition*/ = _ref /*: ControlPosition*/;\n  let translation = `translate(${x}${unitSuffix},${y}${unitSuffix})`;\n  if (positionOffset) {\n    const defaultX = `${typeof positionOffset.x === 'string' ? positionOffset.x : positionOffset.x + unitSuffix}`;\n    const defaultY = `${typeof positionOffset.y === 'string' ? positionOffset.y : positionOffset.y + unitSuffix}`;\n    translation = `translate(${defaultX}, ${defaultY})` + translation;\n  }\n  return translation;\n}\nfunction getTouch(e /*: MouseTouchEvent*/, identifier /*: number*/) /*: ?{clientX: number, clientY: number}*/{\n  return e.targetTouches && (0, _shims.findInArray)(e.targetTouches, t => identifier === t.identifier) || e.changedTouches && (0, _shims.findInArray)(e.changedTouches, t => identifier === t.identifier);\n}\nfunction getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/{\n  if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;\n  if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;\n}\n\n// User-select Hacks:\n//\n// Useful for preventing blue highlights all over everything when dragging.\n\n// Note we're passing `document` b/c we could be iframed\nfunction addUserSelectStyles(doc /*: ?Document*/) {\n  if (!doc) return;\n  let styleEl = doc.getElementById('react-draggable-style-el');\n  if (!styleEl) {\n    styleEl = doc.createElement('style');\n    styleEl.type = 'text/css';\n    styleEl.id = 'react-draggable-style-el';\n    styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {all: inherit;}\\n';\n    styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {all: inherit;}\\n';\n    doc.getElementsByTagName('head')[0].appendChild(styleEl);\n  }\n  if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');\n}\nfunction scheduleRemoveUserSelectStyles(doc /*: ?Document*/) {\n  // Prevent a possible \"forced reflow\"\n  if (window.requestAnimationFrame) {\n    window.requestAnimationFrame(() => {\n      removeUserSelectStyles(doc);\n    });\n  } else {\n    removeUserSelectStyles(doc);\n  }\n}\nfunction removeUserSelectStyles(doc /*: ?Document*/) {\n  if (!doc) return;\n  try {\n    if (doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');\n    // $FlowIgnore: IE\n    if (doc.selection) {\n      // $FlowIgnore: IE\n      doc.selection.empty();\n    } else {\n      // Remove selection caused by scroll, unless it's a focused input\n      // (we use doc.defaultView in case we're in an iframe)\n      const selection = (doc.defaultView || window).getSelection();\n      if (selection && selection.type !== 'Caret') {\n        selection.removeAllRanges();\n      }\n    }\n  } catch (e) {\n    // probably IE\n  }\n}\nfunction addClassName(el /*: HTMLElement*/, className /*: string*/) {\n  if (el.classList) {\n    el.classList.add(className);\n  } else {\n    if (!el.className.match(new RegExp(`(?:^|\\\\s)${className}(?!\\\\S)`))) {\n      el.className += ` ${className}`;\n    }\n  }\n}\nfunction removeClassName(el /*: HTMLElement*/, className /*: string*/) {\n  if (el.classList) {\n    el.classList.remove(className);\n  } else {\n    el.className = el.className.replace(new RegExp(`(?:^|\\\\s)${className}(?!\\\\S)`, 'g'), '');\n  }\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.canDragX = canDragX;\nexports.canDragY = canDragY;\nexports.createCoreData = createCoreData;\nexports.createDraggableData = createDraggableData;\nexports.getBoundPosition = getBoundPosition;\nexports.getControlPosition = getControlPosition;\nexports.snapToGrid = snapToGrid;\nvar _shims = require(\"./shims\");\nvar _domFns = require(\"./domFns\");\n/*:: import type Draggable from '../Draggable';*/\n/*:: import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';*/\n/*:: import type DraggableCore from '../DraggableCore';*/\nfunction getBoundPosition(draggable /*: Draggable*/, x /*: number*/, y /*: number*/) /*: [number, number]*/{\n  // If no bounds, short-circuit and move on\n  if (!draggable.props.bounds) return [x, y];\n\n  // Clone new bounds\n  let {\n    bounds\n  } = draggable.props;\n  bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);\n  const node = findDOMNode(draggable);\n  if (typeof bounds === 'string') {\n    const {\n      ownerDocument\n    } = node;\n    const ownerWindow = ownerDocument.defaultView;\n    let boundNode;\n    if (bounds === 'parent') {\n      boundNode = node.parentNode;\n    } else {\n      // Flow assigns the wrong return type (Node) for getRootNode(),\n      // so we cast it to one of the correct types (Element).\n      // The others are Document and ShadowRoot.\n      // All three implement querySelector() so it's safe to call.\n      const rootNode = ((node.getRootNode() /*: any*/) /*: Element*/);\n      boundNode = rootNode.querySelector(bounds);\n    }\n    if (!(boundNode instanceof ownerWindow.HTMLElement)) {\n      throw new Error('Bounds selector \"' + bounds + '\" could not find an element.');\n    }\n    const boundNodeEl /*: HTMLElement*/ = boundNode; // for Flow, can't seem to refine correctly\n    const nodeStyle = ownerWindow.getComputedStyle(node);\n    const boundNodeStyle = ownerWindow.getComputedStyle(boundNodeEl);\n    // Compute bounds. This is a pain with padding and offsets but this gets it exactly right.\n    bounds = {\n      left: -node.offsetLeft + (0, _shims.int)(boundNodeStyle.paddingLeft) + (0, _shims.int)(nodeStyle.marginLeft),\n      top: -node.offsetTop + (0, _shims.int)(boundNodeStyle.paddingTop) + (0, _shims.int)(nodeStyle.marginTop),\n      right: (0, _domFns.innerWidth)(boundNodeEl) - (0, _domFns.outerWidth)(node) - node.offsetLeft + (0, _shims.int)(boundNodeStyle.paddingRight) - (0, _shims.int)(nodeStyle.marginRight),\n      bottom: (0, _domFns.innerHeight)(boundNodeEl) - (0, _domFns.outerHeight)(node) - node.offsetTop + (0, _shims.int)(boundNodeStyle.paddingBottom) - (0, _shims.int)(nodeStyle.marginBottom)\n    };\n  }\n\n  // Keep x and y below right and bottom limits...\n  if ((0, _shims.isNum)(bounds.right)) x = Math.min(x, bounds.right);\n  if ((0, _shims.isNum)(bounds.bottom)) y = Math.min(y, bounds.bottom);\n\n  // But above left and top limits.\n  if ((0, _shims.isNum)(bounds.left)) x = Math.max(x, bounds.left);\n  if ((0, _shims.isNum)(bounds.top)) y = Math.max(y, bounds.top);\n  return [x, y];\n}\nfunction snapToGrid(grid /*: [number, number]*/, pendingX /*: number*/, pendingY /*: number*/) /*: [number, number]*/{\n  const x = Math.round(pendingX / grid[0]) * grid[0];\n  const y = Math.round(pendingY / grid[1]) * grid[1];\n  return [x, y];\n}\nfunction canDragX(draggable /*: Draggable*/) /*: boolean*/{\n  return draggable.props.axis === 'both' || draggable.props.axis === 'x';\n}\nfunction canDragY(draggable /*: Draggable*/) /*: boolean*/{\n  return draggable.props.axis === 'both' || draggable.props.axis === 'y';\n}\n\n// Get {x, y} positions from event.\nfunction getControlPosition(e /*: MouseTouchEvent*/, touchIdentifier /*: ?number*/, draggableCore /*: DraggableCore*/) /*: ?ControlPosition*/{\n  const touchObj = typeof touchIdentifier === 'number' ? (0, _domFns.getTouch)(e, touchIdentifier) : null;\n  if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch\n  const node = findDOMNode(draggableCore);\n  // User can provide an offsetParent if desired.\n  const offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;\n  return (0, _domFns.offsetXYFromParent)(touchObj || e, offsetParent, draggableCore.props.scale);\n}\n\n// Create an data object exposed by <DraggableCore>'s events\nfunction createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/{\n  const isStart = !(0, _shims.isNum)(draggable.lastX);\n  const node = findDOMNode(draggable);\n  if (isStart) {\n    // If this is our first move, use the x and y as last coords.\n    return {\n      node,\n      deltaX: 0,\n      deltaY: 0,\n      lastX: x,\n      lastY: y,\n      x,\n      y\n    };\n  } else {\n    // Otherwise calculate proper values.\n    return {\n      node,\n      deltaX: x - draggable.lastX,\n      deltaY: y - draggable.lastY,\n      lastX: draggable.lastX,\n      lastY: draggable.lastY,\n      x,\n      y\n    };\n  }\n}\n\n// Create an data exposed by <Draggable>'s events\nfunction createDraggableData(draggable /*: Draggable*/, coreData /*: DraggableData*/) /*: DraggableData*/{\n  const scale = draggable.props.scale;\n  return {\n    node: coreData.node,\n    x: draggable.state.x + coreData.deltaX / scale,\n    y: draggable.state.y + coreData.deltaY / scale,\n    deltaX: coreData.deltaX / scale,\n    deltaY: coreData.deltaY / scale,\n    lastX: draggable.state.x,\n    lastY: draggable.state.y\n  };\n}\n\n// A lot faster than stringify/parse\nfunction cloneBounds(bounds /*: Bounds*/) /*: Bounds*/{\n  return {\n    left: bounds.left,\n    top: bounds.top,\n    right: bounds.right,\n    bottom: bounds.bottom\n  };\n}\nfunction findDOMNode(draggable /*: Draggable | DraggableCore*/) /*: HTMLElement*/{\n  const node = draggable.findDOMNode();\n  if (!node) {\n    throw new Error('<DraggableCore>: Unmounted during event!');\n  }\n  // $FlowIgnore we can't assert on HTMLElement due to tests... FIXME\n  return node;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = log;\n/*eslint no-console:0*/\nfunction log() {\n  if (undefined) console.log(...arguments);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _reactDom = _interopRequireDefault(require(\"react-dom\"));\nvar _domFns = require(\"./utils/domFns\");\nvar _positionFns = require(\"./utils/positionFns\");\nvar _shims = require(\"./utils/shims\");\nvar _log = _interopRequireDefault(require(\"./utils/log\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) \"default\" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/*:: import type {EventHandler, MouseTouchEvent} from './utils/types';*/\n/*:: import type {Element as ReactElement} from 'react';*/\n// Simple abstraction for dragging events names.\nconst eventsFor = {\n  touch: {\n    start: 'touchstart',\n    move: 'touchmove',\n    stop: 'touchend'\n  },\n  mouse: {\n    start: 'mousedown',\n    move: 'mousemove',\n    stop: 'mouseup'\n  }\n};\n\n// Default to mouse events.\nlet dragEventFor = eventsFor.mouse;\n/*:: export type DraggableData = {\n  node: HTMLElement,\n  x: number, y: number,\n  deltaX: number, deltaY: number,\n  lastX: number, lastY: number,\n};*/\n/*:: export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void | false;*/\n/*:: export type ControlPosition = {x: number, y: number};*/\n/*:: export type PositionOffsetControlPosition = {x: number|string, y: number|string};*/\n/*:: export type DraggableCoreDefaultProps = {\n  allowAnyClick: boolean,\n  allowMobileScroll: boolean,\n  disabled: boolean,\n  enableUserSelectHack: boolean,\n  onStart: DraggableEventHandler,\n  onDrag: DraggableEventHandler,\n  onStop: DraggableEventHandler,\n  onMouseDown: (e: MouseEvent) => void,\n  scale: number,\n};*/\n/*:: export type DraggableCoreProps = {\n  ...DraggableCoreDefaultProps,\n  cancel: string,\n  children: ReactElement<any>,\n  offsetParent: HTMLElement,\n  grid: [number, number],\n  handle: string,\n  nodeRef?: ?React.ElementRef<any>,\n};*/\n//\n// Define <DraggableCore>.\n//\n// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can\n// work well with libraries that require more control over the element.\n//\n\nclass DraggableCore extends React.Component /*:: <DraggableCoreProps>*/{\n  constructor() {\n    super(...arguments);\n    _defineProperty(this, \"dragging\", false);\n    // Used while dragging to determine deltas.\n    _defineProperty(this, \"lastX\", NaN);\n    _defineProperty(this, \"lastY\", NaN);\n    _defineProperty(this, \"touchIdentifier\", null);\n    _defineProperty(this, \"mounted\", false);\n    _defineProperty(this, \"handleDragStart\", e => {\n      // Make it possible to attach event handlers on top of this one.\n      this.props.onMouseDown(e);\n\n      // Only accept left-clicks.\n      if (!this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;\n\n      // Get nodes. Be sure to grab relative document (could be iframed)\n      const thisNode = this.findDOMNode();\n      if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {\n        throw new Error('<DraggableCore> not mounted on DragStart!');\n      }\n      const {\n        ownerDocument\n      } = thisNode;\n\n      // Short circuit if handle or cancel prop was provided and selector doesn't match.\n      if (this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || this.props.handle && !(0, _domFns.matchesSelectorAndParentsTo)(e.target, this.props.handle, thisNode) || this.props.cancel && (0, _domFns.matchesSelectorAndParentsTo)(e.target, this.props.cancel, thisNode)) {\n        return;\n      }\n\n      // Prevent scrolling on mobile devices, like ipad/iphone.\n      // Important that this is after handle/cancel.\n      if (e.type === 'touchstart' && !this.props.allowMobileScroll) e.preventDefault();\n\n      // Set touch identifier in component state if this is a touch event. This allows us to\n      // distinguish between individual touches on multitouch screens by identifying which\n      // touchpoint was set to this element.\n      const touchIdentifier = (0, _domFns.getTouchIdentifier)(e);\n      this.touchIdentifier = touchIdentifier;\n\n      // Get the current drag point from the event. This is used as the offset.\n      const position = (0, _positionFns.getControlPosition)(e, touchIdentifier, this);\n      if (position == null) return; // not possible but satisfies flow\n      const {\n        x,\n        y\n      } = position;\n\n      // Create an event object with all the data parents need to make a decision here.\n      const coreEvent = (0, _positionFns.createCoreData)(this, x, y);\n      (0, _log.default)('DraggableCore: handleDragStart: %j', coreEvent);\n\n      // Call event handler. If it returns explicit false, cancel.\n      (0, _log.default)('calling', this.props.onStart);\n      const shouldUpdate = this.props.onStart(e, coreEvent);\n      if (shouldUpdate === false || this.mounted === false) return;\n\n      // Add a style to the body to disable user-select. This prevents text from\n      // being selected all over the page.\n      if (this.props.enableUserSelectHack) (0, _domFns.addUserSelectStyles)(ownerDocument);\n\n      // Initiate dragging. Set the current x and y as offsets\n      // so we know how much we've moved during the drag. This allows us\n      // to drag elements around even if they have been moved, without issue.\n      this.dragging = true;\n      this.lastX = x;\n      this.lastY = y;\n\n      // Add events to the document directly so we catch when the user's mouse/touch moves outside of\n      // this element. We use different events depending on whether or not we have detected that this\n      // is a touch-capable device.\n      (0, _domFns.addEvent)(ownerDocument, dragEventFor.move, this.handleDrag);\n      (0, _domFns.addEvent)(ownerDocument, dragEventFor.stop, this.handleDragStop);\n    });\n    _defineProperty(this, \"handleDrag\", e => {\n      // Get the current drag point from the event. This is used as the offset.\n      const position = (0, _positionFns.getControlPosition)(e, this.touchIdentifier, this);\n      if (position == null) return;\n      let {\n        x,\n        y\n      } = position;\n\n      // Snap to grid if prop has been provided\n      if (Array.isArray(this.props.grid)) {\n        let deltaX = x - this.lastX,\n          deltaY = y - this.lastY;\n        [deltaX, deltaY] = (0, _positionFns.snapToGrid)(this.props.grid, deltaX, deltaY);\n        if (!deltaX && !deltaY) return; // skip useless drag\n        x = this.lastX + deltaX, y = this.lastY + deltaY;\n      }\n      const coreEvent = (0, _positionFns.createCoreData)(this, x, y);\n      (0, _log.default)('DraggableCore: handleDrag: %j', coreEvent);\n\n      // Call event handler. If it returns explicit false, trigger end.\n      const shouldUpdate = this.props.onDrag(e, coreEvent);\n      if (shouldUpdate === false || this.mounted === false) {\n        try {\n          // $FlowIgnore\n          this.handleDragStop(new MouseEvent('mouseup'));\n        } catch (err) {\n          // Old browsers\n          const event = ((document.createEvent('MouseEvents') /*: any*/) /*: MouseTouchEvent*/);\n          // I see why this insanity was deprecated\n          // $FlowIgnore\n          event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n          this.handleDragStop(event);\n        }\n        return;\n      }\n      this.lastX = x;\n      this.lastY = y;\n    });\n    _defineProperty(this, \"handleDragStop\", e => {\n      if (!this.dragging) return;\n      const position = (0, _positionFns.getControlPosition)(e, this.touchIdentifier, this);\n      if (position == null) return;\n      let {\n        x,\n        y\n      } = position;\n\n      // Snap to grid if prop has been provided\n      if (Array.isArray(this.props.grid)) {\n        let deltaX = x - this.lastX || 0;\n        let deltaY = y - this.lastY || 0;\n        [deltaX, deltaY] = (0, _positionFns.snapToGrid)(this.props.grid, deltaX, deltaY);\n        x = this.lastX + deltaX, y = this.lastY + deltaY;\n      }\n      const coreEvent = (0, _positionFns.createCoreData)(this, x, y);\n\n      // Call event handler\n      const shouldContinue = this.props.onStop(e, coreEvent);\n      if (shouldContinue === false || this.mounted === false) return false;\n      const thisNode = this.findDOMNode();\n      if (thisNode) {\n        // Remove user-select hack\n        if (this.props.enableUserSelectHack) (0, _domFns.scheduleRemoveUserSelectStyles)(thisNode.ownerDocument);\n      }\n      (0, _log.default)('DraggableCore: handleDragStop: %j', coreEvent);\n\n      // Reset the el.\n      this.dragging = false;\n      this.lastX = NaN;\n      this.lastY = NaN;\n      if (thisNode) {\n        // Remove event handlers\n        (0, _log.default)('DraggableCore: Removing handlers');\n        (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.move, this.handleDrag);\n        (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.stop, this.handleDragStop);\n      }\n    });\n    _defineProperty(this, \"onMouseDown\", e => {\n      dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse\n\n      return this.handleDragStart(e);\n    });\n    _defineProperty(this, \"onMouseUp\", e => {\n      dragEventFor = eventsFor.mouse;\n      return this.handleDragStop(e);\n    });\n    // Same as onMouseDown (start drag), but now consider this a touch device.\n    _defineProperty(this, \"onTouchStart\", e => {\n      // We're on a touch device now, so change the event handlers\n      dragEventFor = eventsFor.touch;\n      return this.handleDragStart(e);\n    });\n    _defineProperty(this, \"onTouchEnd\", e => {\n      // We're on a touch device now, so change the event handlers\n      dragEventFor = eventsFor.touch;\n      return this.handleDragStop(e);\n    });\n  }\n  componentDidMount() {\n    this.mounted = true;\n    // Touch handlers must be added with {passive: false} to be cancelable.\n    // https://developers.google.com/web/updates/2017/01/scrolling-intervention\n    const thisNode = this.findDOMNode();\n    if (thisNode) {\n      (0, _domFns.addEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {\n        passive: false\n      });\n    }\n  }\n  componentWillUnmount() {\n    this.mounted = false;\n    // Remove any leftover event handlers. Remove both touch and mouse handlers in case\n    // some browser quirk caused a touch event to fire during a mouse move, or vice versa.\n    const thisNode = this.findDOMNode();\n    if (thisNode) {\n      const {\n        ownerDocument\n      } = thisNode;\n      (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.move, this.handleDrag);\n      (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.move, this.handleDrag);\n      (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);\n      (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.stop, this.handleDragStop);\n      (0, _domFns.removeEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {\n        passive: false\n      });\n      if (this.props.enableUserSelectHack) (0, _domFns.scheduleRemoveUserSelectStyles)(ownerDocument);\n    }\n  }\n\n  // React Strict Mode compatibility: if `nodeRef` is passed, we will use it instead of trying to find\n  // the underlying DOM node ourselves. See the README for more information.\n  findDOMNode() /*: ?HTMLElement*/{\n    return this.props?.nodeRef ? this.props?.nodeRef?.current : _reactDom.default.findDOMNode(this);\n  }\n  render() /*: React.Element<any>*/{\n    // Reuse the child provided\n    // This makes it flexible to use whatever element is wanted (div, ul, etc)\n    return /*#__PURE__*/React.cloneElement(React.Children.only(this.props.children), {\n      // Note: mouseMove handler is attached to document so it will still function\n      // when the user drags quickly and leaves the bounds of the element.\n      onMouseDown: this.onMouseDown,\n      onMouseUp: this.onMouseUp,\n      // onTouchStart is added on `componentDidMount` so they can be added with\n      // {passive: false}, which allows it to cancel. See\n      // https://developers.google.com/web/updates/2017/01/scrolling-intervention\n      onTouchEnd: this.onTouchEnd\n    });\n  }\n}\nexports.default = DraggableCore;\n_defineProperty(DraggableCore, \"displayName\", 'DraggableCore');\n_defineProperty(DraggableCore, \"propTypes\", {\n  /**\n   * `allowAnyClick` allows dragging using any mouse button.\n   * By default, we only accept the left button.\n   *\n   * Defaults to `false`.\n   */\n  allowAnyClick: _propTypes.default.bool,\n  /**\n   * `allowMobileScroll` turns off cancellation of the 'touchstart' event\n   * on mobile devices. Only enable this if you are having trouble with click\n   * events. Prefer using 'handle' / 'cancel' instead.\n   *\n   * Defaults to `false`.\n   */\n  allowMobileScroll: _propTypes.default.bool,\n  children: _propTypes.default.node.isRequired,\n  /**\n   * `disabled`, if true, stops the <Draggable> from dragging. All handlers,\n   * with the exception of `onMouseDown`, will not fire.\n   */\n  disabled: _propTypes.default.bool,\n  /**\n   * By default, we add 'user-select:none' attributes to the document body\n   * to prevent ugly text selection during drag. If this is causing problems\n   * for your app, set this to `false`.\n   */\n  enableUserSelectHack: _propTypes.default.bool,\n  /**\n   * `offsetParent`, if set, uses the passed DOM node to compute drag offsets\n   * instead of using the parent node.\n   */\n  offsetParent: function (props /*: DraggableCoreProps*/, propName /*: $Keys<DraggableCoreProps>*/) {\n    if (props[propName] && props[propName].nodeType !== 1) {\n      throw new Error('Draggable\\'s offsetParent must be a DOM Node.');\n    }\n  },\n  /**\n   * `grid` specifies the x and y that dragging should snap to.\n   */\n  grid: _propTypes.default.arrayOf(_propTypes.default.number),\n  /**\n   * `handle` specifies a selector to be used as the handle that initiates drag.\n   *\n   * Example:\n   *\n   * ```jsx\n   *   let App = React.createClass({\n   *       render: function () {\n   *         return (\n   *            <Draggable handle=\".handle\">\n   *              <div>\n   *                  <div className=\"handle\">Click me to drag</div>\n   *                  <div>This is some other content</div>\n   *              </div>\n   *           </Draggable>\n   *         );\n   *       }\n   *   });\n   * ```\n   */\n  handle: _propTypes.default.string,\n  /**\n   * `cancel` specifies a selector to be used to prevent drag initialization.\n   *\n   * Example:\n   *\n   * ```jsx\n   *   let App = React.createClass({\n   *       render: function () {\n   *           return(\n   *               <Draggable cancel=\".cancel\">\n   *                   <div>\n   *                     <div className=\"cancel\">You can't drag from here</div>\n   *                     <div>Dragging here works fine</div>\n   *                   </div>\n   *               </Draggable>\n   *           );\n   *       }\n   *   });\n   * ```\n   */\n  cancel: _propTypes.default.string,\n  /* If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.\n   * Unfortunately, in order for <Draggable> to work properly, we need raw access\n   * to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`\n   * as in this example:\n   *\n   * function MyComponent() {\n   *   const nodeRef = React.useRef(null);\n   *   return (\n   *     <Draggable nodeRef={nodeRef}>\n   *       <div ref={nodeRef}>Example Target</div>\n   *     </Draggable>\n   *   );\n   * }\n   *\n   * This can be used for arbitrarily nested components, so long as the ref ends up\n   * pointing to the actual child DOM node and not a custom component.\n   */\n  nodeRef: _propTypes.default.object,\n  /**\n   * Called when dragging starts.\n   * If this function returns the boolean false, dragging will be canceled.\n   */\n  onStart: _propTypes.default.func,\n  /**\n   * Called while dragging.\n   * If this function returns the boolean false, dragging will be canceled.\n   */\n  onDrag: _propTypes.default.func,\n  /**\n   * Called when dragging stops.\n   * If this function returns the boolean false, the drag will remain active.\n   */\n  onStop: _propTypes.default.func,\n  /**\n   * A workaround option which can be passed if onMouseDown needs to be accessed,\n   * since it'll always be blocked (as there is internal use of onMouseDown)\n   */\n  onMouseDown: _propTypes.default.func,\n  /**\n   * `scale`, if set, applies scaling while dragging an element\n   */\n  scale: _propTypes.default.number,\n  /**\n   * These properties should be defined on the child, not here.\n   */\n  className: _shims.dontSetMe,\n  style: _shims.dontSetMe,\n  transform: _shims.dontSetMe\n});\n_defineProperty(DraggableCore, \"defaultProps\", {\n  allowAnyClick: false,\n  // by default only accept left click\n  allowMobileScroll: false,\n  disabled: false,\n  enableUserSelectHack: true,\n  onStart: function () {},\n  onDrag: function () {},\n  onStop: function () {},\n  onMouseDown: function () {},\n  scale: 1\n});","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nObject.defineProperty(exports, \"DraggableCore\", {\n  enumerable: true,\n  get: function () {\n    return _DraggableCore.default;\n  }\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _reactDom = _interopRequireDefault(require(\"react-dom\"));\nvar _clsx = require(\"clsx\");\nvar _domFns = require(\"./utils/domFns\");\nvar _positionFns = require(\"./utils/positionFns\");\nvar _shims = require(\"./utils/shims\");\nvar _DraggableCore = _interopRequireDefault(require(\"./DraggableCore\"));\nvar _log = _interopRequireDefault(require(\"./utils/log\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) \"default\" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }\nfunction _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); } /*:: import type {ControlPosition, PositionOffsetControlPosition, DraggableCoreProps, DraggableCoreDefaultProps} from './DraggableCore';*/\n/*:: import type {Bounds, DraggableEventHandler} from './utils/types';*/\n/*:: import type {Element as ReactElement} from 'react';*/\n/*:: type DraggableState = {\n  dragging: boolean,\n  dragged: boolean,\n  x: number, y: number,\n  slackX: number, slackY: number,\n  isElementSVG: boolean,\n  prevPropsPosition: ?ControlPosition,\n};*/\n/*:: export type DraggableDefaultProps = {\n  ...DraggableCoreDefaultProps,\n  axis: 'both' | 'x' | 'y' | 'none',\n  bounds: Bounds | string | false,\n  defaultClassName: string,\n  defaultClassNameDragging: string,\n  defaultClassNameDragged: string,\n  defaultPosition: ControlPosition,\n  scale: number,\n};*/\n/*:: export type DraggableProps = {\n  ...DraggableCoreProps,\n  ...DraggableDefaultProps,\n  positionOffset: PositionOffsetControlPosition,\n  position: ControlPosition,\n};*/\n//\n// Define <Draggable>\n//\nclass Draggable extends React.Component /*:: <DraggableProps, DraggableState>*/{\n  // React 16.3+\n  // Arity (props, state)\n  static getDerivedStateFromProps(_ref /*:: */, _ref2 /*:: */) /*: ?Partial<DraggableState>*/{\n    let {\n      position\n    } /*: DraggableProps*/ = _ref /*: DraggableProps*/;\n    let {\n      prevPropsPosition\n    } /*: DraggableState*/ = _ref2 /*: DraggableState*/;\n    // Set x/y if a new position is provided in props that is different than the previous.\n    if (position && (!prevPropsPosition || position.x !== prevPropsPosition.x || position.y !== prevPropsPosition.y)) {\n      (0, _log.default)('Draggable: getDerivedStateFromProps %j', {\n        position,\n        prevPropsPosition\n      });\n      return {\n        x: position.x,\n        y: position.y,\n        prevPropsPosition: {\n          ...position\n        }\n      };\n    }\n    return null;\n  }\n  constructor(props /*: DraggableProps*/) {\n    super(props);\n    _defineProperty(this, \"onDragStart\", (e, coreData) => {\n      (0, _log.default)('Draggable: onDragStart: %j', coreData);\n\n      // Short-circuit if user's callback killed it.\n      const shouldStart = this.props.onStart(e, (0, _positionFns.createDraggableData)(this, coreData));\n      // Kills start event on core as well, so move handlers are never bound.\n      if (shouldStart === false) return false;\n      this.setState({\n        dragging: true,\n        dragged: true\n      });\n    });\n    _defineProperty(this, \"onDrag\", (e, coreData) => {\n      if (!this.state.dragging) return false;\n      (0, _log.default)('Draggable: onDrag: %j', coreData);\n      const uiData = (0, _positionFns.createDraggableData)(this, coreData);\n      const newState = {\n        x: uiData.x,\n        y: uiData.y,\n        slackX: 0,\n        slackY: 0\n      };\n\n      // Keep within bounds.\n      if (this.props.bounds) {\n        // Save original x and y.\n        const {\n          x,\n          y\n        } = newState;\n\n        // Add slack to the values used to calculate bound position. This will ensure that if\n        // we start removing slack, the element won't react to it right away until it's been\n        // completely removed.\n        newState.x += this.state.slackX;\n        newState.y += this.state.slackY;\n\n        // Get bound position. This will ceil/floor the x and y within the boundaries.\n        const [newStateX, newStateY] = (0, _positionFns.getBoundPosition)(this, newState.x, newState.y);\n        newState.x = newStateX;\n        newState.y = newStateY;\n\n        // Recalculate slack by noting how much was shaved by the boundPosition handler.\n        newState.slackX = this.state.slackX + (x - newState.x);\n        newState.slackY = this.state.slackY + (y - newState.y);\n\n        // Update the event we fire to reflect what really happened after bounds took effect.\n        uiData.x = newState.x;\n        uiData.y = newState.y;\n        uiData.deltaX = newState.x - this.state.x;\n        uiData.deltaY = newState.y - this.state.y;\n      }\n\n      // Short-circuit if user's callback killed it.\n      const shouldUpdate = this.props.onDrag(e, uiData);\n      if (shouldUpdate === false) return false;\n      this.setState(newState);\n    });\n    _defineProperty(this, \"onDragStop\", (e, coreData) => {\n      if (!this.state.dragging) return false;\n\n      // Short-circuit if user's callback killed it.\n      const shouldContinue = this.props.onStop(e, (0, _positionFns.createDraggableData)(this, coreData));\n      if (shouldContinue === false) return false;\n      (0, _log.default)('Draggable: onDragStop: %j', coreData);\n      const newState /*: Partial<DraggableState>*/ = {\n        dragging: false,\n        slackX: 0,\n        slackY: 0\n      };\n\n      // If this is a controlled component, the result of this operation will be to\n      // revert back to the old position. We expect a handler on `onDragStop`, at the least.\n      const controlled = Boolean(this.props.position);\n      if (controlled) {\n        const {\n          x,\n          y\n        } = this.props.position;\n        newState.x = x;\n        newState.y = y;\n      }\n      this.setState(newState);\n    });\n    this.state = {\n      // Whether or not we are currently dragging.\n      dragging: false,\n      // Whether or not we have been dragged before.\n      dragged: false,\n      // Current transform x and y.\n      x: props.position ? props.position.x : props.defaultPosition.x,\n      y: props.position ? props.position.y : props.defaultPosition.y,\n      prevPropsPosition: {\n        ...props.position\n      },\n      // Used for compensating for out-of-bounds drags\n      slackX: 0,\n      slackY: 0,\n      // Can only determine if SVG after mounting\n      isElementSVG: false\n    };\n    if (props.position && !(props.onDrag || props.onStop)) {\n      // eslint-disable-next-line no-console\n      console.warn('A `position` was applied to this <Draggable>, without drag handlers. This will make this ' + 'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' + '`position` of this element.');\n    }\n  }\n  componentDidMount() {\n    // Check to see if the element passed is an instanceof SVGElement\n    if (typeof window.SVGElement !== 'undefined' && this.findDOMNode() instanceof window.SVGElement) {\n      this.setState({\n        isElementSVG: true\n      });\n    }\n  }\n  componentWillUnmount() {\n    if (this.state.dragging) {\n      this.setState({\n        dragging: false\n      }); // prevents invariant if unmounted while dragging\n    }\n  }\n\n  // React Strict Mode compatibility: if `nodeRef` is passed, we will use it instead of trying to find\n  // the underlying DOM node ourselves. See the README for more information.\n  findDOMNode() /*: ?HTMLElement*/{\n    return this.props?.nodeRef?.current ?? _reactDom.default.findDOMNode(this);\n  }\n  render() /*: ReactElement<any>*/{\n    const {\n      axis,\n      bounds,\n      children,\n      defaultPosition,\n      defaultClassName,\n      defaultClassNameDragging,\n      defaultClassNameDragged,\n      position,\n      positionOffset,\n      scale,\n      ...draggableCoreProps\n    } = this.props;\n    let style = {};\n    let svgTransform = null;\n\n    // If this is controlled, we don't want to move it - unless it's dragging.\n    const controlled = Boolean(position);\n    const draggable = !controlled || this.state.dragging;\n    const validPosition = position || defaultPosition;\n    const transformOpts = {\n      // Set left if horizontal drag is enabled\n      x: (0, _positionFns.canDragX)(this) && draggable ? this.state.x : validPosition.x,\n      // Set top if vertical drag is enabled\n      y: (0, _positionFns.canDragY)(this) && draggable ? this.state.y : validPosition.y\n    };\n\n    // If this element was SVG, we use the `transform` attribute.\n    if (this.state.isElementSVG) {\n      svgTransform = (0, _domFns.createSVGTransform)(transformOpts, positionOffset);\n    } else {\n      // Add a CSS transform to move the element around. This allows us to move the element around\n      // without worrying about whether or not it is relatively or absolutely positioned.\n      // If the item you are dragging already has a transform set, wrap it in a <span> so <Draggable>\n      // has a clean slate.\n      style = (0, _domFns.createCSSTransform)(transformOpts, positionOffset);\n    }\n\n    // Mark with class while dragging\n    const className = (0, _clsx.clsx)(children.props.className || '', defaultClassName, {\n      [defaultClassNameDragging]: this.state.dragging,\n      [defaultClassNameDragged]: this.state.dragged\n    });\n\n    // Reuse the child provided\n    // This makes it flexible to use whatever element is wanted (div, ul, etc)\n    return /*#__PURE__*/React.createElement(_DraggableCore.default, _extends({}, draggableCoreProps, {\n      onStart: this.onDragStart,\n      onDrag: this.onDrag,\n      onStop: this.onDragStop\n    }), /*#__PURE__*/React.cloneElement(React.Children.only(children), {\n      className: className,\n      style: {\n        ...children.props.style,\n        ...style\n      },\n      transform: svgTransform\n    }));\n  }\n}\nexports.default = Draggable;\n_defineProperty(Draggable, \"displayName\", 'Draggable');\n_defineProperty(Draggable, \"propTypes\", {\n  // Accepts all props <DraggableCore> accepts.\n  ..._DraggableCore.default.propTypes,\n  /**\n   * `axis` determines which axis the draggable can move.\n   *\n   *  Note that all callbacks will still return data as normal. This only\n   *  controls flushing to the DOM.\n   *\n   * 'both' allows movement horizontally and vertically.\n   * 'x' limits movement to horizontal axis.\n   * 'y' limits movement to vertical axis.\n   * 'none' limits all movement.\n   *\n   * Defaults to 'both'.\n   */\n  axis: _propTypes.default.oneOf(['both', 'x', 'y', 'none']),\n  /**\n   * `bounds` determines the range of movement available to the element.\n   * Available values are:\n   *\n   * 'parent' restricts movement within the Draggable's parent node.\n   *\n   * Alternatively, pass an object with the following properties, all of which are optional:\n   *\n   * {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}\n   *\n   * All values are in px.\n   *\n   * Example:\n   *\n   * ```jsx\n   *   let App = React.createClass({\n   *       render: function () {\n   *         return (\n   *            <Draggable bounds={{right: 300, bottom: 300}}>\n   *              <div>Content</div>\n   *           </Draggable>\n   *         );\n   *       }\n   *   });\n   * ```\n   */\n  bounds: _propTypes.default.oneOfType([_propTypes.default.shape({\n    left: _propTypes.default.number,\n    right: _propTypes.default.number,\n    top: _propTypes.default.number,\n    bottom: _propTypes.default.number\n  }), _propTypes.default.string, _propTypes.default.oneOf([false])]),\n  defaultClassName: _propTypes.default.string,\n  defaultClassNameDragging: _propTypes.default.string,\n  defaultClassNameDragged: _propTypes.default.string,\n  /**\n   * `defaultPosition` specifies the x and y that the dragged item should start at\n   *\n   * Example:\n   *\n   * ```jsx\n   *      let App = React.createClass({\n   *          render: function () {\n   *              return (\n   *                  <Draggable defaultPosition={{x: 25, y: 25}}>\n   *                      <div>I start with transformX: 25px and transformY: 25px;</div>\n   *                  </Draggable>\n   *              );\n   *          }\n   *      });\n   * ```\n   */\n  defaultPosition: _propTypes.default.shape({\n    x: _propTypes.default.number,\n    y: _propTypes.default.number\n  }),\n  positionOffset: _propTypes.default.shape({\n    x: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),\n    y: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string])\n  }),\n  /**\n   * `position`, if present, defines the current position of the element.\n   *\n   *  This is similar to how form elements in React work - if no `position` is supplied, the component\n   *  is uncontrolled.\n   *\n   * Example:\n   *\n   * ```jsx\n   *      let App = React.createClass({\n   *          render: function () {\n   *              return (\n   *                  <Draggable position={{x: 25, y: 25}}>\n   *                      <div>I start with transformX: 25px and transformY: 25px;</div>\n   *                  </Draggable>\n   *              );\n   *          }\n   *      });\n   * ```\n   */\n  position: _propTypes.default.shape({\n    x: _propTypes.default.number,\n    y: _propTypes.default.number\n  }),\n  /**\n   * These properties should be defined on the child, not here.\n   */\n  className: _shims.dontSetMe,\n  style: _shims.dontSetMe,\n  transform: _shims.dontSetMe\n});\n_defineProperty(Draggable, \"defaultProps\", {\n  ..._DraggableCore.default.defaultProps,\n  axis: 'both',\n  bounds: false,\n  defaultClassName: 'react-draggable',\n  defaultClassNameDragging: 'react-draggable-dragging',\n  defaultClassNameDragged: 'react-draggable-dragged',\n  defaultPosition: {\n    x: 0,\n    y: 0\n  },\n  scale: 1\n});","\"use strict\";\n\nconst {\n  default: Draggable,\n  DraggableCore\n} = require('./Draggable');\n\n// Previous versions of this lib exported <Draggable> as the root export. As to no-// them, or TypeScript, we export *both* as the root and as 'default'.\n// See https://github.com/mzabriskie/react-draggable/pull/254\n// and https://github.com/mzabriskie/react-draggable/issues/266\nmodule.exports = Draggable;\nmodule.exports.default = Draggable;\nmodule.exports.DraggableCore = DraggableCore;","\"use strict\";\n\nexports.__esModule = true;\nexports.cloneElement = cloneElement;\nvar _react = _interopRequireDefault(require(\"react\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n// React.addons.cloneWithProps look-alike that merges style & className.\nfunction cloneElement(element, props) {\n  if (props.style && element.props.style) {\n    props.style = _objectSpread(_objectSpread({}, element.props.style), props.style);\n  }\n  if (props.className && element.props.className) {\n    props.className = `${element.props.className} ${props.className}`;\n  }\n  return /*#__PURE__*/_react.default.cloneElement(element, props);\n}","\"use strict\";\n\nexports.__esModule = true;\nexports.resizableProps = void 0;\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _reactDraggable = require(\"react-draggable\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/* global Element */\n// <Resizable>\nconst resizableProps = exports.resizableProps = {\n  /*\n  * Restricts resizing to a particular axis (default: 'both')\n  * 'both' - allows resizing by width or height\n  * 'x' - only allows the width to be changed\n  * 'y' - only allows the height to be changed\n  * 'none' - disables resizing altogether\n  * */\n  axis: _propTypes.default.oneOf(['both', 'x', 'y', 'none']),\n  className: _propTypes.default.string,\n  /*\n  * Require that one and only one child be present.\n  * */\n  children: _propTypes.default.element.isRequired,\n  /*\n  * These will be passed wholesale to react-draggable's DraggableCore\n  * */\n  draggableOpts: _propTypes.default.shape({\n    allowAnyClick: _propTypes.default.bool,\n    cancel: _propTypes.default.string,\n    children: _propTypes.default.node,\n    disabled: _propTypes.default.bool,\n    enableUserSelectHack: _propTypes.default.bool,\n    // #251: Check for Element to support SSR environments where DOM globals don't exist\n    offsetParent: typeof Element !== 'undefined' ? _propTypes.default.instanceOf(Element) : _propTypes.default.any,\n    grid: _propTypes.default.arrayOf(_propTypes.default.number),\n    handle: _propTypes.default.string,\n    nodeRef: _propTypes.default.object,\n    onStart: _propTypes.default.func,\n    onDrag: _propTypes.default.func,\n    onStop: _propTypes.default.func,\n    onMouseDown: _propTypes.default.func,\n    scale: _propTypes.default.number\n  }),\n  /*\n  * Initial height\n  * */\n  height: function () {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n    const [props] = args;\n    // Required if resizing height or both\n    if (props.axis === 'both' || props.axis === 'y') {\n      return _propTypes.default.number.isRequired(...args);\n    }\n    return _propTypes.default.number(...args);\n  },\n  /*\n  * Customize cursor resize handle\n  * */\n  handle: _propTypes.default.oneOfType([_propTypes.default.node, _propTypes.default.func]),\n  /*\n  * If you change this, be sure to update your css\n  * */\n  handleSize: _propTypes.default.arrayOf(_propTypes.default.number),\n  lockAspectRatio: _propTypes.default.bool,\n  /*\n  * Max X & Y measure\n  * */\n  maxConstraints: _propTypes.default.arrayOf(_propTypes.default.number),\n  /*\n  * Min X & Y measure\n  * */\n  minConstraints: _propTypes.default.arrayOf(_propTypes.default.number),\n  /*\n  * Called on stop resize event\n  * */\n  onResizeStop: _propTypes.default.func,\n  /*\n  * Called on start resize event\n  * */\n  onResizeStart: _propTypes.default.func,\n  /*\n  * Called on resize event\n  * */\n  onResize: _propTypes.default.func,\n  /*\n  * Defines which resize handles should be rendered (default: 'se')\n  * 's' - South handle (bottom-center)\n  * 'w' - West handle (left-center)\n  * 'e' - East handle (right-center)\n  * 'n' - North handle (top-center)\n  * 'sw' - Southwest handle (bottom-left)\n  * 'nw' - Northwest handle (top-left)\n  * 'se' - Southeast handle (bottom-right)\n  * 'ne' - Northeast handle (top-center)\n  * */\n  resizeHandles: _propTypes.default.arrayOf(_propTypes.default.oneOf(['s', 'w', 'e', 'n', 'sw', 'nw', 'se', 'ne'])),\n  /*\n  * If `transform: scale(n)` is set on the parent, this should be set to `n`.\n  * */\n  transformScale: _propTypes.default.number,\n  /*\n   * Initial width\n   */\n  width: function () {\n    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n      args[_key2] = arguments[_key2];\n    }\n    const [props] = args;\n    // Required if resizing width or both\n    if (props.axis === 'both' || props.axis === 'x') {\n      return _propTypes.default.number.isRequired(...args);\n    }\n    return _propTypes.default.number(...args);\n  }\n};","\"use strict\";\n\nexports.__esModule = true;\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _reactDraggable = require(\"react-draggable\");\nvar _utils = require(\"./utils\");\nvar _propTypes = require(\"./propTypes\");\nconst _excluded = [\"children\", \"className\", \"draggableOpts\", \"width\", \"height\", \"handle\", \"handleSize\", \"lockAspectRatio\", \"axis\", \"minConstraints\", \"maxConstraints\", \"onResize\", \"onResizeStop\", \"onResizeStart\", \"resizeHandles\", \"transformScale\"];\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) \"default\" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }\nfunction _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }\nfunction _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }\nfunction _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n// The base <Resizable> component.\n// This component does not have state and relies on the parent to set its props based on callback data.\nclass Resizable extends React.Component {\n  constructor() {\n    super(...arguments);\n    this.handleRefs = {};\n    this.lastHandleRect = null;\n    this.slack = null;\n    this.lastSize = null;\n  }\n  componentWillUnmount() {\n    this.resetData();\n  }\n  resetData() {\n    this.lastHandleRect = this.slack = this.lastSize = null;\n  }\n\n  // Clamp width and height within provided constraints\n  runConstraints(width, height) {\n    const {\n      minConstraints,\n      maxConstraints,\n      lockAspectRatio\n    } = this.props;\n    // short circuit\n    if (!minConstraints && !maxConstraints && !lockAspectRatio) return [width, height];\n\n    // If constraining to min and max, we need to also fit width and height to aspect ratio.\n    if (lockAspectRatio) {\n      const ratio = this.props.width / this.props.height;\n      const deltaW = width - this.props.width;\n      const deltaH = height - this.props.height;\n\n      // Find which coordinate was greater and should push the other toward it.\n      // E.g.:\n      // ratio = 1, deltaW = 10, deltaH = 5, deltaH should become 10.\n      // ratio = 2, deltaW = 10, deltaH = 6, deltaW should become 12.\n      if (Math.abs(deltaW) > Math.abs(deltaH * ratio)) {\n        height = width / ratio;\n      } else {\n        width = height * ratio;\n      }\n    }\n    const [oldW, oldH] = [width, height];\n\n    // Add slack to the values used to calculate bound position. This will ensure that if\n    // we start removing slack, the element won't react to it right away until it's been\n    // completely removed.\n    let [slackW, slackH] = this.slack || [0, 0];\n    width += slackW;\n    height += slackH;\n    if (minConstraints) {\n      width = Math.max(minConstraints[0], width);\n      height = Math.max(minConstraints[1], height);\n    }\n    if (maxConstraints) {\n      width = Math.min(maxConstraints[0], width);\n      height = Math.min(maxConstraints[1], height);\n    }\n\n    // If the width or height changed, we must have introduced some slack. Record it for the next iteration.\n    this.slack = [slackW + (oldW - width), slackH + (oldH - height)];\n    return [width, height];\n  }\n\n  /**\n   * Wrapper around drag events to provide more useful data.\n   *\n   * @param  {String} handlerName Handler name to wrap.\n   * @return {Function}           Handler function.\n   */\n  resizeHandler(handlerName, axis) {\n    return (e, _ref) => {\n      let {\n        node,\n        deltaX,\n        deltaY\n      } = _ref;\n      // Reset data in case it was left over somehow (should not be possible)\n      if (handlerName === 'onResizeStart') this.resetData();\n\n      // Axis restrictions\n      const canDragX = (this.props.axis === 'both' || this.props.axis === 'x') && axis !== 'n' && axis !== 's';\n      const canDragY = (this.props.axis === 'both' || this.props.axis === 'y') && axis !== 'e' && axis !== 'w';\n      // No dragging possible.\n      if (!canDragX && !canDragY) return;\n\n      // Decompose axis for later use\n      const axisV = axis[0];\n      const axisH = axis[axis.length - 1]; // intentionally not axis[1], so that this catches axis === 'w' for example\n\n      // Track the element being dragged to account for changes in position.\n      // If a handle's position is changed between callbacks, we need to factor this in to the next callback.\n      // Failure to do so will cause the element to \"skip\" when resized upwards or leftwards.\n      const handleRect = node.getBoundingClientRect();\n      if (this.lastHandleRect != null) {\n        // If the handle has repositioned on either axis since last render,\n        // we need to increase our callback values by this much.\n        // Only checking 'n', 'w' since resizing by 's', 'w' won't affect the overall position on page,\n        if (axisH === 'w') {\n          const deltaLeftSinceLast = handleRect.left - this.lastHandleRect.left;\n          deltaX += deltaLeftSinceLast;\n        }\n        if (axisV === 'n') {\n          const deltaTopSinceLast = handleRect.top - this.lastHandleRect.top;\n          deltaY += deltaTopSinceLast;\n        }\n      }\n      // Storage of last rect so we know how much it has really moved.\n      this.lastHandleRect = handleRect;\n\n      // Reverse delta if using top or left drag handles.\n      if (axisH === 'w') deltaX = -deltaX;\n      if (axisV === 'n') deltaY = -deltaY;\n\n      // Update w/h by the deltas. Also factor in transformScale.\n      let width = this.props.width + (canDragX ? deltaX / this.props.transformScale : 0);\n      let height = this.props.height + (canDragY ? deltaY / this.props.transformScale : 0);\n\n      // Run user-provided constraints.\n      [width, height] = this.runConstraints(width, height);\n\n      // For onResizeStop, use the last size from onResize rather than recalculating.\n      // This avoids issues where props.width/height are stale due to React's batched updates.\n      if (handlerName === 'onResizeStop' && this.lastSize) {\n        ({\n          width,\n          height\n        } = this.lastSize);\n      }\n      const dimensionsChanged = width !== this.props.width || height !== this.props.height;\n\n      // Store the size for use in onResizeStop. We do this after the onResizeStop check\n      // above so we don't overwrite the stored value with a potentially stale calculation.\n      if (handlerName !== 'onResizeStop') {\n        this.lastSize = {\n          width,\n          height\n        };\n      }\n\n      // Call user-supplied callback if present.\n      const cb = typeof this.props[handlerName] === 'function' ? this.props[handlerName] : null;\n      // Don't call 'onResize' if dimensions haven't changed.\n      const shouldSkipCb = handlerName === 'onResize' && !dimensionsChanged;\n      if (cb && !shouldSkipCb) {\n        e.persist?.();\n        cb(e, {\n          node,\n          size: {\n            width,\n            height\n          },\n          handle: axis\n        });\n      }\n\n      // Reset internal data\n      if (handlerName === 'onResizeStop') this.resetData();\n    };\n  }\n\n  // Render a resize handle given an axis & DOM ref. Ref *must* be attached for\n  // the underlying draggable library to work properly.\n  renderResizeHandle(handleAxis, ref) {\n    const {\n      handle\n    } = this.props;\n    // No handle provided, make the default\n    if (!handle) {\n      return /*#__PURE__*/React.createElement(\"span\", {\n        className: `react-resizable-handle react-resizable-handle-${handleAxis}`,\n        ref: ref\n      });\n    }\n    // Handle is a function, such as:\n    // `handle={(handleAxis) => <span className={...} />}`\n    if (typeof handle === 'function') {\n      return handle(handleAxis, ref);\n    }\n    // Handle is a React component (composite or DOM).\n    const isDOMElement = typeof handle.type === 'string';\n    const props = _objectSpread({\n      ref\n    }, isDOMElement ? {} : {\n      handleAxis\n    });\n    return /*#__PURE__*/React.cloneElement(handle, props);\n  }\n  render() {\n    // Pass along only props not meant for the `<Resizable>`.`\n    // eslint-disable-next-line no-unused-vars\n    const _this$props = this.props,\n      {\n        children,\n        className,\n        draggableOpts,\n        width,\n        height,\n        handle,\n        handleSize,\n        lockAspectRatio,\n        axis,\n        minConstraints,\n        maxConstraints,\n        onResize,\n        onResizeStop,\n        onResizeStart,\n        resizeHandles,\n        transformScale\n      } = _this$props,\n      p = _objectWithoutProperties(_this$props, _excluded);\n\n    // What we're doing here is getting the child of this element, and cloning it with this element's props.\n    // We are then defining its children as:\n    // 1. Its original children (resizable's child's children), and\n    // 2. One or more draggable handles.\n    return (0, _utils.cloneElement)(children, _objectSpread(_objectSpread({}, p), {}, {\n      className: `${className ? `${className} ` : ''}react-resizable`,\n      children: [...React.Children.toArray(children.props.children), ...resizeHandles.map(handleAxis => {\n        // Create a ref to the handle so that `<DraggableCore>` doesn't have to use ReactDOM.findDOMNode().\n        const ref = this.handleRefs[handleAxis] ?? (this.handleRefs[handleAxis] = /*#__PURE__*/React.createRef());\n        return /*#__PURE__*/React.createElement(_reactDraggable.DraggableCore, _extends({}, draggableOpts, {\n          nodeRef: ref,\n          key: `resizableHandle-${handleAxis}`,\n          onStop: this.resizeHandler('onResizeStop', handleAxis),\n          onStart: this.resizeHandler('onResizeStart', handleAxis),\n          onDrag: this.resizeHandler('onResize', handleAxis)\n        }), this.renderResizeHandle(handleAxis, ref));\n      })]\n    }));\n  }\n}\nexports.default = Resizable;\nResizable.propTypes = _propTypes.resizableProps;\nResizable.defaultProps = {\n  axis: 'both',\n  handleSize: [20, 20],\n  lockAspectRatio: false,\n  minConstraints: [20, 20],\n  maxConstraints: [Infinity, Infinity],\n  resizeHandles: ['se'],\n  transformScale: 1\n};","\"use strict\";\n\nexports.__esModule = true;\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _Resizable = _interopRequireDefault(require(\"./Resizable\"));\nvar _propTypes2 = require(\"./propTypes\");\nconst _excluded = [\"handle\", \"handleSize\", \"onResize\", \"onResizeStart\", \"onResizeStop\", \"draggableOpts\", \"minConstraints\", \"maxConstraints\", \"lockAspectRatio\", \"axis\", \"width\", \"height\", \"resizeHandles\", \"style\", \"transformScale\"];\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) \"default\" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }\nfunction _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }\nfunction _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }\n// ElementConfig gives us an object type where all items present in `defaultProps` are made optional.\n// <ResizableBox> does not have defaultProps, so we can use this type to tell Flow that we don't\n// care about that and will handle it in <Resizable> instead.\n// A <ResizableBox> can also have a `style` property.\n\nclass ResizableBox extends React.Component {\n  constructor() {\n    super(...arguments);\n    this.state = {\n      width: this.props.width,\n      height: this.props.height,\n      propsWidth: this.props.width,\n      propsHeight: this.props.height\n    };\n    this.onResize = (e, data) => {\n      const {\n        size\n      } = data;\n      if (this.props.onResize) {\n        e.persist?.();\n        this.setState(size, () => this.props.onResize && this.props.onResize(e, data));\n      } else {\n        this.setState(size);\n      }\n    };\n  }\n  static getDerivedStateFromProps(props, state) {\n    // If parent changes height/width, set that in our state.\n    if (state.propsWidth !== props.width || state.propsHeight !== props.height) {\n      return {\n        width: props.width,\n        height: props.height,\n        propsWidth: props.width,\n        propsHeight: props.height\n      };\n    }\n    return null;\n  }\n  render() {\n    // Basic wrapper around a Resizable instance.\n    // If you use Resizable directly, you are responsible for updating the child component\n    // with a new width and height.\n    const _this$props = this.props,\n      {\n        handle,\n        handleSize,\n        onResize,\n        onResizeStart,\n        onResizeStop,\n        draggableOpts,\n        minConstraints,\n        maxConstraints,\n        lockAspectRatio,\n        axis,\n        width,\n        height,\n        resizeHandles,\n        style,\n        transformScale\n      } = _this$props,\n      props = _objectWithoutProperties(_this$props, _excluded);\n    return /*#__PURE__*/React.createElement(_Resizable.default, {\n      axis: axis,\n      draggableOpts: draggableOpts,\n      handle: handle,\n      handleSize: handleSize,\n      height: this.state.height,\n      lockAspectRatio: lockAspectRatio,\n      maxConstraints: maxConstraints,\n      minConstraints: minConstraints,\n      onResizeStart: onResizeStart,\n      onResize: this.onResize,\n      onResizeStop: onResizeStop,\n      resizeHandles: resizeHandles,\n      transformScale: transformScale,\n      width: this.state.width\n    }, /*#__PURE__*/React.createElement(\"div\", _extends({}, props, {\n      style: _objectSpread(_objectSpread({}, style), {}, {\n        width: this.state.width + 'px',\n        height: this.state.height + 'px'\n      })\n    })));\n  }\n}\nexports.default = ResizableBox;\n// PropTypes are identical to <Resizable>, except that children are not strictly required to be present.\nResizableBox.propTypes = _objectSpread(_objectSpread({}, _propTypes2.resizableProps), {}, {\n  children: _propTypes.default.element\n});","'use strict';\nmodule.exports = function() {\n  throw new Error(\"Don't instantiate Resizable directly! Use require('react-resizable').Resizable\");\n};\n\nmodule.exports.Resizable = require('./build/Resizable').default;\nmodule.exports.ResizableBox = require('./build/ResizableBox').default;\n","import { defaultConstraints, setTransform, setTopLeft, perc, applyPositionConstraints, resizeItemInDirection, applySizeConstraints, defaultPositionStrategy, defaultGridConfig, defaultDragConfig, defaultResizeConfig, defaultDropConfig, getCompactor, getBreakpointFromWidth, getColsFromBreakpoint, findOrGenerateResponsiveLayout, getIndentationValue } from './chunk-KDANGDDL.mjs';\nimport { calcXYRaw, calcGridItemWHPx, clamp, calcGridColWidth, calcWHRaw, calcGridItemPosition, bottom, getLayoutItem, cloneLayoutItem, moveElement, withLayoutItem, getAllCollisions, calcXY, cloneLayout, correctBounds } from './chunk-76RTO6EO.mjs';\nimport React2, { useState, useRef, useMemo, useCallback, useEffect } from 'react';\nimport { DraggableCore } from 'react-draggable';\nimport { Resizable } from 'react-resizable';\nimport clsx from 'clsx';\nimport { jsx, jsxs } from 'react/jsx-runtime';\nimport { deepEqual } from 'fast-equals';\n\nfunction GridItem(props) {\n  const {\n    children,\n    cols,\n    containerWidth,\n    margin,\n    containerPadding,\n    rowHeight,\n    maxRows,\n    isDraggable,\n    isResizable,\n    isBounded,\n    static: isStatic,\n    useCSSTransforms = true,\n    usePercentages = false,\n    transformScale = 1,\n    positionStrategy,\n    dragThreshold = 0,\n    droppingPosition,\n    className = \"\",\n    style,\n    handle = \"\",\n    cancel = \"\",\n    x,\n    y,\n    w,\n    h,\n    minW = 1,\n    maxW = Infinity,\n    minH = 1,\n    maxH = Infinity,\n    i,\n    resizeHandles,\n    resizeHandle,\n    constraints = defaultConstraints,\n    layoutItem,\n    layout = [],\n    onDragStart: onDragStartProp,\n    onDrag: onDragProp,\n    onDragStop: onDragStopProp,\n    onResizeStart: onResizeStartProp,\n    onResize: onResizeProp,\n    onResizeStop: onResizeStopProp\n  } = props;\n  const [dragging, setDragging] = useState(false);\n  const [resizing, setResizing] = useState(false);\n  const elementRef = useRef(null);\n  const dragPositionRef = useRef({ left: 0, top: 0 });\n  const resizePositionRef = useRef({\n    top: 0,\n    left: 0,\n    width: 0,\n    height: 0\n  });\n  const prevDroppingPositionRef = useRef(\n    void 0\n  );\n  const layoutRef = useRef(layout);\n  layoutRef.current = layout;\n  const onDragStartRef = useRef(null);\n  const onDragRef = useRef(null);\n  const dragPendingRef = useRef(false);\n  const initialDragClientRef = useRef({ x: 0, y: 0 });\n  const thresholdExceededRef = useRef(false);\n  const positionParams = useMemo(\n    () => ({\n      cols,\n      containerPadding,\n      containerWidth,\n      margin,\n      maxRows,\n      rowHeight\n    }),\n    [cols, containerPadding, containerWidth, margin, maxRows, rowHeight]\n  );\n  const constraintContext = useMemo(\n    () => ({\n      cols,\n      maxRows,\n      containerWidth,\n      containerHeight: 0,\n      // Auto-height grids don't have a fixed container height\n      rowHeight,\n      margin,\n      // Use empty layout here - the actual layout will be accessed via layoutRef when needed\n      // This prevents the context from changing when layout changes, avoiding callback recreation\n      layout: []\n    }),\n    [cols, maxRows, containerWidth, rowHeight, margin]\n  );\n  const getConstraintContext = useCallback(\n    () => ({\n      ...constraintContext,\n      layout: layoutRef.current\n    }),\n    [constraintContext]\n  );\n  const effectiveLayoutItem = useMemo(\n    () => layoutItem ?? {\n      i,\n      x,\n      y,\n      w,\n      h,\n      minW,\n      maxW,\n      minH,\n      maxH\n    },\n    [layoutItem, i, x, y, w, h, minW, maxW, minH, maxH]\n  );\n  const createStyle = useCallback(\n    (pos2) => {\n      if (positionStrategy?.calcStyle) {\n        return positionStrategy.calcStyle(pos2);\n      }\n      if (useCSSTransforms) {\n        return setTransform(pos2);\n      }\n      const styleObj = setTopLeft(pos2);\n      if (usePercentages) {\n        return {\n          ...styleObj,\n          left: perc(pos2.left / containerWidth),\n          width: perc(pos2.width / containerWidth)\n        };\n      }\n      return styleObj;\n    },\n    [positionStrategy, useCSSTransforms, usePercentages, containerWidth]\n  );\n  const onDragStart = useCallback(\n    (e, { node }) => {\n      if (!onDragStartProp) return;\n      const { offsetParent } = node;\n      if (!offsetParent) return;\n      const parentRect = offsetParent.getBoundingClientRect();\n      const clientRect = node.getBoundingClientRect();\n      const cLeft = clientRect.left / transformScale;\n      const pLeft = parentRect.left / transformScale;\n      const cTop = clientRect.top / transformScale;\n      const pTop = parentRect.top / transformScale;\n      let newPosition;\n      if (positionStrategy?.calcDragPosition) {\n        const mouseEvent = e;\n        newPosition = positionStrategy.calcDragPosition(\n          mouseEvent.clientX,\n          mouseEvent.clientY,\n          mouseEvent.clientX - clientRect.left,\n          mouseEvent.clientY - clientRect.top\n        );\n      } else {\n        newPosition = {\n          left: cLeft - pLeft + offsetParent.scrollLeft,\n          top: cTop - pTop + offsetParent.scrollTop\n        };\n      }\n      dragPositionRef.current = newPosition;\n      if (dragThreshold > 0) {\n        const mouseEvent = e;\n        initialDragClientRef.current = {\n          x: mouseEvent.clientX,\n          y: mouseEvent.clientY\n        };\n        dragPendingRef.current = true;\n        thresholdExceededRef.current = false;\n        setDragging(true);\n        return;\n      }\n      setDragging(true);\n      const rawPos = calcXYRaw(\n        positionParams,\n        newPosition.top,\n        newPosition.left\n      );\n      const { x: newX, y: newY } = applyPositionConstraints(\n        constraints,\n        effectiveLayoutItem,\n        rawPos.x,\n        rawPos.y,\n        getConstraintContext()\n      );\n      onDragStartProp(i, newX, newY, {\n        e,\n        node,\n        newPosition\n      });\n    },\n    [\n      onDragStartProp,\n      transformScale,\n      positionParams,\n      positionStrategy,\n      dragThreshold,\n      constraints,\n      effectiveLayoutItem,\n      getConstraintContext,\n      i\n    ]\n  );\n  const onDrag = useCallback(\n    (e, { node, deltaX, deltaY }) => {\n      if (!onDragProp || !dragging) return;\n      const mouseEvent = e;\n      if (dragPendingRef.current && !thresholdExceededRef.current) {\n        const dx = mouseEvent.clientX - initialDragClientRef.current.x;\n        const dy = mouseEvent.clientY - initialDragClientRef.current.y;\n        const distance = Math.hypot(dx, dy);\n        if (distance < dragThreshold) {\n          return;\n        }\n        thresholdExceededRef.current = true;\n        dragPendingRef.current = false;\n        if (onDragStartProp) {\n          const rawPos2 = calcXYRaw(\n            positionParams,\n            dragPositionRef.current.top,\n            dragPositionRef.current.left\n          );\n          const { x: startX, y: startY } = applyPositionConstraints(\n            constraints,\n            effectiveLayoutItem,\n            rawPos2.x,\n            rawPos2.y,\n            getConstraintContext()\n          );\n          onDragStartProp(i, startX, startY, {\n            e,\n            node,\n            newPosition: dragPositionRef.current\n          });\n        }\n      }\n      let top = dragPositionRef.current.top + deltaY;\n      let left = dragPositionRef.current.left + deltaX;\n      if (isBounded) {\n        const { offsetParent } = node;\n        if (offsetParent) {\n          const bottomBoundary = offsetParent.clientHeight - calcGridItemWHPx(h, rowHeight, margin[1]);\n          top = clamp(top, 0, bottomBoundary);\n          const colWidth2 = calcGridColWidth(positionParams);\n          const rightBoundary = containerWidth - calcGridItemWHPx(w, colWidth2, margin[0]);\n          left = clamp(left, 0, rightBoundary);\n        }\n      }\n      const newPosition = { top, left };\n      dragPositionRef.current = newPosition;\n      const rawPos = calcXYRaw(positionParams, top, left);\n      const { x: newX, y: newY } = applyPositionConstraints(\n        constraints,\n        effectiveLayoutItem,\n        rawPos.x,\n        rawPos.y,\n        getConstraintContext()\n      );\n      onDragProp(i, newX, newY, {\n        e,\n        node,\n        newPosition\n      });\n    },\n    [\n      onDragProp,\n      onDragStartProp,\n      dragging,\n      dragThreshold,\n      isBounded,\n      h,\n      rowHeight,\n      margin,\n      positionParams,\n      containerWidth,\n      w,\n      i,\n      constraints,\n      effectiveLayoutItem,\n      getConstraintContext\n    ]\n  );\n  const onDragStop = useCallback(\n    (e, { node }) => {\n      if (!onDragStopProp || !dragging) return;\n      const wasPending = dragPendingRef.current;\n      dragPendingRef.current = false;\n      thresholdExceededRef.current = false;\n      initialDragClientRef.current = { x: 0, y: 0 };\n      if (wasPending) {\n        setDragging(false);\n        dragPositionRef.current = { left: 0, top: 0 };\n        return;\n      }\n      const { left, top } = dragPositionRef.current;\n      const newPosition = { top, left };\n      setDragging(false);\n      dragPositionRef.current = { left: 0, top: 0 };\n      const rawPos = calcXYRaw(positionParams, top, left);\n      const { x: newX, y: newY } = applyPositionConstraints(\n        constraints,\n        effectiveLayoutItem,\n        rawPos.x,\n        rawPos.y,\n        getConstraintContext()\n      );\n      onDragStopProp(i, newX, newY, {\n        e,\n        node,\n        newPosition\n      });\n    },\n    [\n      onDragStopProp,\n      dragging,\n      positionParams,\n      constraints,\n      effectiveLayoutItem,\n      getConstraintContext,\n      i\n    ]\n  );\n  onDragStartRef.current = onDragStart;\n  onDragRef.current = onDrag;\n  const onResizeHandler = useCallback(\n    (e, { node, size, handle: resizeHandle2 }, position, handlerName) => {\n      const handler = handlerName === \"onResizeStart\" ? onResizeStartProp : handlerName === \"onResize\" ? onResizeProp : onResizeStopProp;\n      if (!handler) return;\n      let updatedSize;\n      if (node) {\n        updatedSize = resizeItemInDirection(\n          resizeHandle2,\n          position,\n          size,\n          containerWidth\n        );\n      } else {\n        updatedSize = {\n          ...size,\n          top: position.top,\n          left: position.left\n        };\n      }\n      resizePositionRef.current = updatedSize;\n      const rawSize = calcWHRaw(\n        positionParams,\n        updatedSize.width,\n        updatedSize.height\n      );\n      const { w: newW, h: newH } = applySizeConstraints(\n        constraints,\n        effectiveLayoutItem,\n        rawSize.w,\n        rawSize.h,\n        resizeHandle2,\n        getConstraintContext()\n      );\n      handler(i, newW, newH, {\n        e: e.nativeEvent,\n        node,\n        size: updatedSize,\n        handle: resizeHandle2\n      });\n    },\n    [\n      onResizeStartProp,\n      onResizeProp,\n      onResizeStopProp,\n      containerWidth,\n      positionParams,\n      i,\n      constraints,\n      effectiveLayoutItem,\n      getConstraintContext\n    ]\n  );\n  const handleResizeStart = useCallback(\n    (e, data) => {\n      setResizing(true);\n      const pos2 = calcGridItemPosition(positionParams, x, y, w, h);\n      const typedData = {\n        ...data,\n        handle: data.handle\n      };\n      onResizeHandler(e, typedData, pos2, \"onResizeStart\");\n    },\n    [onResizeHandler, positionParams, x, y, w, h]\n  );\n  const handleResize = useCallback(\n    (e, data) => {\n      const pos2 = calcGridItemPosition(positionParams, x, y, w, h);\n      const typedData = {\n        ...data,\n        handle: data.handle\n      };\n      onResizeHandler(e, typedData, pos2, \"onResize\");\n    },\n    [onResizeHandler, positionParams, x, y, w, h]\n  );\n  const handleResizeStop = useCallback(\n    (e, data) => {\n      setResizing(false);\n      resizePositionRef.current = { top: 0, left: 0, width: 0, height: 0 };\n      const pos2 = calcGridItemPosition(positionParams, x, y, w, h);\n      const typedData = {\n        ...data,\n        handle: data.handle\n      };\n      onResizeHandler(e, typedData, pos2, \"onResizeStop\");\n    },\n    [onResizeHandler, positionParams, x, y, w, h]\n  );\n  useEffect(() => {\n    if (!droppingPosition) return;\n    const node = elementRef.current;\n    if (!node) return;\n    const prevDroppingPosition = prevDroppingPositionRef.current || {\n      left: 0,\n      top: 0\n    };\n    const shouldDrag = dragging && (droppingPosition.left !== prevDroppingPosition.left || droppingPosition.top !== prevDroppingPosition.top);\n    if (!dragging) {\n      const fakeData = {\n        node,\n        deltaX: droppingPosition.left,\n        deltaY: droppingPosition.top,\n        lastX: 0,\n        lastY: 0,\n        x: droppingPosition.left,\n        y: droppingPosition.top\n      };\n      onDragStartRef.current?.(\n        droppingPosition.e,\n        fakeData\n      );\n    } else if (shouldDrag) {\n      const deltaX = droppingPosition.left - dragPositionRef.current.left;\n      const deltaY = droppingPosition.top - dragPositionRef.current.top;\n      const fakeData = {\n        node,\n        deltaX,\n        deltaY,\n        lastX: dragPositionRef.current.left,\n        lastY: dragPositionRef.current.top,\n        x: droppingPosition.left,\n        y: droppingPosition.top\n      };\n      onDragRef.current?.(\n        droppingPosition.e,\n        fakeData\n      );\n    }\n    prevDroppingPositionRef.current = droppingPosition;\n  }, [droppingPosition, dragging, i]);\n  const pos = calcGridItemPosition(\n    positionParams,\n    x,\n    y,\n    w,\n    h,\n    dragging ? dragPositionRef.current : null,\n    resizing ? resizePositionRef.current : null\n  );\n  const child = React2.Children.only(children);\n  const colWidth = calcGridColWidth(positionParams);\n  const minConstraints = [\n    calcGridItemWHPx(minW, colWidth, margin[0]),\n    calcGridItemWHPx(minH, rowHeight, margin[1])\n  ];\n  const maxConstraints = [\n    calcGridItemWHPx(maxW, colWidth, margin[0]),\n    calcGridItemWHPx(maxH, rowHeight, margin[1])\n  ];\n  const childProps = child.props;\n  const childClassName = childProps[\"className\"];\n  const childStyle = childProps[\"style\"];\n  let newChild = React2.cloneElement(child, {\n    ref: elementRef,\n    className: clsx(\"react-grid-item\", childClassName, className, {\n      static: isStatic,\n      resizing,\n      \"react-draggable\": isDraggable,\n      \"react-draggable-dragging\": dragging,\n      dropping: Boolean(droppingPosition),\n      cssTransforms: useCSSTransforms\n    }),\n    style: {\n      ...style,\n      ...childStyle,\n      ...createStyle(pos)\n    }\n  });\n  const resizableHandle = resizeHandle;\n  newChild = /* @__PURE__ */ jsx(\n    Resizable,\n    {\n      draggableOpts: { disabled: !isResizable },\n      className: isResizable ? void 0 : \"react-resizable-hide\",\n      width: pos.width,\n      height: pos.height,\n      minConstraints,\n      maxConstraints,\n      onResizeStart: handleResizeStart,\n      onResize: handleResize,\n      onResizeStop: handleResizeStop,\n      transformScale,\n      resizeHandles,\n      handle: resizableHandle,\n      children: newChild\n    }\n  );\n  newChild = /* @__PURE__ */ jsx(\n    DraggableCore,\n    {\n      disabled: !isDraggable,\n      onStart: onDragStart,\n      onDrag,\n      onStop: onDragStop,\n      handle,\n      cancel: \".react-resizable-handle\" + (cancel ? \",\" + cancel : \"\"),\n      scale: transformScale,\n      nodeRef: elementRef,\n      children: newChild\n    }\n  );\n  return newChild;\n}\nvar noop = () => {\n};\nvar layoutClassName = \"react-grid-layout\";\nvar isFirefox = false;\ntry {\n  isFirefox = /firefox/i.test(navigator.userAgent);\n} catch {\n}\nfunction childrenEqual(a, b) {\n  const aArr = React2.Children.toArray(a);\n  const bArr = React2.Children.toArray(b);\n  if (aArr.length !== bArr.length) return false;\n  for (let i = 0; i < aArr.length; i++) {\n    const aChild = aArr[i];\n    const bChild = bArr[i];\n    if (aChild?.key !== bChild?.key) return false;\n  }\n  return true;\n}\nfunction synchronizeLayoutWithChildren(initialLayout, children, cols, compactor) {\n  const layout = [];\n  const childKeys = /* @__PURE__ */ new Set();\n  React2.Children.forEach(children, (child) => {\n    if (!React2.isValidElement(child) || child.key === null) return;\n    const key = String(child.key);\n    childKeys.add(key);\n    const existingItem = initialLayout.find((l) => l.i === key);\n    if (existingItem) {\n      layout.push(cloneLayoutItem(existingItem));\n    } else {\n      const childProps = child.props;\n      const dataGrid = childProps[\"data-grid\"];\n      if (dataGrid) {\n        layout.push({\n          i: key,\n          x: dataGrid.x ?? 0,\n          y: dataGrid.y ?? 0,\n          w: dataGrid.w ?? 1,\n          h: dataGrid.h ?? 1,\n          minW: dataGrid.minW,\n          maxW: dataGrid.maxW,\n          minH: dataGrid.minH,\n          maxH: dataGrid.maxH,\n          static: dataGrid.static,\n          isDraggable: dataGrid.isDraggable,\n          isResizable: dataGrid.isResizable,\n          resizeHandles: dataGrid.resizeHandles,\n          isBounded: dataGrid.isBounded\n        });\n      } else {\n        layout.push({\n          i: key,\n          x: 0,\n          y: bottom(layout),\n          w: 1,\n          h: 1\n        });\n      }\n    }\n  });\n  const corrected = correctBounds(layout, { cols });\n  return compactor.compact(corrected, cols);\n}\nfunction GridLayout(props) {\n  const {\n    // Required\n    children,\n    width,\n    // Composable config interfaces\n    gridConfig: gridConfigProp,\n    dragConfig: dragConfigProp,\n    resizeConfig: resizeConfigProp,\n    dropConfig: dropConfigProp,\n    positionStrategy = defaultPositionStrategy,\n    compactor: compactorProp,\n    constraints = defaultConstraints,\n    // Layout data\n    layout: propsLayout = [],\n    droppingItem: droppingItemProp,\n    // Container props\n    autoSize = true,\n    className = \"\",\n    style = {},\n    innerRef,\n    // Callbacks\n    onLayoutChange = noop,\n    onDragStart: onDragStartProp = noop,\n    onDrag: onDragProp = noop,\n    onDragStop: onDragStopProp = noop,\n    onResizeStart: onResizeStartProp = noop,\n    onResize: onResizeProp = noop,\n    onResizeStop: onResizeStopProp = noop,\n    onDrop: onDropProp = noop,\n    onDropDragOver: onDropDragOverProp = noop\n  } = props;\n  const gridConfig = useMemo(\n    () => ({ ...defaultGridConfig, ...gridConfigProp }),\n    [gridConfigProp]\n  );\n  const dragConfig = useMemo(\n    () => ({ ...defaultDragConfig, ...dragConfigProp }),\n    [dragConfigProp]\n  );\n  const resizeConfig = useMemo(\n    () => ({ ...defaultResizeConfig, ...resizeConfigProp }),\n    [resizeConfigProp]\n  );\n  const dropConfig = useMemo(\n    () => ({ ...defaultDropConfig, ...dropConfigProp }),\n    [dropConfigProp]\n  );\n  const { cols, rowHeight, maxRows, margin, containerPadding } = gridConfig;\n  const {\n    enabled: isDraggable,\n    bounded: isBounded,\n    handle: draggableHandle,\n    cancel: draggableCancel,\n    threshold: dragThreshold\n  } = dragConfig;\n  const {\n    enabled: isResizable,\n    handles: resizeHandles,\n    handleComponent: resizeHandle\n  } = resizeConfig;\n  const {\n    enabled: isDroppable,\n    defaultItem: defaultDropItem,\n    onDragOver: dropConfigOnDragOver\n  } = dropConfig;\n  const compactor = compactorProp ?? getCompactor(\"vertical\");\n  const compactType = compactor.type;\n  const allowOverlap = compactor.allowOverlap;\n  const preventCollision = compactor.preventCollision ?? false;\n  const droppingItem = useMemo(\n    () => droppingItemProp ?? {\n      i: \"__dropping-elem__\",\n      ...defaultDropItem\n    },\n    [droppingItemProp, defaultDropItem]\n  );\n  const useCSSTransforms = positionStrategy.type === \"transform\";\n  const transformScale = positionStrategy.scale;\n  const effectiveContainerPadding = containerPadding ?? margin;\n  const [mounted, setMounted] = useState(false);\n  const [layout, setLayout] = useState(\n    () => synchronizeLayoutWithChildren(propsLayout, children, cols, compactor)\n  );\n  const [activeDrag, setActiveDrag] = useState(null);\n  const [resizing, setResizing] = useState(false);\n  const [droppingDOMNode, setDroppingDOMNode] = useState(\n    null\n  );\n  const [droppingPosition, setDroppingPosition] = useState();\n  const oldDragItemRef = useRef(null);\n  const oldResizeItemRef = useRef(null);\n  const oldLayoutRef = useRef(null);\n  const dragEnterCounterRef = useRef(0);\n  const prevLayoutRef = useRef(layout);\n  const prevPropsLayoutRef = useRef(propsLayout);\n  const prevChildrenRef = useRef(children);\n  const prevCompactTypeRef = useRef(compactType);\n  const layoutRef = useRef(layout);\n  layoutRef.current = layout;\n  useEffect(() => {\n    setMounted(true);\n    if (!deepEqual(layout, propsLayout)) {\n      onLayoutChange(layout);\n    }\n  }, []);\n  useEffect(() => {\n    if (activeDrag) return;\n    if (droppingDOMNode) return;\n    const layoutChanged = !deepEqual(propsLayout, prevPropsLayoutRef.current);\n    const childrenChanged = !childrenEqual(children, prevChildrenRef.current);\n    const compactTypeChanged = compactType !== prevCompactTypeRef.current;\n    if (layoutChanged || childrenChanged || compactTypeChanged) {\n      const baseLayout = layoutChanged ? propsLayout : layout;\n      const newLayout = synchronizeLayoutWithChildren(\n        baseLayout,\n        children,\n        cols,\n        compactor\n      );\n      if (!deepEqual(newLayout, layout)) {\n        setLayout(newLayout);\n      }\n    }\n    prevPropsLayoutRef.current = propsLayout;\n    prevChildrenRef.current = children;\n    prevCompactTypeRef.current = compactType;\n  }, [\n    propsLayout,\n    children,\n    cols,\n    compactType,\n    compactor,\n    activeDrag,\n    droppingDOMNode,\n    layout\n  ]);\n  useEffect(() => {\n    if (!activeDrag && !deepEqual(layout, prevLayoutRef.current)) {\n      prevLayoutRef.current = layout;\n      const publicLayout = layout.filter((l) => l.i !== droppingItem.i);\n      onLayoutChange(publicLayout);\n    }\n  }, [layout, activeDrag, onLayoutChange, droppingItem.i]);\n  const containerHeight = useMemo(() => {\n    if (!autoSize) return void 0;\n    const nbRow = bottom(layout);\n    const containerPaddingY = effectiveContainerPadding[1];\n    return nbRow * rowHeight + (nbRow - 1) * margin[1] + containerPaddingY * 2 + \"px\";\n  }, [autoSize, layout, rowHeight, margin, effectiveContainerPadding]);\n  const onDragStart = useCallback(\n    (i, _x, _y, data) => {\n      const currentLayout = layoutRef.current;\n      const l = getLayoutItem(currentLayout, i);\n      if (!l) return;\n      const placeholder = {\n        w: l.w,\n        h: l.h,\n        x: l.x,\n        y: l.y,\n        i\n      };\n      oldDragItemRef.current = cloneLayoutItem(l);\n      oldLayoutRef.current = currentLayout;\n      setActiveDrag(placeholder);\n      onDragStartProp(currentLayout, l, l, null, data.e, data.node);\n    },\n    [onDragStartProp]\n  );\n  const onDrag = useCallback(\n    (i, x, y, data) => {\n      const currentLayout = layoutRef.current;\n      const oldDragItem = oldDragItemRef.current;\n      const l = getLayoutItem(currentLayout, i);\n      if (!l) return;\n      const placeholder = {\n        w: l.w,\n        h: l.h,\n        x: l.x,\n        y: l.y,\n        i\n      };\n      const newLayout = moveElement(\n        currentLayout,\n        l,\n        x,\n        y,\n        true,\n        preventCollision,\n        compactType,\n        cols,\n        allowOverlap\n      );\n      onDragProp(newLayout, oldDragItem, l, placeholder, data.e, data.node);\n      setLayout(compactor.compact(newLayout, cols));\n      setActiveDrag(placeholder);\n    },\n    [preventCollision, compactType, cols, allowOverlap, compactor, onDragProp]\n  );\n  const onDragStop = useCallback(\n    (i, x, y, data) => {\n      if (!activeDrag) return;\n      const currentLayout = layoutRef.current;\n      const oldDragItem = oldDragItemRef.current;\n      const l = getLayoutItem(currentLayout, i);\n      if (!l) return;\n      const newLayout = moveElement(\n        currentLayout,\n        l,\n        x,\n        y,\n        true,\n        preventCollision,\n        compactType,\n        cols,\n        allowOverlap\n      );\n      const finalLayout = compactor.compact(newLayout, cols);\n      onDragStopProp(finalLayout, oldDragItem, l, null, data.e, data.node);\n      const oldLayout = oldLayoutRef.current;\n      oldDragItemRef.current = null;\n      oldLayoutRef.current = null;\n      setActiveDrag(null);\n      setLayout(finalLayout);\n      if (oldLayout && !deepEqual(oldLayout, finalLayout)) {\n        onLayoutChange(finalLayout);\n      }\n    },\n    [\n      activeDrag,\n      preventCollision,\n      compactType,\n      cols,\n      allowOverlap,\n      compactor,\n      onDragStopProp,\n      onLayoutChange\n    ]\n  );\n  const onResizeStart = useCallback(\n    (i, _w, _h, data) => {\n      const currentLayout = layoutRef.current;\n      const l = getLayoutItem(currentLayout, i);\n      if (!l) return;\n      oldResizeItemRef.current = cloneLayoutItem(l);\n      oldLayoutRef.current = currentLayout;\n      setResizing(true);\n      onResizeStartProp(currentLayout, l, l, null, data.e, data.node);\n    },\n    [onResizeStartProp]\n  );\n  const onResize = useCallback(\n    (i, w, h, data) => {\n      const currentLayout = layoutRef.current;\n      const oldResizeItem = oldResizeItemRef.current;\n      const { handle } = data;\n      let shouldMoveItem = false;\n      let newX;\n      let newY;\n      const [newLayout, l] = withLayoutItem(currentLayout, i, (item) => {\n        newX = item.x;\n        newY = item.y;\n        if ([\"sw\", \"w\", \"nw\", \"n\", \"ne\"].includes(handle)) {\n          if ([\"sw\", \"nw\", \"w\"].includes(handle)) {\n            newX = item.x + (item.w - w);\n            w = item.x !== newX && newX < 0 ? item.w : w;\n            newX = newX < 0 ? 0 : newX;\n          }\n          if ([\"ne\", \"n\", \"nw\"].includes(handle)) {\n            newY = item.y + (item.h - h);\n            h = item.y !== newY && newY < 0 ? item.h : h;\n            newY = newY < 0 ? 0 : newY;\n          }\n          shouldMoveItem = true;\n        }\n        if (preventCollision && !allowOverlap) {\n          const collisions = getAllCollisions(currentLayout, {\n            ...item,\n            w,\n            h,\n            x: newX ?? item.x,\n            y: newY ?? item.y\n          }).filter((layoutItem) => layoutItem.i !== item.i);\n          if (collisions.length > 0) {\n            newY = item.y;\n            h = item.h;\n            newX = item.x;\n            w = item.w;\n            shouldMoveItem = false;\n          }\n        }\n        item.w = w;\n        item.h = h;\n        return item;\n      });\n      if (!l) return;\n      let finalLayout = newLayout;\n      if (shouldMoveItem && newX !== void 0 && newY !== void 0) {\n        finalLayout = moveElement(\n          newLayout,\n          l,\n          newX,\n          newY,\n          true,\n          preventCollision,\n          compactType,\n          cols,\n          allowOverlap\n        );\n      }\n      const placeholder = {\n        w: l.w,\n        h: l.h,\n        x: l.x,\n        y: l.y,\n        i,\n        static: true\n      };\n      onResizeProp(\n        finalLayout,\n        oldResizeItem,\n        l,\n        placeholder,\n        data.e,\n        data.node\n      );\n      setLayout(compactor.compact(finalLayout, cols));\n      setActiveDrag(placeholder);\n    },\n    [preventCollision, compactType, cols, allowOverlap, compactor, onResizeProp]\n  );\n  const onResizeStop = useCallback(\n    (i, _w, _h, data) => {\n      const currentLayout = layoutRef.current;\n      const oldResizeItem = oldResizeItemRef.current;\n      const l = getLayoutItem(currentLayout, i);\n      const finalLayout = compactor.compact(currentLayout, cols);\n      onResizeStopProp(\n        finalLayout,\n        oldResizeItem,\n        l ?? null,\n        null,\n        data.e,\n        data.node\n      );\n      const oldLayout = oldLayoutRef.current;\n      oldResizeItemRef.current = null;\n      oldLayoutRef.current = null;\n      setActiveDrag(null);\n      setResizing(false);\n      setLayout(finalLayout);\n      if (oldLayout && !deepEqual(oldLayout, finalLayout)) {\n        onLayoutChange(finalLayout);\n      }\n    },\n    [cols, compactor, onResizeStopProp, onLayoutChange]\n  );\n  const removeDroppingPlaceholder = useCallback(() => {\n    const currentLayout = layoutRef.current;\n    const hasDroppingItem = currentLayout.some((l) => l.i === droppingItem.i);\n    if (!hasDroppingItem) {\n      setDroppingDOMNode(null);\n      setActiveDrag(null);\n      setDroppingPosition(void 0);\n      return;\n    }\n    const newLayout = compactor.compact(\n      currentLayout.filter((l) => l.i !== droppingItem.i),\n      cols\n    );\n    setLayout(newLayout);\n    setDroppingDOMNode(null);\n    setActiveDrag(null);\n    setDroppingPosition(void 0);\n  }, [droppingItem.i, cols, compactor]);\n  const handleDragOver = useCallback(\n    (e) => {\n      e.preventDefault();\n      e.stopPropagation();\n      if (isFirefox && !e.nativeEvent.target?.classList.contains(\n        layoutClassName\n      )) {\n        return false;\n      }\n      const rawResult = dropConfigOnDragOver ? dropConfigOnDragOver(e.nativeEvent) : onDropDragOverProp(e);\n      if (rawResult === false) {\n        if (droppingDOMNode) {\n          removeDroppingPlaceholder();\n        }\n        return false;\n      }\n      const {\n        dragOffsetX = 0,\n        dragOffsetY = 0,\n        ...onDragOverResult\n      } = rawResult ?? {};\n      const finalDroppingItem = { ...droppingItem, ...onDragOverResult };\n      const gridRect = e.currentTarget.getBoundingClientRect();\n      const positionParams = {\n        cols,\n        margin,\n        maxRows,\n        rowHeight,\n        containerWidth: width,\n        containerPadding: effectiveContainerPadding\n      };\n      const actualColWidth = calcGridColWidth(positionParams);\n      const itemPixelWidth = calcGridItemWHPx(\n        finalDroppingItem.w,\n        actualColWidth,\n        margin[0]\n      );\n      const itemPixelHeight = calcGridItemWHPx(\n        finalDroppingItem.h,\n        rowHeight,\n        margin[1]\n      );\n      const itemCenterOffsetX = itemPixelWidth / 2;\n      const itemCenterOffsetY = itemPixelHeight / 2;\n      const rawGridX = e.clientX - gridRect.left + dragOffsetX - itemCenterOffsetX;\n      const rawGridY = e.clientY - gridRect.top + dragOffsetY - itemCenterOffsetY;\n      const clampedGridX = Math.max(0, rawGridX);\n      const clampedGridY = Math.max(0, rawGridY);\n      const newDroppingPosition = {\n        left: clampedGridX / transformScale,\n        top: clampedGridY / transformScale,\n        e: e.nativeEvent\n      };\n      if (!droppingDOMNode) {\n        const calculatedPosition = calcXY(\n          positionParams,\n          clampedGridY,\n          clampedGridX,\n          finalDroppingItem.w,\n          finalDroppingItem.h\n        );\n        setDroppingDOMNode(/* @__PURE__ */ jsx(\"div\", {}, finalDroppingItem.i));\n        setDroppingPosition(newDroppingPosition);\n        const baseLayout = layoutRef.current.filter(\n          (l) => l.i !== finalDroppingItem.i\n        );\n        setLayout([\n          ...baseLayout,\n          {\n            ...finalDroppingItem,\n            x: calculatedPosition.x,\n            y: calculatedPosition.y,\n            static: false,\n            isDraggable: true\n          }\n        ]);\n      } else if (droppingPosition) {\n        const shouldUpdate = droppingPosition.left !== newDroppingPosition.left || droppingPosition.top !== newDroppingPosition.top;\n        if (shouldUpdate) {\n          setDroppingPosition(newDroppingPosition);\n        }\n      }\n    },\n    [\n      droppingDOMNode,\n      droppingPosition,\n      droppingItem,\n      dropConfigOnDragOver,\n      onDropDragOverProp,\n      removeDroppingPlaceholder,\n      transformScale,\n      cols,\n      margin,\n      maxRows,\n      rowHeight,\n      width,\n      effectiveContainerPadding\n    ]\n  );\n  const handleDragLeave = useCallback(\n    (e) => {\n      e.preventDefault();\n      e.stopPropagation();\n      dragEnterCounterRef.current--;\n      if (dragEnterCounterRef.current < 0) {\n        dragEnterCounterRef.current = 0;\n      }\n      if (dragEnterCounterRef.current === 0) {\n        removeDroppingPlaceholder();\n      }\n    },\n    [removeDroppingPlaceholder]\n  );\n  const handleDragEnter = useCallback((e) => {\n    e.preventDefault();\n    e.stopPropagation();\n    dragEnterCounterRef.current++;\n  }, []);\n  const handleDrop = useCallback(\n    (e) => {\n      e.preventDefault();\n      e.stopPropagation();\n      const currentLayout = layoutRef.current;\n      const item = currentLayout.find((l) => l.i === droppingItem.i);\n      dragEnterCounterRef.current = 0;\n      removeDroppingPlaceholder();\n      onDropProp(currentLayout, item, e.nativeEvent);\n    },\n    [droppingItem.i, removeDroppingPlaceholder, onDropProp]\n  );\n  const processGridItem = useCallback(\n    (child, isDroppingItem) => {\n      if (!child || !child.key) return null;\n      const l = getLayoutItem(layout, String(child.key));\n      if (!l) return null;\n      const draggable = typeof l.isDraggable === \"boolean\" ? l.isDraggable : !l.static && isDraggable;\n      const resizable = typeof l.isResizable === \"boolean\" ? l.isResizable : !l.static && isResizable;\n      const resizeHandlesOptions = l.resizeHandles || [...resizeHandles];\n      const bounded = draggable && isBounded && l.isBounded !== false;\n      const resizeHandleElement = resizeHandle;\n      return /* @__PURE__ */ jsx(\n        GridItem,\n        {\n          containerWidth: width,\n          cols,\n          margin,\n          containerPadding: effectiveContainerPadding,\n          maxRows,\n          rowHeight,\n          cancel: draggableCancel,\n          handle: draggableHandle,\n          onDragStart,\n          onDrag,\n          onDragStop,\n          onResizeStart,\n          onResize,\n          onResizeStop,\n          isDraggable: draggable,\n          isResizable: resizable,\n          isBounded: bounded,\n          useCSSTransforms: useCSSTransforms && mounted,\n          usePercentages: !mounted,\n          transformScale,\n          positionStrategy,\n          dragThreshold,\n          w: l.w,\n          h: l.h,\n          x: l.x,\n          y: l.y,\n          i: l.i,\n          minH: l.minH,\n          minW: l.minW,\n          maxH: l.maxH,\n          maxW: l.maxW,\n          static: l.static,\n          droppingPosition: isDroppingItem ? droppingPosition : void 0,\n          resizeHandles: resizeHandlesOptions,\n          resizeHandle: resizeHandleElement,\n          constraints,\n          layoutItem: l,\n          layout,\n          children: child\n        },\n        l.i\n      );\n    },\n    [\n      layout,\n      width,\n      cols,\n      margin,\n      effectiveContainerPadding,\n      maxRows,\n      rowHeight,\n      draggableCancel,\n      draggableHandle,\n      onDragStart,\n      onDrag,\n      onDragStop,\n      onResizeStart,\n      onResize,\n      onResizeStop,\n      isDraggable,\n      isResizable,\n      isBounded,\n      useCSSTransforms,\n      mounted,\n      transformScale,\n      positionStrategy,\n      dragThreshold,\n      droppingPosition,\n      resizeHandles,\n      resizeHandle,\n      constraints\n    ]\n  );\n  const renderPlaceholder = () => {\n    if (!activeDrag) return null;\n    return /* @__PURE__ */ jsx(\n      GridItem,\n      {\n        w: activeDrag.w,\n        h: activeDrag.h,\n        x: activeDrag.x,\n        y: activeDrag.y,\n        i: activeDrag.i,\n        className: `react-grid-placeholder ${resizing ? \"placeholder-resizing\" : \"\"}`,\n        containerWidth: width,\n        cols,\n        margin,\n        containerPadding: effectiveContainerPadding,\n        maxRows,\n        rowHeight,\n        isDraggable: false,\n        isResizable: false,\n        isBounded: false,\n        useCSSTransforms,\n        transformScale,\n        constraints,\n        layout,\n        children: /* @__PURE__ */ jsx(\"div\", {})\n      }\n    );\n  };\n  const mergedClassName = clsx(layoutClassName, className);\n  const mergedStyle = {\n    height: containerHeight,\n    ...style\n  };\n  return /* @__PURE__ */ jsxs(\n    \"div\",\n    {\n      ref: innerRef,\n      className: mergedClassName,\n      style: mergedStyle,\n      onDrop: isDroppable ? handleDrop : void 0,\n      onDragLeave: isDroppable ? handleDragLeave : void 0,\n      onDragEnter: isDroppable ? handleDragEnter : void 0,\n      onDragOver: isDroppable ? handleDragOver : void 0,\n      children: [\n        React2.Children.map(children, (child) => {\n          if (!React2.isValidElement(child)) return null;\n          return processGridItem(child);\n        }),\n        isDroppable && droppingDOMNode && processGridItem(droppingDOMNode, true),\n        renderPlaceholder()\n      ]\n    }\n  );\n}\nvar DEFAULT_BREAKPOINTS = {\n  lg: 1200,\n  md: 996,\n  sm: 768,\n  xs: 480,\n  xxs: 0\n};\nvar DEFAULT_COLS = {\n  lg: 12,\n  md: 10,\n  sm: 6,\n  xs: 4,\n  xxs: 2\n};\nvar noop2 = () => {\n};\nfunction synchronizeLayoutWithChildren2(initialLayout, children, cols, compactor) {\n  const layout = [];\n  React2.Children.forEach(children, (child) => {\n    if (!React2.isValidElement(child) || child.key === null) return;\n    const key = String(child.key);\n    const existingItem = initialLayout.find((l) => l.i === key);\n    if (existingItem) {\n      layout.push({\n        ...existingItem,\n        i: key\n      });\n    } else {\n      const childProps = child.props;\n      const dataGrid = childProps[\"data-grid\"];\n      if (dataGrid) {\n        layout.push({\n          i: key,\n          x: dataGrid.x ?? 0,\n          y: dataGrid.y ?? 0,\n          w: dataGrid.w ?? 1,\n          h: dataGrid.h ?? 1,\n          minW: dataGrid.minW,\n          maxW: dataGrid.maxW,\n          minH: dataGrid.minH,\n          maxH: dataGrid.maxH,\n          static: dataGrid.static,\n          isDraggable: dataGrid.isDraggable,\n          isResizable: dataGrid.isResizable,\n          resizeHandles: dataGrid.resizeHandles,\n          isBounded: dataGrid.isBounded\n        });\n      } else {\n        layout.push({\n          i: key,\n          x: 0,\n          y: bottom(layout),\n          w: 1,\n          h: 1\n        });\n      }\n    }\n  });\n  const corrected = correctBounds(layout, { cols });\n  return compactor.compact(corrected, cols);\n}\nfunction ResponsiveGridLayout(props) {\n  const {\n    children,\n    width,\n    breakpoint: propBreakpoint,\n    breakpoints = DEFAULT_BREAKPOINTS,\n    cols: colsConfig = DEFAULT_COLS,\n    layouts: propsLayouts = {},\n    rowHeight = 150,\n    maxRows = Infinity,\n    margin: propMargin = [10, 10],\n    containerPadding: propContainerPadding = null,\n    compactor: compactorProp,\n    onBreakpointChange = noop2,\n    onLayoutChange = noop2,\n    onWidthChange = noop2,\n    ...restProps\n  } = props;\n  const compactor = compactorProp ?? getCompactor(\"vertical\");\n  const compactType = compactor.type;\n  const allowOverlap = compactor.allowOverlap;\n  const initialBreakpoint = useMemo(() => {\n    return propBreakpoint ?? getBreakpointFromWidth(breakpoints, width);\n  }, []);\n  const initialCols = useMemo(() => {\n    return getColsFromBreakpoint(initialBreakpoint, colsConfig);\n  }, [initialBreakpoint, colsConfig]);\n  const initialLayout = useMemo(() => {\n    return findOrGenerateResponsiveLayout(\n      propsLayouts,\n      breakpoints,\n      initialBreakpoint,\n      initialBreakpoint,\n      initialCols,\n      compactType\n    );\n  }, []);\n  const [breakpoint, setBreakpoint] = useState(initialBreakpoint);\n  const [cols, setCols] = useState(initialCols);\n  const [layout, setLayout] = useState(initialLayout);\n  const [layouts, setLayouts] = useState(propsLayouts);\n  const prevWidthRef = useRef(width);\n  const prevBreakpointRef = useRef(propBreakpoint);\n  const prevBreakpointsRef = useRef(breakpoints);\n  const prevColsRef = useRef(colsConfig);\n  const prevLayoutsRef = useRef(propsLayouts);\n  const prevCompactTypeRef = useRef(compactType);\n  const layoutsRef = useRef(layouts);\n  useEffect(() => {\n    layoutsRef.current = layouts;\n  }, [layouts]);\n  const derivedLayout = useMemo(() => {\n    if (!deepEqual(propsLayouts, prevLayoutsRef.current)) {\n      return findOrGenerateResponsiveLayout(\n        propsLayouts,\n        breakpoints,\n        breakpoint,\n        breakpoint,\n        cols,\n        compactor\n      );\n    }\n    return null;\n  }, [propsLayouts, breakpoints, breakpoint, cols, compactor]);\n  const effectiveLayout = derivedLayout ?? layout;\n  useEffect(() => {\n    if (derivedLayout !== null) {\n      setLayout(derivedLayout);\n      setLayouts(propsLayouts);\n      layoutsRef.current = propsLayouts;\n      prevLayoutsRef.current = propsLayouts;\n    }\n  }, [derivedLayout, propsLayouts]);\n  useEffect(() => {\n    if (compactType !== prevCompactTypeRef.current) {\n      const newLayout = compactor.compact(cloneLayout(effectiveLayout), cols);\n      const newLayouts = {\n        ...layoutsRef.current,\n        [breakpoint]: newLayout\n      };\n      setLayout(newLayout);\n      setLayouts(newLayouts);\n      layoutsRef.current = newLayouts;\n      onLayoutChange(newLayout, newLayouts);\n      prevCompactTypeRef.current = compactType;\n    }\n  }, [\n    compactType,\n    compactor,\n    effectiveLayout,\n    cols,\n    allowOverlap,\n    breakpoint,\n    onLayoutChange\n  ]);\n  useEffect(() => {\n    const widthChanged = width !== prevWidthRef.current;\n    const breakpointPropChanged = propBreakpoint !== prevBreakpointRef.current;\n    const breakpointsChanged = !deepEqual(\n      breakpoints,\n      prevBreakpointsRef.current\n    );\n    const colsChanged = !deepEqual(colsConfig, prevColsRef.current);\n    if (widthChanged || breakpointPropChanged || breakpointsChanged || colsChanged) {\n      const newBreakpoint = propBreakpoint ?? getBreakpointFromWidth(breakpoints, width);\n      const newCols = getColsFromBreakpoint(newBreakpoint, colsConfig);\n      const lastBreakpoint = breakpoint;\n      if (lastBreakpoint !== newBreakpoint || breakpointsChanged || colsChanged) {\n        const newLayouts = { ...layoutsRef.current };\n        if (!newLayouts[lastBreakpoint]) {\n          newLayouts[lastBreakpoint] = cloneLayout(layout);\n        }\n        let newLayout = findOrGenerateResponsiveLayout(\n          newLayouts,\n          breakpoints,\n          newBreakpoint,\n          lastBreakpoint,\n          newCols,\n          compactor\n        );\n        newLayout = synchronizeLayoutWithChildren2(\n          newLayout,\n          children,\n          newCols,\n          compactor\n        );\n        newLayouts[newBreakpoint] = newLayout;\n        setBreakpoint(newBreakpoint);\n        setCols(newCols);\n        setLayout(newLayout);\n        setLayouts(newLayouts);\n        layoutsRef.current = newLayouts;\n        onBreakpointChange(newBreakpoint, newCols);\n        onLayoutChange(newLayout, newLayouts);\n      }\n      const currentMargin2 = getIndentationValue(\n        propMargin,\n        newBreakpoint\n      );\n      const currentPadding = propContainerPadding ? getIndentationValue(\n        propContainerPadding,\n        newBreakpoint\n      ) : null;\n      onWidthChange(width, currentMargin2, newCols, currentPadding);\n      prevWidthRef.current = width;\n      prevBreakpointRef.current = propBreakpoint;\n      prevBreakpointsRef.current = breakpoints;\n      prevColsRef.current = colsConfig;\n    }\n  }, [\n    width,\n    propBreakpoint,\n    breakpoints,\n    colsConfig,\n    breakpoint,\n    cols,\n    layout,\n    children,\n    compactor,\n    compactType,\n    allowOverlap,\n    propMargin,\n    propContainerPadding,\n    onBreakpointChange,\n    onLayoutChange,\n    onWidthChange\n  ]);\n  const handleLayoutChange = useCallback(\n    (newLayout) => {\n      const currentLayouts = layoutsRef.current;\n      const newLayouts = {\n        ...currentLayouts,\n        [breakpoint]: newLayout\n      };\n      setLayout(newLayout);\n      setLayouts(newLayouts);\n      layoutsRef.current = newLayouts;\n      onLayoutChange(newLayout, newLayouts);\n    },\n    [breakpoint, onLayoutChange]\n  );\n  const currentMargin = useMemo(() => {\n    return getIndentationValue(\n      propMargin,\n      breakpoint\n    );\n  }, [propMargin, breakpoint]);\n  const currentContainerPadding = useMemo(() => {\n    if (propContainerPadding === null) return null;\n    return getIndentationValue(\n      propContainerPadding,\n      breakpoint\n    );\n  }, [propContainerPadding, breakpoint]);\n  const gridConfig = useMemo(\n    () => ({\n      cols,\n      rowHeight,\n      maxRows,\n      margin: currentMargin,\n      containerPadding: currentContainerPadding\n    }),\n    [cols, rowHeight, maxRows, currentMargin, currentContainerPadding]\n  );\n  return /* @__PURE__ */ jsx(\n    GridLayout,\n    {\n      ...restProps,\n      width,\n      gridConfig,\n      compactor,\n      onLayoutChange: handleLayoutChange,\n      layout: effectiveLayout,\n      children\n    }\n  );\n}\n\nexport { GridItem, GridLayout, ResponsiveGridLayout };\n","import React, { useEffect, useState, useRef } from 'react';\n\n/**\n * HOC Personalizado de WidthProvider.\n * \n * ¿Por qué este componente y no el oficial?\n * En entornos con Vite > 4.x (especialmente Vite 8 como indica el PRD), \n * el `WidthProvider` exportado por `react-grid-layout` usa lifecycle hooks de clases antiguas \n * y refs incompatibles que crashean en React 18+ strict mode.\n * \n * Este HOC soluciona el problema usando el moderno `ResizeObserver` API,\n * garantizando que el Layout funcione sin fugas de memoria y empaquetado fluidamente.\n */\n\ninterface WidthProviderProps {\n  measureBeforeMount?: boolean;\n  [key: string]: any;\n}\n\nexport function withResponsiveWidth<P extends { width: number }>(\n  WrappedComponent: React.ComponentType<P>\n) {\n  return function ResponsiveGrid(props: Omit<P, 'width'> & WidthProviderProps) {\n    const { measureBeforeMount = false, ...rest } = props;\n    const [width, setWidth] = useState<number>(0);\n    const containerRef = useRef<HTMLDivElement>(null);\n\n    useEffect(() => {\n      const container = containerRef.current;\n      if (!container) return;\n\n      // Usar ResizeObserver para mayor rendimiento y cero crasheos\n      const resizeObserver = new ResizeObserver((entries) => {\n        for (const entry of entries) {\n          const newWidth = entry.contentRect.width;\n          if (newWidth > 0 && newWidth !== width) {\n            // Un pequeño rAF previene el error \"ResizeObserver loop limit exceeded\" en UI pesadas\n            window.requestAnimationFrame(() => {\n              setWidth(newWidth);\n            });\n          }\n        }\n      });\n\n      resizeObserver.observe(container);\n\n      // Limpieza (Vital para la regla de cero memory leaks BMAD6)\n      return () => {\n        resizeObserver.disconnect();\n      };\n    }, []);\n\n    // Si requiere medida antes de montar, no renderizamos el componente hasta no tener ancho\n    if (measureBeforeMount && width === 0) {\n      return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />;\n    }\n\n    return (\n      <div ref={containerRef} style={{ width: '100%', minHeight: '100%' }}>\n        <WrappedComponent {...(rest as P)} width={width || 1200} />\n      </div>\n    );\n  };\n}\n","/**\n * Migración del alto de fila de la grilla.\n *\n * <b>El problema.</b> `rowHeight` era 148px y el diseño pide 80. No es un ajuste\n * cosmético: <b>148 no tiene granularidad</b>. Una tarjeta de KPI necesita unos\n * 170px —cifra, sparkline y delta— y con 148 sólo se puede pedir 148 (no cabe) o\n * 296 (el doble de lo necesario). Con 80: `2 × 80 + 12 = 172`, exacto.\n *\n * <b>Por qué no un UPDATE masivo.</b> Cambiar `rowHeight` sin tocar los `row_span`\n * guardados encogería todos los widgets existentes casi a la mitad. Y un script que\n * recorra los tenants asume que todos corren la misma versión del kit el mismo día,\n * que en un producto con muchos clientes no es cierto.\n *\n * <b>La salida: perezosa y sellada.</b> La tabla de preferencias ya tiene una\n * columna `config_json` (jsonb). Se estampa ahí `layoutVersion`. La primera vez que\n * un usuario abre el tablero, las filas sin sello se convierten en memoria y el\n * sello viaja en el siguiente guardado. Sin cambios de esquema, sin tocar el\n * contrato del paquete NuGet, idempotente, y cada cliente migra cuando le llega su\n * versión.\n */\n\n/** Alto de fila anterior. */\nexport const LEGACY_ROW_HEIGHT = 148;\n\n/** Alto de fila actual. */\nexport const ROW_HEIGHT = 80;\n\n/** Versión del formato de layout. Subirla obliga a una nueva conversión. */\nexport const LAYOUT_VERSION = 2;\n\ninterface MigratablePreference {\n  row_span: number;\n  config_json?: Record<string, unknown> | null;\n}\n\n/**\n * Convierte una preferencia al formato actual si aún no lo está.\n *\n * Devuelve el mismo objeto —por referencia— cuando no hay nada que hacer, para que\n * React no vea un cambio donde no lo hubo.\n */\nexport function migratePreference<T extends MigratablePreference>(preference: T): T {\n  const version = (preference.config_json?.layoutVersion as number | undefined) ?? 1;\n  if (version >= LAYOUT_VERSION) return preference;\n\n  /**\n   * El alto en píxeles se conserva; lo que cambia es en cuántas filas se expresa.\n   * `Math.round` y no `ceil`: redondear siempre hacia arriba haría crecer el\n   * tablero entero un poco en cada migración.\n   */\n  const converted = Math.max(1, Math.round((preference.row_span * LEGACY_ROW_HEIGHT) / ROW_HEIGHT));\n\n  return {\n    ...preference,\n    row_span: converted,\n    config_json: { ...(preference.config_json ?? {}), layoutVersion: LAYOUT_VERSION },\n  };\n}\n\n/** Aplica la conversión a un layout completo. */\nexport function migrateLayout<T extends MigratablePreference>(layout: T[]): T[] {\n  return layout.map(migratePreference);\n}\n\n/** Si un layout tiene alguna fila pendiente de convertir. */\nexport function needsMigration<T extends MigratablePreference>(layout: T[]): boolean {\n  return layout.some(\n    pref => ((pref.config_json?.layoutVersion as number | undefined) ?? 1) < LAYOUT_VERSION,\n  );\n}\n","import React, { useMemo } from 'react';\nimport { Responsive as ResponsiveGridLayoutOriginal } from 'react-grid-layout';\nimport type { Layout, LayoutItem } from 'react-grid-layout';\nimport 'react-grid-layout/css/styles.css';\nimport 'react-resizable/css/styles.css';\n\nimport { withResponsiveWidth } from '../components/DashboardEngine/components/WidthProviderHOC';\nimport type { UserWidgetPreferenceBase, WidgetDefinitionBase } from '../components/DashboardEngine/types';\nimport { ROW_HEIGHT, migrateLayout } from './utils/layoutMigration';\n\n// Envolvemos el grid responsivo con nuestro HOC a prueba de memory leaks (Vite 8 fix)\nconst ResponsiveGrid = withResponsiveWidth(ResponsiveGridLayoutOriginal);\n\ninterface DashboardGridProps<\n  TPreference extends UserWidgetPreferenceBase = UserWidgetPreferenceBase,\n  TDefinition extends WidgetDefinitionBase = WidgetDefinitionBase\n> {\n  layout: TPreference[];\n  catalog: TDefinition[];\n  isEditMode: boolean;\n  globalFilters: Record<string, unknown>;\n  onLayoutChange: (newLayout: TPreference[]) => void;\n  onRemoveWidget: (id: string) => void;\n  renderWidget: (\n    preference: TPreference,\n    definition: TDefinition,\n    isEditMode: boolean,\n    globalFilters: Record<string, unknown>,\n    onRemove: (id: string) => void\n  ) => React.ReactNode;\n}\n\nexport const DashboardGrid = <\n  TPreference extends UserWidgetPreferenceBase,\n  TDefinition extends WidgetDefinitionBase\n>({\n  layout,\n  catalog,\n  isEditMode,\n  globalFilters,\n  onLayoutChange,\n  onRemoveWidget,\n  renderWidget\n}: DashboardGridProps<TPreference, TDefinition>) => {\n  /**\n   * Layout ya convertido al formato actual. Ver `layoutMigration.ts`: las filas sin\n   * sello se convierten en memoria y el sello viaja en el siguiente guardado, así\n   * que ningún cliente necesita un script ni un despliegue coordinado.\n   */\n  const migrated = useMemo(() => migrateLayout(layout), [layout]);\n\n  const gridLayouts = useMemo(() => {\n    const validLayouts: LayoutItem[] = migrated.map(pref => {\n      const def = catalog.find(c => c.widget_id === pref.widget_id);\n      return {\n        i: pref.id,\n        x: pref.pos_x,\n        y: pref.pos_y,\n        w: pref.col_span,\n        h: pref.row_span,\n        minW: def?.col_min || 2,\n        maxW: def?.col_max || 12,\n        isDraggable: isEditMode,\n        isResizable: isEditMode,\n      };\n    });\n\n    return { lg: validLayouts, md: validLayouts };\n  }, [migrated, catalog, isEditMode]);\n\n  const handleLayoutChange = (currentLayout: Layout) => {\n    if (!isEditMode) return;\n\n    const updatedPreferences = migrated.map(pref => {\n      const gridItem = currentLayout.find(item => item.i === pref.id);\n      if (gridItem) {\n        return {\n          ...pref,\n          pos_x: gridItem.x,\n          pos_y: gridItem.y,\n          col_span: gridItem.w,\n          row_span: gridItem.h,\n          modificado_en: new Date().toISOString()\n        } as TPreference;\n      }\n      return pref;\n    });\n\n    onLayoutChange(updatedPreferences);\n  };\n\n  return (\n    <div className={`min-h-[500px] transition-all duration-300 ${isEditMode ? 'bg-gray-50/50 rounded-xl outline outline-2 outline-dashed outline-gray-200' : ''}`}>\n      <ResponsiveGrid\n        className=\"layout\"\n        layouts={gridLayouts}\n        measureBeforeMount={true}\n        breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}\n        cols={{ lg: 12, md: 8, sm: 4, xs: 2, xxs: 1 }}\n        rowHeight={ROW_HEIGHT}\n        margin={[12, 12]}\n        preventCollision={false}\n        onLayoutChange={handleLayoutChange}\n        isDraggable={isEditMode}\n        isResizable={isEditMode}\n        draggableHandle=\".drag-handle\"\n        compactType=\"vertical\"\n        useCSSTransforms={true}\n      >\n        {migrated.map((pref, index) => {\n          const definition = catalog.find(c => c.widget_id === pref.widget_id);\n          /**\n           * Sin definición en el catálogo, el widget NO se pinta.\n           *\n           * Antes se dejaba un \"Widget desconocido\" ocupando su celda. Eso pasa\n           * cuando alguien desactiva un widget del catálogo o el usuario pierde el\n           * permiso que lo concedía —los dos casos normales—, y en ninguno tiene\n           * sentido dejar una lápida en medio del tablero.\n           */\n          if (!definition) return null;\n\n          return (\n            /**\n             * Entrada escalonada, sólo al montar. El retardo se corta a los 300 ms:\n             * con veinte widgets, un stagger sin techo dejaría el último entrando\n             * más de medio segundo después — se leería como lentitud, no como ritmo.\n             */\n            <div\n              key={pref.id}\n              className=\"dash-card-enter\"\n              style={{ '--dash-enter-delay': `${Math.min(index * 30, 300)}ms` } as React.CSSProperties}\n            >\n              {renderWidget(pref, definition, isEditMode, globalFilters, onRemoveWidget)}\n            </div>\n          );\n        })}\n      </ResponsiveGrid>\n    </div>\n  );\n};\n","/**\n * Fuente de verdad única para la configuración visual de tipos de widget.\n * Importar desde aquí en lugar de redefinir en cada componente.\n *\n * Usado por: WidgetManagerPanel, WidgetCustomizationPanel, Step3PresentationType.\n */\n\nimport {\n  Hash, BarChart3, LayoutList, TrendingUp, PieChart, Table2, Image, Puzzle,\n} from 'lucide-react';\nimport type { WidgetPresentationType } from '../types';\n\nexport interface WidgetTypeConfig {\n  id: WidgetPresentationType;\n  label: string;\n  description: string;\n  icon: React.FC<{ className?: string }>;\n}\n\nexport const WIDGET_TYPE_CONFIG: WidgetTypeConfig[] = [\n  {\n    id: 'kpi',\n    label: 'KPI',\n    description: 'Un número principal con tendencia',\n    icon: Hash,\n  },\n  {\n    id: 'chart_bar_vertical',\n    label: 'Barras',\n    description: 'Comparación por categorías',\n    icon: BarChart3,\n  },\n  {\n    id: 'chart_bar_horizontal',\n    label: 'Barras H.',\n    description: 'Ranking horizontal',\n    icon: LayoutList,\n  },\n  {\n    id: 'chart_line',\n    label: 'Líneas',\n    description: 'Evolución temporal',\n    icon: TrendingUp,\n  },\n  {\n    id: 'chart_donut',\n    label: 'Circular',\n    description: 'Distribución porcentual',\n    icon: PieChart,\n  },\n  {\n    id: 'table',\n    label: 'Tabla',\n    description: 'Lista con columnas dinámicas',\n    icon: Table2,\n  },\n  {\n    id: 'image',\n    label: 'Imagen',\n    description: 'Imagen estática o dinámica',\n    icon: Image,\n  },\n  {\n    id: 'custom',\n    label: 'Custom',\n    description: 'Componente React personalizado',\n    icon: Puzzle,\n  },\n];\n\n/** Mapa tipo → config (para lookups O(1)) */\nexport const WIDGET_TYPE_MAP = Object.fromEntries(\n  WIDGET_TYPE_CONFIG.map(c => [c.id, c])\n) as Record<WidgetPresentationType, WidgetTypeConfig>;\n\n/** Obtiene el ícono de un tipo. Fallback: Hash */\nexport function getTypeIcon(tipo: string): React.FC<{ className?: string }> {\n  return WIDGET_TYPE_MAP[tipo as WidgetPresentationType]?.icon ?? Hash;\n}\n\n/** Obtiene el label de un tipo. Fallback: el tipo crudo */\nexport function getTypeLabel(tipo: string): string {\n  return WIDGET_TYPE_MAP[tipo as WidgetPresentationType]?.label ?? tipo;\n}\n","import { createContext, useContext } from 'react';\nimport type { DashboardFetcher, WidgetDefinition } from './types';\nimport type { WidgetAccessAdapter } from './access/types';\n\n/**\n * El contexto del tablero y su hook de lectura.\n *\n * <b>Vive aparte de `DashboardContext.tsx` a propósito.</b> Ese archivo exporta un COMPONENTE\n * (el provider) y `react-refresh/only-export-components` exige que un módulo con componentes\n * solo exporte componentes: mezclar el hook con el provider rompe el hot reload y era un error\n * de lint preexistente del módulo. Es la misma separación que ya hacía `skeletonShape.ts`\n * respecto de `WidgetSkeletons.tsx`.\n */\nexport interface DashboardContextValue {\n  fetcher: DashboardFetcher;\n  /**\n   * El catálogo de widgets, para resolver la definición de un widget REFERENCIADO por otro.\n   *\n   * Lo necesita `useSecondarySource`: el sparkline de un KPI pide los datos de OTRA entrada del\n   * catálogo bajo la MISMA clave de caché que usaría ese widget, así que tiene que aplicar el\n   * `field_mapping.rename` de ESE widget —no el del KPI— o la entrada compartida quedaría con\n   * los campos sin renombrar y el gráfico grande no encontraría sus `valueKeys`.\n   *\n   * Opcional: un host que monte piezas del tablero por separado sigue funcionando sin él (la\n   * fuente secundaria degrada a no aplicar renombre, como hacía antes).\n   */\n  catalog?: WidgetDefinition[];\n\n  /**\n   * 🔴 El adaptador del diálogo de acceso, cuando el host tiene un modelo de permisos por\n   * instancia. **Opcional**: sin él, el botón de acceso no se pinta en ningún sitio y el tablero\n   * queda exactamente como estaba.\n   *\n   * <para>Viaja por CONTEXTO y no por props porque su consumidor es la tarjeta del widget, que está\n   * cinco niveles por debajo de la página (`DashboardPage` → `renderWidget` → `LazyWidget` →\n   * `WidgetWrapper`). Atravesar cinco firmas con una prop que la mayoría de los hosts no usa es\n   * justo lo que el contexto existe para evitar — y es donde ya viaja el `fetcher`.</para>\n   */\n  accessAdapter?: WidgetAccessAdapter;\n}\n\nexport const DashboardContext = createContext<DashboardContextValue | null>(null);\n\n/**\n * Expone el fetcher inyectado por el host, el catálogo de widgets y —si lo hay— el adaptador del\n * diálogo de acceso.\n * Lanza error si se usa fuera de `DashboardProvider`.\n */\nexport const useDashboardContext = (): DashboardContextValue => {\n  const ctx = useContext(DashboardContext);\n  if (!ctx) {\n    throw new Error('useDashboardContext debe usarse dentro de <DashboardProvider>. Asegurate de pasar un fetcher a <DashboardPage>.');\n  }\n  return ctx;\n};\n","/**\n * Catálogo de indicadores económicos externos para el Widget Builder.\n * Solo se incluyen indicadores VERIFICADOS end-to-end (endpoint accesible, respuesta parseable).\n *\n * Estado actual (2026-04-16):\n *   ✅ co_trm  — TRM Colombia, datos.gov.co (Socrata), verificado\n *   ✅ int_btc — Bitcoin USD, CoinGecko, verificado\n *\n * 🗺️ ROADMAP — Pendientes de investigación:\n *   IPC Colombia  → datos.gov.co IDs cambiaron; nueva ruta: suameca.banrep.gov.co (SDMX)\n *   TPM Colombia  → Portal Banrep migró a SDMX; requiere doc de parámetros específicos\n *   FRED (USA/Int) → Verificados estructuralmente (400 = key faltante, no 404), pendiente\n *                    prueba con api_key real (gratuita en fredaccount.stlouisfed.org)\n */\n\nexport interface EconomicIndicator {\n  id: string;\n  bandera: string;\n  pais: 'Colombia' | 'USA' | 'Internacional';\n  categoria: 'Divisa' | 'Precios' | 'Tasas' | 'Laboral' | 'Macro' | 'Commodities' | 'Cripto';\n  nombre: string;\n  descripcion: string;\n  unidad: string;\n  frecuencia: string;\n  endpoint: string;\n  metodo: 'GET' | 'POST';\n  /** Params estáticos que se agregan a la URL (sin api_key — se agrega dinámicamente) */\n  params: Record<string, string>;\n  /** Path al campo valor en la respuesta (dot-notation, ej: \"valor\", \"observations[0].value\") */\n  campo_valor: string;\n  /** Path al campo fecha en la respuesta */\n  campo_fecha: string;\n  requiere_key: boolean;\n  key_nombre?: string;\n  key_url?: string;\n  notas?: string;\n}\n\nexport const INDICATORS_CATALOG: EconomicIndicator[] = [\n  // ────────────────────────────────────────────────────────────\n  // 🇨🇴 COLOMBIA\n  // ────────────────────────────────────────────────────────────\n  {\n    id: 'co_trm',\n    bandera: '🇨🇴',\n    pais: 'Colombia',\n    categoria: 'Divisa',\n    nombre: 'Dólar (TRM)',\n    descripcion: 'Tasa Representativa del Mercado — valor oficial del dólar',\n    unidad: 'COP / USD',\n    frecuencia: 'Diaria',\n    endpoint: 'https://www.datos.gov.co/resource/32sa-8pi3.json',\n    metodo: 'GET',\n    params: { $limit: '1', $order: 'vigenciadesde DESC' },\n    campo_valor: '[0].valor',\n    campo_fecha: '[0].vigenciadesde',\n    requiere_key: false,\n    notas: 'API Socrata (datos.gov.co). El valor viene como string; se parsea a float en el widget.',\n  },\n\n  // ────────────────────────────────────────────────────────────\n  // 🌍 INTERNACIONAL\n  // ────────────────────────────────────────────────────────────\n  {\n    id: 'int_btc',\n    bandera: '🌍',\n    pais: 'Internacional',\n    categoria: 'Cripto',\n    nombre: 'Bitcoin (BTC/USD)',\n    descripcion: 'Precio del Bitcoin en tiempo real — CoinGecko',\n    unidad: 'USD',\n    frecuencia: 'Tiempo real',\n    endpoint: 'https://api.coingecko.com/api/v3/simple/price',\n    metodo: 'GET',\n    params: { ids: 'bitcoin', vs_currencies: 'usd' },\n    campo_valor: 'bitcoin.usd',\n    campo_fecha: '',\n    requiere_key: false,\n    notas: 'Límite: ~30 req/min sin key. Usar refresh_policy mínimo 3600s para no exceder el rate limit.',\n  },\n];\n\nexport const INDICATOR_PAISES = ['Todos', 'Colombia', 'Internacional'] as const;\nexport const INDICATOR_CATEGORIAS = ['Todas', 'Divisa', 'Cripto'] as const;\n\nexport function getIndicatorById(id: string): EconomicIndicator | undefined {\n  return INDICATORS_CATALOG.find(i => i.id === id);\n}\n\n/**\n * Construye la URL completa del indicador con params + api_key opcional.\n *\n * IMPORTANTE: No usa URLSearchParams porque codifica '$' como '%24',\n * lo que rompe las APIs Socrata (datos.gov.co) que requieren '$literal'\n * en parámetros como $limit, $order, $where.\n * Las claves se pasan sin codificar; solo los valores se codifican.\n */\nexport function buildIndicatorUrl(indicator: EconomicIndicator, apiKey?: string): string {\n  const parts: string[] = [];\n\n  for (const [k, v] of Object.entries(indicator.params)) {\n    parts.push(`${k}=${encodeURIComponent(v)}`);\n  }\n\n  if (indicator.requiere_key && apiKey) {\n    parts.push(`api_key=${encodeURIComponent(apiKey)}`);\n  }\n\n  if (parts.length === 0) return indicator.endpoint;\n\n  const separator = indicator.endpoint.includes('?') ? '&' : '?';\n  return `${indicator.endpoint}${separator}${parts.join('&')}`;\n}\n","import type { WidgetDefinition, WidgetPresentationType, DomainCategory } from '../../types';\n\nexport interface WizardFormData extends Partial<WidgetDefinition> {\n  nombre: string;\n  descripcion: string;\n  categoria: DomainCategory;\n  tipo: WidgetPresentationType;\n  icono: string;\n  roles_permitidos: string[];\n  col_min: number;\n  col_max: number;\n  cols_default: number;\n  altura_default: number;\n  activo: boolean;\n  endpoint_url: string;\n  endpoint_method: 'GET' | 'POST';\n  endpoint_headers: Record<string, string>;\n  endpoint_params: Record<string, string | number | boolean>;\n  refresh_policy: number;\n  es_privado: boolean;\n  is_internal: boolean;\n\n  // ── Catálogo de indicadores económicos ──────────────────────\n  /** Modo de selección de fuente de datos */\n  catalog_mode: 'catalogo' | 'manual';\n  /** ID del indicador seleccionado del catálogo */\n  catalog_indicator_id?: string;\n  /** API Key para indicadores que la requieren (ej: FRED) */\n  catalog_api_key: string;\n  /** Path al campo valor en la respuesta (pre-fill desde catálogo) */\n  campo_valor: string;\n  /** Path al campo fecha en la respuesta (pre-fill desde catálogo) */\n  campo_fecha: string;\n}\n\nexport interface WizardState {\n  formData: WizardFormData;\n  testSuccess: boolean;\n  isTesting: boolean;\n  jsonPreview: Record<string, unknown>[] | null;\n  mappingX: string;\n  mappingY: string;\n}\n\nexport const INITIAL_FORM_DATA: WizardFormData = {\n  nombre: '',\n  descripcion: '',\n  // Sin categoría: la elige el usuario entre las que declara el host. Antes nacía en\n  // 'Operaciones', una categoría de Siesa Comercial que en otro host no existe.\n  categoria: '' as DomainCategory,\n  tipo: 'kpi' as WidgetPresentationType,\n  icono: 'Layout',\n  roles_permitidos: ['admin'],\n  col_min: 2,\n  col_max: 12,\n  cols_default: 3,\n  altura_default: 1,\n  activo: true,\n  endpoint_url: '',\n  endpoint_method: 'GET',\n  endpoint_headers: {},\n  endpoint_params: {},\n  refresh_policy: 300,\n  es_privado: true,\n  is_internal: true,\n  // Catálogo\n  catalog_mode: 'catalogo',\n  catalog_indicator_id: undefined,\n  catalog_api_key: '',\n  campo_valor: '',\n  campo_fecha: '',\n};\n","import React, { useState, useEffect } from 'react';\nimport { useDashboardTranslation } from '../../i18n';\nimport {\n  Loader2, Activity, CheckCircle, Globe, Plus, X, Settings2, FileJson,\n  AlertTriangle, Search, Key, ExternalLink, BookOpen,\n} from 'lucide-react';\nimport type { WizardFormData } from './types';\nimport type { AllowedInternalRoutes } from '../../types';\nimport {\n  INDICATORS_CATALOG, INDICATOR_PAISES, INDICATOR_CATEGORIAS,\n  buildIndicatorUrl, type EconomicIndicator,\n} from '../../utils/indicatorsCatalog';\n\nconst HIGH_VOLUME_THRESHOLD = 1000;\n\ninterface Step1DataSourceProps {\n  formData: WizardFormData;\n  testSuccess: boolean;\n  isTesting: boolean;\n  testError: string | null;\n  totalRecords?: number;\n  allowedRoutes?: AllowedInternalRoutes;\n  isAdmin?: boolean;\n  showExternalEndpoints?: boolean;\n  onUpdateForm: (key: keyof WizardFormData, value: unknown) => void;\n  onTestConnection: () => void;\n  onIndicatorSelect: (indicator: EconomicIndicator | null) => void;\n}\n\nexport const Step1DataSource: React.FC<Step1DataSourceProps> = ({\n  formData,\n  testSuccess,\n  isTesting,\n  testError,\n  totalRecords,\n  onUpdateForm,\n  onTestConnection,\n  onIndicatorSelect,\n}) => {\n  const { t } = useDashboardTranslation();\n  // ── Estado de catálogo ──────────────────────────────────────\n  const [filtroPais, setFiltroPais] = useState<string>('Todos');\n  const [filtroCateg, setFiltroCateg] = useState<string>('Todas');\n  const [busqueda, setBusqueda] = useState('');\n\n  // ── Estado de modo manual (avanzado) ───────────────────────\n  const [newHeaderKey, setNewHeaderKey] = useState('');\n  const [newHeaderValue, setNewHeaderValue] = useState('');\n  const headers = formData.endpoint_headers ?? {};\n  const headerCount = Object.keys(headers).length;\n  const hasParams = Object.keys(formData.endpoint_params ?? {}).length > 0;\n  const [showAdvanced, setShowAdvanced] = useState(headerCount > 0 || hasParams);\n  const [bodyJsonText, setBodyJsonText] = useState(() =>\n    hasParams ? JSON.stringify(formData.endpoint_params, null, 2) : ''\n  );\n  const [bodyJsonError, setBodyJsonError] = useState<string | null>(null);\n\n  useEffect(() => {\n    if (hasParams) setBodyJsonText(JSON.stringify(formData.endpoint_params, null, 2));\n  }, [formData.endpoint_params, hasParams]);\n\n  // ── Indicador seleccionado ──────────────────────────────────\n  const selectedIndicator = INDICATORS_CATALOG.find(i => i.id === formData.catalog_indicator_id) ?? null;\n\n  const catalogMode = formData.catalog_mode;\n\n  const handleModeChange = (mode: 'catalogo' | 'manual') => {\n    onUpdateForm('catalog_mode', mode);\n    onIndicatorSelect(null);\n    onUpdateForm('endpoint_url', '');\n    onUpdateForm('catalog_indicator_id', undefined);\n    onUpdateForm('campo_valor', '');\n    onUpdateForm('campo_fecha', '');\n  };\n\n  const handleIndicatorClick = (ind: EconomicIndicator) => {\n    const isAlreadySelected = formData.catalog_indicator_id === ind.id;\n    if (isAlreadySelected) {\n      // Deseleccionar\n      onUpdateForm('catalog_indicator_id', undefined);\n      onUpdateForm('endpoint_url', '');\n      onUpdateForm('campo_valor', '');\n      onUpdateForm('campo_fecha', '');\n      // Al deseleccionar se deshace también: si no, quedaría marcado externo con la URL vacía y el\n      // siguiente paso manual heredaría una decisión que ya no viene de ningún sitio.\n      onUpdateForm('is_internal', undefined);\n      onIndicatorSelect(null);\n    } else {\n      onUpdateForm('catalog_indicator_id', ind.id);\n      onUpdateForm('endpoint_url', buildIndicatorUrl(ind, formData.catalog_api_key || undefined));\n      onUpdateForm('endpoint_method', ind.metodo);\n      onUpdateForm('campo_valor', ind.campo_valor);\n      onUpdateForm('campo_fecha', ind.campo_fecha);\n      onUpdateForm('catalog_api_key', formData.catalog_api_key);\n      // 🔴 Un indicador del catálogo es EXTERNO por definición —todos apuntan a una API pública— y\n      // hay que decirlo AQUÍ, al elegirlo.\n      //\n      // Antes no se decía en ninguna parte de este camino: `is_internal` solo se calculaba dentro de\n      // `handleTestConnection`, y en modo catálogo no hay que probar para avanzar —correcto, el\n      // indicador ya viene verificado—. Así que la detección nunca corría, al guardar caía a\n      // `?? true`, y el widget nacía declarado INTERNO apuntando a `www.datos.gov.co`. El error no\n      // aparecía al crearlo sino al pintarlo: «Host no está en la lista blanca de hosts internos».\n      //\n      // ⚠️ Era un dato que se calculaba como efecto secundario de otra acción, y desaparecía cuando\n      // esa acción no ocurría. Por eso se pone al elegir y no al probar.\n      onUpdateForm('is_internal', false);\n      // Pre-rellenar nombre del widget con el del indicador\n      if (!formData.nombre) onUpdateForm('nombre', ind.nombre);\n      onIndicatorSelect(ind);\n    }\n  };\n\n  const handleApiKeyChange = (key: string) => {\n    onUpdateForm('catalog_api_key', key);\n    // Actualizar la URL del indicador seleccionado con la nueva key\n    if (selectedIndicator) {\n      onUpdateForm('endpoint_url', buildIndicatorUrl(selectedIndicator, key || undefined));\n    }\n  };\n\n  const filteredCatalog = INDICATORS_CATALOG.filter(i =>\n    (filtroPais === 'Todos' || i.pais === filtroPais) &&\n    (filtroCateg === 'Todas' || i.categoria === filtroCateg) &&\n    (busqueda === '' || i.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||\n     i.descripcion.toLowerCase().includes(busqueda.toLowerCase()))\n  );\n\n  // ── Handlers modo manual ────────────────────────────────────\n  const addHeader = () => {\n    const key = newHeaderKey.trim();\n    if (!key) return;\n    onUpdateForm('endpoint_headers', { ...headers, [key]: newHeaderValue });\n    setNewHeaderKey('');\n    setNewHeaderValue('');\n  };\n\n  const handleBodyJsonChange = (text: string) => {\n    setBodyJsonText(text);\n    if (!text.trim()) { onUpdateForm('endpoint_params', {}); setBodyJsonError(null); return; }\n    try {\n      const parsed = JSON.parse(text);\n      if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n        setBodyJsonError('Debe ser un objeto JSON (no array ni primitivo)'); return;\n      }\n      onUpdateForm('endpoint_params', parsed); setBodyJsonError(null);\n    } catch { setBodyJsonError('JSON inválido'); }\n  };\n\n  return (\n    <div className=\"max-w-2xl mx-auto space-y-4\">\n      <div>\n        <h3 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.builder.step1.title')}</h3>\n        <p className=\"text-sm text-gray-600 mt-0.5\">{t('dashboard.builder.step1.subtitle')}</p>\n      </div>\n\n      {/* ── Toggle modo ─────────────────────────────────────── */}\n      <div className=\"flex bg-gray-100 p-1 rounded-lg w-full gap-1\">\n        <button\n          onClick={() => handleModeChange('catalogo')}\n          className={`flex-1 flex flex-col items-center px-4 py-1.5 rounded-md text-xs font-medium transition-all ${\n            catalogMode === 'catalogo' ? 'bg-white shadow-sm text-gray-800' : 'text-gray-500 hover:text-gray-700'\n          }`}\n        >\n          <span className=\"font-semibold\">{t('dashboard.builder.step1.catalog')}</span>\n          <span className={`text-[10px] font-semibold ${catalogMode === 'catalogo' ? 'text-blue-600' : 'text-gray-400'}`}>\n            Recomendado\n          </span>\n        </button>\n        <button\n          onClick={() => handleModeChange('manual')}\n          className={`flex-1 flex flex-col items-center px-4 py-1.5 rounded-md text-xs font-medium transition-all ${\n            catalogMode === 'manual' ? 'bg-white shadow-sm text-gray-800' : 'text-gray-500 hover:text-gray-700'\n          }`}\n        >\n          <span className=\"font-semibold\">{t('dashboard.builder.step1.manual')}</span>\n          <span className={`text-[10px] font-semibold ${catalogMode === 'manual' ? 'text-blue-600' : 'text-gray-400'}`}>\n            Avanzado\n          </span>\n        </button>\n      </div>\n\n      {/* ══════════════════════════════════════════════════════ */}\n      {/* MODO CATÁLOGO                                         */}\n      {/* ══════════════════════════════════════════════════════ */}\n      {catalogMode === 'catalogo' && (\n        <div className=\"space-y-3\">\n          {/* Buscador */}\n          <div className=\"relative\">\n            <Search className=\"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400\" />\n            <input\n              type=\"text\"\n              placeholder={t('dashboard.builder.step1.searchIndicator')}\n              value={busqueda}\n              onChange={e => setBusqueda(e.target.value)}\n              className=\"w-full pl-8 pr-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500\"\n            />\n          </div>\n\n          {/* Filtros por país */}\n          <div className=\"flex flex-wrap gap-1.5\">\n            {INDICATOR_PAISES.map(p => (\n              <button\n                key={p}\n                onClick={() => setFiltroPais(p)}\n                className={`px-2.5 py-0.5 rounded-full text-xs font-medium border transition-colors ${\n                  filtroPais === p\n                    ? 'bg-gray-800 text-white border-gray-800'\n                    : 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50'\n                }`}\n              >\n                {p}\n              </button>\n            ))}\n          </div>\n\n          {/* Filtros por categoría */}\n          <div className=\"flex flex-wrap gap-1.5\">\n            {INDICATOR_CATEGORIAS.map(c => (\n              <button\n                key={c}\n                onClick={() => setFiltroCateg(c)}\n                className={`px-2.5 py-0.5 rounded-full text-xs font-medium border transition-colors ${\n                  filtroCateg === c\n                    ? 'bg-blue-600 text-white border-blue-600'\n                    : 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50'\n                }`}\n              >\n                {c}\n              </button>\n            ))}\n          </div>\n\n          {/* Lista de indicadores */}\n          <div className=\"flex flex-col gap-1.5 max-h-64 overflow-y-auto pr-1\">\n            {filteredCatalog.map(ind => {\n              const isSelected = formData.catalog_indicator_id === ind.id;\n              return (\n                <button\n                  key={ind.id}\n                  onClick={() => handleIndicatorClick(ind)}\n                  className={`w-full text-left rounded-lg px-3 py-2.5 border transition-all ${\n                    isSelected\n                      ? 'border-blue-500 bg-blue-50/50 shadow-[0_0_0_3px_#DBEAFE]'\n                      : 'border-gray-200 bg-white hover:border-blue-300 hover:bg-blue-50/20'\n                  }`}\n                >\n                  <div className=\"flex items-center justify-between gap-2\">\n                    <div className=\"flex items-center gap-2.5 min-w-0\">\n                      <span className=\"text-base flex-shrink-0\">{ind.bandera}</span>\n                      <div className=\"min-w-0\">\n                        <div className=\"flex items-center gap-1.5 flex-wrap\">\n                          <span className={`text-sm font-semibold truncate ${isSelected ? 'text-blue-700' : 'text-gray-800'}`}>\n                            {ind.nombre}\n                          </span>\n                          <span className=\"text-[10px] font-semibold px-1.5 py-0.5 rounded bg-gray-100 text-gray-500 border border-gray-200\">\n                            {ind.categoria}\n                          </span>\n                          {ind.requiere_key && (\n                            <span className=\"inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200\">\n                              <Key className=\"w-2.5 h-2.5\" /> Key\n                            </span>\n                          )}\n                        </div>\n                        <p className=\"text-[11px] text-gray-400 mt-0.5\">\n                          {ind.descripcion} · {ind.frecuencia} · {ind.unidad}\n                        </p>\n                      </div>\n                    </div>\n                    {isSelected && (\n                      <div className=\"w-5 h-5 rounded-full bg-blue-600 flex items-center justify-center flex-shrink-0\">\n                        <CheckCircle className=\"w-3 h-3 text-white\" />\n                      </div>\n                    )}\n                  </div>\n                </button>\n              );\n            })}\n            {filteredCatalog.length === 0 && (\n              <div className=\"text-center text-gray-400 text-sm py-8\">\n                <BookOpen className=\"w-8 h-8 mx-auto mb-2 text-gray-300\" />\n                Sin resultados para esa búsqueda\n              </div>\n            )}\n          </div>\n\n          {/* Input API Key si el indicador la requiere */}\n          {selectedIndicator?.requiere_key && (\n            <div className=\"p-3 bg-gray-50 border border-gray-200 rounded-lg space-y-2\">\n              <p className=\"text-xs font-semibold text-gray-700 flex items-center gap-1.5\">\n                <Key className=\"w-3.5 h-3.5\" /> {selectedIndicator.key_nombre} requerida\n              </p>\n              <input\n                type=\"text\"\n                placeholder={`Pega aquí tu ${selectedIndicator.key_nombre}...`}\n                value={formData.catalog_api_key}\n                onChange={e => handleApiKeyChange(e.target.value)}\n                className=\"w-full px-2.5 py-1.5 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500\"\n              />\n              {selectedIndicator.key_url && (\n                <a\n                  href={selectedIndicator.key_url}\n                  target=\"_blank\"\n                  rel=\"noreferrer\"\n                  className=\"text-xs text-blue-600 hover:underline flex items-center gap-1\"\n                >\n                  <ExternalLink className=\"w-3 h-3\" />\n                  Obtener gratis → {selectedIndicator.key_url.replace('https://', '')}\n                </a>\n              )}\n            </div>\n          )}\n\n          {/* Info banner — el catálogo no requiere probar conexión */}\n          {selectedIndicator && (\n            <div className=\"flex items-start gap-2 px-3 py-2.5 bg-blue-50 border border-blue-200 rounded-lg\">\n              <CheckCircle className=\"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5\" />\n              <div className=\"text-xs text-blue-800\">\n                <span className=\"font-semibold\">{t('dashboard.builder.step1.ready')}</span>\n                <span className=\"text-blue-600\"> — tipo y mapeo se configuran automáticamente. No necesitas probar la conexión.</span>\n              </div>\n            </div>\n          )}\n        </div>\n      )}\n\n      {/* ══════════════════════════════════════════════════════ */}\n      {/* MODO MANUAL                                           */}\n      {/* ══════════════════════════════════════════════════════ */}\n      {catalogMode === 'manual' && (\n        <div className=\"space-y-4\">\n          <div className=\"flex items-center gap-2 px-3 py-2 bg-amber-50/50 border border-amber-200 rounded-lg text-xs text-amber-800\">\n            <Globe className=\"w-4 h-4 flex-shrink-0\" />\n            <span>{t('dashboard.builder.step1.external')}</span>\n          </div>\n\n          <div className=\"flex gap-2\">\n            <div className=\"w-24 flex-shrink-0\">\n              <label className=\"block text-xs font-medium text-gray-700 mb-1\">{t('dashboard.builder.step1.method')}</label>\n              <select\n                value={formData.endpoint_method}\n                onChange={e => onUpdateForm('endpoint_method', e.target.value)}\n                className=\"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white text-sm\"\n              >\n                <option value=\"GET\">GET</option>\n                <option value=\"POST\">POST</option>\n              </select>\n            </div>\n            <div className=\"flex-1\">\n              <label className=\"block text-xs font-medium text-gray-700 mb-1\">{t('dashboard.builder.step1.url')}</label>\n              <input\n                type=\"url\"\n                placeholder=\"https://api.externa.com/v1/datos\"\n                value={formData.endpoint_url}\n                onChange={e => onUpdateForm('endpoint_url', e.target.value)}\n                className=\"w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm\"\n              />\n            </div>\n          </div>\n\n          <div className=\"flex justify-end items-center gap-2\">\n            <button\n              onClick={() => setShowAdvanced(!showAdvanced)}\n              className={`relative p-2 border rounded-lg transition-colors ${\n                showAdvanced || headerCount > 0 || hasParams\n                  ? 'bg-blue-50 border-blue-300 text-blue-700'\n                  : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'\n              }`}\n              title=\"Headers y Body\"\n            >\n              <Settings2 className=\"w-4 h-4\" />\n              {(headerCount > 0 || hasParams) && (\n                <span className=\"absolute -top-1 -right-1 w-4 h-4 bg-blue-600 text-white text-[10px] font-bold rounded-full flex items-center justify-center\">\n                  {headerCount + (hasParams ? 1 : 0)}\n                </span>\n              )}\n            </button>\n            <button\n              onClick={onTestConnection}\n              disabled={!formData.endpoint_url || isTesting}\n              className=\"flex items-center gap-2 px-4 py-2 bg-gray-100 border border-gray-300 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed\"\n            >\n              {isTesting ? <Loader2 className=\"w-4 h-4 animate-spin\" /> : <Activity className=\"w-4 h-4\" />}\n              Probar Conexión\n            </button>\n          </div>\n\n          {showAdvanced && (\n            <div className=\"border-t border-gray-200 pt-3 space-y-4\">\n              <div className=\"space-y-2.5\">\n                <label className=\"text-sm font-medium text-gray-700\">{t('dashboard.builder.step1.customHeaders')}</label>\n                {Object.entries(headers).map(([key, value]) => (\n                  <div key={key} className=\"flex items-center gap-1.5\">\n                    <input type=\"text\" value={key} disabled className=\"w-1/3 px-2 py-1.5 border border-gray-200 rounded-md text-xs bg-gray-50 font-mono\" />\n                    <input type=\"text\" value={value} onChange={e => onUpdateForm('endpoint_headers', { ...headers, [key]: e.target.value })} className=\"flex-1 px-2 py-1.5 border border-gray-300 rounded-md text-xs focus:ring-2 focus:ring-blue-500\" />\n                    <button onClick={() => { const n = { ...headers }; delete n[key]; onUpdateForm('endpoint_headers', n); }} className=\"p-1.5 text-gray-400 hover:text-red-600 rounded-md\"><X className=\"w-3.5 h-3.5\" /></button>\n                  </div>\n                ))}\n                <div className=\"flex items-center gap-1.5\">\n                  <input type=\"text\" value={newHeaderKey} onChange={e => setNewHeaderKey(e.target.value)} onKeyDown={e => e.key === 'Enter' && addHeader()} placeholder=\"Authorization\" className=\"w-1/3 px-2 py-1.5 border border-gray-300 rounded-md text-xs focus:ring-2 focus:ring-blue-500 font-mono\" />\n                  <input type=\"text\" value={newHeaderValue} onChange={e => setNewHeaderValue(e.target.value)} onKeyDown={e => e.key === 'Enter' && addHeader()} placeholder=\"Bearer abc123...\" className=\"flex-1 px-2 py-1.5 border border-gray-300 rounded-md text-xs focus:ring-2 focus:ring-blue-500\" />\n                  <button onClick={addHeader} disabled={!newHeaderKey.trim()} className=\"flex items-center gap-1 px-2 py-1.5 bg-blue-50 text-blue-700 border border-blue-200 rounded-md text-xs font-medium hover:bg-blue-100 disabled:opacity-50\">\n                    <Plus className=\"w-3 h-3\" /> Agregar\n                  </button>\n                </div>\n              </div>\n\n              {formData.endpoint_method === 'POST' && (\n                <div className=\"space-y-1 pt-3 border-t border-gray-100\">\n                  <label className=\"text-sm font-medium text-gray-700 flex items-center gap-1.5\">\n                    <FileJson className=\"w-3.5 h-3.5\" /> Body JSON\n                  </label>\n                  <textarea\n                    value={bodyJsonText}\n                    onChange={e => handleBodyJsonChange(e.target.value)}\n                    placeholder='{\"from\": \"2026-01-01\", \"to\": \"2026-01-31\"}'\n                    rows={5}\n                    className={`w-full p-2 border rounded-md text-xs font-mono focus:ring-2 ${bodyJsonError ? 'border-red-300 focus:ring-red-400' : 'border-gray-300 focus:ring-blue-500'}`}\n                  />\n                  {bodyJsonError && <p className=\"text-xs text-red-600\">{bodyJsonError}</p>}\n                </div>\n              )}\n            </div>\n          )}\n        </div>\n      )}\n\n      {/* ── Banners de estado (compartidos ambos modos) ────────── */}\n      {testSuccess && (\n        <div className=\"p-2.5 bg-green-50 text-green-800 text-sm rounded-lg border border-green-200 flex items-center gap-2\">\n          <CheckCircle className=\"w-4 h-4 flex-shrink-0\" />\n          Conexión exitosa. El proxy devolvió un JSON válido.\n        </div>\n      )}\n      {testError && (\n        <div className=\"p-2.5 bg-red-50 text-red-800 text-sm rounded-lg border border-red-200 flex items-start gap-2\">\n          <Activity className=\"w-4 h-4 mt-0.5 flex-shrink-0\" />\n          <span><strong>{t('dashboard.builder.step1.error')}</strong> {testError}</span>\n        </div>\n      )}\n      {testSuccess && totalRecords != null && totalRecords > HIGH_VOLUME_THRESHOLD && (\n        <div className=\"p-2.5 bg-amber-50 text-amber-800 text-sm rounded-lg border border-amber-200 flex items-start gap-2\">\n          <AlertTriangle className=\"w-4 h-4 mt-0.5 flex-shrink-0\" />\n          <span>\n            <strong>{t('dashboard.builder.step1.performance')}</strong> Esta fuente devuelve <strong>{totalRecords.toLocaleString('es-CO')}</strong> registros.\n            Considera usar una fuente que devuelva datos ya agrupados.\n          </span>\n        </div>\n      )}\n    </div>\n  );\n};\n","import React, { useState, useEffect } from 'react';\nimport { useDashboardTranslation } from '../../i18n';\nimport { Activity, CheckCircle, Info, GripVertical, Plus, X as XIcon } from 'lucide-react';\nimport { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';\nimport { SortableContext, verticalListSortingStrategy, useSortable, arrayMove, sortableKeyboardCoordinates } from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport type { WidgetPresentationType, MappingConfig, AggregationType } from '../../types';\n\ninterface Step2FieldMappingProps {\n  presentationType: WidgetPresentationType;\n  jsonPreview: Record<string, unknown>[] | null;\n  mappingConfig: MappingConfig | null;\n  onMappingConfigChange: (config: MappingConfig) => void;\n  /** Si true (modo catálogo), muestra banner de auto-fill */\n  isCatalogMode?: boolean;\n  /** Path pre-rellenado del campo valor (desde el catálogo) */\n  campoValorPrefill?: string;\n  /** Path pre-rellenado del campo fecha (desde el catálogo) */\n  campoFechaPrefill?: string;\n  /** Nombre del indicador seleccionado (para el banner) */\n  indicatorName?: string;\n}\n\n/**\n * Clasifica los campos del primer registro del JSON preview.\n * Aplana objetos anidados a dot-notation (ej: name.common).\n */\nfunction classifyFields(sample: Record<string, unknown>, prefix = '') {\n  const textFields: string[] = [];\n  const numericFields: string[] = [];\n  const dateFields: string[] = [];\n  const allFields: string[] = [];\n\n  for (const [key, val] of Object.entries(sample)) {\n    const fullKey = prefix ? `${prefix}.${key}` : key;\n\n    if (typeof val === 'number') {\n      allFields.push(fullKey);\n      numericFields.push(fullKey);\n    } else if (typeof val === 'string') {\n      allFields.push(fullKey);\n      if (/^\\d{4}-\\d{2}-\\d{2}/.test(val)) {\n        dateFields.push(fullKey);\n      } else {\n        textFields.push(fullKey);\n      }\n    } else if (typeof val === 'boolean') {\n      allFields.push(fullKey);\n      textFields.push(fullKey);\n    } else if (val != null && typeof val === 'object' && !Array.isArray(val)) {\n      // Aplanar objetos anidados (ej: name: {common: \"Colombia\"} → name.common)\n      const nested = classifyFields(val as Record<string, unknown>, fullKey);\n      textFields.push(...nested.textFields);\n      numericFields.push(...nested.numericFields);\n      dateFields.push(...nested.dateFields);\n      allFields.push(...nested.allFields);\n    } else {\n      // Arrays u otros tipos — solo agregar a allFields\n      allFields.push(fullKey);\n    }\n  }\n\n  return { textFields, numericFields, dateFields, allFields };\n}\n\nconst AGGREGATIONS = [\n  { value: 'sum', label: 'Suma' },\n  { value: 'average', label: 'Promedio' },\n  { value: 'count', label: 'Conteo' },\n  { value: 'last', label: 'Último valor' },\n  { value: 'min', label: 'Mínimo' },\n  { value: 'max', label: 'Máximo' },\n] as const;\n\nconst CHART_AGGREGATIONS = [\n  { value: 'none', label: 'Ninguna (datos ya agrupados)' },\n  { value: 'sum', label: 'Suma' },\n  { value: 'average', label: 'Promedio' },\n  { value: 'count', label: 'Conteo' },\n  { value: 'min', label: 'Mínimo' },\n  { value: 'max', label: 'Máximo' },\n  { value: 'last', label: 'Último valor' },\n  { value: 'first', label: 'Primer valor' },\n] as const;\n\nconst selectClass = \"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white text-sm\";\nconst labelClass = \"block text-sm font-medium text-gray-700 mb-1\";\nconst optionalBadge = <span className=\"text-gray-400 font-normal ml-1\">(opcional)</span>;\n\nexport const Step2FieldMapping: React.FC<Step2FieldMappingProps> = ({\n  presentationType,\n  jsonPreview,\n  mappingConfig,\n  onMappingConfigChange,\n  isCatalogMode = false,\n  campoValorPrefill,\n  campoFechaPrefill,\n  indicatorName,\n}) => {\n  const { t } = useDashboardTranslation();\n  if (!jsonPreview || jsonPreview.length === 0) {\n    return (\n      <div className=\"max-w-2xl mx-auto space-y-6\">\n        <h3 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.builder.step2.title')}</h3>\n        <div className=\"flex flex-col items-center justify-center py-10 text-center\">\n          <Activity className=\"w-10 h-10 text-gray-300 mb-3\" />\n          <p className=\"text-gray-500 text-sm\">{t('dashboard.builder.step2.noData')}</p>\n        </div>\n      </div>\n    );\n  }\n\n  const { textFields, numericFields, dateFields, allFields } = classifyFields(jsonPreview[0]);\n  const labelFields = [...textFields, ...dateFields];\n\n  const renderKpiMapping = () => {\n    const cfg = mappingConfig?.type === 'kpi' ? mappingConfig : null;\n    return (\n      <div className=\"space-y-4\">\n        <div>\n          <label className={labelClass}>{t('dashboard.builder.step2.valueFieldLabel')} <span className=\"text-gray-400 font-normal\">(numérico)</span></label>\n          <select className={selectClass} value={cfg?.valueField ?? ''}\n            onChange={e => onMappingConfigChange({ type: 'kpi', valueField: e.target.value, labelField: cfg?.labelField, aggregation: cfg?.aggregation ?? 'last' })}>\n            <option value=\"\">— Seleccionar —</option>\n            {numericFields.map(f => <option key={f} value={f}>{f}</option>)}\n          </select>\n        </div>\n        <div>\n          <label className={labelClass}>Campo de etiqueta {optionalBadge}</label>\n          <select className={selectClass} value={cfg?.labelField ?? ''}\n            onChange={e => onMappingConfigChange({ ...cfg!, labelField: e.target.value || undefined })}>\n            <option value=\"\">— Ninguno —</option>\n            {labelFields.map(f => <option key={f} value={f}>{f}</option>)}\n          </select>\n        </div>\n        <div>\n          <label className={labelClass}>{t('dashboard.builder.step2.aggregation')}</label>\n          <select className={selectClass} value={cfg?.aggregation ?? 'last'}\n            onChange={e => onMappingConfigChange({ ...cfg!, aggregation: e.target.value as MappingConfig & { type: 'kpi' } extends { aggregation: infer A } ? A : never })}>\n            {AGGREGATIONS.map(a => <option key={a.value} value={a.value}>{a.label}</option>)}\n          </select>\n        </div>\n        <div className=\"grid grid-cols-2 gap-4\">\n          <div>\n            <label className={labelClass}>Prefijo del valor {optionalBadge}</label>\n            <input type=\"text\" placeholder=\"ej: $, €, COP\" className={selectClass}\n              value={cfg?.valuePrefix ?? ''}\n              onChange={e => onMappingConfigChange({ ...cfg!, valuePrefix: e.target.value || undefined })} />\n          </div>\n          <div>\n            <label className={labelClass}>Sufijo del valor {optionalBadge}</label>\n            <input type=\"text\" placeholder=\"ej: hab., km², %\" className={selectClass}\n              value={cfg?.valueSuffix ?? ''}\n              onChange={e => onMappingConfigChange({ ...cfg!, valueSuffix: e.target.value || undefined })} />\n          </div>\n        </div>\n        {cfg?.valueField && (\n          <SummaryBadge text={`${cfg.valuePrefix ?? ''}${cfg.valueField}${cfg.valueSuffix ? ' ' + cfg.valueSuffix : ''} — agregación: \"${AGGREGATIONS.find(a => a.value === cfg.aggregation)?.label ?? cfg.aggregation}\".`} />\n        )}\n      </div>\n    );\n  };\n\n  const renderBarMapping = () => {\n    const cfg = mappingConfig?.type === 'chart_bar_vertical' ? mappingConfig : null;\n    return (\n      <div className=\"space-y-4\">\n        <div className=\"grid grid-cols-2 gap-4\">\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.axisXLabels')}</label>\n            <select className={selectClass} value={cfg?.xField ?? ''}\n              onChange={e => onMappingConfigChange({ type: 'chart_bar_vertical', xField: e.target.value, yField: cfg?.yField ?? '', groupByField: cfg?.groupByField })}>\n              <option value=\"\">— Seleccionar —</option>\n              {labelFields.map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.axisYValues')}</label>\n            <select className={selectClass} value={cfg?.yField ?? ''}\n              onChange={e => onMappingConfigChange({ type: 'chart_bar_vertical', xField: cfg?.xField ?? '', yField: e.target.value, groupByField: cfg?.groupByField })}>\n              <option value=\"\">— Seleccionar —</option>\n              {numericFields.map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n        </div>\n        <div>\n          <label className={labelClass}>Agrupar por {optionalBadge}</label>\n          <select className={selectClass} value={cfg?.groupByField ?? ''}\n            onChange={e => onMappingConfigChange({ ...cfg!, groupByField: e.target.value || undefined })}>\n            <option value=\"\">— Sin agrupación —</option>\n            {labelFields.map(f => <option key={f} value={f}>{f}</option>)}\n          </select>\n        </div>\n        {/* Agregación — oculta si hay groupByField (stacked bars necesitan datos pre-agrupados) */}\n        {!cfg?.groupByField && (\n          <div>\n            <label className={labelClass}>Cálculo (Agregación) {optionalBadge}</label>\n            <select className={selectClass} value={cfg?.aggregation ?? 'none'}\n              onChange={e => onMappingConfigChange({ ...cfg!, aggregation: e.target.value as AggregationType })}>\n              {CHART_AGGREGATIONS.map(a => <option key={a.value} value={a.value}>{a.label}</option>)}\n            </select>\n            <p className=\"text-[11px] text-gray-500 mt-0.5\">Si el endpoint devuelve datos desagrupados, selecciona cómo calcular el valor por categoría.</p>\n          </div>\n        )}\n        {cfg?.xField && cfg?.yField && (\n          <SummaryBadge text={`Eje X: \"${cfg.xField}\", Eje Y: \"${cfg.yField}\".${cfg.groupByField ? ` Agrupado por \"${cfg.groupByField}\".` : ''}${cfg.aggregation && cfg.aggregation !== 'none' ? ` Agregación: ${CHART_AGGREGATIONS.find(a => a.value === cfg.aggregation)?.label}.` : ''}`} />\n        )}\n      </div>\n    );\n  };\n\n  const renderLineMapping = () => {\n    const cfg = mappingConfig?.type === 'chart_line' ? mappingConfig : null;\n    return (\n      <div className=\"space-y-4\">\n        <div className=\"grid grid-cols-2 gap-4\">\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.axisXTime')}</label>\n            <select className={selectClass} value={cfg?.xField ?? ''}\n              onChange={e => onMappingConfigChange({ type: 'chart_line', xField: e.target.value, yField: cfg?.yField ?? '', seriesFields: cfg?.seriesFields })}>\n              <option value=\"\">— Seleccionar —</option>\n              {[...labelFields, ...dateFields.filter(d => !labelFields.includes(d))].map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.axisYValues')}</label>\n            <select className={selectClass} value={cfg?.yField ?? ''}\n              onChange={e => onMappingConfigChange({ type: 'chart_line', xField: cfg?.xField ?? '', yField: e.target.value, seriesFields: cfg?.seriesFields })}>\n              <option value=\"\">— Seleccionar —</option>\n              {numericFields.map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n        </div>\n        <div>\n          <label className={labelClass}>Series múltiples {optionalBadge}</label>\n          <div className=\"flex flex-wrap gap-2 mt-1\">\n            {numericFields.filter(f => f !== cfg?.yField).map(f => {\n              const selected = cfg?.seriesFields?.includes(f) ?? false;\n              return (\n                <button key={f} type=\"button\"\n                  onClick={() => {\n                    const current = cfg?.seriesFields ?? [];\n                    const next = selected ? current.filter(s => s !== f) : [...current, f];\n                    onMappingConfigChange({ ...cfg!, seriesFields: next.length > 0 ? next : undefined });\n                  }}\n                  className={`px-3 py-1 text-xs rounded-full border transition-colors ${selected ? 'bg-blue-100 border-blue-400 text-blue-700' : 'bg-white border-gray-300 text-gray-600 hover:border-blue-300'}`}>\n                  {f}\n                </button>\n              );\n            })}\n          </div>\n        </div>\n        <div>\n          <label className={labelClass}>Cálculo (Agregación) {optionalBadge}</label>\n          <select className={selectClass} value={cfg?.aggregation ?? 'none'}\n            onChange={e => onMappingConfigChange({ ...cfg!, aggregation: e.target.value as AggregationType })}>\n            {CHART_AGGREGATIONS.map(a => <option key={a.value} value={a.value}>{a.label}</option>)}\n          </select>\n          <p className=\"text-[11px] text-gray-500 mt-0.5\">Si el endpoint devuelve datos desagrupados, selecciona cómo calcular el valor por categoría.</p>\n        </div>\n        {cfg?.xField && cfg?.yField && (\n          <SummaryBadge text={`Eje X: \"${cfg.xField}\", Eje Y: \"${cfg.yField}\"${cfg.seriesFields?.length ? `. Series: ${cfg.seriesFields.join(', ')}.` : '.'}${cfg.aggregation && cfg.aggregation !== 'none' ? ` Agregación: ${CHART_AGGREGATIONS.find(a => a.value === cfg.aggregation)?.label}.` : ''}`} />\n        )}\n      </div>\n    );\n  };\n\n  const renderDonutMapping = () => {\n    const cfg = mappingConfig?.type === 'chart_donut' ? mappingConfig : null;\n    return (\n      <div className=\"space-y-4\">\n        <div className=\"grid grid-cols-2 gap-4\">\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.categoryField')}</label>\n            <select className={selectClass} value={cfg?.categoryField ?? ''}\n              onChange={e => onMappingConfigChange({ type: 'chart_donut', categoryField: e.target.value, valueField: cfg?.valueField ?? '' })}>\n              <option value=\"\">— Seleccionar —</option>\n              {labelFields.map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.valuesField')}</label>\n            <select className={selectClass} value={cfg?.valueField ?? ''}\n              onChange={e => onMappingConfigChange({ type: 'chart_donut', categoryField: cfg?.categoryField ?? '', valueField: e.target.value })}>\n              <option value=\"\">— Seleccionar —</option>\n              {numericFields.map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n        </div>\n        <div>\n          <label className={labelClass}>Cálculo (Agregación) {optionalBadge}</label>\n          <select className={selectClass} value={cfg?.aggregation ?? 'none'}\n            onChange={e => onMappingConfigChange({ ...cfg!, aggregation: e.target.value as AggregationType })}>\n            {CHART_AGGREGATIONS.map(a => <option key={a.value} value={a.value}>{a.label}</option>)}\n          </select>\n          <p className=\"text-[11px] text-gray-500 mt-0.5\">Si el endpoint devuelve datos desagrupados, selecciona cómo calcular el valor por categoría.</p>\n        </div>\n        {cfg?.categoryField && cfg?.valueField && (\n          <SummaryBadge text={`Porciones por \"${cfg.categoryField}\", tamaño: \"${cfg.valueField}\".${cfg.aggregation && cfg.aggregation !== 'none' ? ` Agregación: ${CHART_AGGREGATIONS.find(a => a.value === cfg.aggregation)?.label}.` : ''}`} />\n        )}\n      </div>\n    );\n  };\n\n  const renderTableMapping = () => {\n    const cfg = mappingConfig?.type === 'table' ? mappingConfig : null;\n    const selected = cfg?.visibleColumns ?? [];\n    const available = allFields.filter(f => !selected.includes(f));\n\n    const sensors = useSensors(\n      useSensor(PointerSensor, { activationConstraint: { delay: 100, tolerance: 5 } }),\n      useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })\n    );\n\n    const handleDragEnd = (event: DragEndEvent) => {\n      const { active, over } = event;\n      if (!over || active.id === over.id) return;\n      const oldIdx = selected.indexOf(active.id as string);\n      const newIdx = selected.indexOf(over.id as string);\n      if (oldIdx === -1 || newIdx === -1) return;\n      const reordered = arrayMove(selected, oldIdx, newIdx);\n      onMappingConfigChange({ type: 'table', visibleColumns: reordered, sortField: cfg?.sortField, sortDirection: cfg?.sortDirection });\n    };\n\n    const addColumn = (field: string) => {\n      onMappingConfigChange({ type: 'table', visibleColumns: [...selected, field], sortField: cfg?.sortField, sortDirection: cfg?.sortDirection });\n    };\n\n    const removeColumn = (field: string) => {\n      onMappingConfigChange({ type: 'table', visibleColumns: selected.filter(c => c !== field), sortField: cfg?.sortField, sortDirection: cfg?.sortDirection });\n    };\n\n    return (\n      <div className=\"space-y-4\">\n        <div className=\"grid grid-cols-2 gap-3\">\n          {/* Lista: Disponibles */}\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.availableColumns')}</label>\n            <div className=\"border border-gray-200 rounded-lg bg-gray-50 min-h-[120px] max-h-[200px] overflow-y-auto p-1.5 space-y-1\">\n              {available.length === 0 ? (\n                <p className=\"text-xs text-gray-400 p-2 text-center\">{t('dashboard.builder.step2.allAssigned')}</p>\n              ) : (\n                available.map(f => (\n                  <button key={f} onClick={() => addColumn(f)} type=\"button\"\n                    className=\"w-full flex items-center gap-1.5 px-2 py-1.5 text-xs text-gray-700 bg-white border border-gray-200 rounded hover:border-blue-300 hover:bg-blue-50 transition-colors text-left\">\n                    <Plus className=\"w-3 h-3 text-gray-400 flex-shrink-0\" />\n                    <span className=\"truncate\">{f}</span>\n                  </button>\n                ))\n              )}\n            </div>\n          </div>\n\n          {/* Lista: Seleccionadas (sortable) */}\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.selectedColumns')}</label>\n            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>\n              <SortableContext items={selected} strategy={verticalListSortingStrategy}>\n                <div className=\"border border-blue-200 rounded-lg bg-blue-50/30 min-h-[120px] max-h-[200px] overflow-y-auto p-1.5 space-y-1\">\n                  {selected.length === 0 ? (\n                    <p className=\"text-xs text-gray-400 p-2 text-center\">{t('dashboard.builder.step2.dragHint')}</p>\n                  ) : (\n                    selected.map((field, idx) => (\n                      <SortableColumnItem key={field} id={field} index={idx} onRemove={removeColumn} />\n                    ))\n                  )}\n                </div>\n              </SortableContext>\n            </DndContext>\n          </div>\n        </div>\n\n        {/* Sort field + direction */}\n        <div className=\"grid grid-cols-2 gap-4\">\n          <div>\n            <label className={labelClass}>Ordenar por {optionalBadge}</label>\n            <select className={selectClass} value={cfg?.sortField ?? ''}\n              onChange={e => onMappingConfigChange({ ...cfg!, sortField: e.target.value || undefined })}>\n              <option value=\"\">— Sin ordenamiento —</option>\n              {allFields.map(f => <option key={f} value={f}>{f}</option>)}\n            </select>\n          </div>\n          <div>\n            <label className={labelClass}>{t('dashboard.builder.step2.direction')}</label>\n            <select className={selectClass} value={cfg?.sortDirection ?? 'asc'}\n              onChange={e => onMappingConfigChange({ ...cfg!, sortDirection: e.target.value as 'asc' | 'desc' })}>\n              <option value=\"asc\">{t('dashboard.builder.step2.asc')}</option>\n              <option value=\"desc\">{t('dashboard.builder.step2.desc')}</option>\n            </select>\n          </div>\n        </div>\n\n        {selected.length > 0 && (\n          <SummaryBadge text={`Se mostrarán ${selected.length} de ${allFields.length} columnas: ${selected.join(' → ')}${cfg?.sortField ? `. Orden: ${cfg.sortField} ${cfg.sortDirection === 'desc' ? '↓' : '↑'}` : ''}`} />\n        )}\n      </div>\n    );\n  };\n\n  const renderMapping = () => {\n    switch (presentationType) {\n      case 'kpi': return renderKpiMapping();\n      case 'chart_bar_vertical': return renderBarMapping();\n      case 'chart_bar_horizontal': return renderBarMapping();\n      case 'chart_line': return renderLineMapping();\n      case 'chart_donut': return renderDonutMapping();\n      case 'table': return renderTableMapping();\n      default: return renderBarMapping();\n    }\n  };\n\n  return (\n    <div className=\"max-w-2xl mx-auto space-y-6\">\n      <div>\n        <h3 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.builder.step2.title')}</h3>\n        <p className=\"text-sm text-gray-600 mt-1\">{t('dashboard.builder.step2.subtitle')}</p>\n      </div>\n\n      {/* Banner auto-fill desde catálogo */}\n      {isCatalogMode && (campoValorPrefill || campoFechaPrefill) && (\n        <div className=\"flex items-start gap-2 px-3 py-2.5 bg-green-50 border border-green-200 rounded-lg\">\n          <CheckCircle className=\"w-4 h-4 text-green-600 flex-shrink-0 mt-0.5\" />\n          <div className=\"text-xs text-green-800\">\n            <span className=\"font-semibold\">{t('dashboard.builder.step2.autoMapping')}</span>\n            {indicatorName && <span> — {indicatorName}</span>}\n            <div className=\"mt-1 text-green-700 space-y-0.5\">\n              {campoValorPrefill && <div>{t('dashboard.builder.step2.detectedValue')} <code className=\"bg-green-100 px-1 rounded\">{campoValorPrefill}</code></div>}\n              {campoFechaPrefill && <div>{t('dashboard.builder.step2.detectedDate')} <code className=\"bg-green-100 px-1 rounded\">{campoFechaPrefill}</code></div>}\n            </div>\n          </div>\n        </div>\n      )}\n\n      {/* Campos disponibles del endpoint */}\n      <div>\n        <p className=\"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2\">\n          Campos detectados del endpoint\n          <span className=\"ml-2 font-normal normal-case text-gray-400\">({allFields.length} campo{allFields.length !== 1 ? 's' : ''})</span>\n        </p>\n        <div className=\"flex flex-wrap gap-1.5\">\n          {textFields.map(f => (\n            <span key={f} className=\"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-md border bg-blue-50 border-blue-200 text-blue-700\">\n              <span className=\"font-bold text-[9px] bg-blue-200 text-blue-800 px-1 rounded\">A</span>\n              {f}\n            </span>\n          ))}\n          {dateFields.map(f => (\n            <span key={f} className=\"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-md border bg-purple-50 border-purple-200 text-purple-700\">\n              <span className=\"font-bold text-[9px] bg-purple-200 text-purple-800 px-1 rounded\">📅</span>\n              {f}\n            </span>\n          ))}\n          {numericFields.map(f => (\n            <span key={f} className=\"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-md border bg-emerald-50 border-emerald-200 text-emerald-700\">\n              <span className=\"font-bold text-[9px] bg-emerald-200 text-emerald-800 px-1 rounded\">#</span>\n              {f}\n            </span>\n          ))}\n        </div>\n      </div>\n\n      {/* Mapping form per type */}\n      {renderMapping()}\n    </div>\n  );\n};\n\n/** Item sortable dentro de la lista \"Columnas seleccionadas\" */\nconst SortableColumnItem: React.FC<{ id: string; index: number; onRemove: (id: string) => void }> = ({ id, index, onRemove }) => {\n  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id });\n  const style = { transform: CSS.Transform.toString(transform), transition };\n\n  return (\n    <div ref={setNodeRef} style={style}\n      className={`flex items-center gap-1.5 px-2 py-1.5 text-xs bg-white border rounded transition-colors ${isDragging ? 'border-blue-400 shadow-md z-10' : 'border-gray-200'}`}>\n      <span className=\"text-[10px] text-gray-400 font-mono w-4 text-right\">{index + 1}</span>\n      <button {...attributes} {...listeners} className=\"cursor-grab text-gray-400 hover:text-gray-600 touch-none\" tabIndex={-1}>\n        <GripVertical className=\"w-3 h-3\" />\n      </button>\n      <span className=\"flex-1 truncate text-gray-700\">{id}</span>\n      <button onClick={() => onRemove(id)} className=\"text-gray-400 hover:text-red-600 transition-colors\" type=\"button\">\n        <XIcon className=\"w-3 h-3\" />\n      </button>\n    </div>\n  );\n};\n\n/** Badge informativo azul con resumen */\nconst SummaryBadge: React.FC<{ text: string }> = ({ text }) => (\n  <div className=\"p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800 flex items-start gap-2\">\n    <Info className=\"w-4 h-4 flex-shrink-0 mt-0.5\" />\n    <span>{text}</span>\n  </div>\n);\n","import React from 'react';\nimport { useDashboardTranslation } from '../../i18n';\nimport type { WidgetPresentationType } from '../../types';\nimport { WIDGET_TYPE_CONFIG } from '../../utils/widgetTypeConfig';\n\ninterface Step3PresentationTypeProps {\n  selectedTipo: WidgetPresentationType;\n  onSelect: (tipo: WidgetPresentationType) => void;\n}\n\n// Solo los tipos creables desde el Builder (excluye image y custom que requieren componente propio)\nconst SELECTABLE_TYPES: WidgetPresentationType[] = [\n  'kpi', 'chart_bar_vertical', 'chart_bar_horizontal', 'chart_line', 'chart_donut', 'table',\n];\n\nconst TIPOS = WIDGET_TYPE_CONFIG.filter(t => SELECTABLE_TYPES.includes(t.id));\n\nexport const Step3PresentationType: React.FC<Step3PresentationTypeProps> = ({\n  selectedTipo,\n  onSelect,\n}) => {\n  const { t } = useDashboardTranslation();\n  return (\n    <div className=\"max-w-2xl mx-auto space-y-6\">\n      <div>\n        <h3 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.builder.step3.title')}</h3>\n        <p className=\"text-sm text-gray-500 mt-1\">{t('dashboard.builder.step3.subtitle')}</p>\n      </div>\n\n      <div className=\"grid grid-cols-3 gap-3\">\n        {TIPOS.map(tipo => {\n          const isActive = selectedTipo === tipo.id;\n          return (\n            <button\n              key={tipo.id}\n              type=\"button\"\n              onClick={() => onSelect(tipo.id)}\n              className={`flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all text-left ${\n                isActive\n                  ? 'border-blue-500 bg-blue-50 text-blue-700'\n                  : 'border-gray-200 text-gray-600 hover:border-blue-300 hover:bg-blue-50/30 bg-white'\n              }`}\n            >\n              <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${\n                isActive ? 'bg-blue-100' : 'bg-gray-100'\n              }`}>\n                <tipo.icon className={`w-5 h-5 ${isActive ? 'text-blue-600' : 'text-gray-500'}`} />\n              </div>\n\n              <div>\n                <div className={`text-sm font-semibold ${isActive ? 'text-blue-700' : 'text-gray-800'}`}>\n                  {tipo.label}\n                </div>\n                <div className=\"text-[11px] text-gray-400 mt-0.5 leading-tight\">\n                  {tipo.description}\n                </div>\n              </div>\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n};\n","/**\n * 🔴 **La categoría y la vertical, en un solo objeto.** Es la pieza de F3 en el kit, y el motivo por\n * el que el Constructor dejó de preguntar la vertical.\n *\n * ## El defecto que esto cierra\n *\n * Hasta el 2026-09-14 el asistente pedía **dos veces lo mismo**: la categoría en *Apariencia* y la\n * vertical en *Permisos*. En el host de Comercial las dos están declaradas **en la misma línea** y son\n * 1:1 — y aun así nada impedía archivar un indicador en «Ventas» y marcarlo de «compras». Como los dos\n * campos «funcionaban», la divergencia no producía ningún error: solo un indicador guardado en un\n * cajón que no se corresponde con quién lo ve.\n *\n * ## Por qué el mapeo lo pone el HOST\n *\n * El kit **no puede** deducir la vertical de una categoría: son vocabulario de dominio, y el kit lo\n * consumen Comercial, Financiero y Nómina. Cablearlo aquí sería exactamente el defecto que\n * `DEFAULT_AVAILABLE_ROLES` existe para no repetir —segmentar los widgets de un host con los módulos\n * de otro, sin error y con una interfaz de aspecto normal—. Así que el host publica la **pareja**, y\n * el kit solo la lee.\n */\nexport interface DashboardCategoryOption {\n  /** Lo que se guarda en la columna `categoria` del widget. */\n  id: string;\n  /** Lo que ve la persona. Ya traducido por el host: el kit no traduce vocabulario que no conoce. */\n  label: string;\n  /**\n   * 🔴 **La vertical que esta categoría determina** — lo que el Builder escribe en\n   * `roles_permitidos` sin volver a preguntarlo.\n   *\n   * Opcional a propósito: un host anterior a F3 publica sus categorías sin vertical, y en ese caso el\n   * Constructor **lo dice** en vez de inventarse una. Ver `Step5Permissions`.\n   */\n  role?: string;\n}\n\n/**\n * Lo que el Builder acepta como vocabulario de categorías.\n *\n * ⚠️ **La forma `string` se conserva a propósito**, y no por cortesía con hosts viejos: es lo que hace\n * que 3.a se pueda desplegar antes que 3.b —la dependencia dura del plan— sin dejar una ventana en la\n * que el Constructor no funcione.\n */\nexport type DashboardCategoryInput = string | DashboardCategoryOption;\n\n/**\n * Normaliza el vocabulario a la forma rica.\n *\n * 🔴 **Y arregla una avería real de pantalla.** Antes esta prop estaba tipada `string[]` y el `select`\n * pintaba `{categoria}` directo. El host de Comercial lleva desde el 2026-09-10 mandando objetos\n * `{id, label}` — así que el `<option>` recibía un OBJETO como hijo, que en React es un error de\n * render: **el paso de Apariencia del Constructor se caía**. No lo vio ninguna prueba porque todas\n * miden el servidor, que en este camino nunca se equivocó.\n */\nexport function normalizeCategories(\n  categorias: readonly DashboardCategoryInput[] | undefined,\n): DashboardCategoryOption[] {\n  return (categorias ?? []).map(c =>\n    typeof c === 'string'\n      ? { id: c, label: c }\n      : { id: c.id, label: c.label ?? c.id, role: c.role },\n  );\n}\n\n/**\n * La vertical de la categoría elegida, o `null` si el host no publicó la pareja.\n *\n * ⚠️ `null` **no** es «sin vertical»: es «no lo sé». La diferencia importa porque escribir\n * `roles_permitidos: []` significa *«este widget no pertenece a ninguna vertical, pertenece a su\n * autor»*, que es una afirmación distinta y que nadie pidió. Por eso el paso de permisos, ante un\n * `null`, no ofrece publicar en vez de publicar en el vacío.\n */\nexport function verticalDeLaCategoria(\n  categorias: readonly DashboardCategoryOption[],\n  categoria: string | undefined,\n): DashboardCategoryOption | null {\n  if (!categoria) return null;\n  const encontrada = categorias.find(c => c.id === categoria);\n  return encontrada?.role ? encontrada : null;\n}\n","import React from 'react';\nimport { useDashboardTranslation } from '../../i18n';\nimport { TrendingUp, CheckCircle } from 'lucide-react';\nimport type { WizardFormData } from './types';\nimport type { EconomicIndicator } from '../../utils/indicatorsCatalog';\nimport { normalizeCategories, type DashboardCategoryInput } from './categories';\n\n/**\n * Vacío a propósito — mismo motivo que `DEFAULT_AVAILABLE_ROLES`: eran las categorías de Siesa\n * Comercial dentro de una librería compartida. El host declara las suyas con `availableCategories`.\n */\nexport const DEFAULT_WIDGET_CATEGORIES: DashboardCategoryInput[] = [];\n\ninterface Step4AppearanceProps {\n  formData: WizardFormData;\n  onUpdateForm: (key: keyof WizardFormData, value: unknown) => void;\n  /** Unidad del indicador seleccionado (para la vista previa) */\n  indicatorUnidad?: string;\n  /** Bandera del país del indicador (para la vista previa) */\n  indicatorBandera?: string;\n  /** Indicador completo seleccionado (para badge de resumen) */\n  selectedIndicator?: EconomicIndicator | null;\n  /** Si está en modo catálogo (muestra badge de resumen) */\n  isCatalogMode?: boolean;\n  /**\n   * 🔴 **El vocabulario de categorías, y desde F3 con su vertical.** Ver `DashboardCategoryOption`.\n   *\n   * ⚠️ **Estaba tipado `string[]` y era mentira.** El host de Comercial lleva desde el 2026-09-10\n   * mandando objetos `{id, label}` —porque la etiqueta se traduce y el id se guarda—, así que el\n   * `<option>` recibía un OBJETO como hijo. En React eso no se pinta: **rompe el render del paso**.\n   * Se acepta la forma antigua para no dejar ninguna ventana rota entre 3.a y 3.b.\n   */\n  availableCategories?: DashboardCategoryInput[];\n}\n\nexport const Step4Appearance: React.FC<Step4AppearanceProps> = ({\n  formData,\n  onUpdateForm,\n  indicatorUnidad,\n  indicatorBandera,\n  selectedIndicator,\n  isCatalogMode = false,\n  availableCategories = DEFAULT_WIDGET_CATEGORIES,\n}) => {\n  const { t } = useDashboardTranslation();\n\n  // La categoría en curso puede no estar en el vocabulario del host: pasa al editar un widget\n  // sembrado antes, y también con el valor inicial del wizard. Si no se ofreciera como opción, el\n  // `select` pintaría la primera de la lista mientras el formulario sigue guardando la otra —\n  // el usuario creería haber elegido algo que no eligió.\n  //\n  // ⚠️ El valor inicial es la cadena vacía —la categoría es OBLIGATORIA y nace sin elegir—, y esa sí\n  // se ofrece: es lo que hace que el `select` abra en blanco en vez de en la primera opción, que\n  // sería elegir por la persona.\n  const delHost = normalizeCategories(availableCategories);\n  const categorias = delHost.some(c => c.id === formData.categoria)\n    ? delHost\n    : [{ id: formData.categoria, label: formData.categoria }, ...delHost];\n  return (\n    <div className=\"max-w-2xl mx-auto space-y-5\">\n      <h3 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.builder.step4.title')}</h3>\n\n      {/* Badge resumen — solo modo catálogo */}\n      {isCatalogMode && selectedIndicator && (\n        <div className=\"flex items-center gap-3 px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-lg\">\n          <span className=\"text-xl flex-shrink-0\">{selectedIndicator.bandera}</span>\n          <div className=\"flex-1 min-w-0\">\n            <p className=\"text-sm font-semibold text-gray-800 truncate\">{selectedIndicator.nombre}</p>\n            <p className=\"text-[11px] text-gray-400\">KPI · {selectedIndicator.frecuencia} · {selectedIndicator.unidad}</p>\n          </div>\n          <div className=\"flex items-center gap-1.5 text-xs text-green-700 font-semibold flex-shrink-0\">\n            <CheckCircle className=\"w-3.5 h-3.5\" /> Tipo y mapeo configurados\n          </div>\n        </div>\n      )}\n\n      <div className=\"grid gap-4\">\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.name')}</label>\n          <input\n            type=\"text\"\n            placeholder={t('dashboard.builder.step4.namePlaceholder')}\n            value={formData.nombre}\n            onChange={e => onUpdateForm('nombre', e.target.value)}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500\"\n          />\n        </div>\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.builder.step4.description')}</label>\n          <input\n            type=\"text\"\n            value={formData.descripcion}\n            onChange={e => onUpdateForm('descripcion', e.target.value)}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500\"\n          />\n        </div>\n        <div className=\"grid grid-cols-2 gap-4\">\n          <div>\n            <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.category')}</label>\n            <select\n              value={formData.categoria}\n              onChange={e => onUpdateForm('categoria', e.target.value)}\n              className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white\"\n            >\n              {categorias.map(categoria => (\n                <option key={categoria.id} value={categoria.id}>{categoria.label}</option>\n              ))}\n            </select>\n          </div>\n          <div>\n            <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.width')}</label>\n            <select\n              value={formData.cols_default}\n              onChange={e => onUpdateForm('cols_default', Number(e.target.value))}\n              className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white\"\n            >\n              <option value={3}>{t('dashboard.customize.widthSmall')}</option>\n              <option value={6}>{t('dashboard.customize.widthMedium')}</option>\n              <option value={12}>{t('dashboard.customize.widthFull')}</option>\n            </select>\n          </div>\n        </div>\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.refresh')}</label>\n          <select\n            value={formData.refresh_policy ?? 300}\n            onChange={e => onUpdateForm('refresh_policy', Number(e.target.value))}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white\"\n          >\n            <option value={0}>{t('dashboard.builder.step4.noRefresh')}</option>\n            <option value={30}>{t('dashboard.builder.step4.every30s')}</option>\n            <option value={60}>{t('dashboard.builder.step4.every1m')}</option>\n            <option value={120}>{t('dashboard.builder.step4.every2m')}</option>\n            <option value={300}>{t('dashboard.builder.step4.every5m')}</option>\n            <option value={600}>{t('dashboard.builder.step4.every10m')}</option>\n            <option value={1800}>{t('dashboard.builder.step4.every30m')}</option>\n          </select>\n          <p className=\"text-xs text-gray-500 mt-1\">Tiempo entre consultas automáticas al endpoint. Aplica cuando el widget está visible en el dashboard.</p>\n        </div>\n      </div>\n\n      {/* Vista previa — solo KPI */}\n      {formData.tipo === 'kpi' && (\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1.5\">{t('dashboard.builder.step4.preview')}</label>\n          <div className=\"bg-gray-50 border border-gray-200 rounded-xl p-3\">\n            <div className=\"bg-white rounded-lg px-4 py-3 shadow-sm border border-gray-100\">\n              <p className=\"text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-1\">\n                {indicatorBandera && <span className=\"mr-1\">{indicatorBandera}</span>}\n                {formData.nombre || 'Widget'}\n              </p>\n              <p className=\"text-2xl font-bold text-gray-900 mb-1 tracking-tight\">\n                — {indicatorUnidad ?? ''}\n              </p>\n              <div className=\"flex items-center gap-2\">\n                <span className=\"text-xs text-green-600 font-semibold flex items-center gap-0.5\">\n                  <TrendingUp className=\"w-3 h-3\" /> +0.00%\n                </span>\n                <span className=\"text-[11px] text-gray-400\">· Hoy</span>\n              </div>\n              {formData.descripcion && (\n                <p className=\"text-[11px] text-gray-400 mt-1\">{formData.descripcion}</p>\n              )}\n            </div>\n          </div>\n          <p className=\"text-[11px] text-gray-400 mt-1\">La vista previa muestra el layout — los valores reales se cargarán desde el endpoint.</p>\n        </div>\n      )}\n    </div>\n  );\n};\n","import React, { useEffect, useRef, useState } from 'react';\nimport { useDashboardTranslation } from '../../i18n';\nimport { Lock, Globe, Users, Search, X, Loader2, AlertTriangle } from 'lucide-react';\nimport type { WidgetAccessPerson } from '../../access/types';\nimport type { DashboardCategoryOption } from './categories';\n\n/**\n * 🔴 **RETIRADO EL 2026-09-14 (F3).** El Constructor ya no pregunta la vertical: la **determina la\n * categoría** que se eligió en *Apariencia*.\n *\n * Se conserva el tipo exportado porque **no está huérfano**: el diálogo de acceso lo sigue usando para\n * ofrecer «que lo vea todo ventas» como sujeto de un grant, que es un acto distinto —repartir algo que\n * ya existe— y sí se pregunta. Lo que desapareció es el selector de ESTE paso.\n *\n * @deprecated para el Widget Builder. Para el diálogo de acceso, ver `WidgetAccessTerm`.\n */\nexport interface DashboardRoleOption {\n  /** Valor que se guarda en `roles_permitidos` y que el backend cruza. */\n  id: string;\n  /** Texto que ve el administrador. */\n  label: string;\n}\n\n/**\n * Vacío A PROPÓSITO, y ya casi sin consumidores: desde F3 el Builder no lo usa.\n *\n * Traía `admin | ventas | compras | inventario`, el vocabulario de Siesa Comercial dentro de una\n * librería compartida, y eso hacía que un host que olvidara declarar el suyo **segmentara sus widgets\n * con los módulos de otro producto** — sin error, y con una interfaz que se veía perfectamente normal.\n */\nexport const DEFAULT_AVAILABLE_ROLES: DashboardRoleOption[] = [];\n\n/** Cómo se reparte un widget público, elegido al crearlo. */\nexport type RepartoInicial = 'module' | 'people';\n\ninterface Step5PermissionsProps {\n  esPrivado: boolean;\n  onUpdatePrivacy: (isPrivate: boolean) => void;\n\n  /**\n   * 🔴 **La vertical DERIVADA de la categoría.** `null` significa que el host no publicó la pareja\n   * para esa categoría — y entonces publicar no se ofrece, porque no se sabe dónde.\n   */\n  vertical: DashboardCategoryOption | null;\n\n  reparto: RepartoInicial;\n  onUpdateReparto: (r: RepartoInicial) => void;\n\n  personas: WidgetAccessPerson[];\n  onUpdatePersonas: (p: WidgetAccessPerson[]) => void;\n\n  /**\n   * Buscador del host. **Es el mismo `searchPeople` del adaptador de acceso**, no uno nuevo: si el\n   * host no lo declara, la opción «solo a estas personas» no se ofrece — teclear un id de usuario a\n   * mano en un asistente de creación es la misma falla que el diálogo de acceso ya cerró.\n   */\n  searchPeople?: (query: string) => Promise<WidgetAccessPerson[]>;\n\n  /**\n   * Si el host puede restringir y conceder (`savePolicy` + `grant`). Sin las dos, repartir al crear no\n   * se ofrece: el widget se crearía público y el segundo paso no llegaría nunca.\n   */\n  puedeRepartirAlCrear: boolean;\n}\n\nconst nombreDe = (p: WidgetAccessPerson) => p.nombre?.trim() || p.email?.trim() || p.id;\n\nexport const Step5Permissions: React.FC<Step5PermissionsProps> = ({\n  esPrivado,\n  onUpdatePrivacy,\n  vertical,\n  reparto,\n  onUpdateReparto,\n  personas,\n  onUpdatePersonas,\n  searchPeople,\n  puedeRepartirAlCrear,\n}) => {\n  const { t } = useDashboardTranslation();\n\n  const [consulta, setConsulta] = useState('');\n  const [resultados, setResultados] = useState<WidgetAccessPerson[]>([]);\n  const [buscando, setBuscando] = useState(false);\n  const ultimaBusqueda = useRef(0);\n\n  /**\n   * El buscador se reutiliza tal cual del adaptador de acceso. La lógica propia es descartar\n   * respuestas fuera de orden: sin el contador, teclear rápido deja pintados los resultados de una\n   * consulta anterior y la persona elegiría a alguien que no buscó.\n   *\n   * 🔴 **Dos cosas de este efecto son cicatrices de un spinner que no se apagaba nunca**, y las dos\n   * hay que dejarlas como están:\n   *\n   * 1. **`setBuscando(true)` va DENTRO del `setTimeout`.** Estaba fuera, así que cada pulsación lo\n   *    encendía y el `clearTimeout` del cleanup cancelaba la búsqueda antes de lanzarla: si el\n   *    efecto se remonta —por lo que sea— el spinner queda encendido **para siempre**, porque nadie\n   *    llega al `finally` que lo apaga. Dentro, un debounce cancelado no deja rastro.\n   * 2. **El efecto NO depende de `searchPeople`.** Es una prop de función, y basta con que el\n   *    llamador la construya en el render —un `.bind()`, una lambda— para que cambie de identidad en\n   *    cada pasada y remonte el efecto en bucle. Se lee por `ref`, que es lo que se quiere: usar\n   *    siempre la última sin que su identidad dispare nada.\n   */\n  const buscarRef = useRef(searchPeople);\n  useEffect(() => { buscarRef.current = searchPeople; });\n\n  useEffect(() => {\n    const buscar = buscarRef.current;\n    if (!buscar || consulta.trim().length < 2) {\n      setResultados([]);\n      setBuscando(false);\n      return;\n    }\n    const turno = ++ultimaBusqueda.current;\n    const id = setTimeout(() => {\n      setBuscando(true);\n      buscar(consulta.trim())\n        .then(r => {\n          if (turno === ultimaBusqueda.current) setResultados(r);\n        })\n        .catch(() => {\n          if (turno === ultimaBusqueda.current) setResultados([]);\n        })\n        .finally(() => {\n          if (turno === ultimaBusqueda.current) setBuscando(false);\n        });\n    }, 250);\n    return () => clearTimeout(id);\n  }, [consulta]);\n\n  const ofrecePersonas = puedeRepartirAlCrear && !!searchPeople;\n  const agregar = (p: WidgetAccessPerson) => {\n    if (!personas.some(x => x.id === p.id)) onUpdatePersonas([...personas, p]);\n    setConsulta('');\n    setResultados([]);\n  };\n\n  return (\n    <div className=\"max-w-2xl mx-auto space-y-6\">\n      <h3 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.builder.step5.title')}</h3>\n\n      <div className=\"p-4 border border-gray-200 rounded-xl bg-white space-y-4\">\n        {/* ── Privado ─────────────────────────────────────────────────────────────────────── */}\n        <label className=\"flex items-start gap-3 cursor-pointer\">\n          <input\n            type=\"radio\"\n            name=\"privacidad\"\n            checked={esPrivado === true}\n            onChange={() => onUpdatePrivacy(true)}\n            className=\"mt-1 text-blue-600 focus:ring-blue-500\"\n          />\n          <div className=\"flex items-start gap-2\">\n            <Lock className=\"w-4 h-4 mt-0.5 text-amber-600 flex-shrink-0\" />\n            <div>\n              <span className=\"block font-medium text-gray-800\">{t('dashboard.builder.step5.private')}</span>\n              <span className=\"text-sm text-gray-500\">{t('dashboard.builder.step5.privateHint')}</span>\n            </div>\n          </div>\n        </label>\n\n        {/* ── Público EN la vertical ──────────────────────────────────────────────────────── */}\n        {/*\n          🔴 El rótulo NO es cosmético. Decía «Público» a secas, que sugiere «todo el mundo» y NUNCA\n          fue cierto: siempre fue «todo el mundo DE ESTA VERTICAL» —el techo de módulo se aplica\n          igual—. Decirlo mal es la mitad de por qué este mecanismo se malinterpretaba.\n        */}\n        <label\n          className={`flex items-start gap-3 border-t border-gray-100 pt-4 ${\n            vertical ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'\n          }`}\n        >\n          <input\n            type=\"radio\"\n            name=\"privacidad\"\n            checked={esPrivado === false}\n            disabled={!vertical}\n            onChange={() => onUpdatePrivacy(false)}\n            className=\"mt-1 text-blue-600 focus:ring-blue-500\"\n          />\n          <div className=\"flex items-start gap-2\">\n            <Globe className=\"w-4 h-4 mt-0.5 text-blue-600 flex-shrink-0\" />\n            <div>\n              <span className=\"block font-medium text-gray-800\">\n                {vertical\n                  ? t('dashboard.builder.step5.publicIn', { alcance: vertical.label })\n                  : t('dashboard.builder.step5.public')}\n              </span>\n              <span className=\"text-sm text-gray-500\">\n                {vertical\n                  ? t('dashboard.builder.step5.publicInHint', { alcance: vertical.label })\n                  : t('dashboard.builder.step5.noScopeHint')}\n              </span>\n            </div>\n          </div>\n        </label>\n\n        {/* ── A quién, dentro de la vertical ──────────────────────────────────────────────── */}\n        {esPrivado === false && vertical && (\n          <div className=\"ml-8 mt-2 p-3 bg-gray-50 rounded-lg border border-gray-200 space-y-3\">\n            <label className=\"flex items-start gap-3 cursor-pointer\">\n              <input\n                type=\"radio\"\n                name=\"reparto\"\n                checked={reparto === 'module'}\n                onChange={() => onUpdateReparto('module')}\n                className=\"mt-0.5 text-blue-600 focus:ring-blue-500\"\n              />\n              <span className=\"text-sm text-gray-800\">\n                {t('dashboard.builder.step5.toEveryone', { alcance: vertical.label })}\n              </span>\n            </label>\n\n            <label\n              className={`flex items-start gap-3 ${ofrecePersonas ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'}`}\n            >\n              <input\n                type=\"radio\"\n                name=\"reparto\"\n                checked={reparto === 'people'}\n                disabled={!ofrecePersonas}\n                onChange={() => onUpdateReparto('people')}\n                className=\"mt-0.5 text-blue-600 focus:ring-blue-500\"\n              />\n              <span className=\"text-sm text-gray-800\">\n                {t('dashboard.builder.step5.toPeople')}\n                {!ofrecePersonas && (\n                  <span className=\"block text-xs text-gray-500\">{t('dashboard.builder.step5.noSearch')}</span>\n                )}\n              </span>\n            </label>\n\n            {reparto === 'people' && ofrecePersonas && (\n              <div className=\"ml-7 space-y-2\">\n                <div className=\"relative\">\n                  <Search className=\"w-4 h-4 absolute left-2.5 top-2.5 text-gray-400\" />\n                  <input\n                    type=\"text\"\n                    value={consulta}\n                    onChange={e => setConsulta(e.target.value)}\n                    placeholder={t('dashboard.builder.step5.searchPerson')}\n                    aria-label={t('dashboard.builder.step5.searchPerson')}\n                    className=\"w-full pl-8 pr-8 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500\"\n                  />\n                  {buscando && <Loader2 className=\"w-4 h-4 absolute right-2.5 top-2.5 text-gray-400 animate-spin\" />}\n                </div>\n\n                {resultados.length > 0 && (\n                  <ul className=\"border border-gray-200 rounded-lg bg-white divide-y divide-gray-100 max-h-40 overflow-y-auto\">\n                    {resultados.map(p => (\n                      <li key={p.id}>\n                        <button\n                          type=\"button\"\n                          onClick={() => agregar(p)}\n                          className=\"w-full text-left px-3 py-2 text-sm hover:bg-blue-50\"\n                        >\n                          {nombreDe(p)}\n                          {p.email && <span className=\"text-xs text-gray-400 ml-2\">{p.email}</span>}\n                        </button>\n                      </li>\n                    ))}\n                  </ul>\n                )}\n\n                {personas.length > 0 && (\n                  <ul className=\"flex flex-wrap gap-2\">\n                    {personas.map(p => (\n                      <li\n                        key={p.id}\n                        className=\"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800 border border-blue-300\"\n                      >\n                        <Users className=\"w-3 h-3\" />\n                        {nombreDe(p)}\n                        <button\n                          type=\"button\"\n                          onClick={() => onUpdatePersonas(personas.filter(x => x.id !== p.id))}\n                          aria-label={t('dashboard.builder.step5.removePerson', { persona: nombreDe(p) })}\n                          className=\"hover:text-blue-950\"\n                        >\n                          <X className=\"w-3 h-3\" />\n                        </button>\n                      </li>\n                    ))}\n                  </ul>\n                )}\n\n                {/*\n                  🔴 Se dice ANTES de guardar, no después. Son tres llamadas sin transacción —crear,\n                  restringir, conceder— y quien elige esta opción tiene que saber que el reparto es un\n                  segundo acto que puede fallar por su cuenta.\n                */}\n                {personas.length === 0 && (\n                  <p className=\"text-[11px] text-gray-500 italic\">\n                    {t('dashboard.builder.step5.noPeopleYet', { alcance: vertical.label })}\n                  </p>\n                )}\n\n                <p className=\"text-[11px] text-gray-500 flex items-start gap-1.5\">\n                  <AlertTriangle className=\"w-3.5 h-3.5 mt-px flex-shrink-0 text-amber-500\" />\n                  <span>{t('dashboard.builder.step5.ceilingWarning', { alcance: vertical.label })}</span>\n                </p>\n              </div>\n            )}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n};\n","import React, { useState, useEffect } from 'react';\nimport { X, ArrowRight, ArrowLeft, CheckCircle, Database, Layout, Palette, ShieldCheck, Activity, Loader2, Save, AlertTriangle } from 'lucide-react';\nimport type { WidgetDefinition, DomainCategory, WidgetPresentationType, MappingConfig, AllowedInternalRoutes, WidgetFieldMapping } from '../../types';\nimport { createWidget, updateWidget, getAllowedInternalRoutes } from '../../api/dashboardCatalog';\nimport { useDashboardContext } from '../../useDashboardContext';\nimport { useDashboardTranslation } from '../../i18n';\nimport { type EconomicIndicator } from '../../utils/indicatorsCatalog';\nimport { INITIAL_FORM_DATA } from './types';\nimport type { WizardFormData } from './types';\nimport { Step1DataSource } from './Step1DataSource';\nimport { Step2FieldMapping } from './Step2FieldMapping';\nimport { Step3PresentationType } from './Step3PresentationType';\nimport { Step4Appearance } from './Step4Appearance';\nimport { Step5Permissions, type RepartoInicial } from './Step5Permissions';\nimport {\n  normalizeCategories,\n  verticalDeLaCategoria,\n  type DashboardCategoryInput,\n  type DashboardCategoryOption,\n} from './categories';\nimport type { WidgetAccessPerson } from '../../access/types';\n\ninterface WidgetBuilderProps {\n  isOpen: boolean;\n  onClose: () => void;\n  onSuccess: (widget: WidgetDefinition) => void;\n  mode?: 'create' | 'edit';\n  editWidget?: WidgetDefinition;\n  isAdmin?: boolean;\n  /**\n   * Capacidad de cambiar la EXPOSICION de un widget: a quien alcanza (`es_privado`,\n   * `roles_permitidos`) y con que autoridad se pide su dato (`is_internal`). Es lo que gobierna el\n   * paso de permisos del asistente.\n   *\n   * Se separa de `isAdmin` porque el backend la exige por separado, y en modo edicion manda lo que\n   * diga el propio widget (`permissions.can_publish`). Sin valor cae a `isAdmin`, que es el\n   * comportamiento historico.\n   */\n  canPublishWidgets?: boolean;\n  showExternalEndpoints?: boolean;\n  /**\n   * 🔴 **`availableRoles` se RETIRÓ el 2026-09-14 (F3).** El paso de permisos ya no pregunta la\n   * vertical: la determina la categoría. El tipo sigue exportado porque el **diálogo de acceso** lo\n   * usa para ofrecer «que lo vea todo ventas» como sujeto de un grant — que es repartir algo que ya\n   * existe, otro acto —, pero el Constructor no lo recibe.\n   *\n   * El vocabulario de categorías trae ahora la **pareja** categoría→vertical. Ver\n   * `DashboardCategoryOption`.\n   */\n  availableCategories?: DashboardCategoryInput[];\n\n  /**\n   * 🔴 **F4.4 — «ofrece abrir el diálogo de acceso».** Se llama cuando el indicador se creó pero el\n   * reparto quedó a medias, con el widget ya creado.\n   *\n   * <para>Sin esto el aviso sería un callejón: se le dice a alguien que su indicador quedó\n   * restringido y sin nadie dentro, y se le deja buscarlo en el catálogo. El host conecta esto con\n   * su diálogo de acceso; si no lo declara, el asistente solo cierra.</para>\n   */\n  onNeedsAccessDialog?: (widget: WidgetDefinition) => void;\n}\n\ninterface ProxyTestResponse {\n  success: boolean;\n  data?: Record<string, unknown>[];\n  fields?: string[];\n  numericFields?: string[];\n  error?: string;\n  total_records?: number;\n}\n\n/**\n * Flujo CATÁLOGO (3 pasos): Fuente → Apariencia → Permisos\n * Salta Presentación (siempre KPI) y Mapeo (automático del catálogo).\n */\nconst CATALOG_STEPS = [\n  { id: 'dataSource',  title: 'Fuente de Datos', icon: Database   },\n  { id: 'appearance',  title: 'Apariencia',       icon: Palette    },\n  { id: 'permissions', title: 'Permisos',          icon: ShieldCheck},\n];\n\n/**\n * Flujo MANUAL (5 pasos): Fuente → Presentación → Mapeo → Apariencia → Permisos\n * Flujo completo para APIs arbitrarias.\n */\nconst MANUAL_STEPS = [\n  { id: 'dataSource',   title: 'Fuente de Datos', icon: Database   },\n  { id: 'presentation', title: 'Presentación',    icon: Layout     },\n  { id: 'mapping',      title: 'Mapeo',            icon: Activity   },\n  { id: 'appearance',   title: 'Apariencia',       icon: Palette    },\n  { id: 'permissions',  title: 'Permisos',          icon: ShieldCheck},\n];\n\n/**\n * Genera un field_mapping simple (Record<string,string>) a partir de MappingConfig\n * para mantener compatibilidad con applyFieldMapping() en useWidgetFetch.\n */\nfunction buildFieldMapping(config: MappingConfig | null): Record<string, string> {\n  if (!config) return {};\n  const fm: Record<string, string> = {};\n\n  switch (config.type) {\n    case 'kpi':\n      if (config.valueField !== 'valor') fm['valor'] = config.valueField;\n      if (config.labelField && config.labelField !== 'etiqueta') fm['etiqueta'] = config.labelField;\n      break;\n    case 'chart_bar_vertical':\n      if (config.xField !== 'name') fm['name'] = config.xField;\n      if (config.yField !== 'value') fm['value'] = config.yField;\n      break;\n    case 'chart_line':\n      if (config.xField !== 'name') fm['name'] = config.xField;\n      if (config.yField !== 'value') fm['value'] = config.yField;\n      break;\n    case 'chart_donut':\n      if (config.categoryField !== 'name') fm['name'] = config.categoryField;\n      if (config.valueField !== 'value') fm['value'] = config.valueField;\n      break;\n    case 'table':\n      // Table no necesita field_mapping para renderizar\n      break;\n  }\n\n  return fm;\n}\n\n/** Valida si el mappingConfig tiene los campos obligatorios completos */\nfunction isMappingValid(config: MappingConfig | null): boolean {\n  if (!config) return false;\n  switch (config.type) {\n    case 'kpi': return !!config.valueField;\n    case 'chart_bar_vertical': return !!config.xField && !!config.yField;\n    case 'chart_line': return !!config.xField && !!config.yField;\n    case 'chart_donut': return !!config.categoryField && !!config.valueField;\n    case 'table': return config.visibleColumns.length > 0;\n    default: return false;\n  }\n}\n\nexport const WidgetBuilder: React.FC<WidgetBuilderProps> = ({\n  isOpen,\n  onClose,\n  onSuccess,\n  mode = 'create',\n  editWidget,\n  isAdmin = false,\n  canPublishWidgets,\n  showExternalEndpoints = false,\n  availableCategories,\n  onNeedsAccessDialog,\n}) => {\n  const { fetcher, accessAdapter } = useDashboardContext();\n  const { t } = useDashboardTranslation();\n  const isEditMode = mode === 'edit' && !!editWidget;\n\n  const [step, setStep] = useState(1);\n  const [isTesting, setIsTesting] = useState(false);\n  const [testSuccess, setTestSuccess] = useState(false);\n  const [testError, setTestError] = useState<string | null>(null);\n  const [isSaving, setIsSaving] = useState(false);\n  const [jsonPreview, setJsonPreview] = useState<Record<string, unknown>[] | null>(null);\n  const [mappingConfig, setMappingConfig] = useState<MappingConfig | null>(null);\n  const [formData, setFormData] = useState<WizardFormData>({ ...INITIAL_FORM_DATA, is_internal: false });\n\n  // ── F4 · Repartir al crear ───────────────────────────────────────────────────────────────────\n  //\n  // ⚠️ Y hay que decirlo donde se implementa, porque se vende mal: con el Constructor restringido a\n  // administradores (F1), esto es COMODIDAD, NO SEGURIDAD. Ese administrador ya podía hacerlo en dos\n  // pantallas. Se hace porque cuatro pasos para una intención —crear, cerrar, abrir el diálogo,\n  // repartir— es una mala pantalla, no porque cierre ningún hueco.\n  const [reparto, setReparto] = useState<RepartoInicial>('module');\n  const [personas, setPersonas] = useState<WidgetAccessPerson[]>([]);\n  const [avisoReparto, setAvisoReparto] = useState<string | null>(null);\n  /**\n   * El indicador que SÍ se creó cuando el reparto quedó a medias. Se guarda porque `onSuccess` —que\n   * es lo que el host usa para refrescar y CERRAR el asistente— no se llama todavía: cerrar con el\n   * aviso puesto sería dejarlo sin sitio donde leerse.\n   */\n  const [creadoAMedias, setCreadoAMedias] = useState<WidgetDefinition | null>(null);\n\n  // Flujo dinámico: catálogo=3 pasos, manual=5 pasos\n  // En modo edición siempre flujo manual (el widget ya tiene URL configurada)\n  const isCatalogMode = !isEditMode && formData.catalog_mode === 'catalogo';\n  const baseSteps = isCatalogMode ? CATALOG_STEPS : MANUAL_STEPS;\n\n  /**\n   * Si esta persona puede mover la exposicion DE ESTE widget. En edicion manda lo que dijo el\n   * servidor sobre la fila; al crear, la capacidad global; y sin ninguna de las dos, `isAdmin`, que\n   * es lo que gobernaba antes.\n   *\n   * Gobierna el paso de permisos y los tres campos que se mandan: sin esto, el asistente ofrecia el\n   * paso a quien el API iba a rechazar -o, peor, mandaba `es_privado: true` a espaldas de quien\n   * editaba, volviendo privado un widget de modulo y quitandoselo a todo el mundo-.\n   */\n  const puedeExponer = isEditMode\n    ? (editWidget?.permissions?.can_publish ?? canPublishWidgets ?? isAdmin)\n    : (canPublishWidgets ?? isAdmin);\n\n  /**\n   * 🔴 **La vertical NO se pregunta: se deriva de la categoría.** Es F3, y lo que cierra es un\n   * defecto que no daba ningún error: categoría y vertical eran dos campos distintos que\n   * significaban lo mismo, y nada impedía archivar un indicador en «Ventas» y marcarlo de «compras».\n   *\n   * `null` cuando el host no publicó la pareja para esa categoría. Ver `verticalDeLaCategoria`.\n   */\n  const categoriasDelHost = React.useMemo(\n    () => normalizeCategories(availableCategories),\n    [availableCategories],\n  );\n  const vertical: DashboardCategoryOption | null = verticalDeLaCategoria(\n    categoriasDelHost,\n    formData.categoria,\n  );\n\n  /**\n   * Repartir al crear exige las DOS operaciones del host: restringir (`savePolicy`) y conceder\n   * (`grant`). Con una sola, el widget se crearía público y el segundo acto no llegaría — que es\n   * justo el final que 4.4 existe para no producir en silencio.\n   */\n  const puedeRepartirAlCrear =\n    !isEditMode && !!accessAdapter?.savePolicy && !!accessAdapter?.grant;\n\n  /**\n   * 🔴 **Memoizado, y no `accessAdapter.searchPeople.bind(...)` en el JSX.** `bind` devuelve una\n   * función NUEVA en cada render: el buscador del paso 5 la recibía como prop, su efecto se\n   * remontaba en cada pasada y el debounce se cancelaba antes de lanzarse — **el spinner se quedaba\n   * girando y no aparecía ni un resultado**. El hijo ya se defiende de eso, pero pasar una identidad\n   * estable es lo correcto aquí: no es una optimización, es no romperlo desde fuera.\n   */\n  const buscarPersonas = React.useMemo(\n    () =>\n      accessAdapter?.searchPeople\n        ? (q: string) => accessAdapter.searchPeople!(q)\n        : undefined,\n    [accessAdapter],\n  );\n\n  const steps = puedeExponer ? baseSteps : baseSteps.filter(s => s.id !== 'permissions');\n  const maxStep = steps.length;\n  // ID del paso actual (para render y validación)\n  const currentStepId = steps[step - 1]?.id ?? 'dataSource';\n  const [totalRecords, setTotalRecords] = useState(0);\n  const [allowedRoutes, setAllowedRoutes] = useState<AllowedInternalRoutes | undefined>();\n  // Estado del indicador seleccionado del catálogo\n  const [selectedIndicator, setSelectedIndicator] = useState<EconomicIndicator | null>(null);\n\n  // Cargar config del whitelist al abrir el Builder\n  useEffect(() => {\n    if (isOpen) {\n      getAllowedInternalRoutes(fetcher)\n        .then(setAllowedRoutes)\n        .catch(() => setAllowedRoutes(undefined));\n    }\n  }, [isOpen, fetcher]);\n\n  // Precargar datos cuando se abre en modo edición\n  useEffect(() => {\n    if (isEditMode && editWidget) {\n      setFormData({\n        nombre: editWidget.nombre,\n        descripcion: editWidget.descripcion,\n        categoria: editWidget.categoria as DomainCategory,\n        tipo: editWidget.tipo as WidgetPresentationType,\n        icono: editWidget.icono,\n        roles_permitidos: editWidget.roles_permitidos,\n        col_min: editWidget.col_min,\n        col_max: editWidget.col_max,\n        cols_default: editWidget.cols_default,\n        altura_default: editWidget.altura_default,\n        activo: editWidget.activo,\n        endpoint_url: editWidget.endpoint_url ?? '',\n        endpoint_method: (editWidget.endpoint_method as 'GET' | 'POST') ?? 'GET',\n        endpoint_headers: editWidget.endpoint_headers ?? {},\n        endpoint_params: editWidget.endpoint_params ?? {},\n        refresh_policy: editWidget.refresh_policy ?? 300,\n        es_privado: editWidget.es_privado ?? false,\n        is_internal: editWidget.is_internal ?? true,\n        // Catálogo — modo manual por defecto al editar (el widget ya tenía URL)\n        catalog_mode: 'manual',\n        catalog_indicator_id: undefined,\n        catalog_api_key: '',\n        campo_valor: '',\n        campo_fecha: '',\n      });\n      // Restaurar MappingConfig desde config_schema si existe\n      if (editWidget.config_schema && typeof editWidget.config_schema === 'object' && 'type' in editWidget.config_schema) {\n        setMappingConfig(editWidget.config_schema as unknown as MappingConfig);\n      }\n      // Marcar test como exitoso si ya tiene URL configurada\n      if (editWidget.endpoint_url) {\n        setTestSuccess(true);\n      }\n      setStep(1);\n    }\n  }, [isEditMode, editWidget]);\n\n  const updateForm = (key: keyof WizardFormData, value: unknown) => {\n    setFormData(prev => ({ ...prev, [key]: value }));\n  };\n\n  // Auto-detectar si una URL parece ser interna (mismo host, localhost o URL relativa)\n  /**\n   * 🔴 `is_internal` EFECTIVO, resuelto en el momento de guardar y no antes.\n   *\n   * <para>Existe porque el valor del formulario puede no estar puesto: en modo catálogo se pone al\n   * elegir el indicador, y en modo manual dentro de `handleTestConnection`. Un camino que no pase\n   * por ninguno de los dos —o el estado de React todavía sin aplicar en este render— dejaba\n   * `undefined`, y el `?? true` de abajo lo convertía en INTERNO. Un widget externo declarado interno\n   * no falla al crearse: falla al pedir su dato, lejos de donde se causó.</para>\n   *\n   * <para>Aquí se decide con lo que de verdad manda: si viene del catálogo es externo, y si no, se\n   * deriva de la URL. Es una función pura sobre los datos del formulario, así que no depende de que\n   * ningún efecto haya corrido.</para>\n   */\n  const resolverIsInternal = (): boolean => {\n    if (formData.catalog_indicator_id) return false;\n    if (formData.is_internal !== undefined) return formData.is_internal;\n    return detectIsInternal(formData.endpoint_url ?? '');\n  };\n\n  const detectIsInternal = (url: string): boolean => {\n    const u = url.toLowerCase().trim();\n    if (u.startsWith('/') || !u.includes('://')) return true; // URL relativa\n    try {\n      const parsed = new URL(u);\n      const currentHost = typeof window !== 'undefined' ? window.location.hostname.toLowerCase() : '';\n      return (\n        parsed.hostname === 'localhost' ||\n        parsed.hostname === '127.0.0.1' ||\n        (currentHost !== '' && parsed.hostname === currentHost)\n      );\n    } catch {\n      return false;\n    }\n  };\n\n  // ───── Paso 2: Test de conexión via proxy/test ─────\n  const handleTestConnection = async () => {\n    setIsTesting(true);\n    setTestSuccess(false);\n    setTestError(null);\n    setJsonPreview(null);\n\n    // Auto-detectar is_internal solo en modo create (no sobrescribir decision del usuario en edit)\n    if (!isEditMode) {\n      const detected = detectIsInternal(formData.endpoint_url);\n      if (detected !== formData.is_internal) {\n        setFormData(prev => ({ ...prev, is_internal: detected }));\n      }\n    }\n\n    try {\n      if (fetcher) {\n        const result = await fetcher<ProxyTestResponse>('/api/dashboard/proxy/test', {\n          method: 'POST',\n          body: {\n            url: formData.endpoint_url,\n            method: formData.endpoint_method,\n            headers: Object.keys(formData.endpoint_headers ?? {}).length > 0\n              ? formData.endpoint_headers\n              : undefined,\n            params: formData.endpoint_method === 'POST' && Object.keys(formData.endpoint_params ?? {}).length > 0\n              ? formData.endpoint_params\n              : undefined,\n          },\n        });\n\n        if (result.success && result.data && result.data.length > 0) {\n          setTestSuccess(true);\n          setJsonPreview(result.data);\n          setTotalRecords(result.total_records ?? result.data.length);\n        } else {\n          setTestError(result.error || 'El endpoint no devolvió datos válidos.');\n        }\n      } else {\n        await new Promise(r => setTimeout(r, 800));\n        setTestSuccess(true);\n        setJsonPreview([\n          { nombre: 'Ene', valor: 12400, meta: 15000 },\n          { nombre: 'Feb', valor: 18200, meta: 15000 },\n          { nombre: 'Mar', valor: 9800, meta: 15000 },\n        ]);\n      }\n    } catch (error) {\n      setTestError(error instanceof Error ? error.message : 'Error de conexión desconocido');\n    } finally {\n      setIsTesting(false);\n    }\n  };\n\n  // ───── Guardar/Actualizar widget ─────\n  /** Si esta creación tiene que repartir a personas después de crear. */\n  const repartoAPersonas =\n    !isEditMode && puedeExponer && !!vertical && !formData.es_privado\n    && reparto === 'people' && puedeRepartirAlCrear;\n\n  /**\n   * 🔴 **Los dos actos que van DESPUÉS de crear, y el mensaje cuando alguno no ocurre.**\n   *\n   * Devuelve `null` si todo salió, o el texto de lo que quedó a medias. **No lanza**: el widget ya\n   * existe, así que tratar esto como un error del guardado diría «no se pudo crear» sobre algo que sí\n   * se creó — y la persona volvería a intentarlo y tendría dos.\n   *\n   * ⚠️ **El peor final tiene nombre propio:** un indicador creado, restringido y **sin nadie dentro**\n   * — invisible hasta para su autor, y sin un solo error en ningún log. Ese caso no comparte mensaje\n   * con los demás.\n   */\n  const repartirAlCrear = async (widgetId: string, nombre: string): Promise<string | null> => {\n    // Paso 2 — restringir. Si esto falla, el widget se queda privado (nació así): lo ve su autor y\n    // nadie más. Es el fallo más benigno de los tres y aun así se dice.\n    try {\n      await accessAdapter!.savePolicy!(widgetId, { visibility: 'restricted' });\n    } catch {\n      return t('dashboard.builder.step5.partialNotRestricted', { nombre });\n    }\n\n    // Paso 3 — conceder, una llamada por persona. Se hacen TODAS aunque alguna falle: parar en la\n    // primera dejaría un reparto a medias distinto en cada corrida, y sin decir cuál.\n    const ok: string[] = [];\n    const fallidos: string[] = [];\n    for (const persona of personas) {\n      try {\n        await accessAdapter!.grant(widgetId, {\n          subjectType: 'user',\n          subjectId: persona.id,\n          level: 'viewer',\n        });\n        ok.push(persona.nombre?.trim() || persona.email?.trim() || persona.id);\n      } catch {\n        fallidos.push(persona.nombre?.trim() || persona.email?.trim() || persona.id);\n      }\n    }\n\n    if (fallidos.length === 0) return null;\n    if (ok.length === 0) return t('dashboard.builder.step5.partialNobody', { nombre });\n    return t('dashboard.builder.step5.partialSome', {\n      nombre,\n      ok: ok.join(', '),\n      fallidos: fallidos.join(', '),\n    });\n  };\n\n  /** Deja el asistente como recién abierto. Lo usan el guardado feliz y las dos salidas del aviso. */\n  const limpiarAsistente = () => {\n    setFormData({ ...INITIAL_FORM_DATA, is_internal: false });\n    setStep(1);\n    setTestSuccess(false);\n    setTestError(null);\n    setJsonPreview(null);\n    setMappingConfig(null);\n    setTotalRecords(0);\n    setSelectedIndicator(null);\n    setReparto('module');\n    setPersonas([]);\n    setAvisoReparto(null);\n    setCreadoAMedias(null);\n  };\n\n  const handleSave = async () => {\n    setIsSaving(true);\n    try {\n      // Para modo catálogo, construir field_mapping desde el indicador seleccionado\n      let fieldMapping: Record<string, string> = {};\n      let configSchema: Record<string, unknown> | undefined;\n      let catalogFieldMappingObj: WidgetFieldMapping | undefined;\n\n      if (isCatalogMode && selectedIndicator) {\n        // Extraer el nombre del campo limpio (sin notación array [0].)\n        const rawField = selectedIndicator.campo_valor.replace(/^\\[\\d+\\]\\./, '').replace(/\\[.*?\\]\\./g, '');\n        const rawDateField = selectedIndicator.campo_fecha\n          ? selectedIndicator.campo_fecha.replace(/^\\[\\d+\\]\\./, '').replace(/\\[.*?\\]\\./g, '')\n          : undefined;\n\n        // Si el campo contiene puntos (ruta anidada, ej: \"bitcoin.usd\"), usar rename\n        // para que applyFieldMapping lo aplane a \"value\" usando getNestedValue (dot-notation).\n        const hasNestedPath = rawField.includes('.');\n        const canonicalField = hasNestedPath ? 'value' : rawField;\n\n        catalogFieldMappingObj = {\n          values: [canonicalField],\n          aliases: { [canonicalField]: selectedIndicator.nombre },\n          // rename: { widgetField: apiField } — \"value\" se lee de \"bitcoin.usd\" (dot-notation)\n          ...(hasNestedPath ? { rename: { [canonicalField]: rawField } } : {}),\n          fields: [\n            { name: canonicalField, type: 'number' as const, label: selectedIndicator.nombre },\n            ...(rawDateField ? [{ name: rawDateField, type: 'date' as const, label: 'Fecha' }] : []),\n          ],\n        };\n        configSchema = { type: 'kpi', valueField: canonicalField, aggregation: 'last' };\n      } else {\n        fieldMapping = buildFieldMapping(mappingConfig);\n        configSchema = mappingConfig ? { ...mappingConfig } as unknown as Record<string, unknown> : undefined;\n      }\n\n      if (isEditMode && editWidget) {\n        // PATCH — actualizar widget existente\n        const patch: Partial<WidgetDefinition> = {\n          nombre: formData.nombre || editWidget.nombre,\n          descripcion: formData.descripcion,\n          categoria: formData.categoria as DomainCategory,\n          tipo: formData.tipo as WidgetPresentationType,\n          icono: formData.icono || editWidget.icono,\n          cols_default: formData.cols_default,\n          altura_default: formData.tipo === 'kpi' ? 1 : 2,\n          endpoint_url: formData.endpoint_url,\n          endpoint_method: formData.endpoint_method,\n          endpoint_headers: Object.keys(formData.endpoint_headers ?? {}).length > 0\n            ? formData.endpoint_headers\n            : undefined,\n          endpoint_params: Object.keys(formData.endpoint_params ?? {}).length > 0\n            ? formData.endpoint_params\n            : undefined,\n          field_mapping: Object.keys(fieldMapping).length > 0 ? fieldMapping : undefined,\n          config_schema: configSchema,\n          refresh_policy: formData.refresh_policy || undefined,\n          // 🔴 Los campos de EXPOSICION solo viajan si se pueden mover. Antes iba\n          // `es_privado: isAdmin ? ... : true`, y eso tenia una consecuencia que no daba la cara:\n          // un editor no-administrador que corrigiera un titulo mandaba `es_privado: true` sin\n          // saberlo y volvia PRIVADO un widget de modulo, con lo que desaparecia del tablero de\n          // todos los demas. El backend lo aceptaba porque no distinguia editar de exponer.\n          //\n          // 🔴 F3 — y AQUI TAMBIEN, que es la mitad que se olvida. Si la vertical se derivara solo\n          // al crear, editar un widget y cambiarle la categoria lo dejaria archivado en un sitio y\n          // visible en otro: exactamente la divergencia que F3 cierra, reabierta por la puerta de\n          // atras. `verticalDeCategoria ?? roles actuales` conserva lo que hubiera cuando el host no\n          // publica la pareja, en vez de vaciarlo sin que nadie lo pida.\n          ...(puedeExponer\n            ? {\n                roles_permitidos: vertical ? [vertical.role!] : formData.roles_permitidos,\n                es_privado: formData.es_privado,\n                is_internal: resolverIsInternal(),\n              }\n            : {}),\n        };\n        const updated = await updateWidget(editWidget.widget_id, patch, fetcher);\n        onSuccess(updated);\n      } else {\n        // POST — crear widget nuevo\n        const tipo = isCatalogMode ? 'kpi' : formData.tipo as WidgetPresentationType;\n        const widgetGenerado: Omit<WidgetDefinition, 'version'> = {\n          widget_id: `custom_${crypto.randomUUID()}`,\n          nombre: formData.nombre || selectedIndicator?.nombre || 'Widget Sin Nombre',\n          descripcion: formData.descripcion || selectedIndicator?.descripcion || '',\n          categoria: formData.categoria as DomainCategory,\n          tipo,\n          icono: isCatalogMode ? 'Hash' : (formData.icono || 'Layout'),\n          // Sin autoridad para exponer, el backend fuerza privado y sin modulos: mandarlo asi evita\n          // que la pantalla diga una cosa y la fila guardada otra.\n          //\n          // 🔴 F3 — con autoridad, la vertical es LA DE LA CATEGORIA y no se pregunta. El default\n          // historico era `['admin']`, que no es una vertical de nadie: era el vocabulario cableado\n          // del kit asomando por el valor inicial del formulario.\n          roles_permitidos: puedeExponer && vertical ? [vertical.role!] : [],\n          col_min: 2,\n          col_max: 12,\n          cols_default: formData.cols_default || 3,\n          altura_default: tipo === 'table' ? 2 : 1,\n          orden_default: 99,\n          activo: true,\n          endpoint_url: formData.endpoint_url,\n          endpoint_method: formData.endpoint_method,\n          endpoint_headers: Object.keys(formData.endpoint_headers ?? {}).length > 0\n            ? formData.endpoint_headers\n            : undefined,\n          endpoint_params: Object.keys(formData.endpoint_params ?? {}).length > 0\n            ? formData.endpoint_params\n            : undefined,\n          field_mapping: catalogFieldMappingObj ?? (Object.keys(fieldMapping).length > 0 ? fieldMapping : undefined),\n          config_schema: configSchema,\n          refresh_policy: formData.refresh_policy || (isCatalogMode ? 3600 : undefined),\n          // 🔴 F4 — la ruta «solo a estas personas» nace PRIVADA, y luego se restringe.\n          //\n          // Son tres llamadas y no hay transaccion, asi que lo que importa es hacia donde falla cada\n          // una. Naciendo `es_privado: false` (modulo) un fallo del segundo paso dejaria el widget\n          // ABIERTO A TODA LA VERTICAL: el estado que nadie pidio, y silencioso. Naciendo privado, el\n          // peor final de cada paso es «lo ve menos gente de la que queria», que se arregla abriendo\n          // el dialogo de acceso. FALLA CERRANDO, a proposito.\n          es_privado: puedeExponer ? (repartoAPersonas ? true : formData.es_privado) : true,\n          is_internal: resolverIsInternal(),\n        };\n        const finalWidget = await createWidget(widgetGenerado, fetcher);\n\n        if (repartoAPersonas) {\n          const aviso = await repartirAlCrear(finalWidget.widget_id, widgetGenerado.nombre);\n          if (aviso) {\n            // 🔴 NO se cierra el asistente, y por eso NO se llama a `onSuccess`: el host lo usa para\n            // refrescar Y CERRAR. Cerrar con el aviso puesto seria dejarlo sin sitio donde leerse,\n            // que es la version educada de no decirlo. Se cierra cuando la persona lo acepta.\n            setAvisoReparto(aviso);\n            setCreadoAMedias(finalWidget);\n            setIsSaving(false);\n            return;\n          }\n        }\n\n        onSuccess(finalWidget);\n      }\n\n      limpiarAsistente();\n      onClose();\n    } catch (error) {\n      setTestError(error instanceof Error ? error.message : 'Error al guardar el widget');\n    } finally {\n      setIsSaving(false);\n    }\n  };\n\n  if (!isOpen) return null;\n\n  // Validaciones por paso\n  const canAdvance = (() => {\n    switch (currentStepId) {\n      case 'dataSource':\n        if (isCatalogMode) {\n          return !!selectedIndicator && (!selectedIndicator.requiere_key || !!formData.catalog_api_key);\n        }\n        return !formData.endpoint_url || testSuccess;\n      case 'presentation': return true;\n      case 'mapping': return !jsonPreview || isMappingValid(mappingConfig);\n      // 🔴 La CATEGORIA es obligatoria, igual que el nombre. Antes solo se exigia el nombre, y el\n      // backend tampoco la pedia —medido: `categoria: \"\"` devolvia 201—, asi que un indicador podia\n      // acabar sin ella y caer en el grupo «Otros» para siempre. No es una fuga, es desorden\n      // permanente en el catalogo del tenant, y nadie se enteraba.\n      //\n      // El componente ya la rechaza (`CreateWidgetValidator` con `NotEmpty`, que desde 0.0.27 SI se\n      // ejecuta). Esto es la mitad de UX: que no se pueda llegar al final para recibir un 400.\n      case 'appearance': return !!formData.nombre?.trim() && !!formData.categoria?.trim();\n      default: return true;\n    }\n  })();\n\n  const validationHint = (() => {\n    if (currentStepId === 'dataSource') {\n      if (isCatalogMode && !selectedIndicator) return 'Selecciona un indicador del catálogo';\n      if (isCatalogMode && selectedIndicator?.requiere_key && !formData.catalog_api_key)\n        return `Ingresa tu ${selectedIndicator.key_nombre} para continuar`;\n      if (!isCatalogMode && formData.endpoint_url && !testSuccess)\n        return 'Prueba la conexión antes de continuar';\n    }\n    if (currentStepId === 'mapping' && jsonPreview && !isMappingValid(mappingConfig))\n      return 'Completa los campos de mapeo obligatorios';\n    if (currentStepId === 'appearance' && !formData.nombre?.trim())\n      return 'El nombre del widget es obligatorio';\n    if (currentStepId === 'appearance' && !formData.categoria?.trim())\n      return 'Elige la categoría donde va a quedar el indicador';\n    return '';\n  })();\n\n  return (\n    <div className=\"fixed inset-0 z-[60] flex items-center justify-center bg-gray-900/60 backdrop-blur-sm p-4 sm:p-6\">\n      <div className=\"bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden animate-in fade-in zoom-in duration-200\">\n\n        {/* Cabecera */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-gray-50/50\">\n          <div>\n            <h2 className=\"text-xl font-bold text-gray-800\">\n              {isEditMode ? `Editar widget: ${editWidget?.nombre}` : 'Constructor de Widgets'}\n            </h2>\n            <p className=\"text-sm text-gray-500\">\n              {isEditMode ? 'Modifica la configuración del widget' : 'Crea un nuevo indicador sin programar'}\n            </p>\n          </div>\n          <button onClick={onClose} className=\"p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors\">\n            <X className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/* Stepper Visual */}\n        <div className=\"flex items-center justify-between px-10 py-4 border-b border-gray-100 bg-white\">\n          {steps.map((s, index) => (\n            <div key={s.id} className=\"flex flex-col items-center relative z-10 w-full\">\n              <div className={`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-colors duration-300 bg-white\n                ${step === index + 1 ? 'border-blue-600 text-blue-600' : step > index + 1 ? 'border-green-500 bg-green-50 text-green-500' : 'border-gray-200 text-gray-400'}\n              `}>\n                {step > index + 1 ? <CheckCircle className=\"w-5 h-5\" /> : <s.icon className=\"w-5 h-5\" />}\n              </div>\n              <span className={`text-xs mt-2 font-medium ${step === index + 1 ? 'text-blue-700' : 'text-gray-500'}`}>{s.title}</span>\n              {index < steps.length - 1 && (\n                <div className={`absolute top-5 left-[50%] right-[-50%] h-[2px] -z-10\n                  ${step > index + 1 ? 'bg-green-400' : 'bg-gray-200'}\n                `} />\n              )}\n            </div>\n          ))}\n        </div>\n\n        {/* Contenido del Paso Actual */}\n        <div className=\"flex-1 overflow-y-auto p-8 bg-gray-50/30\">\n          {/* Placeholder — nunca debería renderse porque currentStepId maneja todo */}\n          {currentStepId === 'dataSource' && (\n            <Step1DataSource\n              formData={formData}\n              testSuccess={testSuccess}\n              isTesting={isTesting}\n              testError={testError}\n              totalRecords={totalRecords}\n              allowedRoutes={allowedRoutes}\n              isAdmin={isAdmin}\n              showExternalEndpoints={showExternalEndpoints}\n              onUpdateForm={updateForm}\n              onTestConnection={handleTestConnection}\n              onIndicatorSelect={(ind) => setSelectedIndicator(ind)}\n            />\n          )}\n          {currentStepId === 'presentation' && (\n            <Step3PresentationType\n              selectedTipo={formData.tipo}\n              onSelect={(tipo) => updateForm('tipo', tipo)}\n            />\n          )}\n          {currentStepId === 'mapping' && (\n            <Step2FieldMapping\n              presentationType={formData.tipo}\n              jsonPreview={jsonPreview}\n              mappingConfig={mappingConfig}\n              onMappingConfigChange={setMappingConfig}\n              isCatalogMode={false}\n              campoValorPrefill={formData.campo_valor || undefined}\n              campoFechaPrefill={formData.campo_fecha || undefined}\n            />\n          )}\n          {currentStepId === 'appearance' && (\n            <Step4Appearance\n              availableCategories={availableCategories}\n              formData={formData}\n              onUpdateForm={updateForm}\n              indicatorUnidad={selectedIndicator?.unidad}\n              indicatorBandera={selectedIndicator?.bandera}\n              selectedIndicator={selectedIndicator}\n              isCatalogMode={isCatalogMode}\n            />\n          )}\n          {currentStepId === 'permissions' && puedeExponer && (\n            <Step5Permissions\n              esPrivado={formData.es_privado}\n              onUpdatePrivacy={(isPrivate) => updateForm('es_privado', isPrivate)}\n              vertical={vertical}\n              reparto={reparto}\n              onUpdateReparto={setReparto}\n              personas={personas}\n              onUpdatePersonas={setPersonas}\n              searchPeople={buscarPersonas}\n              puedeRepartirAlCrear={puedeRepartirAlCrear}\n            />\n          )}\n        </div>\n\n        {/*\n          🔴 F4.4 — el final a medias, DICHO. El widget ya existe, asi que esto no es un error del\n          guardado: es el estado en que quedo. Se pinta aqui y el asistente NO se cierra, porque\n          cerrarlo seria dejar el aviso sin sitio donde leerse.\n        */}\n        {avisoReparto && (\n          <div className=\"px-6 py-3 border-t border-amber-200 bg-amber-50 flex items-start gap-3\">\n            <AlertTriangle className=\"w-4 h-4 mt-0.5 text-amber-600 flex-shrink-0\" />\n            <div className=\"flex-1\">\n              <p className=\"text-sm text-amber-900\">{avisoReparto}</p>\n              <div className=\"mt-2 flex gap-2\">\n                {/*\n                  🔴 La salida que el aviso promete. Sin ella se le dice a alguien que su indicador\n                  quedó a medias y se le deja buscarlo en el catálogo — el aviso sería un callejón.\n                */}\n                {onNeedsAccessDialog && creadoAMedias && (\n                  <button\n                    onClick={() => { const w = creadoAMedias; limpiarAsistente(); onNeedsAccessDialog(w); }}\n                    className=\"px-3 py-1.5 text-xs font-semibold text-amber-900 bg-white border border-amber-300 rounded hover:bg-amber-100\"\n                  >\n                    {t('dashboard.builder.step5.openAccessDialog')}\n                  </button>\n                )}\n                <button\n                  onClick={() => { const w = creadoAMedias; limpiarAsistente(); if (w) onSuccess(w); }}\n                  className=\"px-3 py-1.5 text-xs font-medium text-amber-900 hover:underline\"\n                >\n                  {t('dashboard.builder.step5.dismissPartial')}\n                </button>\n              </div>\n            </div>\n          </div>\n        )}\n\n        {/* Footer Controles */}\n        <div className=\"flex items-center justify-between px-6 py-4 border-t border-gray-100 bg-white gap-4\">\n          <button\n            onClick={() => setStep(s => Math.max(1, s - 1))}\n            className={`px-5 py-2.5 rounded-lg font-medium flex items-center gap-2 transition-colors\n              ${step === 1 ? 'text-gray-300 cursor-not-allowed' : 'text-gray-700 bg-gray-100 hover:bg-gray-200'}\n            `}\n            disabled={step === 1}\n          >\n            <ArrowLeft className=\"w-4 h-4\" /> Anterior\n          </button>\n\n          <span className=\"text-xs text-amber-600 flex-1 text-center\">{validationHint}</span>\n\n          {step < maxStep ? (\n            <button\n              onClick={() => setStep(s => Math.min(maxStep, s + 1))}\n              className=\"px-6 py-2.5 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed\"\n              disabled={!canAdvance}\n            >\n              Siguiente <ArrowRight className=\"w-4 h-4\" />\n            </button>\n          ) : (\n            <button\n              onClick={handleSave}\n              disabled={isSaving || !formData.nombre}\n              className=\"px-6 py-2.5 bg-green-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-green-700 transition-colors shadow-sm disabled:opacity-70 disabled:cursor-not-allowed\"\n            >\n              {isSaving ? <Loader2 className=\"w-4 h-4 animate-spin\" /> : <Save className=\"w-4 h-4\" />}\n              {isSaving ? 'Guardando...' : isEditMode ? 'Actualizar Widget' : 'Finalizar y Crear Widget'}\n            </button>\n          )}\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { AlertTriangle, Loader2, Search, ShieldCheck, Trash2, Users, X } from 'lucide-react';\nimport type { WidgetDefinition } from '../types';\nimport type { WidgetVerbFlags } from '../../components/DashboardEngine/types';\n\n/**\n * 🔴 El diálogo pide **solo lo que usa**: el id, el nombre para el encabezado y los verbos. No una\n * `WidgetDefinition` completa.\n *\n * No es cosmética de tipos: el contenedor de la tarjeta recibe del motor una vista más estrecha\n * (`WidgetDefinitionBase`), así que exigir la forma completa obligaría a un cast en el único sitio\n * desde donde se abre. Pedir lo mínimo deja que lo abran los dos —la tarjeta y el panel del\n * catálogo— sin mentir sobre el tipo.\n */\ntype WidgetAccessTarget = Pick<WidgetDefinition, 'widget_id' | 'nombre'> & {\n  permissions?: WidgetVerbFlags;\n  /**\n   * 🔴 **F5 — de aquí sale la vertical, igual que en el Constructor.** No se pide la vertical: se\n   * pide la categoría y se deriva, con el mismo `verticalDeLaCategoria` que usa el Builder. Así\n   * «que las dos pantallas coincidan» deja de ser disciplina y pasa a ser una consecuencia.\n   */\n  categoria?: string;\n  /**\n   * 🔴 **F5.f — lo único que decide si «privado» se le reserva a alguien.** Un indicador con dueño\n   * privado es un tablero personal, y ahí el administrador NO entra. Un **sembrado** privado no\n   * tiene dueño al que referirse: lo ven todos los administradores de esa vertical.\n   */\n  propietario_id?: string | null;\n};\nimport { useDashboardTranslation } from '../i18n';\nimport { verticalDeLaCategoria } from '../components/WidgetBuilder/categories';\nimport { toast } from '../../components/Toast';\nimport type {\n  WidgetAccessAdapter,\n  WidgetAccessPerson,\n  WidgetGrantLevel,\n  WidgetGrantRow,\n  WidgetGrantSubjectType,\n  WidgetPolicy,\n  WidgetVisibilityState,\n} from './types';\n\n/**\n * 🔴 **El diálogo de acceso de un widget: quién lo ve, y qué exige para verse.**\n *\n * Es la mitad que faltaba del modelo de permisos por instancia. Hasta ahora el tablero solo tenía la\n * pantalla de REVISIÓN —ver lo repartido y revocarlo—, así que conceder acceso o marcar un widget\n * como sensible solo se podía hacer por API. Eso alcanza para validar el modelo; no para\n * entregárselo a nadie.\n *\n * 🔴 **Una sola pantalla con DOS BLOQUES, y son las dos preguntas del modelo** (F5.b, 2026-09-14):\n *\n * - **① ¿Quién entra?** — la visibilidad y los accesos, JUNTOS. *Un administrador la salta.*\n * - **② ¿Quién sale?** — la sensibilidad, sola. *NADIE la salta, ni el administrador.*\n *\n * <para>Antes eran dos pestañas partidas por CAPACIDAD (`can_share` / `can_edit`), y eso **partía la\n * pregunta ① por la mitad**: *restringir* vivía en una pestaña y *a quién se lo abro* en la otra,\n * siendo el mismo acto. Quien abría la de personas veía una lista de accesos sin poder ver si el\n * indicador estaba restringido siquiera — que es la única razón por la que esos accesos importan.</para>\n *\n * <para>⚠️ **Quitar las pestañas NO es quitar el gateo.** Las capacidades siguen mandando: quien tiene\n * `can_share` y no `can_edit` no ve el bloque ②, ni la parte de visibilidad del ①. Se oculta el\n * BLOQUE, que es lo que el contrato por capacidades ya hacía — la pestaña era solo el envoltorio.</para>\n *\n * <para>Y el **alcance de caché salió de esta ventana**: no es visibilidad, es de quién es el dato.</para>\n *\n * **El kit no habla HTTP:** todo pasa por el `WidgetAccessAdapter` que provee el host. Y todo lo que\n * el diálogo ofrece sale de las capacidades que ese adaptador declara, así que un host con un modelo\n * más pequeño obtiene un formulario más pequeño en vez de casillas que su backend va a rechazar. Ver\n * `access/types.ts`.\n */\nexport const WidgetAccessDialog: React.FC<{\n  widget: WidgetAccessTarget;\n  adapter: WidgetAccessAdapter;\n  isOpen: boolean;\n  onClose: () => void;\n  /** Se llama tras cualquier cambio que pueda alterar el catálogo del usuario. */\n  onChanged?: () => void;\n}> = ({ widget, adapter, isOpen, onClose, onChanged }) => {\n  const { t } = useDashboardTranslation();\n  const caps = adapter.capabilities ?? {};\n\n  // ── Qué se ofrece, y por qué cada cosa ──────────────────────────────────────────────────────\n  //\n  // ⚠️ Se decide con los verbos que el SERVIDOR resolvió para ESTE widget. `can_share` gobierna\n  // repartir; `can_edit` gobierna la política. Y `can_publish` gobierna una sola opción dentro de\n  // ella —abrir a un módulo—, que es exactamente cómo lo gatea el backend: la escritura pide la\n  // capacidad de editar y solo la transición hacia «de módulo» pide además la de publicar.\n  const puedeCompartir = widget.permissions?.can_share === true;\n  const puedeEditarPolitica =\n    widget.permissions?.can_edit === true && !!adapter.getPolicy && !!adapter.savePolicy;\n  const puedePublicar = widget.permissions?.can_publish === true;\n\n  const niveles = useMemo<WidgetGrantLevel[]>(() => caps.levels ?? ['viewer'], [caps.levels]);\n  const sujetosDeclarados = useMemo<WidgetGrantSubjectType[]>(\n    () => caps.subjects ?? ['user'],\n    [caps.subjects],\n  );\n\n  /**\n   * 🔴 **La vertical del indicador, derivada de su CATEGORÍA** — el mismo `verticalDeLaCategoria`\n   * que usa el Constructor, no una copia de la regla.\n   */\n  const vertical = useMemo(\n    () => verticalDeLaCategoria(caps.categories ?? [], widget.categoria),\n    [caps.categories, widget.categoria],\n  );\n\n  /**\n   * 🔴 **F5.a.2 — el sujeto «Un módulo» NO se recorta: se RETIRA** en todo indicador que declare\n   * vertical.\n   *\n   * <para>Recortarlo a «solo la suya» parecía la respuesta, y es peor que no hacer nada: deja una\n   * opción con **exactamente una respuesta posible**, y esa respuesta —conceder a su propia\n   * vertical— **es lo mismo que no haberlo restringido**. O sea un formulario que ofrece deshacer lo\n   * que acabas de hacer, sin decirlo. Las otras dos verticales, ofrecidas, producirían un acceso que\n   * se guarda y **no abre nada**.</para>\n   *\n   * <para>🟢 Sigue existiendo en un indicador **sin vertical** —los personales creados antes de F1,\n   * a los que el servidor vaciaba `roles_permitidos`—: ahí no hay techo, así que conceder a un\n   * módulo sí abre algo. Es la única razón por la que el sujeto no desaparece del contrato.</para>\n   */\n  /**\n   * 🔴 **Esta pantalla solo reparte a PERSONAS** (2026-09-14). Se retira «Un permiso», y «Un módulo»\n   * ya se retiraba en cuanto el indicador declara vertical. Con una sola opción no hay selector: los\n   * botones de sujeto no se pintan.\n   *\n   * ⚠️ **El contrato NO cambia**, y las ramas de `permission` y `module` de más abajo se quedan: el\n   * host sigue declarando los tres sujetos, el servidor sigue aceptándolos y el panel de revisión\n   * sigue mostrando los grants que ya existan. Lo que se retira es **ofrecerlos aquí**.\n   *\n   * 🔴 Y hay que decir lo que cuesta: conceder **por un permiso** es el mecanismo que la auditoría\n   * llama central —el que pasó cinco revisiones funcionando en el servidor con su única pantalla\n   * inutilizable— y vuelve a quedarse **solo-API**.\n   */\n  const sujetos = useMemo<WidgetGrantSubjectType[]>(\n    () => sujetosDeclarados.filter((s) => s === 'user'),\n    [sujetosDeclarados],\n  );\n\n  // ── Accesos concedidos ──────────────────────────────────────────────────────────────────────\n  const [filas, setFilas] = useState<WidgetGrantRow[] | null>(null);\n  const [cargando, setCargando] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  const [aviso, setAviso] = useState<string | null>(null);\n\n  const cargarFilas = useCallback(async () => {\n    setCargando(true);\n    setError(null);\n    try {\n      setFilas(await adapter.listGrants(widget.widget_id));\n    } catch (e) {\n      setError(e instanceof Error ? e.message : String(e));\n    } finally {\n      setCargando(false);\n    }\n  }, [adapter, widget.widget_id]);\n\n  useEffect(() => {\n    if (isOpen && puedeCompartir) void cargarFilas();\n  }, [isOpen, puedeCompartir, cargarFilas]);\n\n  // ── El formulario de conceder ───────────────────────────────────────────────────────────────\n  const [tipoSujeto, setTipoSujeto] = useState<WidgetGrantSubjectType>(sujetos[0]);\n  const [sujetoId, setSujetoId] = useState('');\n  const [sujetoLabel, setSujetoLabel] = useState('');\n  const [nivel, setNivel] = useState<WidgetGrantLevel>(niveles[0]);\n  const [vencimiento, setVencimiento] = useState<'default' | 'ninguno' | 'fecha'>('default');\n  const [fecha, setFecha] = useState('');\n\n  /**\n   * 🔴 **El borrador.** `agregados` son accesos que solo existen en pantalla; `revocados`, ids que\n   * se van al guardar. La lista que se pinta es `filas − revocados + agregados`, así que lo que se\n   * ve es **el estado al que se va a llegar**, no una mezcla del actual con lo pedido.\n   */\n  const [agregados, setAgregados] = useState<WidgetGrantRow[]>([]);\n  const [revocados, setRevocados] = useState<string[]>([]);\n\n  /** La política tal y como vino del servidor, para saber si cambió. */\n  const politicaOriginal = useRef<WidgetPolicy | null>(null);\n\n  /**\n   * El vencimiento que se aplica de verdad.\n   *\n   * 🔴 **Con «por defecto» se CALCULA la fecha aquí.** Antes se mandaba `undefined` y el acceso\n   * nacía **sin vencimiento** — o sea, el selector decía «caduca a los 182 días» y la fila guardada\n   * decía «nunca». Dos datos que se contradicen, y el que manda es el invisible.\n   */\n  const vencimientoElegido = (): string | null | undefined => {\n    if (vencimiento === 'ninguno') return null;\n    if (vencimiento === 'fecha') return fecha || undefined;\n    const dias = caps.expiry?.defaultDays;\n    if (!dias) return undefined;\n    const d = new Date();\n    d.setDate(d.getDate() + dias);\n    return d.toISOString();\n  };\n\n  // ── El buscador de permisos (solo si el host los declara) ───────────────────────────────────\n  //\n  // A diferencia del de personas, este NO consulta al servidor: la lista viene entera en las\n  // capacidades y se filtra en memoria. Y eso no es una simplificación, es lo correcto — la lista\n  // que hay que ofrecer son LOS PERMISOS DE QUIEN CONCEDE, que el host ya conoce. El servidor exige\n  // que uno tenga el permiso que asocia, así que ofrecer cualquier otro es ofrecer un 403.\n  const permisosOfrecibles = useMemo(() => caps.permissions?.options ?? [], [caps.permissions]);\n\n  // ── El buscador de personas (solo si el host lo provee) ─────────────────────────────────────\n  const [consulta, setConsulta] = useState('');\n  const [personas, setPersonas] = useState<WidgetAccessPerson[]>([]);\n  const [buscando, setBuscando] = useState(false);\n\n  // Con la caja vacía se ofrece la lista entera: son los permisos propios, no un catálogo ajeno, y\n  // verlos completos es parte de saber qué se está eligiendo.\n  const permisosFiltrados = useMemo(() => {\n    const q = consulta.trim().toLowerCase();\n    if (!q) return permisosOfrecibles;\n    return permisosOfrecibles.filter(\n      (pm) => pm.id.toLowerCase().includes(q) || pm.label.toLowerCase().includes(q),\n    );\n  }, [consulta, permisosOfrecibles]);\n\n  /**\n   * 🔴 **El efecto NO depende de `adapter`, y es una cicatriz.**\n   *\n   * <para>`adapter` es un objeto que construye el host. Basta con que su memo pierda una dependencia\n   * —o no lo memoice— para que cambie de identidad en cada render: el efecto se remonta, el\n   * `clearTimeout` del cleanup cancela el debounce **antes de lanzarlo**, y el buscador se queda\n   * girando sin llegar a pedir nada. Pasó en el Constructor, con un `.bind()` en el JSX.</para>\n   *\n   * <para>Se lee por `ref`, que es justo lo que se quiere: usar siempre el último adaptador sin que\n   * su identidad dispare nada. Y `setBuscando(true)` va DENTRO del `setTimeout`, para que un\n   * debounce cancelado no deje el spinner encendido.</para>\n   *\n   * <para>El contador descarta respuestas fuera de orden: sin él, teclear rápido deja pintados los\n   * resultados de una consulta anterior y se elegiría a alguien que no se buscó.</para>\n   */\n  const adapterRef = useRef(adapter);\n  useEffect(() => { adapterRef.current = adapter; });\n  const turnoBusqueda = useRef(0);\n\n  useEffect(() => {\n    const buscar = adapterRef.current.searchPeople;\n    if (!buscar || tipoSujeto !== 'user' || consulta.trim().length < 2) {\n      setPersonas([]);\n      setBuscando(false);\n      return;\n    }\n    const turno = ++turnoBusqueda.current;\n    // Debounce: el directorio de personas es una consulta al Access Manager, no una lista local.\n    const id = setTimeout(async () => {\n      setBuscando(true);\n      try {\n        const r = await buscar.call(adapterRef.current, consulta.trim());\n        if (turno === turnoBusqueda.current) setPersonas(r);\n      } catch {\n        if (turno === turnoBusqueda.current) setPersonas([]);\n      } finally {\n        if (turno === turnoBusqueda.current) setBuscando(false);\n      }\n    }, 300);\n    return () => clearTimeout(id);\n  }, [consulta, tipoSujeto]);\n\n  /**\n   * 🔴 **Añadir ya NO escribe: encola.** Nada de esta ventana se persiste hasta «Guardar cambios».\n   *\n   * <para>Antes, conceder y revocar llamaban al API en el acto mientras la visibilidad esperaba a un\n   * botón. Eso dejaba la pantalla contando **dos verdades a la vez**: media ventana ya había pasado\n   * y la otra media no, y quien cerraba sin guardar se llevaba los accesos escritos igual. Ahora la\n   * ventana entera es un borrador, y el pie dice cuántos cambios hay sin guardar.</para>\n   */\n  const encolarAcceso = () => {\n    if (!sujetoId.trim()) return;\n    const id = sujetoId.trim();\n    setError(null);\n    setAviso(null);\n\n    // Revocar y volver a añadir a la misma persona se anulan: es un no-cambio, y contarlo como dos\n    // sería mentir en el contador del pie.\n    setRevocados((r) => r.filter((x) => x !== id));\n    setAgregados((a) =>\n      a.some((x) => x.subjectId === id)\n        ? a\n        : [\n            ...a,\n            {\n              subjectType: tipoSujeto,\n              subjectId: id,\n              subjectLabel: sujetoLabel || undefined,\n              level: nivel,\n              expiresAt: vencimientoElegido(),\n            },\n          ],\n    );\n\n    setSujetoId('');\n    setSujetoLabel('');\n    setConsulta('');\n  };\n\n  /** Quitar tampoco escribe: si estaba solo en el borrador se deshace, y si no se marca para borrar. */\n  const quitarAcceso = (fila: WidgetGrantRow) => {\n    setError(null);\n    if (agregados.some((a) => a.subjectId === fila.subjectId)) {\n      setAgregados((a) => a.filter((x) => x.subjectId !== fila.subjectId));\n      return;\n    }\n    setRevocados((r) => (r.includes(fila.subjectId) ? r : [...r, fila.subjectId]));\n  };\n\n  // ── La política del widget ──────────────────────────────────────────────────────────────────\n  const [politica, setPolitica] = useState<WidgetPolicy | null>(null);\n  const [guardando, setGuardando] = useState(false);\n\n  // Se carga al ABRIR. Antes esperaba a que alguien pulsara la pestaña de política; sin pestañas,\n  // la visibilidad forma parte del bloque ① y tiene que estar ahí desde el primer render — si no, el\n  // bloque abriría sin saber si el indicador está restringido, que es justo lo que da sentido a la\n  // lista de accesos que hay debajo.\n  useEffect(() => {\n    if (!isOpen || !puedeEditarPolitica || !adapter.getPolicy || politica) return;\n    let vivo = true;\n    setCargando(true);\n    adapter\n      .getPolicy(widget.widget_id)\n      .then((p) => { if (vivo) { setPolitica(p); politicaOriginal.current = p; } })\n      .catch((e) => { if (vivo) setError(e instanceof Error ? e.message : String(e)); })\n      .finally(() => { if (vivo) setCargando(false); });\n    return () => { vivo = false; };\n  }, [isOpen, puedeEditarPolitica, adapter, widget.widget_id, politica]);\n\n  /** Lo que se ve: lo del servidor, menos lo marcado para quitar, más lo añadido en pantalla. */\n  const filasEfectivas: WidgetGrantRow[] = [\n    ...(filas ?? []).filter((f) => !revocados.includes(f.subjectId)),\n    ...agregados,\n  ];\n\n  const politicaCambio =\n    !!politica && !!politicaOriginal.current\n    && politica.visibility !== politicaOriginal.current.visibility;\n\n  const cambios = agregados.length + revocados.length + (politicaCambio ? 1 : 0);\n\n  /**\n   * 🔴 **Guardar aplica el borrador ENTERO, y en este orden.**\n   *\n   * <para>La política primero: si alguien pasó de «lo ve toda la vertical» a «personas específicas»,\n   * aplicar antes los accesos dejaría una ventana en la que el indicador sigue abierto y ya tiene\n   * lista — el estado que parece cerrado y no lo está.</para>\n   *\n   * <para>⚠️ **No hay transacción**, igual que en el reparto al crear. Si algo falla a mitad, se\n   * dice **qué quedó sin aplicar** y se recarga lo que sí: dejar el borrador como si nada hubiera\n   * pasado sería pedirle a alguien que adivine qué repetir.</para>\n   */\n  const guardarCambios = async () => {\n    // 🔴 SIN `if (!politica) return`. Lo tenia, y dejaba a quien solo REPARTE —`can_share` sin\n    // `can_edit`, que es el caso de un analista— sin poder guardar nada: su ventana no carga\n    // politica, asi que salia por aqui y sus accesos no se escribian jamas. El boton se veia\n    // habilitado y no hacia nada.\n    setGuardando(true);\n    setError(null);\n    setAviso(null);\n\n    // 🔴 Los avisos se ACUMULAN. Antes cada `setAviso` pisaba al anterior, así que de dos accesos\n    // que quedaban inertes solo se veía uno — y quien compartía se iba creyendo que el otro sí\n    // había surtido efecto. Se juntan y se pintan todos, sin repetir el mismo texto dos veces.\n    const avisos: string[] = [];\n    const fallidos: string[] = [];\n    try {\n      if (politica && politicaCambio && adapter.savePolicy) {\n        const r = await adapter.savePolicy(widget.widget_id, politica);\n        if (r?.warning) avisos.push(r.warning);\n        politicaOriginal.current = politica;\n      }\n\n      for (const a of agregados) {\n        try {\n          const r = await adapter.grant(widget.widget_id, {\n            subjectType: a.subjectType,\n            subjectId: a.subjectId,\n            level: a.level,\n            expiresAt: a.expiresAt,\n          });\n          // El aviso de I-2: se concedió, y a esa persona NO le va a aparecer porque le falta una\n          // capacidad de más arriba. No es un error —la fila queda escrita y servirá el día que le\n          // den el permiso— pero callarlo dejaría a quien comparte creyendo que compartió.\n          const res = r ?? undefined;\n          if (res?.warning) avisos.push(res.warning);\n          else if (res?.inert) avisos.push(t('dashboard.access.grantInert'));\n        } catch {\n          fallidos.push(a.subjectLabel || a.subjectId);\n        }\n      }\n\n      for (const id of revocados) {\n        const fila = (filas ?? []).find((f) => f.subjectId === id);\n        try {\n          await adapter.revoke(widget.widget_id, fila?.subjectType ?? 'user', id);\n        } catch {\n          fallidos.push(fila?.subjectLabel || id);\n        }\n      }\n\n      setAgregados([]);\n      setRevocados([]);\n\n      // ── 🔴 SI NO FALLÓ NADA: la ventana SE CIERRA y lo dice fuera ────────────────────────\n      //\n      // Antes se quedaba abierta, con el pie en «Sin cambios» y sin una sola señal de que el\n      // guardado hubiera ocurrido. Y ese silencio se lee mal en las dos direcciones: quien pulsa\n      // no sabe si pasó algo —así que vuelve a pulsar—, y quien no mira el pie se queda con la\n      // ventana delante creyendo que todavía tiene trabajo pendiente.\n      //\n      // ⚠️ **Avisar DESPUÉS de cerrar obliga a sacar el mensaje de aquí**: dentro del diálogo se\n      // iría con él. Por eso va al `toast` del kit —que es del kit, no del host, así que esto no\n      // cuesta genericidad— y por eso los avisos del host viajan también ahí en vez de perderse.\n      if (!fallidos.length) {\n        onChanged?.();\n        if (avisos.length) toast.warning([...new Set(avisos)].join(' '));\n        else toast.success(t('dashboard.access.savedOk'));\n        onClose();\n        return;\n      }\n\n      // ── 🔴 SI ALGO FALLÓ: NO se cierra ──────────────────────────────────────────────────\n      //\n      // Cerrar aquí sería lo peor de las dos opciones: el mensaje diría qué quedó sin aplicar y la\n      // ventana desaparecería antes de que se pueda hacer nada al respecto. Se queda abierta, con\n      // la lista recargada —para que se vea el estado REAL— y el error nombrando a quién le falta.\n      if (avisos.length) setAviso([...new Set(avisos)].join(' '));\n      await cargarFilas();\n      onChanged?.();\n      setError(t('dashboard.access.saveFailedSome', { quienes: fallidos.join(', ') }));\n    } catch (e) {\n      setError(e instanceof Error ? e.message : String(e));\n    } finally {\n      setGuardando(false);\n    }\n  };\n\n  useEffect(() => {\n    if (!isOpen) return;\n    const cerrarConEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };\n    window.addEventListener('keydown', cerrarConEsc);\n    return () => window.removeEventListener('keydown', cerrarConEsc);\n  }, [isOpen, onClose]);\n\n  /**\n   * La visibilidad a la que se vuelve al marcar. Se recuerda en vez de asumir `restricted`, para que\n   * abrir y volver a cerrar un tablero **personal** no lo convierta en otra cosa.\n   *\n   * 🔴 **Va ANTES del `return null`, y no es cosmético.** Estaba después: React cuenta los hooks por\n   * render, así que un montaje permanente con `isOpen` alternando renderizaba N hooks cerrado y N+2\n   * abierto — *«Rendered more hooks than during the previous render»*. No reventaba porque los dos\n   * sitios que lo montan (`WidgetWrapper`, `WidgetManagerPanel`) lo montan condicionalmente con\n   * `isOpen` fijo en `true`; pero el diálogo se **exporta público**, así que era una mina para\n   * cualquier host que lo montara de otra forma.\n   */\n  const visibilidadCerrada = useRef<WidgetVisibilityState>('restricted');\n  useEffect(() => {\n    if (politica && politica.visibility !== 'module') visibilidadCerrada.current = politica.visibility;\n  }, [politica]);\n\n  if (!isOpen) return null;\n\n  const etiquetaNivel = (n: WidgetGrantLevel) => t(`dashboard.access.level.${n}`);\n\n  /**\n   * «15 mar 2027». Con día, mes corto y año en vez de `toLocaleDateString()`, que en es-CO sale\n   * `15/3/2027` — tres números que hay que descifrar en una fila que ya tiene otros dos.\n   */\n  const fechaCorta = (iso: string) =>\n    new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });\n\n  /**\n   * 🔴 **F5.a.1/5.a.3 — la visibilidad «de módulo» nombra la vertical: «Todo Ventas».**\n   *\n   * Decir «todo el módulo» mientras el Constructor dice «Público en Ventas» son **dos vocabularios\n   * para un solo concepto**, y quien opera las dos pantallas tiene que traducir de memoria. Sin\n   * vertical derivable se conserva el texto genérico, que es la verdad disponible.\n   */\n  /**\n   * 🔴 **El rótulo de cada visibilidad lo resuelve el HOST, y el kit cae a un texto NEUTRO.**\n   *\n   * <para>⚠️ Esto estuvo muerto: el diálogo rediseñado elegía el texto él mismo con\n   * `widget.propietario_id`, aplicando una regla que es del host —*«privado SIN dueño lo ven los\n   * administradores»*—. Un kit que lo consumen Comercial, Financiero y Nómina no puede saber eso.\n   * Ahora se pregunta; si el host no contesta, el kit dice lo que **sí** puede afirmar.</para>\n   */\n  const delHost = (v: WidgetVisibilityState) =>\n    adapter.describeVisibility?.({\n      widgetId: widget.widget_id,\n      visibility: v,\n      tieneDueno: !!widget.propietario_id,\n      vertical: vertical ? { id: vertical.role!, label: vertical.label } : undefined,\n    });\n\n  const etiquetaVisibilidad = (v: WidgetVisibilityState, porDefecto: string) =>\n    delHost(v)?.label ?? porDefecto;\n\n  const pistaVisibilidad = (v: WidgetVisibilityState, porDefecto: string) =>\n    delHost(v)?.hint ?? porDefecto;\n\n  /**\n   * 🔴 **Sin respuesta del host, la nota NO se pinta.** Afirmar «hay alguien que lo ve siempre» es\n   * una afirmación sobre el modelo de autorización del host, no sobre este formulario.\n   */\n  const notaSiempreVe = adapter.describeAlwaysSee?.({\n    widgetId: widget.widget_id,\n    vertical: vertical ? { id: vertical.role!, label: vertical.label } : undefined,\n  });\n\n  /**\n   * 🔴 **Restringido = «no es de módulo».** Es el binario que la casilla expresa, y agrupa a\n   * propósito `restricted` y `private`: desde esta pantalla la pregunta es una sola —¿lo ve toda la\n   * vertical, o solo los de la lista?—, y un tablero personal responde lo mismo que uno restringido.\n   */\n  const restringido = (politica?.visibility ?? 'module') !== 'module';\n\n  /**\n   * 🔴 **F5.e — «Hoy lo ve: …».** La resuelve el HOST; el kit la pinta y no la interpreta. Sigue la\n   * política EN CURSO del formulario, no la guardada: si alguien marca «sensible», la frase cambia\n   * antes de guardar — que es donde sirve.\n   */\n  const hoyLoVe = adapter.describeAudience?.({\n    widgetId: widget.widget_id,\n    policy: politica,\n    grants: filasEfectivas,\n    vertical: vertical ? { id: vertical.role!, label: vertical.label } : undefined,\n  });\n\n  return (\n    <div\n      className=\"fixed inset-0 z-[80] flex items-center justify-center bg-gray-900/60 backdrop-blur-sm p-4\"\n      role=\"dialog\"\n      aria-modal=\"true\"\n      aria-label={t('dashboard.access.dialogTitle')}\n    >\n      <div className=\"bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col\">\n        {/* Cabecera */}\n        <div className=\"flex items-start justify-between gap-4 p-5 border-b border-gray-200\">\n          <div className=\"min-w-0\">\n            <h2 className=\"text-base font-semibold text-gray-900\">{t('dashboard.access.dialogTitle')}</h2>\n            <p className=\"text-sm text-gray-500 truncate\" title={widget.nombre}>{widget.nombre}</p>\n          </div>\n          <button\n            onClick={onClose}\n            className=\"p-1 text-gray-400 hover:text-gray-600 rounded\"\n            aria-label={t('dashboard.access.close')}\n          >\n            <X className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/*\n          🔴 F5.c — «Hoy lo ve: …», SIEMPRE y arriba del todo.\n          La combinación de tres cerraduras es difícil de deducir mirando los controles, y hay un\n          estado que hoy no tiene ninguna señal en pantalla: restringido + sensible SIN accesos no lo\n          ve nadie. Decir el resultado convierte el modelo en algo que se lee en vez de calcularse.\n          El texto lo resuelve el host; aquí solo se pinta.\n        */}\n        {hoyLoVe && (\n          <div className=\"mx-5 mt-4 flex items-start gap-2 rounded-lg bg-blue-50 px-3 py-2.5 text-sm text-blue-900\">\n            <Users className=\"mt-0.5 h-4 w-4 flex-shrink-0\" />\n            <p>\n              <span className=\"font-semibold\">{t('dashboard.access.audienceToday')}</span>{' '}\n              <span data-testid=\"access-audience\">{hoyLoVe}</span>\n            </p>\n          </div>\n        )}\n\n        {/*\n          🔴 El área de contenido NO hace scroll: lo hace **solo la lista de accesos**. Con todo\n          desplazándose, el banner de «Hoy lo ven» se iba de la pantalla justo al cambiar lo que\n          describe — y el pie con el contador, también.\n        */}\n        <div className=\"flex-1 overflow-hidden flex flex-col p-5 pt-4\">\n          {error && (\n            <div className=\"mb-4 flex items-start gap-2 p-3 rounded-lg bg-red-50 text-sm text-red-800\" role=\"alert\">\n              <AlertTriangle className=\"w-4 h-4 flex-shrink-0 mt-0.5\" /> <span>{error}</span>\n            </div>\n          )}\n          {aviso && (\n            <div className=\"mb-4 flex items-start gap-2 p-3 rounded-lg bg-amber-50 text-sm text-amber-900\" role=\"status\">\n              <AlertTriangle className=\"w-4 h-4 flex-shrink-0 mt-0.5\" /> <span>{aviso}</span>\n            </div>\n          )}\n\n          {/*\n            ══ ① ¿QUIÉN ENTRA? ═══════════════════════════════════════════════════════════════════\n            La visibilidad y los accesos, JUNTOS, porque son el mismo acto: restringir sin decir a\n            quién se lo abres deja el indicador sin nadie dentro, y abrirlo a alguien sin haberlo\n            restringido no cambia nada. Partidos en dos pestañas, cada mitad parecía completa.\n          */}\n          <section aria-labelledby=\"bloque-quien-entra\" className=\"mb-6\">\n            {/*\n              🔴 **Sin encabezado de bloque.** Lo llevaba —«Widget disponible para:»— y con una sola\n              sección en la ventana era un título repetido: el de la ventana ya dice de qué va. Y la\n              columna «Un administrador la salta» se fue con él: decía en abstracto lo que la nota de\n              debajo de la lista dice en concreto, donde importa.\n            */}\n\n            {/*\n              🔴 **«Quién ve este indicador» — una LISTA y una CASILLA** (2026-09-14).\n              ────────────────────────────────────────────────────────────────────────────────────\n              Se retiran de esta pantalla los tres radios de visibilidad y el sujeto «Un permiso».\n              Lo que queda es **quién lo ve**, en una lista, y una casilla para cerrarlo o abrirlo.\n\n              **Por qué una casilla y no radios:** quitados «Solo su dueño» y el resto, lo que sobra\n              es **binario** —o lo ve toda la vertical, o solo los de la lista— y un binario se dice\n              con una casilla. Además deja ① y ② leyéndose igual.\n\n              ⚠️ **ESTO ES SOLO LA PANTALLA.** El modelo conserva las tres visibilidades y los tres\n              sujetos, y el servidor los sigue aceptando. Lo que queda pendiente, y hay que tenerlo\n              escrito donde se vea: **conceder NO restringe solo**. Añadir a alguien en un indicador\n              de módulo guarda el acceso y no cambia a quién alcanza hasta que se marque la casilla —\n              la instancia ya está satisfecha para toda la vertical. La frase «Hoy lo ve…» de arriba\n              es hoy lo único que lo delata, y por eso no se toca.\n            */}\n\n\n            {/*\n              🔴 **LA CASILLA MANDA, Y LAS DOS OPCIONES CUELGAN DE ELLA** (2026-09-14).\n              ──────────────────────────────────────────────────────────────────────────────────────\n              Las tres visibilidades del modelo quedan cubiertas sin nombrar ninguna:\n\n                  desmarcada                      → de módulo  (lo ve toda la vertical)\n                  marcada + «Solo administradores» → privado\n                  marcada + «Por usuario»          → restringido + la lista\n\n              **Por qué una casilla arriba y radios debajo, y no tres radios planos:** la primera\n              pregunta —¿está restringido?— es binaria y gobierna a la segunda. Puestas al mismo\n              nivel, «Todo Ventas» competía visualmente con «Solo administradores» como si fueran\n              del mismo orden, y no lo son: una abre y las otras dos cierran de formas distintas.\n\n              ⚠️ **Desmarcarla es PUBLICAR** —abrir el indicador a un colectivo— y por eso pide\n              `can_publish`. Marcarla y elegir entre las dos pide poder editar la política.\n            */}\n            {puedeEditarPolitica && politica ? (\n              <>\n                <label\n                  className={`flex items-start gap-2 text-sm ${\n                    restringido && !puedePublicar ? 'cursor-not-allowed opacity-60' : 'cursor-pointer text-gray-800'\n                  }`}\n                  title={restringido && !puedePublicar ? t('dashboard.access.restrictedNeedsPublish') : undefined}\n                >\n                  <input\n                    type=\"checkbox\"\n                    className=\"mt-1\"\n                    checked={restringido}\n                    disabled={restringido && !puedePublicar}\n                    onChange={(e) => {\n                      if (e.target.checked) {\n                        setPolitica({ ...politica, visibility: visibilidadCerrada.current });\n                      } else {\n                        visibilidadCerrada.current =\n                          politica.visibility === 'module' ? 'restricted' : politica.visibility;\n                        setPolitica({ ...politica, visibility: 'module' });\n                      }\n                    }}\n                  />\n                  <span>\n                    <span className=\"font-medium\">{t('dashboard.access.restrictedCheck')}</span>\n                    <span className=\"block text-xs text-gray-500\">\n                      {restringido\n                        ? t('dashboard.access.restrictedCheckOn')\n                        : pistaVisibilidad(\n                            'module',\n                            vertical\n                              ? t('dashboard.access.restrictedCheckOffNamed', { alcance: vertical.label })\n                              : t('dashboard.access.restrictedCheckOff'),\n                          )}\n                    </span>\n                  </span>\n                </label>\n\n                {/*\n                  Las dos formas de cerrarlo. Excluyentes de verdad —son dos visibilidades distintas\n                  del modelo— así que radios, no casillas.\n\n                  ⚠️ **«Solo administradores» es `private`, y en un indicador CON DUEÑO significa otra\n                  cosa**: ahí el administrador no entra y quien queda es su dueño. Por eso el rótulo\n                  cambia, en vez de mentir con el mismo texto para dos estados distintos.\n                */}\n                {restringido && (\n                  <div className=\"ml-6 mt-3 space-y-3 border-l-2 border-gray-100 pl-4\">\n                    <label className=\"flex items-start gap-2 text-sm cursor-pointer\">\n                      <input\n                        type=\"radio\"\n                        name=\"alcance\"\n                        className=\"mt-1\"\n                        checked={politica.visibility === 'private'}\n                        onChange={() => setPolitica({ ...politica, visibility: 'private' })}\n                      />\n                      <span>\n                        <span className=\"font-medium text-gray-800\">\n                          {etiquetaVisibilidad('private', t('dashboard.access.scopeClosed'))}\n                        </span>\n                        <span className=\"block text-xs text-gray-500\">\n                          {pistaVisibilidad('private', t('dashboard.access.scopeClosedHint'))}\n                        </span>\n                      </span>\n                    </label>\n\n                    <label className=\"flex items-start gap-2 text-sm cursor-pointer\">\n                      <input\n                        type=\"radio\"\n                        name=\"alcance\"\n                        className=\"mt-1\"\n                        checked={politica.visibility === 'restricted'}\n                        onChange={() => setPolitica({ ...politica, visibility: 'restricted' })}\n                      />\n                      <span>\n                        <span className=\"font-medium text-gray-800\">\n                          {etiquetaVisibilidad('restricted', t('dashboard.access.scopeUsers'))}\n                        </span>\n                        <span className=\"block text-xs text-gray-500\">\n                          {pistaVisibilidad('restricted', t('dashboard.access.scopeUsersHint'))}\n                        </span>\n                      </span>\n                    </label>\n\n                    {politica.visibility === 'restricted' && (\n                      <div className=\"ml-6\">\n                    {/*\n                      El reparto sigue gateado por `can_share`. Quitar los radios NO es quitar el gateo:\n                      quien puede editar la política pero no repartir no debe ver este formulario — se lo\n                      ofreceríamos para que el API se lo rechazara.\n                    */}\n                    {puedeCompartir && (\n                      <>\n                      <div className=\"space-y-3 mb-6\">\n                        {sujetos.length > 1 && (\n                          <div className=\"flex gap-2\">\n                            {sujetos.map((s) => (\n                              <button\n                                key={s}\n                                onClick={() => { setTipoSujeto(s); setSujetoId(''); setSujetoLabel(''); setConsulta(''); }}\n                                className={`px-2.5 py-1 text-xs rounded-full border ${\n                                  tipoSujeto === s\n                                    ? 'border-blue-600 text-blue-700 bg-blue-50'\n                                    : 'border-gray-200 text-gray-600'\n                                }`}\n                              >\n                                {t(`dashboard.access.subject.${s}`)}\n                              </button>\n                            ))}\n                          </div>\n                        )}\n\n                        {/* El sujeto: buscado si el host tiene directorio, tecleado si no */}\n                        {tipoSujeto === 'user' && adapter.searchPeople ? (\n                          <div className=\"relative\">\n                            <Search className=\"absolute left-3 top-2.5 w-4 h-4 text-gray-400\" />\n                            <input\n                              value={sujetoLabel || consulta}\n                              onChange={(e) => { setConsulta(e.target.value); setSujetoLabel(''); setSujetoId(''); }}\n                              placeholder={t('dashboard.access.searchPeople')}\n                              className=\"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500\"\n                            />\n                            {buscando && <Loader2 className=\"absolute right-3 top-2.5 w-4 h-4 text-gray-400 animate-spin\" />}\n                            {personas.length > 0 && !sujetoId && (\n                              <ul className=\"absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto\">\n                                {personas.map((p) => (\n                                  <li key={p.id}>\n                                    <button\n                                      onClick={() => { setSujetoId(p.id); setSujetoLabel(p.nombre || p.id); setPersonas([]); }}\n                                      className=\"w-full text-left px-3 py-2 text-sm hover:bg-gray-50\"\n                                    >\n                                      <span className=\"font-medium text-gray-800\">{p.nombre || p.id}</span>\n                                      {p.email && <span className=\"text-gray-500 ml-2\">{p.email}</span>}\n                                    </button>\n                                  </li>\n                                ))}\n                              </ul>\n                            )}\n                          </div>\n                        ) : tipoSujeto === 'module' && caps.modules?.length ? (\n                          /*\n                           * Solo se llega aquí en un indicador SIN vertical: con vertical, el sujeto se\n                           * retiró de `sujetos`. Ver la nota de F5.a.2 arriba.\n                           */\n                          <select\n                            value={sujetoId}\n                            onChange={(e) => setSujetoId(e.target.value)}\n                            className=\"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                          >\n                            <option value=\"\">{t('dashboard.access.pickModule')}</option>\n                            {caps.modules.map((m) => (\n                              <option key={m.id} value={m.id}>{m.label}</option>\n                            ))}\n                          </select>\n                        ) : tipoSujeto === 'permission' && permisosOfrecibles.length > 0 ? (\n                          /*\n                           * 🔴 El selector de permisos. Antes de esto, el mecanismo central —conceder a quien\n                           * tenga un permiso— caia al `<input>` libre de abajo: habia que saberse el codigo\n                           * entre cientos, y el premio por equivocarse era un 403 despues de teclear. Es la\n                           * misma falla que ya se habia cerrado para las clases de sensibilidad.\n                           *\n                           * Es BUSCABLE y no un `<select>` porque la lista de un administrador es larga, y\n                           * porque el codigo se reconoce leyendolo, no desplegando doscientas opciones.\n                           */\n                          <div className=\"relative\">\n                            <Search className=\"absolute left-3 top-2.5 w-4 h-4 text-gray-400\" />\n                            <input\n                              value={sujetoLabel || consulta}\n                              onChange={(e) => { setConsulta(e.target.value); setSujetoLabel(''); setSujetoId(''); }}\n                              placeholder={t('dashboard.access.searchPermissions')}\n                              className=\"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500\"\n                            />\n                            {permisosFiltrados.length > 0 && !sujetoId && (\n                              <ul className=\"absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto\">\n                                {permisosFiltrados.map((pm) => (\n                                  <li key={pm.id}>\n                                    <button\n                                      onClick={() => { setSujetoId(pm.id); setSujetoLabel(pm.label || pm.id); setConsulta(''); }}\n                                      className=\"w-full text-left px-3 py-2 text-sm hover:bg-gray-50\"\n                                    >\n                                      <span className=\"font-medium text-gray-800\">{pm.label || pm.id}</span>\n                                      {pm.label && pm.label !== pm.id && (\n                                        <span className=\"text-gray-500 ml-2 text-xs font-mono\">{pm.id}</span>\n                                      )}\n                                    </button>\n                                  </li>\n                                ))}\n                              </ul>\n                            )}\n                            {consulta && permisosFiltrados.length === 0 && !sujetoId && (\n                              <p className=\"mt-1 text-xs text-gray-500\">\n                                {t('dashboard.access.noPermissionMatch')}\n                              </p>\n                            )}\n                            {/*\n                              * La guarda del servidor, dicha donde se elige. «Solo puedes asociar un permiso\n                              * que tú tienes» es una regla correcta que no estaba escrita en ninguna parte:\n                              * ni en el modelo, ni en la doc, ni en la pantalla. Sin ella, una lista corta\n                              * parece un catálogo incompleto en vez de la respuesta exacta.\n                              */}\n                            <p className=\"mt-1.5 text-xs text-gray-500\">\n                              {t('dashboard.access.permissionOwnScope')}\n                            </p>\n                          </div>\n                        ) : (\n                          <input\n                            value={sujetoId}\n                            onChange={(e) => setSujetoId(e.target.value)}\n                            placeholder={t('dashboard.access.subjectIdPlaceholder')}\n                            className=\"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                          />\n                        )}\n\n                        {/*\n                          * La advertencia del host para este tipo de sujeto. El kit la pinta y NO la\n                          * interpreta: el texto viene ya resuelto, porque el kit no traduce mensajes de un\n                          * modelo que no conoce. Es la misma regla que en WidgetGrantResult.warning.\n                          */}\n                        {caps.subjectHint?.[tipoSujeto] && (\n                          <p className=\"flex items-start gap-2 text-xs text-amber-900 bg-amber-50 rounded-lg p-2.5\">\n                            <AlertTriangle className=\"w-3.5 h-3.5 flex-shrink-0 mt-0.5\" />\n                            <span>{caps.subjectHint[tipoSujeto]}</span>\n                          </p>\n                        )}\n\n                        <div className=\"flex flex-wrap gap-3 items-center\">\n                          {niveles.length > 1 && (\n                            <select\n                              value={nivel}\n                              onChange={(e) => setNivel(e.target.value as WidgetGrantLevel)}\n                              className=\"px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                              aria-label={t('dashboard.access.level')}\n                            >\n                              {niveles.map((n) => (\n                                <option key={n} value={n}>{etiquetaNivel(n)}</option>\n                              ))}\n                            </select>\n                          )}\n\n                          {caps.expiry && (\n                            <>\n                              <select\n                                value={vencimiento}\n                                onChange={(e) => setVencimiento(e.target.value as typeof vencimiento)}\n                                className=\"px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                                aria-label={t('dashboard.access.expiry')}\n                              >\n                                <option value=\"default\">\n                                  {caps.expiry.defaultDays\n                                    ? t('dashboard.access.expiryDefaultDays').replace('{days}', String(caps.expiry.defaultDays))\n                                    : t('dashboard.access.expiryDefault')}\n                                </option>\n                                <option value=\"fecha\">{t('dashboard.access.expiryDate')}</option>\n                                {caps.expiry.allowNoExpiry && (\n                                  <option value=\"ninguno\">{t('dashboard.access.expiryNever')}</option>\n                                )}\n                              </select>\n                              {vencimiento === 'fecha' && (\n                                <input\n                                  type=\"date\"\n                                  value={fecha}\n                                  onChange={(e) => setFecha(e.target.value)}\n                                  className=\"px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                                  aria-label={t('dashboard.access.expiryDate')}\n                                />\n                              )}\n                            </>\n                          )}\n\n                          <button\n                            onClick={encolarAcceso}\n                            disabled={!sujetoId.trim()}\n                            className=\"ml-auto px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-40\"\n                          >\n                            {t('dashboard.access.grant')}\n                          </button>\n                        </div>\n                      </div>\n\n                      {/* Lo ya concedido */}\n                      <h3 className=\"text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2\">\n                        {t('dashboard.access.currentAccess')}\n                      </h3>\n                      {cargando && !filas ? (\n                        <p className=\"text-sm text-gray-500 flex items-center gap-2\">\n                          <Loader2 className=\"w-4 h-4 animate-spin\" /> {t('dashboard.access.loading')}\n                        </p>\n                      ) : !filasEfectivas.length ? (\n                        <p className=\"text-sm text-gray-500\">{t('dashboard.access.noneYet')}</p>\n                      ) : (\n                        <ul className=\"max-h-56 overflow-y-auto divide-y divide-gray-100 border border-gray-100 rounded-lg\">\n                          {filasEfectivas.map((f) => (\n                            <li key={`${f.subjectType}:${f.subjectId}`} className=\"flex items-center gap-3 px-3 py-2\">\n                              <div className=\"min-w-0 flex-1\">\n                                <p className=\"text-sm text-gray-800 truncate\">\n                                  {f.subjectLabel || f.subjectId}\n                                  {f.inert && (\n                                    <span\n                                      className=\"ml-2 text-[10px] uppercase font-bold text-amber-700 bg-amber-50 px-1.5 py-0.5 rounded\"\n                                      title={t('dashboard.access.grantInert')}\n                                    >\n                                      {t('dashboard.access.inert')}\n                                    </span>\n                                  )}\n                                </p>\n                                <p className=\"text-xs text-gray-500\">\n                                  {etiquetaNivel(f.level)}\n                                  {' · '}\n                                  {f.expiresAt\n                                    ? t('dashboard.access.expiresOn').replace('{date}', fechaCorta(f.expiresAt))\n                                    : t('dashboard.access.expiryNever')}\n                                </p>\n                              </div>\n                              <button\n                                onClick={() => quitarAcceso(f)}\n                                className=\"p-1 text-gray-400 hover:text-red-600 rounded\"\n                                title={t('dashboard.access.revoke')}\n                                aria-label={`${t('dashboard.access.revoke')} — ${f.subjectLabel || f.subjectId}`}\n                              >\n                                <Trash2 className=\"w-4 h-4\" />\n                              </button>\n                            </li>\n                          ))}\n                        </ul>\n                      )}\n\n                      </>\n                    )}\n\n                {/*\n                  🔴 **Una nota, no una fila del recuadro.** Estaba dentro de la lista de accesos, y\n                  eso la hacía parecer **un acceso más**: algo que alguien concedió y que se puede\n                  quitar. No lo es — quien entra por encima de la lista lo hace por una regla del\n                  host, y no hay fila que borrar.\n\n                  🔴 **Y la ESCRIBE EL HOST.** Era un literal del kit —«quienes administran X lo ven\n                  siempre»—, o sea el kit afirmando que el modelo del host tiene un rol que salta la\n                  lista. En Comercial es cierto; en un host sin ese bypass era una garantía falsa\n                  debajo de la lista. Sin respuesta del host **no se pinta**: el kit no dice lo que no\n                  puede saber, y menos sobre quién ve el dato a pesar de esta pantalla.\n                */}\n                {notaSiempreVe && (\n                  <p className=\"mt-2 flex items-start gap-1.5 text-xs text-gray-500\">\n                    <ShieldCheck className=\"mt-0.5 h-3.5 w-3.5 flex-shrink-0\" />\n                    <span>{notaSiempreVe}</span>\n                  </p>\n                )}\n\n                      </div>\n                    )}\n                  </div>\n                )}\n              </>\n            ) : (\n              /* Sin poder editar la política no hay casilla ni radios: quien solo reparte ve la\n                 lista, que es su única pantalla. El reparto sigue gateado por `can_share`: quitar\n                 los radios NO es quitar el gateo. */\n              puedeCompartir && (\n              <>\n              <div className=\"space-y-3 mb-6\">\n                {sujetos.length > 1 && (\n                  <div className=\"flex gap-2\">\n                    {sujetos.map((s) => (\n                      <button\n                        key={s}\n                        onClick={() => { setTipoSujeto(s); setSujetoId(''); setSujetoLabel(''); setConsulta(''); }}\n                        className={`px-2.5 py-1 text-xs rounded-full border ${\n                          tipoSujeto === s\n                            ? 'border-blue-600 text-blue-700 bg-blue-50'\n                            : 'border-gray-200 text-gray-600'\n                        }`}\n                      >\n                        {t(`dashboard.access.subject.${s}`)}\n                      </button>\n                    ))}\n                  </div>\n                )}\n\n                {/* El sujeto: buscado si el host tiene directorio, tecleado si no */}\n                {tipoSujeto === 'user' && adapter.searchPeople ? (\n                  <div className=\"relative\">\n                    <Search className=\"absolute left-3 top-2.5 w-4 h-4 text-gray-400\" />\n                    <input\n                      value={sujetoLabel || consulta}\n                      onChange={(e) => { setConsulta(e.target.value); setSujetoLabel(''); setSujetoId(''); }}\n                      placeholder={t('dashboard.access.searchPeople')}\n                      className=\"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500\"\n                    />\n                    {buscando && <Loader2 className=\"absolute right-3 top-2.5 w-4 h-4 text-gray-400 animate-spin\" />}\n                    {personas.length > 0 && !sujetoId && (\n                      <ul className=\"absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto\">\n                        {personas.map((p) => (\n                          <li key={p.id}>\n                            <button\n                              onClick={() => { setSujetoId(p.id); setSujetoLabel(p.nombre || p.id); setPersonas([]); }}\n                              className=\"w-full text-left px-3 py-2 text-sm hover:bg-gray-50\"\n                            >\n                              <span className=\"font-medium text-gray-800\">{p.nombre || p.id}</span>\n                              {p.email && <span className=\"text-gray-500 ml-2\">{p.email}</span>}\n                            </button>\n                          </li>\n                        ))}\n                      </ul>\n                    )}\n                  </div>\n                ) : tipoSujeto === 'module' && caps.modules?.length ? (\n                  /*\n                   * Solo se llega aquí en un indicador SIN vertical: con vertical, el sujeto se\n                   * retiró de `sujetos`. Ver la nota de F5.a.2 arriba.\n                   */\n                  <select\n                    value={sujetoId}\n                    onChange={(e) => setSujetoId(e.target.value)}\n                    className=\"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                  >\n                    <option value=\"\">{t('dashboard.access.pickModule')}</option>\n                    {caps.modules.map((m) => (\n                      <option key={m.id} value={m.id}>{m.label}</option>\n                    ))}\n                  </select>\n                ) : tipoSujeto === 'permission' && permisosOfrecibles.length > 0 ? (\n                  /*\n                   * 🔴 El selector de permisos. Antes de esto, el mecanismo central —conceder a quien\n                   * tenga un permiso— caia al `<input>` libre de abajo: habia que saberse el codigo\n                   * entre cientos, y el premio por equivocarse era un 403 despues de teclear. Es la\n                   * misma falla que ya se habia cerrado para las clases de sensibilidad.\n                   *\n                   * Es BUSCABLE y no un `<select>` porque la lista de un administrador es larga, y\n                   * porque el codigo se reconoce leyendolo, no desplegando doscientas opciones.\n                   */\n                  <div className=\"relative\">\n                    <Search className=\"absolute left-3 top-2.5 w-4 h-4 text-gray-400\" />\n                    <input\n                      value={sujetoLabel || consulta}\n                      onChange={(e) => { setConsulta(e.target.value); setSujetoLabel(''); setSujetoId(''); }}\n                      placeholder={t('dashboard.access.searchPermissions')}\n                      className=\"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500\"\n                    />\n                    {permisosFiltrados.length > 0 && !sujetoId && (\n                      <ul className=\"absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto\">\n                        {permisosFiltrados.map((pm) => (\n                          <li key={pm.id}>\n                            <button\n                              onClick={() => { setSujetoId(pm.id); setSujetoLabel(pm.label || pm.id); setConsulta(''); }}\n                              className=\"w-full text-left px-3 py-2 text-sm hover:bg-gray-50\"\n                            >\n                              <span className=\"font-medium text-gray-800\">{pm.label || pm.id}</span>\n                              {pm.label && pm.label !== pm.id && (\n                                <span className=\"text-gray-500 ml-2 text-xs font-mono\">{pm.id}</span>\n                              )}\n                            </button>\n                          </li>\n                        ))}\n                      </ul>\n                    )}\n                    {consulta && permisosFiltrados.length === 0 && !sujetoId && (\n                      <p className=\"mt-1 text-xs text-gray-500\">\n                        {t('dashboard.access.noPermissionMatch')}\n                      </p>\n                    )}\n                    {/*\n                      * La guarda del servidor, dicha donde se elige. «Solo puedes asociar un permiso\n                      * que tú tienes» es una regla correcta que no estaba escrita en ninguna parte:\n                      * ni en el modelo, ni en la doc, ni en la pantalla. Sin ella, una lista corta\n                      * parece un catálogo incompleto en vez de la respuesta exacta.\n                      */}\n                    <p className=\"mt-1.5 text-xs text-gray-500\">\n                      {t('dashboard.access.permissionOwnScope')}\n                    </p>\n                  </div>\n                ) : (\n                  <input\n                    value={sujetoId}\n                    onChange={(e) => setSujetoId(e.target.value)}\n                    placeholder={t('dashboard.access.subjectIdPlaceholder')}\n                    className=\"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                  />\n                )}\n\n                {/*\n                  * La advertencia del host para este tipo de sujeto. El kit la pinta y NO la\n                  * interpreta: el texto viene ya resuelto, porque el kit no traduce mensajes de un\n                  * modelo que no conoce. Es la misma regla que en WidgetGrantResult.warning.\n                  */}\n                {caps.subjectHint?.[tipoSujeto] && (\n                  <p className=\"flex items-start gap-2 text-xs text-amber-900 bg-amber-50 rounded-lg p-2.5\">\n                    <AlertTriangle className=\"w-3.5 h-3.5 flex-shrink-0 mt-0.5\" />\n                    <span>{caps.subjectHint[tipoSujeto]}</span>\n                  </p>\n                )}\n\n                <div className=\"flex flex-wrap gap-3 items-center\">\n                  {niveles.length > 1 && (\n                    <select\n                      value={nivel}\n                      onChange={(e) => setNivel(e.target.value as WidgetGrantLevel)}\n                      className=\"px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                      aria-label={t('dashboard.access.level')}\n                    >\n                      {niveles.map((n) => (\n                        <option key={n} value={n}>{etiquetaNivel(n)}</option>\n                      ))}\n                    </select>\n                  )}\n\n                  {caps.expiry && (\n                    <>\n                      <select\n                        value={vencimiento}\n                        onChange={(e) => setVencimiento(e.target.value as typeof vencimiento)}\n                        className=\"px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                        aria-label={t('dashboard.access.expiry')}\n                      >\n                        <option value=\"default\">\n                          {caps.expiry.defaultDays\n                            ? t('dashboard.access.expiryDefaultDays').replace('{days}', String(caps.expiry.defaultDays))\n                            : t('dashboard.access.expiryDefault')}\n                        </option>\n                        <option value=\"fecha\">{t('dashboard.access.expiryDate')}</option>\n                        {caps.expiry.allowNoExpiry && (\n                          <option value=\"ninguno\">{t('dashboard.access.expiryNever')}</option>\n                        )}\n                      </select>\n                      {vencimiento === 'fecha' && (\n                        <input\n                          type=\"date\"\n                          value={fecha}\n                          onChange={(e) => setFecha(e.target.value)}\n                          className=\"px-3 py-2 text-sm border border-gray-200 rounded-lg\"\n                          aria-label={t('dashboard.access.expiryDate')}\n                        />\n                      )}\n                    </>\n                  )}\n\n                  <button\n                    onClick={encolarAcceso}\n                    disabled={!sujetoId.trim()}\n                    className=\"ml-auto px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-40\"\n                  >\n                    {t('dashboard.access.grant')}\n                  </button>\n                </div>\n              </div>\n\n              {/* Lo ya concedido */}\n              <h3 className=\"text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2\">\n                {t('dashboard.access.currentAccess')}\n              </h3>\n              {cargando && !filas ? (\n                <p className=\"text-sm text-gray-500 flex items-center gap-2\">\n                  <Loader2 className=\"w-4 h-4 animate-spin\" /> {t('dashboard.access.loading')}\n                </p>\n              ) : !filasEfectivas.length ? (\n                <p className=\"text-sm text-gray-500\">{t('dashboard.access.noneYet')}</p>\n              ) : (\n                <ul className=\"max-h-56 overflow-y-auto divide-y divide-gray-100 border border-gray-100 rounded-lg\">\n                  {filasEfectivas.map((f) => (\n                    <li key={`${f.subjectType}:${f.subjectId}`} className=\"flex items-center gap-3 px-3 py-2\">\n                      <div className=\"min-w-0 flex-1\">\n                        <p className=\"text-sm text-gray-800 truncate\">\n                          {f.subjectLabel || f.subjectId}\n                          {f.inert && (\n                            <span\n                              className=\"ml-2 text-[10px] uppercase font-bold text-amber-700 bg-amber-50 px-1.5 py-0.5 rounded\"\n                              title={t('dashboard.access.grantInert')}\n                            >\n                              {t('dashboard.access.inert')}\n                            </span>\n                          )}\n                        </p>\n                        <p className=\"text-xs text-gray-500\">\n                          {etiquetaNivel(f.level)}\n                          {' · '}\n                          {f.expiresAt\n                            ? t('dashboard.access.expiresOn').replace('{date}', fechaCorta(f.expiresAt))\n                            : t('dashboard.access.expiryNever')}\n                        </p>\n                      </div>\n                      <button\n                        onClick={() => quitarAcceso(f)}\n                        className=\"p-1 text-gray-400 hover:text-red-600 rounded\"\n                        title={t('dashboard.access.revoke')}\n                        aria-label={`${t('dashboard.access.revoke')} — ${f.subjectLabel || f.subjectId}`}\n                      >\n                        <Trash2 className=\"w-4 h-4\" />\n                      </button>\n                    </li>\n                  ))}\n                </ul>\n              )}\n\n              </>\n              )\n\n            )}\n          </section>\n\n          {/*\n            🔴 **UNA SOLA PREGUNTA, Y EL SEGUNDO EJE YA NO EXISTE.**\n            ──────────────────────────────────────────────────────────────────────────────────────\n            Aquí hubo un bloque ② para la **sensibilidad**: marcar que un indicador exige un permiso\n            de dato. Se retiró de la pantalla el 2026-09-14 —dos preguntas que se parecen («las dos\n            quitan gente») y se comportan al revés— y ese mismo día se retiró del modelo entero:\n            columna, catálogo y permisos incluidos.\n\n            🔴 **La consecuencia, escrita donde se pueda leer:** lo que queda decide **quién ve la\n            tarjeta**, no quién puede leer la cifra. Los endpoints de datos siguen exigiendo solo el\n            módulo (deuda B1), así que restringir aquí **oculta, no protege**.\n          */}\n        </div>\n\n        {/*\n          🔴 **El pie de la ventana, y el botón vive AQUÍ.**\n\n          Estaba dentro del bloque de sensibilidad, que se retiró — y meterlo dentro del bloque de\n          restringir habría repetido el mismo error con otro nombre: un botón que guarda **la\n          ventana** no puede colgar de una de sus secciones, porque entonces parece que guarda solo\n          esa. En el pie, fuera del área que hace scroll, está siempre a la vista y dice lo que hace.\n\n          ⚠️ Solo se pinta si esta persona puede cambiar la política: quien únicamente reparte\n          concede y revoca al instante, y no tiene nada que guardar.\n        */}\n        {/*\n          🔴 **El contador a la izquierda, y no es adorno.** Con la ventana entera convertida en\n          borrador, esta línea es lo único que separa «he cambiado tres cosas» de «no he tocado\n          nada». Sin ella, cerrar sin guardar es indistinguible de guardar.\n        */}\n        <div className=\"flex items-center justify-between gap-3 border-t border-gray-200 px-5 py-3\">\n          <span className={`text-xs ${cambios ? 'font-medium text-amber-700' : 'text-gray-400'}`}>\n            {cambios\n              ? t('dashboard.access.pendingChanges', { count: cambios })\n              : t('dashboard.access.noChanges')}\n          </span>\n          <div className=\"flex gap-2\">\n            <button\n              onClick={onClose}\n              className=\"px-3 py-2 text-sm font-medium text-gray-600 rounded-lg hover:bg-gray-50\"\n            >\n              {t('dashboard.access.cancel')}\n            </button>\n            <button\n              onClick={guardarCambios}\n              disabled={guardando || !cambios}\n              className=\"px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-40\"\n            >\n              {guardando ? t('dashboard.access.saving') : t('dashboard.access.saveChanges')}\n            </button>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n};\n","import React, { useContext, useState, useMemo } from 'react';\nimport { Search, X, Plus, Minus, Pencil, Settings2, Trash2, AlertTriangle, Users } from 'lucide-react';\nimport type { WidgetDefinition, UserWidgetPreference } from '../types';\nimport { getTypeIcon, getTypeLabel } from '../utils/widgetTypeConfig';\nimport { WidgetBuilder } from './WidgetBuilder/WidgetBuilder';\nimport type { DashboardCategoryInput } from './WidgetBuilder/categories';\nimport { resolveWidgetPermissions } from '../ability';\nimport { DashboardContext } from '../useDashboardContext';\nimport { WidgetAccessDialog } from '../access/WidgetAccessDialog';\nimport { useDashboardTranslation } from '../i18n';\n\ninterface WidgetManagerPanelProps {\n  isOpen: boolean;\n  catalog: WidgetDefinition[];\n  currentLayout: UserWidgetPreference[];\n  /**\n   * Administracion del catalogo. Gobierna el boton del Widget Builder (una capacidad global, que si\n   * es un `isAdmin`) y sirve de **respaldo** por widget cuando el catalogo no trae `permissions`.\n   */\n  isAdmin?: boolean;\n  /**\n   * Capacidad de crear y editar definiciones de widget — lo que abre el Widget Builder.\n   *\n   * 🔴 Antes esa puerta la gateaba `isAdmin`, y eso dejaba **inerte** la capacidad fina del host:\n   * quien podía escribir widgets sin ser administrador creaba uno por API y no veía el botón para\n   * hacerlo. Son dos preguntas distintas y se habían colapsado en una — administrar el catálogo no\n   * es lo mismo que poder añadirle algo.\n   *\n   * Sin valor cae a `isAdmin`, que es el comportamiento histórico: un host que no la pase no cambia.\n   */\n  canWriteWidgets?: boolean;\n  /** Respaldo de visibilidad para hosts sin `permissions` en el DTO. Ver `resolveWidgetPermissions`. */\n  userRoles?: string[];\n  /**\n   * Capacidad de cambiar la exposicion de un widget -a quien alcanza-. Gobierna el paso de permisos\n   * del asistente. Sin valor cae a `isAdmin`.\n   */\n  canPublishWidgets?: boolean;\n  userId?: string;\n  /**\n   * 🔴 **Si el Constructor ofrece conectar una fuente EXTERNA** — un Power BI, otro ERP, un API\n   * público. Es un paso DENTRO del asistente, no la puerta de entrada.\n   *\n   * ⚠️ Hasta aquí hacía **dos trabajos**: abría la puerta del Constructor *y* ofrecía la fuente\n   * externa. Por eso un analista con `canWriteWidgets` veía un botón llamado «Conectar API externa»\n   * que el API le rechazaba — y por eso no se podía abrir el Constructor sin abrir también las\n   * fuentes externas. Es el cuarto caso de *un dato que significa dos cosas a la vez*.\n   */\n  showExternalEndpoints?: boolean;\n  /**\n   * **Si la puerta del Constructor existe.** La otra mitad de la deuda anterior, ahora separada.\n   *\n   * Sin valor cae a `showExternalEndpoints`, así que **ningún host cambia de conducta** al actualizar:\n   * quien pasaba el flag viejo sigue viendo exactamente lo mismo. Abrir el Constructor sin abrir las\n   * fuentes externas pasa a ser **una decisión de producto de una línea**, que es lo que antes no se\n   * podía tomar.\n   */\n  showWidgetBuilder?: boolean;\n  onClose: () => void;\n  onRequestAdd: (widget: WidgetDefinition) => void;\n  onRequestModify: (widget: WidgetDefinition, preference: UserWidgetPreference) => void;\n  onRemoveWidget: (instanceId: string) => void;\n  onWidgetCreated: (definition: WidgetDefinition) => void | Promise<void>;\n  onWidgetUpdated?: (definition: WidgetDefinition) => void;\n  onDeleteWidget?: (widgetId: string) => void;\n  /** Vocabulario de segmentación del host. Ver Step5Permissions. */\n  /**\n   * 🔴 **RETIRADO el 2026-09-14 (F3.b.5).** Era un paso a paso puro —página → panel → Constructor— y\n   * el Constructor dejó de preguntarlo: la vertical la determina la categoría. Se quita en vez de\n   * dejarlo ignorado, porque una prop que se acepta y no hace nada es la clase de cosa que alguien\n   * rellena mañana creyendo que segmenta algo.\n   *\n   * Repartir a una vertical sigue existiendo: es el sujeto «un módulo» del **diálogo de acceso**, que\n   * lo recibe por `accessAdapter.capabilities.modules` — otro camino y otro acto.\n   */\n  /**\n   * 🔴 Desde F3 puede traer la **pareja** categoría→vertical, y por eso deja de ser `string[]`.\n   * Este panel no la usa: solo la deja pasar al Constructor, que es quien deriva.\n   */\n  availableCategories?: DashboardCategoryInput[];\n}\n\n\nexport const WidgetManagerPanel: React.FC<WidgetManagerPanelProps> = ({\n  isOpen, catalog, currentLayout, isAdmin = false, canWriteWidgets, canPublishWidgets, userRoles = [], userId,\n  showExternalEndpoints = false, showWidgetBuilder, onClose, onRequestAdd, onRequestModify,\n  onRemoveWidget, onWidgetCreated, onWidgetUpdated, onDeleteWidget, availableCategories,\n}) => {\n  const { t } = useDashboardTranslation();\n\n  // La puerta cae al flag viejo mientras el host no diga otra cosa: separar los dos conceptos no\n  // debe mover a nadie de sitio en la versión en que se separan.\n  const puertaDelConstructor = showWidgetBuilder ?? showExternalEndpoints;\n\n  /**\n   * 🔴 La misma entrada al diálogo de acceso que tiene la tarjeta, aquí también — y no es una\n   * duplicación por comodidad: la tarjeta solo existe para los widgets que están EN tu tablero, y\n   * los que hay que acotar suelen ser justo los que no te has puesto. Sin esta, para restringir un\n   * widget del catálogo habría que agregárselo primero al tablero propio.\n   *\n   * Contexto crudo por lo mismo que en la tarjeta: un adaptador opcional no puede volver el provider\n   * obligatorio para quien monte el panel por separado.\n   */\n  const accessAdapter = useContext(DashboardContext)?.accessAdapter;\n  const [accessWidget, setAccessWidget] = useState<WidgetDefinition | null>(null);\n  // La capacidad de escritura, con el respaldo histórico. Ver la prop.\n  const puedeEscribir = canWriteWidgets ?? isAdmin;\n  const [searchTerm, setSearchTerm] = useState('');\n  const [categoryFilter, setCategoryFilter] = useState<string>('Todas');\n  const [isBuilderOpen, setIsBuilderOpen] = useState(false);\n  const [pendingDeleteWidget, setPendingDeleteWidget] = useState<WidgetDefinition | null>(null);\n\n  const categories = useMemo(() => {\n    const cats = new Set(catalog.map(w => w.categoria).filter(Boolean));\n    return ['Todas', ...Array.from(cats)];\n  }, [catalog]);\n\n  const filteredCatalog = useMemo(() => {\n    const inLayoutIds = new Set(currentLayout.map(p => p.widget_id));\n    return catalog\n      .filter(w => {\n        const matchSearch = w.nombre.toLowerCase().includes(searchTerm.toLowerCase());\n        const matchCategory = categoryFilter === 'Todas' || w.categoria === categoryFilter;\n        return matchSearch && matchCategory;\n      })\n      .sort((a, b) => {\n        const aIn = inLayoutIds.has(a.widget_id) ? 0 : 1;\n        const bIn = inLayoutIds.has(b.widget_id) ? 0 : 1;\n        return aIn - bIn;\n      });\n  }, [catalog, currentLayout, searchTerm, categoryFilter]);\n\n  if (!isOpen) return null;\n\n  return (\n    <>\n      <div className=\"fixed inset-y-0 right-0 w-[348px] bg-white shadow-2xl border-l border-gray-200 z-50 flex flex-col\">\n\n        {/* Header */}\n        <div className=\"flex items-center justify-between p-4 border-b border-gray-100\">\n          <h2 className=\"text-lg font-semibold text-gray-800\">{t('dashboard.catalog.title')}</h2>\n          <button onClick={onClose} className=\"p-1 hover:bg-gray-100 rounded text-gray-500\">\n            <X className=\"w-5 h-5\" />\n          </button>\n        </div>\n\n        {/* Búsqueda y filtros */}\n        <div className=\"p-4 border-b border-gray-100 space-y-3 bg-gray-50\">\n          <div className=\"relative\">\n            <Search className=\"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400\" />\n            <input\n              type=\"text\"\n              placeholder={t('dashboard.catalog.search')}\n              value={searchTerm}\n              onChange={e => setSearchTerm(e.target.value)}\n              className=\"w-full pl-9 pr-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500\"\n            />\n          </div>\n          <div className=\"flex gap-2 overflow-x-auto pb-1 custom-scrollbar\">\n            {categories.map(cat => (\n              <button\n                key={cat}\n                onClick={() => setCategoryFilter(cat)}\n                className={`px-3 py-1 text-xs font-medium rounded-full whitespace-nowrap transition-colors ${\n                  categoryFilter === cat\n                    ? 'bg-blue-600 text-white'\n                    : 'bg-white border border-gray-200 text-gray-600 hover:bg-gray-50'\n                }`}\n              >\n                {cat}\n              </button>\n            ))}\n          </div>\n        </div>\n\n        {/* Lista de widgets */}\n        <div className=\"flex-1 overflow-y-auto p-4 space-y-3\">\n          {filteredCatalog.length === 0 ? (\n            <div className=\"text-center text-gray-500 mt-10 text-sm\">{t('dashboard.catalog.empty')}</div>\n          ) : (\n            filteredCatalog.map(widget => {\n              const pref = currentLayout.find(p => p.widget_id === widget.widget_id);\n              const inLayout = !!pref;\n              const TypeIcon = getTypeIcon(widget.tipo);\n              const typeLabel = getTypeLabel(widget.tipo);\n              /**\n               * Quien puede borrar **este** widget lo dice el servidor, no un `isAdmin` global.\n               * Antes era `!isSeed && isAdmin`: el mismo boton para todo widget con dueño, sin\n               * mirar la ACL de la fila — aparecia para un admin frente a un widget que no le\n               * corresponde, y el clic acababa en 403. `resolveWidgetPermissions` cae a esa misma\n               * expresion cuando el host no manda `permissions`.\n               */\n              const { can_delete: canDelete } = resolveWidgetPermissions(widget, { userRoles, isAdmin });\n\n              return (\n                <div\n                  key={widget.widget_id}\n                  className={`p-3 rounded-lg border transition-all ${\n                    inLayout ? 'border-blue-200 bg-blue-50/30' : 'border-gray-200 bg-white hover:border-gray-300'\n                  }`}\n                >\n                  <div className=\"flex justify-between items-start mb-1\">\n                    <div className=\"flex items-center gap-2 min-w-0\">\n                      <TypeIcon className=\"w-4 h-4 text-gray-500 flex-shrink-0\" />\n                      <h4 className=\"text-sm font-semibold text-gray-800 truncate\">{widget.nombre}</h4>\n                    </div>\n                    <div className=\"flex items-center gap-1 flex-shrink-0\">\n                      <span className=\"text-[10px] uppercase font-bold tracking-wider text-blue-700 bg-blue-50 px-1.5 py-0.5 rounded\">\n                        {widget.categoria}\n                      </span>\n                      {accessAdapter &&\n                        (widget.permissions?.can_share === true || widget.permissions?.can_edit === true) && (\n                        <button\n                          onClick={() => setAccessWidget(widget)}\n                          className=\"p-1 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors\"\n                          title={t('dashboard.access.dialogTitle')}\n                          aria-label={`${t('dashboard.access.dialogTitle')} — ${widget.nombre}`}\n                          data-testid={`catalog-access-${widget.widget_id}`}\n                        >\n                          <Users className=\"w-3.5 h-3.5\" />\n                        </button>\n                      )}\n                      {canDelete && onDeleteWidget && (\n                        <button\n                          onClick={() => setPendingDeleteWidget(widget)}\n                          className=\"p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors\"\n                          title={t('dashboard.catalog.deleteWidget')}\n                        >\n                          <Trash2 className=\"w-3.5 h-3.5\" />\n                        </button>\n                      )}\n                    </div>\n                  </div>\n                  <p className=\"text-xs text-gray-500 mb-3 line-clamp-2\">{widget.descripcion}</p>\n                  <div className=\"flex items-center justify-between\">\n                    <span className=\"text-xs text-gray-400\">{typeLabel}</span>\n                    {inLayout ? (\n                      <div className=\"flex gap-1\">\n                        <button\n                          onClick={() => pref && onRemoveWidget(pref.id)}\n                          className=\"flex items-center gap-1 text-xs font-medium text-red-600 hover:text-red-700 bg-red-50 hover:bg-red-100 px-2 py-1 rounded transition-colors\"\n                        >\n                          <Minus className=\"w-3.5 h-3.5\" /> Quitar\n                        </button>\n                        <button\n                          onClick={() => pref && onRequestModify(widget, pref)}\n                          className=\"flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700 bg-blue-50 hover:bg-blue-100 px-2 py-1 rounded transition-colors\"\n                        >\n                          <Pencil className=\"w-3.5 h-3.5\" /> Modificar\n                        </button>\n                      </div>\n                    ) : (\n                      <button\n                        onClick={() => onRequestAdd(widget)}\n                        className=\"flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700 bg-blue-50 hover:bg-blue-100 px-2 py-1 rounded transition-colors\"\n                      >\n                        <Plus className=\"w-3.5 h-3.5\" /> Agregar\n                      </button>\n                    )}\n                  </div>\n                </div>\n              );\n            })\n          )}\n        </div>\n\n        {/* Botón Builder: quien puede ESCRIBIR widgets, no solo el administrador. `isAdmin` sigue\n            gobernando lo que se puede hacer DENTRO del Builder —el paso de permisos y si el widget\n            nace privado—, que son decisiones distintas de si la puerta existe.\n\n            Y la puerta la gobierna `puertaDelConstructor`, no `showExternalEndpoints`: el nombre del\n            botón dejaba ver que el flag hacía dos trabajos. Ahora el rótulo dice lo que hay detrás —\n            «conectar un API externo» solo si de verdad se puede conectar uno. */}\n        {puedeEscribir && puertaDelConstructor && (\n          <div className=\"p-4 border-t border-gray-200 bg-gray-50\">\n            <button\n              onClick={() => setIsBuilderOpen(true)}\n              className=\"w-full py-2 bg-white border border-gray-300 text-gray-600 text-xs font-medium rounded shadow-sm hover:bg-gray-50 transition-all flex items-center justify-center gap-1.5\"\n            >\n              <Settings2 className=\"w-3.5 h-3.5\" />\n              {showExternalEndpoints\n                ? t('dashboard.builder.openExternal')\n                : t('dashboard.builder.open')}\n            </button>\n          </div>\n        )}\n      </div>\n\n      {/* El diálogo de acceso del widget elegido en la lista. */}\n      {accessAdapter && accessWidget && (\n        <WidgetAccessDialog\n          widget={accessWidget}\n          adapter={accessAdapter}\n          isOpen\n          onClose={() => setAccessWidget(null)}\n        />\n      )}\n\n      <WidgetBuilder\n        availableCategories={availableCategories}\n        isOpen={isBuilderOpen}\n        onClose={() => setIsBuilderOpen(false)}\n        onSuccess={(w) => { onWidgetCreated(w); setIsBuilderOpen(false); }}\n        /*\n         * 🔴 F4.4 — la salida del aviso de reparto a medias: se cierra el Constructor y se abre el\n         * diálogo de acceso SOBRE el indicador recién creado, que es donde se termina lo que quedó\n         * sin terminar. Sin esto, el aviso diría «ábrelo en el diálogo» y no habría por dónde.\n         */\n        onNeedsAccessDialog={(w) => {\n          onWidgetCreated(w);\n          setIsBuilderOpen(false);\n          setAccessWidget(w);\n        }}\n        isAdmin={isAdmin}\n        canPublishWidgets={canPublishWidgets}\n        showExternalEndpoints={showExternalEndpoints}\n      />\n\n      {/* Dialog de confirmación — Eliminar Widget del Catálogo */}\n      {pendingDeleteWidget && onDeleteWidget && (\n        <div className=\"fixed inset-0 z-[70] flex items-center justify-center bg-gray-900/60 backdrop-blur-sm p-4\">\n          <div className=\"bg-white rounded-xl shadow-2xl w-full max-w-sm p-6 animate-in fade-in zoom-in duration-150\">\n            <div className=\"flex items-center gap-3 mb-4\">\n              <div className=\"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0\">\n                <AlertTriangle className=\"w-5 h-5 text-red-600\" />\n              </div>\n              <div>\n                <h3 className=\"font-semibold text-gray-900\">{t('dashboard.confirm.deleteTitle')}</h3>\n                <p className=\"text-sm text-gray-500\">{t('dashboard.confirm.deleteBody')}</p>\n              </div>\n            </div>\n            <p className=\"text-sm text-gray-600 mb-6\">\n              ¿Confirmas que quieres eliminar{' '}\n              <span className=\"font-semibold\">\"{pendingDeleteWidget.nombre}\"</span> del catálogo?\n              Se eliminará para todos los usuarios que lo tengan agregado.\n            </p>\n            <div className=\"flex items-center justify-end gap-3\">\n              <button\n                onClick={() => setPendingDeleteWidget(null)}\n                className=\"px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors\"\n              >\n                Cancelar\n              </button>\n              <button\n                onClick={() => { onDeleteWidget(pendingDeleteWidget.widget_id); setPendingDeleteWidget(null); }}\n                className=\"flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg transition-colors\"\n              >\n                <Trash2 className=\"w-4 h-4\" /> Eliminar widget\n              </button>\n            </div>\n          </div>\n        </div>\n      )}\n    </>\n  );\n};\n","/**\n * Contratos e Interfaces del Módulo Dashboard Comercial (BMAD 6)\n * \n * Este archivo es la fuente única de verdad para las entidades que viajan entre\n * el frontend (React) y el backend (Dashboard Module / Proxy).\n */\n\n// ==========================================\n// 1. Tipos Base y Dominios\n// ==========================================\n\n/**\n * Categoría de un widget. Es una CLAVE opaca que declara el host, no un nombre de negocio.\n *\n * Antes era una unión con `'Ventas' | 'Compras' | 'Inventario' | 'Operaciones'`. Eso documentaba el\n * vocabulario de UN producto (Siesa Comercial) dentro de una librería compartida: un host de\n * Financiero o Nómina leía este tipo y concluía, con razón, que el módulo no era para él.\n */\nexport type DomainCategory = string;\n\n/**\n * Un término del vocabulario del host: qué se GUARDA y qué se MUESTRA.\n *\n * <b>La separación es lo que hace posible el i18n.</b> Antes las categorías eran `string[]`, o sea\n * que la etiqueta visible ERA la clave persistida: un widget guardaba `categoria: 'Ventas'` y la\n * pantalla pintaba `Ventas` en cualquier idioma, para siempre. Con `{ id, label }` el host guarda\n * una clave estable y traduce la etiqueta por su cuenta.\n *\n * Lo mismo aplica a los roles: el `id` puede ser el código de permiso del RBAC del host y el\n * `label` su nombre legible.\n */\nexport interface DashboardVocabularyTerm {\n  /** Clave estable. Es lo que se persiste en `roles_permitidos` / `categoria`. */\n  id: string;\n  /** Texto visible, ya traducido por el host. */\n  label: string;\n  /**\n   * 🔴 **Solo en las CATEGORÍAS, y solo desde F3: la vertical que esta categoría determina.**\n   *\n   * Es la pareja que permite al Constructor dejar de preguntar la vertical aparte. Opcional porque\n   * un host anterior a F3 no la publica —y entonces el Constructor lo DICE en vez de inventarse una—\n   * y porque los términos de rol y de sensibilidad no tienen nada que poner aquí.\n   */\n  role?: string;\n}\n\nexport type WidgetPresentationType = \n  | 'kpi' \n  | 'chart_line' \n  | 'chart_bar_vertical' \n  | 'chart_bar_horizontal' \n  | 'chart_donut' \n  | 'table' \n  | 'image' \n  | 'custom';\n\nexport type DashboardPeriod = 'Hoy' | 'Semana' | 'Mes';\n\n/**\n * Función de fetch inyectada por el host (Master Data, Core Frontend, etc.).\n * El host es responsable de agregar autenticación, headers JWT y cualquier\n * lógica de interceptores. El Dashboard usa esta función para TODOS sus requests.\n *\n * @example — Con axios del host\n * const fetcher: DashboardFetcher = (url, opts) =>\n *   axiosInstance.request({ url, method: opts?.method ?? 'GET', data: opts?.body })\n *     .then(r => r.data);\n *\n * @example — Con fetch nativo del host\n * const fetcher: DashboardFetcher = (url, opts) =>\n *   fetch(url, {\n *     method: opts?.method ?? 'GET',\n *     headers: { Authorization: `Bearer ${getToken()}`, 'Content-Type': 'application/json' },\n *     body: opts?.body ? JSON.stringify(opts.body) : undefined,\n *   }).then(r => r.json());\n */\nexport type DashboardFetcher = <T = unknown>(\n  url: string,\n  options?: {\n    method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n    body?: unknown;\n  }\n) => Promise<T>;\n\n/**\n * Punto de dato genérico para gráficas de Recharts.\n * Todos los widgets de gráfica deben usar este tipo en lugar de `any[]`.\n */\nexport type ChartDataPoint = Record<string, string | number>;\n\n/**\n * Field mapping semántico del widget (estándar v2).\n * Define el rol de cada campo para el chart, en lugar de un mapeo plano de renombrado.\n * Almacenado en cmp_kpi_dashboard_widgets.field_mapping (JSONB).\n */\nexport interface WidgetFieldMapping {\n  /** Campo del endpoint que actúa como eje X / dimensión de agrupación. */\n  category?: string;\n  /** Campos del endpoint que se grafican como series / métricas. */\n  values?: string[];\n  /** Labels de visualización para leyenda y tooltip. No cambia el dataKey de Recharts. */\n  aliases?: Record<string, string>;\n  /** Mapeo de renombrado de campos del endpoint (campo_api → nombre_canónico). Solo para APIs con nombres no estándar. */\n  rename?: Record<string, string>;\n  /** Campos conocidos del endpoint (schema hints). Permite mostrar todos los campos disponibles sin que el widget haya cargado datos. */\n  fields?: { name: string; type: 'string' | 'number' | 'date' | 'boolean'; label: string }[];\n}\n\n// ==========================================\n// 2. Catálogo de Widgets (Definición Global)\n// ==========================================\n\n/**\n * Representa la definición base de un widget en el catálogo (tabla `dashboard_widgets`).\n * Gestionado por administradores o a través del Widget Builder.\n */\nexport interface WidgetDefinition {\n  widget_id: string;\n  nombre: string;\n  descripcion: string;\n  categoria: DomainCategory;\n  tipo: WidgetPresentationType;\n  icono: string; // Nombre del ícono en lucide-react\n  roles_permitidos: string[];\n\n  col_min: number;\n  col_max: number;\n  altura_default: number; // En unidades de fila (row_span)\n  cols_default: number;   // En unidades de columna (col_span)\n  orden_default: number;\n  activo: boolean;\n  version: string;\n\n  // Ruta de importación dinámica para React.lazy (ej. '../widgets/KpiVentasHoy')\n  componente_ruta?: string;\n  // JSON Schema que valida los parámetros configurables del widget (config_json)\n  config_schema?: Record<string, unknown>;\n\n  // Propiedades opcionales para Widgets dinámicos (Widget Builder)\n  endpoint_url?: string;\n  endpoint_method?: 'GET' | 'POST';\n  endpoint_headers?: Record<string, string>;\n  endpoint_params?: Record<string, string | number | boolean>;\n  field_mapping?: WidgetFieldMapping;\n  refresh_policy?: number; // TTL en segundos\n  es_privado?: boolean;\n  is_internal?: boolean; // true = propaga auth del usuario al endpoint (widgets de Siesa); false = widget externo (terceros)\n  propietario_id?: string;\n\n  /**\n   * Lo que **este** usuario puede hacer con **este** widget, ya resuelto por el servidor.\n   *\n   * Llega en el DTO del catalogo (`permissions` en `WidgetDefinitionDTO`) cuando el host evalua\n   * acceso por instancia. Es la unica fuente de verdad para pintar acciones: si el servidor\n   * restringe por ACL y el kit vuelve a decidir cruzando `roles_permitidos`, los dos discrepan y\n   * gana el que pinte — botones que no hacen nada, o acciones ausentes para quien si puede.\n   *\n   * Es `undefined` en dos casos legitimos, y por eso no es obligatorio: un host cuyo backend no\n   * evalua acceso por instancia (el comportamiento historico), y las respuestas que no pasan por\n   * una evaluacion de acceso. Ver `resolveWidgetPermissions`.\n   */\n  permissions?: WidgetPermissions;\n}\n\n/**\n * Los cuatro verbos del usuario actual sobre un widget, tal como los emite el servidor.\n *\n * Las claves son `snake_case` porque son las del JSON y **no** se renombran al entrar: el resto de\n * este modulo ya trata el DTO como su tipo de dominio (`roles_permitidos`, `es_privado`), y una capa\n * de traduccion solo para cuatro campos añadiria un sitio mas donde perderlos en silencio.\n */\nexport interface WidgetPermissions {\n  /** Verlo en el catalogo **y** poder pedir su dato al proxy. */\n  can_view: boolean;\n  /** Editar la definicion del widget. */\n  can_edit: boolean;\n  /** Eliminarla. */\n  can_delete: boolean;\n  /** Otorgar acceso a personas nombradas. */\n  can_share: boolean;\n  /**\n   * Cambiar la EXPOSICION del widget: `es_privado`, `roles_permitidos`, `is_internal`.\n   *\n   * Es una autoridad distinta de `can_edit` -editar un titulo no mueve a quien alcanza el widget- y\n   * el backend la exige por separado en el PATCH del catalogo. El formulario no debe ofrecer esos\n   * campos cuando esto es `false`: los mandaria igual y el PATCH acabaria en 403 despues de que la\n   * persona lleno el paso.\n   */\n  can_publish: boolean;\n}\n\n/** Configuracion publica del whitelist de rutas internas (GET /api/dashboard/widgets/allowed-internal-routes) */\nexport interface AllowedInternalRoutes {\n  enforce_whitelist: boolean;\n  allowed_prefixes: string[];\n  allowed_hosts: string[];\n}\n\n/** Fuente de datos disponible en el dropdown del Widget Builder (GET /api/dashboard/widgets/data-sources) */\nexport interface DataSourceOption {\n  name: string;\n  url: string;\n  description?: string;\n  category?: string;\n  method: 'GET' | 'POST';\n  suggested_type?: string;\n  default_field_mapping?: Record<string, string>;\n}\n\n// ==========================================\n// 3. Layout y Preferencias de Usuario\n// ==========================================\n\n/**\n * Representa la configuración específica de un widget para un usuario particular (tabla `dashboard_preferences`).\n */\nexport interface UserWidgetPreference {\n  id: string; // Identificador único de esta instancia en el grid\n  user_id: string;\n  widget_id: string; // Referencia a WidgetDefinition\n  activo: boolean;\n  orden: number;\n\n  col_span: number;\n  row_span: number;\n  pos_x: number;\n  pos_y: number;\n\n  config_json?: Record<string, unknown>; // Configuraciones específicas del usuario (ej. filtros aplicados al widget)\n  modificado_en: string;\n}\n\nexport interface LayoutUpdatePayload {\n  userId: string;\n  period: DashboardPeriod; // Estado actual de la UI a persistir opcionalmente\n  layout: UserWidgetPreference[];\n}\n\n// ==========================================\n// 4. Proxy Fetching y Comunicación\n// ==========================================\n\n/**\n * Payload enviado al endpoint `/api/dashboard/proxy/fetch`\n */\nexport interface FetchProxyPayload {\n  widgetId: string;\n  period: DashboardPeriod; // Crucial para que el backend filtre fechas\n  userParams?: Record<string, string | number | boolean>;\n}\n\n// ==========================================\n// 5. Contrato para Componentes React (Widgets)\n// ==========================================\n\n/**\n * Props estandarizadas que recibe CADA componente de widget que sea montado en el grid.\n */\nexport interface WidgetProps {\n  preference: UserWidgetPreference;\n  definition: WidgetDefinition;\n  isEditMode: boolean;\n  period: DashboardPeriod;\n  onConfigChange?: (newConfig: Record<string, unknown>) => void;\n}\n\n// ==========================================\n// Envelope Estándar de Endpoints Internos\n// ==========================================\n\n/** Descriptor de un campo en el schema del envelope. */\nexport interface SchemaField {\n  name: string;\n  type: 'string' | 'number' | 'date' | 'boolean';\n  label: string;\n  format?: 'currency' | 'percent' | 'integer' | 'decimal';\n}\n\n/** Respuesta estándar de un endpoint interno de dashboard. */\nexport interface EndpointEnvelope {\n  data: Record<string, unknown>[];\n  schema: { fields: SchemaField[] };\n  meta: { generatedAt: string; period: string; rowCount: number };\n}\n\n/** Configuracion de mapeo discriminada por tipo de widget */\n/** Funciones de agregación disponibles para KPIs y gráficos */\nexport type AggregationType = 'none' | 'sum' | 'average' | 'count' | 'min' | 'max' | 'last' | 'first';\n\n/** Familias de tipos de widget — los tipos de una misma familia son intercambiables */\nexport type ChartFamily = 'scalar' | 'categorical' | 'tabular';\n\nexport const TYPE_FAMILIES: Record<string, ChartFamily> = {\n  kpi:                  'scalar',\n  chart_bar_vertical:   'categorical',\n  chart_bar_horizontal: 'categorical',\n  chart_line:           'categorical',\n  chart_donut:          'categorical',\n  table:                'tabular',\n};\n\n/**\n * Retorna los tipos hermanos (excluye el actual).\n * Si valuesCount > 1, excluye donut (solo acepta 1 valor).\n */\nexport function getCompatibleTypes(tipo: string, valuesCount?: number): string[] {\n  const family = TYPE_FAMILIES[tipo];\n  if (!family) return [];\n  return Object.entries(TYPE_FAMILIES)\n    .filter(([t, f]) => {\n      if (f !== family || t === tipo) return false;\n      if (t === 'chart_donut' && valuesCount != null && valuesCount > 1) return false;\n      return true;\n    })\n    .map(([t]) => t);\n}\n\n/**\n * Contrato unificado de datos para todos los charts categóricos.\n * Almacenado en config_schema. Agnóstico del tipo de chart —\n * el mismo contrato sirve para barras, líneas y donut.\n */\nexport interface ChartDataContract {\n  categoryField: string;\n  valueFields: string[];\n  aggregation?: AggregationType;\n}\n\n/**\n * Override de field mapping por usuario.\n * Almacenado en preference.config_json.fieldMapping.\n * Se mergea sobre el contrato del widget (config_schema).\n */\nexport interface FieldMappingOverride {\n  category?: string;\n  values?: string[];\n  aliases?: Record<string, string>;\n}\n\n/**\n * Extrae un ChartDataContract normalizado de config_schema.\n * Soporta: forma directa (categoryField+valueFields), MappingConfig (Builder), o null.\n */\nexport function extractChartContract(\n  configSchema: Record<string, unknown> | undefined | null\n): ChartDataContract | null {\n  if (!configSchema) return null;\n\n  // Forma directa: { categoryField, valueFields }\n  if ('categoryField' in configSchema && 'valueFields' in configSchema) {\n    const c = configSchema as unknown as ChartDataContract;\n    if (typeof c.categoryField === 'string' && Array.isArray(c.valueFields)) {\n      return c;\n    }\n  }\n\n  // Forma MappingConfig (Builder widgets)\n  const type = configSchema.type as string | undefined;\n  if (!type) return null;\n\n  switch (type) {\n    case 'chart_bar_vertical':\n    case 'chart_bar_horizontal': {\n      const cfg = configSchema as { xField?: string; yField?: string; aggregation?: AggregationType };\n      if (cfg.xField && cfg.yField) {\n        return { categoryField: cfg.xField, valueFields: [cfg.yField], aggregation: cfg.aggregation };\n      }\n      return null;\n    }\n    case 'chart_line': {\n      const cfg = configSchema as { xField?: string; yField?: string; seriesFields?: string[]; aggregation?: AggregationType };\n      if (cfg.xField && cfg.yField) {\n        return { categoryField: cfg.xField, valueFields: [cfg.yField, ...(cfg.seriesFields ?? [])], aggregation: cfg.aggregation };\n      }\n      return null;\n    }\n    case 'chart_donut': {\n      const cfg = configSchema as { categoryField?: string; valueField?: string; aggregation?: AggregationType };\n      if (cfg.categoryField && cfg.valueField) {\n        return { categoryField: cfg.categoryField, valueFields: [cfg.valueField], aggregation: cfg.aggregation };\n      }\n      return null;\n    }\n    default:\n      return null;\n  }\n}\n\nexport type MappingConfig =\n  | {\n      type: 'kpi';\n      valueField: string;\n      labelField?: string;\n      aggregation: 'sum' | 'average' | 'count' | 'last' | 'min' | 'max';\n      valuePrefix?: string;\n      valueSuffix?: string;\n    }\n  | {\n      type: 'chart_bar_vertical';\n      xField: string;\n      yField: string;\n      groupByField?: string;\n      aggregation?: AggregationType;\n    }\n  | {\n      type: 'chart_bar_horizontal';\n      xField: string;\n      yField: string;\n      groupByField?: string;\n      aggregation?: AggregationType;\n    }\n  | {\n      type: 'chart_line';\n      xField: string;\n      yField: string;\n      seriesFields?: string[];\n      aggregation?: AggregationType;\n    }\n  | {\n      type: 'chart_donut';\n      categoryField: string;\n      valueField: string;\n      aggregation?: AggregationType;\n    }\n  | {\n      type: 'table';\n      visibleColumns: string[];\n      sortField?: string;\n      sortDirection?: 'asc' | 'desc';\n    };\n","/**\n * Detecta los campos numéricos relevantes de un array de registros.\n * Aplica la misma lógica de prioridad que ChartVentasMensual:\n *\n *  1. Si existen \"meta\" y/o \"actual\" → modo comparación (2 series)\n *  2. Si existe \"value\"             → serie única\n *  3. Fallback                      → primer campo numérico encontrado\n *\n * Esto evita que campos auxiliares como \"porcentaje\" se grafiquen\n * como si fueran series principales.\n *\n * @param data - Registros del endpoint (ya con field mapping)\n * @param groupByField - Campo del eje X (se excluye de la detección)\n */\nexport function detectValueFields(\n  data: Record<string, unknown>[],\n  groupByField: string = 'name'\n): string[] {\n  if (process.env.NODE_ENV === 'development') {\n    // eslint-disable-next-line no-console\n    console.warn(\n      '[KPI Dashboard] detectValueFields activado como fallback heurístico. ' +\n      'El widget no tiene field_mapping semántico (category/values) ni schema del endpoint. ' +\n      'Configurar field_mapping en la BD o garantizar envelope {data,schema,meta} en el endpoint.'\n    );\n  }\n  if (data.length === 0) return ['value'];\n\n  const sample = data[0];\n\n  const hasMeta = typeof sample.meta === 'number';\n  const hasActual = typeof sample.actual === 'number';\n  const hasValue = typeof sample.value === 'number';\n\n  // 1. Modo comparación: meta y/o actual\n  if (hasMeta || hasActual) {\n    return [hasMeta ? 'meta' : null, hasActual ? 'actual' : null].filter(Boolean) as string[];\n  }\n\n  // 2. Campo estándar \"value\"\n  if (hasValue) {\n    return ['value'];\n  }\n\n  // 3. Fallback: primer campo numérico que no sea el eje X\n  const firstNumeric = Object.entries(sample)\n    .find(([k, v]) => k !== groupByField && typeof v === 'number');\n\n  return firstNumeric ? [firstNumeric[0]] : ['value'];\n}\n","import type { FieldMappingOverride, WidgetFieldMapping } from '../types';\nimport { extractChartContract } from '../types';\nimport { detectValueFields } from './detectValueFields';\n\nexport interface ResolvedChartFields {\n  categoryField: string;\n  valueFields: string[];\n}\n\n/**\n * Resolución de campos en 4 capas (prioridad descendente):\n *\n * 1. preference.config_json.fieldMapping (override del usuario)\n * 2. definition.field_mapping.category/values (estándar semántico v2)\n * 3. definition.config_schema (contrato legacy - backward compat)\n * 4. detectValueFields(data) (heurística fallback)\n */\nexport function resolveChartFields(\n  configSchema: Record<string, unknown> | undefined | null,\n  data: Record<string, unknown>[],\n  userOverride?: FieldMappingOverride | null,\n  widgetFieldMapping?: WidgetFieldMapping | null,\n): ResolvedChartFields {\n  // Calcular base desde el contrato del widget\n  let base: ResolvedChartFields;\n\n  if (widgetFieldMapping?.category || widgetFieldMapping?.values?.length) {\n    // Capa 2: field_mapping semántico (nuevo estándar)\n    const cat = widgetFieldMapping.category ?? 'name';\n    base = {\n      categoryField: cat,\n      valueFields: widgetFieldMapping.values?.length\n        ? widgetFieldMapping.values\n        : detectValueFields(data, cat),\n    };\n  } else {\n    // Capa 3: config_schema legacy → heurística\n    const contract = extractChartContract(configSchema);\n    base = contract\n      ? { categoryField: contract.categoryField, valueFields: contract.valueFields }\n      : { categoryField: 'name', valueFields: detectValueFields(data, 'name') };\n  }\n\n  // Capa 1: override del usuario (tiene prioridad sobre todo)\n  if (userOverride) {\n    return {\n      categoryField: userOverride.category ?? base.categoryField,\n      valueFields: userOverride.values?.length ? userOverride.values : base.valueFields,\n    };\n  }\n\n  return base;\n}\n\n/**\n * Resuelve el label de visualización de un campo.\n * Prioridad: aliases del usuario → aliases del widget → nombre técnico del campo.\n */\nexport function resolveLabel(\n  fieldKey: string,\n  widgetAliases?: Record<string, string>,\n  userAliases?: Record<string, string>,\n): string {\n  return userAliases?.[fieldKey] ?? widgetAliases?.[fieldKey] ?? fieldKey;\n}\n","/**\n * Paleta de colores centralizada para todos los widgets de gráficas del dashboard.\n * Usar DEFAULT_CHART_COLORS para la mayoría de los casos.\n * Reemplaza los arrays hardcodeados dispersos en ChartLine, ChartVentasMensual,\n * ChartBarHorizontal, ChartDonut y FieldMappingPanel.\n */\n\nexport const CHART_COLORS = {\n  /** Azules — paleta principal para series y barras */\n  primary:   ['#3182CE', '#90CDF4', '#2B6CB0', '#63B3ED', '#4299E1'],\n  /** Líneas — mayor contraste para series temporales */\n  lines:     ['#0066FF', '#F59E0B', '#10B981', '#EF4444', '#8B5CF6'],\n  /** Verde esmeralda — para indicadores positivos */\n  emerald:   ['#38A169', '#9AE6B4', '#276749', '#68D391', '#48BB78'],\n  /** Cálidos — para distribuciones y donuts */\n  warm:      ['#DD6B20', '#FBD38D', '#C05621', '#F6AD55', '#ED8936'],\n};\n\n/** Paleta por defecto para barras (horizontales y verticales) */\nexport const DEFAULT_CHART_COLORS = CHART_COLORS.primary;\n\n/** Paleta para gráficas de líneas (mayor contraste entre series) */\nexport const LINE_CHART_COLORS = CHART_COLORS.lines;\n\n/** Colores para chips de campos en FieldMappingPanel */\nexport const FIELD_MAPPING_COLORS = CHART_COLORS.primary;\n\n/* ------------------------------------------------------------------ *\n * Paleta categórica del tablero de indicadores\n * ------------------------------------------------------------------ */\n\n/**\n * Paleta para series y categorías del tablero.\n *\n * <b>Sustituye a `DEFAULT_CHART_COLORS` en los widgets del dashboard</b>, que son\n * cinco tonos del mismo azul: con dos categorías ya cuesta distinguirlas, y con\n * ocho es ilegible. Aquí cada entrada es un hue distinto.\n *\n * <b>Rojo y verde no están, y no es un olvido.</b> Los dos portan significado en\n * el tablero — un delta favorable es verde y uno desfavorable es rojo — así que\n * usarlos para \"Alimentos\" o \"Bodega Norte\" haría que el color dejara de\n * significar algo. El verde oliva del índice 6 está lo bastante lejos del verde\n * de éxito como para no confundirse con él.\n *\n * El gris del índice 7 está <b>reservado para \"Otros\"</b>: el grupo que absorbe\n * la cola cuando hay más categorías que colores.\n */\nexport const CATEGORICAL_PALETTE = [\n  '#378ADD', // 1 azul\n  '#1D9E75', // 2 teal\n  '#D85A30', // 3 coral\n  '#BA7517', // 4 ámbar\n  '#7F77DD', // 5 púrpura\n  '#D4537E', // 6 rosa\n  '#639922', // 7 verde oliva\n  '#888780', // 8 gris — reservado para \"Otros\"\n] as const;\n\n/** El color con el que se pinta el grupo que absorbe la cola de categorías. */\nexport const OTHERS_COLOR = CATEGORICAL_PALETTE[CATEGORICAL_PALETTE.length - 1];\n\n/** Clave con la que el tablero agrupa la cola. Se traduce al pintar, no aquí. */\nexport const OTHERS_KEY = '__others__';\n\n/** Cuántas categorías reales existen antes de que el resto caiga en \"Otros\". */\nexport const MAX_CATEGORIES = CATEGORICAL_PALETTE.length - 1;\n\n/**\n * Hash estable de una cadena. FNV-1a: barato, bien distribuido y —lo que importa\n * aquí— **determinista entre sesiones y entre máquinas**.\n */\nfunction hashString(value: string): number {\n  let h = 2166136261;\n  for (let i = 0; i < value.length; i++) {\n    h ^= value.charCodeAt(i);\n    h = Math.imul(h, 16777619);\n  }\n  return Math.abs(h);\n}\n\n/**\n * El color de una categoría, estable por su nombre.\n *\n * <b>Por qué por nombre y no por índice del array de datos.</b> Si el color\n * saliera de la posición, \"Alimentos\" cambiaría de color cada vez que cambia el\n * orden — y el orden cambia al cambiar de periodo, al cambiar de compañía y al\n * pasar de dona a barras, porque las tres cosas reordenan por valor. El usuario\n * vería la misma categoría de dos colores distintos en la misma pantalla.\n *\n * Con el hash, \"Alimentos\" es del mismo color siempre y en todas partes.\n *\n * El gris de \"Otros\" queda fuera de la rotación: se reserva para el grupo de cola,\n * y ninguna categoría real puede recibirlo por sorteo.\n */\nexport function colorForCategory(category: string): string {\n  if (category === OTHERS_KEY) return OTHERS_COLOR;\n  return CATEGORICAL_PALETTE[hashString(category) % MAX_CATEGORIES];\n}\n\n/**\n * Los colores de un gráfico COMPLETO: estables por nombre y <b>sin repetirse entre sí</b>.\n *\n * <b>Por qué no basta con `colorForCategory` fila a fila.</b> `hash % 7` es un sorteo sin\n * desempate: con siete categorías, la probabilidad de que las siete caigan en colores distintos\n * es del <b>0,61 %</b>. Medido sobre nombres reales del dominio, siete categorías de producto\n * producían cuatro colores y «Alimentos» compartía el suyo con «Bebidas» — que es exactamente el\n * defecto que esta paleta vino a corregir, y en una dona dos segmentos contiguos del mismo color\n * se leen como uno solo.\n *\n * El hash sigue mandando: da el color <b>preferido</b> de cada categoría, así que «Alimentos»\n * tiende siempre al mismo. Lo que se añade es un sondeo lineal para el empate, y un orden de\n * recorrido alfabético —independiente del orden en que lleguen los datos, que cambia al cambiar\n * de periodo, de compañía o de tipo de gráfico— para que el mismo conjunto de categorías\n * produzca siempre la misma asignación.\n *\n * @example\n * const colores = colorsForCategories(rows.map(r => String(r[categoryField])));\n * <Cell fill={colores[nombre]} />\n */\nexport function colorsForCategories(categories: string[]): Record<string, string> {\n  const asignados = new Map<number, string>();\n  const resultado: Record<string, string> = {};\n\n  for (const category of [...new Set(categories)].sort()) {\n    if (category === OTHERS_KEY) {\n      resultado[category] = OTHERS_COLOR;\n      continue;\n    }\n    let i = hashString(category) % MAX_CATEGORIES;\n    // Sondeo lineal: si el preferido ya está tomado en ESTE gráfico, el siguiente libre.\n    while (asignados.has(i) && asignados.size < MAX_CATEGORIES) i = (i + 1) % MAX_CATEGORIES;\n    asignados.set(i, category);\n    resultado[category] = CATEGORICAL_PALETTE[i];\n  }\n\n  return resultado;\n}\n\n/**\n * El color de la serie número {@link index} de un gráfico multi-serie.\n *\n * Recorre solo los {@link MAX_CATEGORIES} colores reales: `index % CATEGORICAL_PALETTE.length`\n * llegaba al gris del último índice, que está reservado para «Otros».\n */\nexport function colorForSeries(index: number): string {\n  return CATEGORICAL_PALETTE[index % MAX_CATEGORIES];\n}\n","import React, { useState } from 'react';\nimport { useDashboardTranslation } from '../i18n';\nimport { ChevronDown, X as XIcon, Info, AlertCircle } from 'lucide-react';\nimport type { SchemaField, FieldMappingOverride, WidgetFieldMapping } from '../types';\n\ninterface FieldMappingPanelProps {\n  /** Schema del endpoint (fields con labels). Null si no disponible. */\n  schema: { fields: SchemaField[] } | null;\n  /** Field mapping semántico del widget (fallback cuando no hay schema en cache). */\n  widgetFieldMapping?: WidgetFieldMapping | null;\n  /** Campos actualmente resueltos (del contrato o heurística). */\n  currentCategory: string;\n  currentValues: string[];\n  /** Override del usuario (si existe). */\n  override: FieldMappingOverride | null;\n  /** Tipo de chart actual (para adaptar labels). */\n  chartType: string;\n  /** Callback al cambiar el override. */\n  onChange: (override: FieldMappingOverride | null) => void;\n}\n\n/**\n * Construye un schema sintético desde field_mapping cuando el endpoint\n * no ha respondido todavía (cache vacío). Permite que el panel funcione\n * sin necesidad de que el widget haya cargado datos.\n */\nfunction buildFallbackSchema(fm: WidgetFieldMapping): { fields: SchemaField[] } {\n  // Preferir schema_hints si el widget los tiene pre-declarados en BD\n  if (fm.fields?.length) {\n    return {\n      fields: fm.fields.map(f => ({\n        name: f.name,\n        type: f.type as SchemaField['type'],\n        label: fm.aliases?.[f.name] ?? f.label,\n      })),\n    };\n  }\n  // Fallback: construir desde category + values\n  const fields: SchemaField[] = [];\n  if (fm.category) {\n    fields.push({ name: fm.category, type: 'string', label: fm.aliases?.[fm.category] ?? fm.category });\n  }\n  for (const v of fm.values ?? []) {\n    fields.push({ name: v, type: 'number', label: fm.aliases?.[v] ?? v });\n  }\n  return { fields };\n}\n\nimport { FIELD_MAPPING_COLORS } from '../utils/chartColors';\n\n/** Busca el label humano de un campo en el schema. Fallback al nombre técnico. */\nfunction getLabel(schema: { fields: SchemaField[] } | null, fieldName: string): string {\n  if (!schema) return fieldName;\n  const field = schema.fields.find(f => f.name === fieldName);\n  return field?.label ?? fieldName;\n}\n\n/** Filtra campos válidos para \"Agrupar por\" (eje X / dimensión): string y date. */\nfunction getCategoryFields(schema: { fields: SchemaField[] } | null): SchemaField[] {\n  if (!schema) return [];\n  return schema.fields.filter(f => f.type === 'string' || f.type === 'date');\n}\n\n/** Filtra campos numéricos del schema (candidatos para values). */\nfunction getNumericFields(schema: { fields: SchemaField[] } | null): SchemaField[] {\n  if (!schema) return [];\n  return schema.fields.filter(f => f.type === 'number');\n}\n\nexport const FieldMappingPanel: React.FC<FieldMappingPanelProps> = ({\n  schema,\n  widgetFieldMapping,\n  currentCategory,\n  currentValues,\n  override,\n  chartType,\n  onChange,\n}) => {\n  const { t } = useDashboardTranslation();\n  const [isOpen, setIsOpen] = useState(false);\n\n  // Usar schema en vivo si existe; si no, construir uno desde field_mapping.\n  // Permite que el panel funcione aunque el widget no haya cargado datos todavía.\n  const effectiveSchema = schema\n    ?? (widgetFieldMapping?.values?.length ? buildFallbackSchema(widgetFieldMapping) : null);\n\n  const activeCategory = override?.category ?? currentCategory;\n  const activeValues = override?.values && override.values.length > 0 ? override.values : currentValues;\n  const isDonut = chartType === 'chart_donut';\n  const maxValues = isDonut ? 1 : 5;\n  const hasOverride = override != null;\n\n  const stringFields = getCategoryFields(effectiveSchema);\n  const numericFields = getNumericFields(effectiveSchema);\n  const availableToAdd = numericFields.filter(f => !activeValues.includes(f.name));\n\n  // Label adaptativo según tipo de chart\n  const valuesLabel = chartType === 'chart_line' ? 'Líneas a graficar'\n    : chartType === 'chart_donut' ? 'Valor del gráfico'\n    : 'Mostrar valores de';\n\n  const handleCategoryChange = (field: string) => {\n    onChange({ ...override, category: field, values: override?.values });\n  };\n\n  const handleAddValue = (field: string) => {\n    const newValues = [...activeValues, field];\n    onChange({ ...override, category: override?.category, values: newValues });\n  };\n\n  const handleRemoveValue = (field: string) => {\n    const newValues = activeValues.filter(v => v !== field);\n    if (newValues.length === 0) return; // no permitir vacío\n    onChange({ ...override, category: override?.category, values: newValues });\n  };\n\n  const handleReset = () => {\n    onChange(null);\n  };\n\n  // Sin schema ni field_mapping no hay nada que mostrar\n  if (!effectiveSchema) return null;\n\n  return (\n    <div>\n      {/* Toggle sutil */}\n      <button\n        onClick={() => setIsOpen(!isOpen)}\n        className=\"w-full flex items-center justify-between py-2 text-xs text-gray-500 hover:text-gray-700 transition-colors\"\n      >\n        <div className=\"flex items-center gap-2\">\n          <span className=\"font-medium\">{t('dashboard.fields.chartFields')}</span>\n          {!hasOverride && (\n            <span className=\"text-[10px] text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded border border-gray-200\">auto</span>\n          )}\n          {hasOverride && (\n            <span className=\"text-[10px] text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded border border-blue-200\">personalizado</span>\n          )}\n          {!schema && effectiveSchema && (\n            <span className=\"flex items-center gap-0.5 text-[10px] text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded border border-amber-200\" title=\"El widget no ha cargado datos todavía. Se muestran los campos configurados en el catálogo.\">\n              <AlertCircle className=\"w-2.5 h-2.5\" />sin datos\n            </span>\n          )}\n        </div>\n        <ChevronDown className={`w-3.5 h-3.5 transition-transform ${isOpen ? 'rotate-180' : ''}`} />\n      </button>\n\n      {/* Panel expandido */}\n      {isOpen && (\n        <div className=\"bg-gray-50 rounded-lg p-3.5 space-y-3.5 mt-1\">\n          {/* Agrupar por */}\n          <div>\n            <div className=\"text-[11px] text-gray-500 mb-1.5\">{t('dashboard.fields.groupBy')}</div>\n            <select\n              value={activeCategory}\n              onChange={e => handleCategoryChange(e.target.value)}\n              className=\"w-full bg-white border border-gray-200 rounded-md px-2.5 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 truncate\"\n            >\n              {stringFields.length > 0\n                ? stringFields.map(f => (\n                    <option key={f.name} value={f.name}>\n                      {f.label !== f.name ? `${f.label} (${f.name})` : f.name}\n                    </option>\n                  ))\n                : <option value={activeCategory}>{getLabel(effectiveSchema, activeCategory)}</option>\n              }\n            </select>\n          </div>\n\n          {/* Valores seleccionados */}\n          <div>\n            <div className=\"flex items-center justify-between mb-1.5\">\n              <div className=\"text-[11px] text-gray-500\">{valuesLabel}</div>\n              <div className=\"text-[10px] text-gray-400\">{activeValues.length} de {maxValues} permitido{maxValues > 1 ? 's' : ''}</div>\n            </div>\n\n            <div className=\"space-y-1.5\">\n              {activeValues.map((field, i) => (\n                <div key={field} className=\"bg-white border border-gray-200 rounded-md px-2.5 py-2 flex items-center justify-between text-sm\">\n                  <div className=\"flex items-center gap-2\">\n                    <div className=\"w-2.5 h-2.5 rounded-sm\" style={{ background: FIELD_MAPPING_COLORS[i % FIELD_MAPPING_COLORS.length] }} />\n                    <div className=\"w-4 h-4 rounded bg-emerald-50 text-emerald-700 flex items-center justify-center text-[9px] font-semibold\">#</div>\n                    <div>\n                      <div className=\"font-medium text-gray-800\">{getLabel(effectiveSchema, field)}</div>\n                      <div className=\"text-[10px] text-gray-400\">campo: {field}</div>\n                    </div>\n                  </div>\n                  {activeValues.length > 1 && (\n                    <button onClick={() => handleRemoveValue(field)} className=\"text-gray-400 hover:text-red-500 transition-colors\">\n                      <XIcon className=\"w-3.5 h-3.5\" />\n                    </button>\n                  )}\n                </div>\n              ))}\n\n              {/* Agregar otro valor */}\n              {activeValues.length < maxValues && availableToAdd.length > 0 && (\n                <div className=\"relative group\">\n                  <select\n                    value=\"\"\n                    onChange={e => { if (e.target.value) handleAddValue(e.target.value); }}\n                    className=\"w-full bg-white border border-dashed border-gray-300 rounded-md px-2.5 py-2 text-sm text-gray-500 focus:ring-2 focus:ring-blue-500 appearance-none cursor-pointer\"\n                  >\n                    <option value=\"\">+ Agregar otro valor</option>\n                    {availableToAdd.map(f => (\n                      <option key={f.name} value={f.name}>{f.label} ({f.name})</option>\n                    ))}\n                  </select>\n                </div>\n              )}\n            </div>\n          </div>\n\n          {/* Warning donut */}\n          {isDonut && currentValues.length <= 1 && (\n            <div className=\"bg-amber-50 border border-amber-200 rounded-md px-2.5 py-2 flex gap-2 text-[11px] text-amber-800 leading-relaxed\">\n              <Info className=\"w-3.5 h-3.5 flex-shrink-0 mt-0.5\" />\n              <div>El gráfico circular solo muestra un valor a la vez. Cambia a barras o líneas para comparar varios.</div>\n            </div>\n          )}\n\n          {/* Campos disponibles del endpoint */}\n          <div>\n            <div className=\"text-[11px] text-gray-500 mb-1.5\">{t('dashboard.fields.available')}</div>\n            <div className=\"flex flex-wrap gap-1\">\n              {effectiveSchema.fields.map(f => {\n                const isUsed = f.name === activeCategory || activeValues.includes(f.name);\n                return (\n                  <span\n                    key={f.name}\n                    className={`text-[10px] px-2 py-0.5 rounded border ${\n                      isUsed\n                        ? 'bg-blue-50 border-blue-200 text-blue-600'\n                        : 'bg-white border-gray-200 text-gray-300 line-through'\n                    }`}\n                  >\n                    {f.name}\n                  </span>\n                );\n              })}\n            </div>\n          </div>\n\n          {/* Reset */}\n          {hasOverride && (\n            <button\n              onClick={handleReset}\n              className=\"w-full text-center text-[11px] text-gray-500 hover:text-blue-600 py-1 transition-colors\"\n            >\n              Restaurar campos automáticos\n            </button>\n          )}\n        </div>\n      )}\n    </div>\n  );\n};\n","import React, { useState } from 'react';\nimport { useDashboardTranslation } from '../i18n';\nimport { X, ArrowLeft, RotateCcw, Check } from 'lucide-react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport type {\n  WidgetDefinition, UserWidgetPreference, SchemaField,\n  FieldMappingOverride, DashboardPeriod,\n} from '../types';\nimport { getCompatibleTypes, extractChartContract } from '../types';\nimport { resolveChartFields } from '../utils/resolveChartFields';\nimport { WIDGET_TYPE_MAP } from '../utils/widgetTypeConfig';\nimport { FieldMappingPanel } from './FieldMappingPanel';\n\n/**\n * Vacío a propósito. Esta era la TERCERA lista de categorías del módulo y —peor— no coincidía con\n * las otras dos: agregaba `'General'`, que no existía en el Widget Builder. Un usuario podía\n * clasificar un widget en una categoría que el asistente de creación no ofrecía.\n *\n * Ahora la única fuente son las `availableCategories` que declara el host.\n */\nconst DEFAULT_CATEGORIES: string[] = [];\n\ninterface WidgetCustomizationPanelProps {\n  widget: WidgetDefinition;\n  /** Ausente = modo \"agregar\", presente = modo \"personalizar\" */\n  preference?: UserWidgetPreference;\n  /** Schema del endpoint del cache de React Query. Null si no disponible. */\n  schema?: { fields: SchemaField[] } | null;\n  /** Categorías disponibles (del catálogo). Si no se pasa, usa las por defecto. */\n  availableCategories?: string[];\n  onConfirm: (overrides: Record<string, unknown>) => void;\n  /** Solo en modo \"personalizar\" */\n  onRestore?: () => void;\n  onClose: () => void;\n}\n\nconst REFRESH_OPTIONS = [\n  { value: 0,    label: 'Sin auto-refresh'   },\n  { value: 30,   label: 'Cada 30 segundos'   },\n  { value: 60,   label: 'Cada 1 minuto'      },\n  { value: 120,  label: 'Cada 2 minutos'     },\n  { value: 300,  label: 'Cada 5 minutos'     },\n  { value: 600,  label: 'Cada 10 minutos'    },\n  { value: 1800, label: 'Cada 30 minutos'    },\n];\n\nexport const WidgetCustomizationPanel: React.FC<WidgetCustomizationPanelProps> = ({\n  widget,\n  preference,\n  schema,\n  availableCategories,\n  onConfirm,\n  onRestore,\n  onClose,\n}) => {\n  const { t } = useDashboardTranslation();\n  const categories = availableCategories?.length ? availableCategories : DEFAULT_CATEGORIES;\n  const mode = preference ? 'personalize' : 'add';\n\n  const [overrides, setOverrides] = useState<Record<string, unknown>>(\n    preference?.config_json ?? {}\n  );\n\n  // Resolver campos actuales\n  const contract = extractChartContract(widget.config_schema);\n  const existingFieldMapping = overrides.fieldMapping as FieldMappingOverride | undefined;\n  const resolved = resolveChartFields(widget.config_schema, [], existingFieldMapping, widget.field_mapping);\n\n  const activeValuesCount =\n    existingFieldMapping?.values?.length ??\n    widget.field_mapping?.values?.length ??\n    contract?.valueFields.length;\n  const compatibleTypes = getCompatibleTypes(widget.tipo, activeValuesCount);\n  const showTypeSelector = compatibleTypes.length > 0;\n  const currentType = (overrides.chartType as string) ?? widget.tipo;\n\n  // Campos del gráfico: visible si el widget tiene field_mapping configurado O schema en vivo,\n  // independiente de si tiene tipos compatibles para cambiar.\n  const showFieldMapping = !!(\n    widget.field_mapping?.values?.length ||\n    widget.field_mapping?.category ||\n    schema\n  );\n\n  const update = (key: string, value: unknown) =>\n    setOverrides(prev => ({ ...prev, [key]: value }));\n\n  const handleFieldMappingChange = (newOverride: FieldMappingOverride | null) => {\n    setOverrides(prev => {\n      const next = { ...prev };\n      if (newOverride) {\n        next.fieldMapping = newOverride;\n      } else {\n        delete next.fieldMapping;\n      }\n      return next;\n    });\n  };\n\n  const handleConfirm = () => {\n    const clean: Record<string, unknown> = {};\n\n    /**\n     * El sello de layout NO es un override del usuario: se conserva SIEMPRE.\n     *\n     * `config_json` es la bolsa donde este panel guarda los overrides, pero también donde\n     * `layoutMigration` estampa `layoutVersion` para no volver a convertir un `row_span` ya\n     * convertido. Este panel RECONSTRUYE la bolsa desde cero, así que si el sello no se copia\n     * aquí desaparece con cada \"Confirmar\" — y en la siguiente carga la migración se aplica\n     * otra vez sobre un valor ya migrado: 2 → 4 → 7 → 13 filas, sin tope y en silencio.\n     */\n    if (preference?.config_json?.layoutVersion !== undefined) {\n      clean.layoutVersion = preference.config_json.layoutVersion;\n    }\n    if (overrides.chartType && overrides.chartType !== widget.tipo)                           clean.chartType     = overrides.chartType;\n    if (overrides.title && overrides.title !== widget.nombre)                                 clean.title         = overrides.title;\n    if (overrides.descripcion && overrides.descripcion !== widget.descripcion)                clean.descripcion   = overrides.descripcion;\n    if (overrides.categoria && overrides.categoria !== widget.categoria)                      clean.categoria     = overrides.categoria;\n    if (overrides.cols_default && overrides.cols_default !== widget.cols_default)             clean.cols_default  = overrides.cols_default;\n    if (overrides.refresh_policy !== undefined && overrides.refresh_policy !== widget.refresh_policy) clean.refresh_policy = overrides.refresh_policy;\n    if (overrides.fieldMapping)                                                               clean.fieldMapping  = overrides.fieldMapping;\n    onConfirm(clean);\n  };\n\n  return (\n    <div className=\"fixed inset-y-0 right-0 w-[348px] bg-white shadow-2xl border-l border-gray-200 z-50 flex flex-col\">\n\n      {/* Header */}\n      <div className=\"flex items-center gap-3 p-4 border-b border-gray-100\">\n        {mode === 'add' && (\n          <button onClick={onClose} className=\"p-1 hover:bg-gray-100 rounded text-gray-500\">\n            <ArrowLeft className=\"w-5 h-5\" />\n          </button>\n        )}\n        <div className=\"flex-1 min-w-0\">\n          <h2 className=\"text-lg font-semibold text-gray-800\">\n            {mode === 'add' ? 'Agregar indicador' : 'Personalizar'}\n          </h2>\n          <p className=\"text-xs text-gray-500 truncate\">{widget.nombre}</p>\n        </div>\n        <button onClick={onClose} className=\"p-1 hover:bg-gray-100 rounded text-gray-500\">\n          <X className=\"w-5 h-5\" />\n        </button>\n      </div>\n\n      {/* Controles */}\n      <div className=\"flex-1 overflow-y-auto p-4 space-y-5\">\n\n        {/* 1. Tipo de gráfico */}\n        {showTypeSelector && (\n          <div>\n            <label className=\"block text-sm font-medium text-gray-700 mb-2\">{t('dashboard.customize.visualization')}</label>\n            <div className=\"grid grid-cols-4 gap-2\">\n              {([widget.tipo, ...compatibleTypes] as string[]).map(typeId => {\n                const cfg = WIDGET_TYPE_MAP[typeId as keyof typeof WIDGET_TYPE_MAP];\n                if (!cfg) return null;\n                const isAvailable = true;\n                const isActive = currentType === typeId;\n                return (\n                  <button\n                    key={typeId}\n                    disabled={!isAvailable}\n                    onClick={() => update('chartType', typeId)}\n                    className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border-2 transition-all text-xs font-medium ${\n                      isActive\n                        ? 'border-blue-500 bg-blue-50 text-blue-700'\n                        : 'border-gray-200 text-gray-600 hover:border-blue-300 hover:bg-blue-50/30'\n                    }`}\n                  >\n                    <cfg.icon className=\"w-5 h-5\" />\n                    {cfg.label}\n                  </button>\n                );\n              })}\n            </div>\n            {currentType === 'chart_donut' && (\n              <p className=\"text-[10px] text-amber-600 mt-1.5 leading-relaxed bg-amber-50 border border-amber-200 rounded px-2 py-1\">\n                El gráfico circular solo muestra un valor a la vez. Cambia a barras o líneas para comparar varios.\n              </p>\n            )}\n          </div>\n        )}\n\n        {/* 2. Campos del gráfico — visible si hay field_mapping o schema disponible */}\n        {showFieldMapping && (\n          <FieldMappingPanel\n            schema={schema ?? null}\n            widgetFieldMapping={widget.field_mapping}\n            currentCategory={resolved.categoryField}\n            currentValues={resolved.valueFields}\n            override={existingFieldMapping ?? null}\n            chartType={currentType}\n            onChange={handleFieldMappingChange}\n          />\n        )}\n\n        {/* 3. Nombre */}\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.name')}</label>\n          <input\n            type=\"text\"\n            value={(overrides.title as string) ?? widget.nombre}\n            onChange={e => update('title', e.target.value)}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm\"\n          />\n        </div>\n\n        {/* 4. Descripción */}\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n            Descripción corta <span className=\"text-gray-400 font-normal\">(opcional)</span>\n          </label>\n          <input\n            type=\"text\"\n            value={(overrides.descripcion as string) ?? widget.descripcion}\n            onChange={e => update('descripcion', e.target.value)}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm\"\n          />\n        </div>\n\n        {/* 5. Categoría — solo en modo personalizar */}\n        {mode === 'personalize' && (\n          <div>\n            <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.category')}</label>\n            <select\n              value={(overrides.categoria as string) ?? widget.categoria}\n              onChange={e => update('categoria', e.target.value)}\n              className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white text-sm\"\n            >\n              {categories.map(cat => (\n                <option key={cat} value={cat}>{cat}</option>\n              ))}\n            </select>\n          </div>\n        )}\n\n        {/* 6. Ancho */}\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.width')}</label>\n          <select\n            value={(overrides.cols_default as number) ?? widget.cols_default}\n            onChange={e => update('cols_default', Number(e.target.value))}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white text-sm\"\n          >\n            <option value={3}>{t('dashboard.customize.widthSmall')}</option>\n            <option value={6}>{t('dashboard.customize.widthMedium')}</option>\n            <option value={12}>{t('dashboard.customize.widthFull')}</option>\n          </select>\n        </div>\n\n        {/* 7. Frecuencia de actualización */}\n        <div>\n          <label className=\"block text-sm font-medium text-gray-700 mb-1\">{t('dashboard.customize.refresh')}</label>\n          <select\n            value={(overrides.refresh_policy as number) ?? widget.refresh_policy ?? 300}\n            onChange={e => update('refresh_policy', Number(e.target.value))}\n            className=\"w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white text-sm\"\n          >\n            {REFRESH_OPTIONS.map(opt => (\n              <option key={opt.value} value={opt.value}>{opt.label}</option>\n            ))}\n          </select>\n        </div>\n      </div>\n\n      {/* Footer */}\n      <div className=\"p-4 border-t border-gray-200 bg-gray-50 space-y-3\">\n        {mode === 'personalize' ? (\n          <div className=\"flex gap-2\">\n            <button\n              onClick={() => { onRestore?.(); onClose(); }}\n              className=\"flex-1 flex items-center justify-center gap-1.5 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50\"\n            >\n              <RotateCcw className=\"w-3.5 h-3.5\" /> Restaurar\n            </button>\n            <button\n              onClick={() => { handleConfirm(); onClose(); }}\n              className=\"flex-1 flex items-center justify-center gap-1.5 py-2 text-sm font-semibold text-white bg-blue-600 rounded-lg hover:bg-blue-700\"\n            >\n              <Check className=\"w-3.5 h-3.5\" /> Aplicar\n            </button>\n          </div>\n        ) : (\n          <button\n            onClick={() => { handleConfirm(); onClose(); }}\n            disabled={!(overrides.title as string ?? widget.nombre)?.trim()}\n            className=\"w-full flex items-center justify-center gap-2 py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50\"\n          >\n            <Check className=\"w-4 h-4\" /> Agregar al Dashboard\n          </button>\n        )}\n        <p className=\"text-[11px] text-gray-400 text-center\">\n          {mode === 'personalize'\n            ? 'Los cambios solo afectan tu dashboard. El widget original no se modifica.'\n            : 'El indicador se agrega solo a tu dashboard.'}\n        </p>\n      </div>\n    </div>\n  );\n};\n\n/**\n * Wrapper que inyecta el schema del cache de React Query al panel.\n * Funciona para ambos modos (add y personalize).\n */\nexport const CustomizationWithSchema: React.FC<\n  WidgetCustomizationPanelProps & { period: DashboardPeriod }\n> = ({ period, ...props }) => {\n  const queryClient = useQueryClient();\n  const cached = queryClient.getQueryData<{\n    data: unknown;\n    schema: { fields: SchemaField[] } | null;\n  }>(['widget-data', props.widget.widget_id, period]);\n  return <WidgetCustomizationPanel {...props} schema={cached?.schema} />;\n};\n","import type { UserWidgetPreferenceBase } from '../types';\n\n/**\n * Motor puro de empaquetado 2D para calcular el layout de los widgets.\n * Busca la primera coordenada (X, Y) disponible de izquierda a derecha, de arriba a abajo.\n */\n\n// Interfaz interna para el grid bidimensional (matriz)\ntype GridMap = boolean[][];\n\nexport const MAX_COLS = 12;\n\n/**\n * Inicializa un mapa del grid ocupado por los widgets actuales.\n */\nconst buildOccupiedMap = (layout: UserWidgetPreferenceBase[]): GridMap => {\n  const map: GridMap = [];\n  \n  // Encontrar la altura máxima actual\n  const maxH = layout.reduce((acc, item) => Math.max(acc, item.pos_y + item.row_span), 0);\n  \n  // Inicializar grid con falses\n  for (let y = 0; y < Math.max(maxH + 10, 50); y++) {\n    map[y] = new Array(MAX_COLS).fill(false);\n  }\n\n  // Marcar celdas ocupadas\n  layout.forEach(item => {\n    for (let y = item.pos_y; y < item.pos_y + item.row_span; y++) {\n      for (let x = item.pos_x; x < item.pos_x + item.col_span; x++) {\n        if (map[y] && typeof map[y][x] !== 'undefined') {\n          map[y][x] = true;\n        }\n      }\n    }\n  });\n\n  return map;\n};\n\n/**\n * Verifica si una posición específica está disponible para un tamaño dado.\n */\nconst isPositionFree = (map: GridMap, startX: number, startY: number, w: number, h: number): boolean => {\n  if (startX + w > MAX_COLS) return false; // Se sale del grid horizontalmente\n\n  for (let y = startY; y < startY + h; y++) {\n    for (let x = startX; x < startX + w; x++) {\n      // Si la fila no existe, se considera libre\n      if (map[y] && map[y][x]) {\n        return false;\n      }\n    }\n  }\n  return true;\n};\n\n/**\n * Encuentra la primera posición (X, Y) libre para un widget.\n * Escanea de Izquierda a Derecha, de Arriba a Abajo.\n * \n * @param currentLayout Array de preferencias actuales.\n * @param width Ancho (columnas) requerido.\n * @param height Alto (filas) requerido.\n * @returns Posición {x, y} ideal.\n */\nexport const findFirstAvailablePosition = (\n  currentLayout: UserWidgetPreferenceBase[],\n  width: number,\n  height: number\n): { x: number; y: number } => {\n  const map = buildOccupiedMap(currentLayout);\n  \n  for (let y = 0; y < 1000; y++) { // Límite de seguridad\n    for (let x = 0; x <= MAX_COLS - width; x++) {\n      if (isPositionFree(map, x, y, width, height)) {\n        return { x, y };\n      }\n    }\n  }\n\n  return { x: 0, y: 0 }; // Fallback\n};\n\n/**\n * Agrupa los widgets y aplica un offset Y para evitar colisiones \n * en una vista de múltiples grids en cascada.\n * \n * @param layout Layout original.\n * @param namespaceOffset Modificador multiplicador (ej. categoría index * 100).\n */\nexport const applyCascadeYOffset = (\n  layout: UserWidgetPreferenceBase[], \n  namespaceOffset: number\n): UserWidgetPreferenceBase[] => {\n  return layout.map(item => ({\n    ...item,\n    pos_y: item.pos_y + namespaceOffset\n  }));\n};\n","import React, { Component, ReactNode } from 'react';\n\ninterface ErrorBoundaryProps {\n  children: ReactNode;\n  widgetId: string;\n}\n\ninterface ErrorBoundaryState {\n  hasError: boolean;\n  errorMsg: string | null;\n}\n\n/**\n * Envoltura obligatoria (BMAD6) para atrapar fallos en componentes hijo (gráficos).\n * Garantiza que si un widget falla al procesar datos o renderizar, el dashboard \n * completo no se crashee.\n */\nexport class WidgetErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n  constructor(props: ErrorBoundaryProps) {\n    super(props);\n    this.state = { hasError: false, errorMsg: null };\n  }\n\n  static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n    return { hasError: true, errorMsg: error.message };\n  }\n\n  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n    // Aquí se conectaría con un servicio de logging externo (Sentry, Datadog)\n    console.error(`Error crítico atrapado en el widget [${this.props.widgetId}]:`, error, errorInfo);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return (\n        <div className=\"flex flex-col items-center justify-center w-full h-full p-4 bg-red-50 text-red-600 rounded-lg\">\n          <svg className=\"w-8 h-8 mb-2 text-red-500\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n            <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z\" />\n          </svg>\n          <span className=\"font-semibold text-sm\">Error al cargar widget</span>\n          <span className=\"text-xs text-center opacity-80 mt-1 line-clamp-2\">\n            {this.state.errorMsg || 'Datos corruptos o endpoint fallido'}\n          </span>\n          <button \n            className=\"mt-3 text-xs bg-red-100 px-3 py-1 rounded hover:bg-red-200 transition-colors\"\n            onClick={() => this.setState({ hasError: false, errorMsg: null })}\n          >\n            Reintentar\n          </button>\n        </div>\n      );\n    }\n\n    return this.props.children;\n  }\n}\n","import React from 'react';\nimport type { SkeletonShape } from '../utils/skeletonShape';\n\n/**\n * Esqueletos de carga con la forma del widget.\n *\n * <b>Por qué no un spinner.</b> El tablero pinta seis u ocho tarjetas a la vez y\n * cada una responde cuando responde su propio endpoint (cada widget tiene su\n * `useQuery`). Con un spinner genérico, durante los primeros segundos la pantalla\n * es una rejilla de ruletas idénticas: el usuario no sabe qué está llegando ni\n * cuánto va a ocupar, y la grilla salta cuando el contenido real entra con otra\n * altura.\n *\n * Un esqueleto que respeta la forma resuelve las dos cosas — reserva el espacio y\n * anticipa qué va a aparecer ahí — y cuesta lo mismo.\n *\n * <b>El pulso se anula bajo `prefers-reduced-motion`.</b> Una rejilla de bloques\n * latiendo a la vez es justo el patrón que dispara molestias vestibulares.\n */\n\n/**\n * Bloque gris del esqueleto. Sin animación propia: la pone el contenedor.\n *\n * Usa `--dash-skeleton` y no `--dash-surface-page`: en modo oscuro la superficie de página es\n * MÁS oscura que la de la tarjeta, así que el esqueleto invertía su polaridad y se leía como un\n * hueco negro en vez de como un bloque de contenido por llegar.\n */\nconst Bar: React.FC<{ className?: string; style?: React.CSSProperties }> = ({ className = '', style }) => (\n  <div\n    className={`rounded ${className}`}\n    style={{ background: 'var(--dash-skeleton)', ...style }}\n  />\n);\n\n/** Alturas de las barras del esqueleto de gráfico. Fijas: un `Math.random()` haría que cada render moviera el esqueleto. */\nconst BAR_HEIGHTS = ['45%', '70%', '55%', '85%', '40%', '65%'];\nconst TABLE_WIDTHS = ['38%', '22%', '18%', '14%'];\n\ninterface WidgetSkeletonProps {\n  shape?: SkeletonShape;\n  /** Anula el pulso. Lo resuelve el contenedor con `prefers-reduced-motion`. */\n  reducedMotion?: boolean;\n}\n\nexport const WidgetSkeleton: React.FC<WidgetSkeletonProps> = ({\n  shape = 'generic',\n  reducedMotion = false,\n}) => {\n  const pulse = reducedMotion ? '' : 'animate-pulse';\n\n  return (\n    <div\n      className={`w-full h-full p-4 ${pulse}`}\n      data-testid=\"widget-skeleton\"\n      data-shape={shape}\n      aria-hidden=\"true\"\n    >\n      {shape === 'kpi' && (\n        <div className=\"h-full flex flex-col justify-center gap-3\">\n          <Bar className=\"h-8 w-2/5\" />\n          <Bar className=\"h-6 w-full\" style={{ opacity: 0.6 }} />\n          <Bar className=\"h-3 w-1/3\" style={{ opacity: 0.6 }} />\n        </div>\n      )}\n\n      {shape === 'line' && (\n        <div className=\"h-full flex flex-col justify-end gap-2\">\n          <Bar className=\"h-px w-full\" style={{ opacity: 0.8 }} />\n          <Bar className=\"h-px w-full\" style={{ opacity: 0.8 }} />\n          <Bar className=\"h-px w-full\" style={{ opacity: 0.8 }} />\n          <Bar className=\"h-2 w-1/2 mt-2\" style={{ opacity: 0.6 }} />\n        </div>\n      )}\n\n      {shape === 'bars' && (\n        <div className=\"h-full flex items-end justify-around gap-2\">\n          {BAR_HEIGHTS.map((h, i) => (\n            <Bar key={i} className=\"flex-1\" style={{ height: h, maxWidth: 48 }} />\n          ))}\n        </div>\n      )}\n\n      {shape === 'donut' && (\n        <div className=\"h-full flex items-center justify-center\">\n          <div\n            className=\"rounded-full\"\n            style={{\n              width: 'min(60%, 140px)',\n              aspectRatio: '1',\n              border: '18px solid var(--dash-skeleton)',\n            }}\n          />\n        </div>\n      )}\n\n      {shape === 'table' && (\n        <div className=\"h-full flex flex-col gap-3\">\n          {/* El encabezado es más tenue: anticipa que ahí van etiquetas, no datos. */}\n          <div className=\"flex gap-3\">\n            {TABLE_WIDTHS.map((w, i) => (\n              <Bar key={i} className=\"h-2\" style={{ width: w, opacity: 0.5 }} />\n            ))}\n          </div>\n          {[0, 1, 2, 3].map(row => (\n            <div key={row} className=\"flex gap-3\">\n              {TABLE_WIDTHS.map((w, i) => (\n                <Bar key={i} className=\"h-3\" style={{ width: w }} />\n              ))}\n            </div>\n          ))}\n        </div>\n      )}\n\n      {shape === 'image' && <Bar className=\"w-full h-full\" />}\n\n      {shape === 'generic' && (\n        <div className=\"h-full flex flex-col gap-3\">\n          <Bar className=\"h-4 w-1/3\" />\n          <Bar className=\"flex-1 w-full\" style={{ opacity: 0.6 }} />\n        </div>\n      )}\n    </div>\n  );\n};\n","/**\n * Forma del esqueleto de carga de un widget.\n *\n * Vive aparte del componente que la pinta porque el kit exige que un módulo con\n * componentes sólo exporte componentes (`react-refresh/only-export-components`):\n * mezclar el mapa con el JSX rompe el hot reload.\n */\n\nexport type SkeletonShape = 'kpi' | 'line' | 'bars' | 'donut' | 'table' | 'image' | 'generic';\n\n/** Mapa tipo de widget → forma del esqueleto. */\nconst SHAPE_BY_TYPE: Record<string, SkeletonShape> = {\n  kpi: 'kpi',\n  chart_line: 'line',\n  chart_bar_vertical: 'bars',\n  chart_bar_horizontal: 'bars',\n  chart_donut: 'donut',\n  table: 'table',\n  image: 'image',\n};\n\n/** La forma que corresponde a un `WidgetDefinition.tipo`. Los desconocidos caen en `generic`. */\nexport function skeletonShapeFor(tipo: string | undefined): SkeletonShape {\n  return (tipo && SHAPE_BY_TYPE[tipo]) || 'generic';\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Si el usuario pidió menos movimiento en su sistema operativo.\n *\n * El tablero tiene un presupuesto de animación corto pero real —pulso de los\n * esqueletos, entrada escalonada de tarjetas, crecimiento de barras, count-up del\n * KPI— y todo eso se anula aquí. Media docena de bloques latiendo a la vez es\n * justo el patrón que dispara molestias vestibulares.\n *\n * Se lee por JS y no sólo por CSS porque varias de esas animaciones no son\n * declarativas: un count-up es un `setInterval`, no una `@keyframes`.\n */\nexport function useReducedMotion(): boolean {\n  const [reduced, setReduced] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;\n\n    const query = window.matchMedia('(prefers-reduced-motion: reduce)');\n    setReduced(query.matches);\n\n    const onChange = (event: MediaQueryListEvent) => setReduced(event.matches);\n\n    // Safari < 14 no tiene addEventListener sobre MediaQueryList.\n    if (typeof query.addEventListener === 'function') {\n      query.addEventListener('change', onChange);\n      return () => query.removeEventListener('change', onChange);\n    }\n    query.addListener(onChange);\n    return () => query.removeListener(onChange);\n  }, []);\n\n  return reduced;\n}\n","/**\n * Formato numérico del tablero de indicadores.\n *\n * <b>Por qué es un módulo y no un `toLocaleString` en cada widget.</b> Hoy cada\n * widget formatea a su manera: el KPI concatena prefijo y sufijo, los ejes de los\n * gráficos llaman a `toLocaleString('es-CO')` por su cuenta y la tabla no formatea\n * nada. El resultado es que la misma cifra se ve distinta en tres sitios de la\n * misma pantalla.\n *\n * Las reglas de aquí salen de la especificación del tablero:\n *\n *  - Se abrevia por magnitud (K, M, B), pero <b>nunca</b> en tablas ni en enteros\n *    de conteo: una tabla existe para comparar cifras exactas, y \"20 pedidos\" no\n *    se lee mejor como \"20\".\n *  - La moneda es un <b>símbolo separado y más pequeño</b>, no un prefijo pegado\n *    al número. Por eso `abbreviate` devuelve las piezas por separado en vez de\n *    una cadena: quien pinta decide el tamaño de cada una.\n *  - Todo número que se refresca se pinta con `tabular-nums`. Sin eso los dígitos\n *    cambian de ancho y la cifra tiembla en cada refresco.\n */\n\n/**\n * Locale por defecto del producto.\n *\n * Se exporta porque es el ÚNICO punto donde vive esa decisión: cualquier `toLocaleString`,\n * `toLocaleDateString` o `localeCompare` del tablero lo usa en vez de cablear `'es-CO'` por su\n * cuenta — que es lo que hacían el subtítulo del contenedor, el badge de alto volumen y el\n * comparador de la tabla.\n */\nexport const DASHBOARD_LOCALE = 'es-CO';\nconst DEFAULT_LOCALE = DASHBOARD_LOCALE;\n\n/**\n * Moneda del alcance activo.\n *\n * <b>Hoy el símbolo está cableado, y es a propósito.</b> El endpoint de compañías\n * no devuelve la moneda local (`CompanyDto = {id, code, name}`), aunque el dato\n * exista en base (`segm_companies_prj.local_currency_id`). Mostrar un código de\n * moneda que nadie verificó sería peor que no mostrarlo.\n *\n * El día que el API la exponga, <b>este es el único sitio que cambia</b>: ningún\n * widget formatea moneda por su cuenta.\n */\nexport interface Currency {\n  /** Símbolo visible: `$`, `US$`. */\n  symbol: string;\n  /** Código ISO, para el selector de compañía. `null` mientras no sea confiable. */\n  iso: string | null;\n  locale: string;\n}\n\nexport const DEFAULT_CURRENCY: Currency = { symbol: '$', iso: null, locale: DEFAULT_LOCALE };\n\n/** Lo mínimo que el tablero necesita saber de una compañía para resolver su moneda. */\nexport interface CurrencyScope {\n  /** Moneda local de la compañía. Hoy ningún host la envía. */\n  localCurrency?: { symbol?: string; iso?: string } | null;\n}\n\n/**\n * <b>El único punto donde se decide en qué moneda está una cifra.</b>\n *\n * Ningún widget formatea moneda por su cuenta: todos pasan por aquí. Eso es lo que\n * hace que el día que el API de compañías exponga `local_currency_id` haya que\n * cambiar exactamente una función — y no rastrear cada `toLocaleString` del módulo.\n *\n * Mientras tanto devuelve el peso con `iso: null`, que es una afirmación honesta:\n * \"sé qué símbolo pintar, no sé de qué moneda es\". Por eso el selector de compañía\n * no muestra código de moneda todavía — mostrar \"COP\" para todas sería afirmar algo\n * que nadie verificó.\n */\nexport function resolveCurrency(scope?: CurrencyScope): Currency {\n  const local = scope?.localCurrency;\n  if (local?.symbol) {\n    return { symbol: local.symbol, iso: local.iso ?? null, locale: DEFAULT_LOCALE };\n  }\n  return DEFAULT_CURRENCY;\n}\n\n/** Las tres piezas de una cifra, para que quien pinta decida el tamaño de cada una. */\nexport interface AbbreviatedValue {\n  /** Símbolo de moneda, o `null` si el indicador no es monetario. */\n  symbol: string | null;\n  /** El número ya formateado al locale. */\n  number: string;\n  /**\n   * Sufijo de magnitud, o `null` si no se abrevió.\n   *\n   * Es una cadena libre y NO una unión `K | M | B` a propósito: lo pone `Intl` según\n   * el locale, y las escalas no coinciden entre idiomas — en español 5.230.000.000\n   * lleva `M` (escala larga) y en inglés `B`.\n   */\n  scale: string | null;\n}\n\nexport interface AbbreviateOptions {\n  /** Símbolo de moneda a devolver en `symbol`. */\n  currency?: string | null;\n  /** Entero de conteo: nunca se abrevia (pedidos, documentos, registros). */\n  integer?: boolean;\n  locale?: string;\n  /**\n   * Fuerza la abreviatura desde los miles, ignorando {@link ABBREVIATE_FROM}.\n   *\n   * <b>Es para los ejes de los gráficos y el centro de la dona</b>, donde el espacio\n   * manda: un eje Y con `10.000.000` en cada marca se come el gráfico, y la cifra\n   * exacta ya está en el tooltip. En un KPI o en una celda de tabla, no.\n   */\n  compact?: boolean;\n}\n\nconst nf = (locale: string, decimals: number) =>\n  new Intl.NumberFormat(locale, {\n    minimumFractionDigits: decimals,\n    maximumFractionDigits: decimals,\n  });\n\n/**\n * A partir de qué magnitud se abrevia una cifra.\n *\n * <b>Mil millones, y no un millón como decía el diseño original.</b> Dos razones,\n * y la segunda es de corrección, no de gusto:\n *\n *  1. <b>En pesos, los millones son cotidianos.</b> Diez millones de pesos son unos\n *     USD 2.500: una factura normal, no una cifra grande. Abreviar ahí le quita\n *     precisión a un número que el usuario lee exacto todo el día — y `500 K` en\n *     lugar de `500.000` no le ahorra nada a nadie. Peor aún con una TRM de 3.118,\n *     que abreviada a `3 K` deja de significar lo que significa.\n *  2. <b>La escala corta y la larga no coinciden.</b> En español un *billón* es\n *     10¹², no 10⁹, así que escribir \"5,23 B\" para cinco mil millones es\n *     sencillamente falso para quien lee en español — que es justo lo que hacía la\n *     versión anterior de esta función, con sus sufijos K/M/B escritos a mano.\n */\nconst ABBREVIATE_FROM = 1e9;\n\n/**\n * Formateador compacto del locale.\n *\n * <b>La abreviatura la pone `Intl`, no nosotros.</b> Es lo que garantiza que el\n * sufijo sea el correcto en cada idioma: para 5.230.000.000, `es-CO` produce\n * `5230 M` —escala larga— y `en-US` produce `5.23B`. Codificar esa regla a mano es\n * exactamente el error que se está corrigiendo.\n */\nconst compactNf = (locale: string) =>\n  new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 2 });\n\n/** Separa el sufijo de magnitud del número, para poder pintarlos a tamaños distintos. */\nfunction splitCompact(formatted: string): { number: string; scale: string | null } {\n  // El compacto del locale viene como \"5230 M\", \"10 M\" o \"3,12 K\": el sufijo es lo\n  // que quede después del último dígito.\n  const match = formatted.match(/^([\\d.,\\s-]+?)\\s*([^\\d.,\\s]+)$/);\n  if (!match) return { number: formatted, scale: null };\n  return { number: match[1].trim(), scale: match[2] };\n}\n\n/**\n * Parte una cifra en símbolo + número + magnitud.\n *\n * Por debajo de {@link ABBREVIATE_FROM} devuelve la cifra completa con sus\n * separadores de miles: en un ERP eso es lo que se espera leer.\n */\nexport function abbreviate(value: number, options: AbbreviateOptions = {}): AbbreviatedValue {\n  const { currency = null, integer = false, locale = DEFAULT_LOCALE, compact = false } = options;\n\n  if (!Number.isFinite(value)) {\n    return { symbol: currency, number: '—', scale: null };\n  }\n\n  const abs = Math.abs(value);\n  // Los conteos nunca se abrevian: \"20 pedidos\" no se lee mejor como \"20\".\n  const shouldAbbreviate = !integer && (compact ? abs >= 1_000 : abs >= ABBREVIATE_FROM);\n\n  if (!shouldAbbreviate) {\n    return { symbol: currency, number: nf(locale, 0).format(Math.round(value)), scale: null };\n  }\n\n  const { number, scale } = splitCompact(compactNf(locale).format(value));\n  return { symbol: currency, number, scale };\n}\n\n/**\n * La cifra abreviada como una sola cadena.\n *\n * Para donde no se puede componer con varios elementos: ejes de gráficos,\n * tooltips, el centro de una dona.\n */\nexport function formatCompact(value: number, options: AbbreviateOptions = {}): string {\n  // `compact: true` va DESPUÉS del spread: es la razón de existir de esta función y no algo que\n  // el llamador pueda apagar por accidente pasando `compact: undefined` en el objeto de opciones.\n  const { symbol, number, scale } = abbreviate(value, { ...options, compact: true });\n  return `${symbol ? symbol + ' ' : ''}${number}${scale ? ' ' + scale : ''}`;\n}\n\n/**\n * La cifra completa, sin abreviar.\n *\n * Es lo que va en el `title` del número y en las celdas de tabla: donde el\n * usuario compara magnitudes exactas, abreviar le quita justo lo que busca.\n */\nexport function formatExact(\n  value: number,\n  options: { currency?: string | null; decimals?: number; locale?: string } = {},\n): string {\n  const { currency = null, decimals = 0, locale = DEFAULT_LOCALE } = options;\n  if (!Number.isFinite(value)) return '—';\n  return `${currency ? currency + ' ' : ''}${nf(locale, decimals).format(value)}`;\n}\n\n/** Porcentaje con un decimal. El signo lo pone quien pinta, junto con el icono de tendencia. */\nexport function formatPercent(value: number, locale: string = DEFAULT_LOCALE): string {\n  if (!Number.isFinite(value)) return '—';\n  return `${nf(locale, 1).format(value)} %`;\n}\n\n/**\n * Fecha en formato de negocio: `19 ago 2026`.\n *\n * Nunca ISO crudo. Una fecha de máquina en una tabla que lee un gerente es un\n * detalle de implementación que se escapó a la pantalla.\n */\nexport function formatDate(value: string | Date, locale: string = DEFAULT_LOCALE): string {\n  const date = value instanceof Date ? value : new Date(value);\n  if (Number.isNaN(date.getTime())) return '—';\n\n  /**\n   * <b>Se formatea en UTC, y no es un detalle.</b> Una fecha sin hora —`2026-08-19`,\n   * que es como las manda el backend— se parsea como medianoche UTC; al pintarla en\n   * la zona local (UTC-5 en Colombia) retrocede al día anterior, y la tabla mostraba\n   * \"18 de ago\" para un dato del 19.\n   *\n   * Estas fechas son de negocio, no instantes: la fecha de una entrada de inventario\n   * es la misma en Bogotá que en Madrid.\n   */\n  const hasTime = value instanceof Date\n    || /[T ]\\d{2}:/.test(String(value));\n\n  return date\n    .toLocaleDateString(locale, {\n      day: 'numeric', month: 'short', year: 'numeric',\n      ...(hasTime ? {} : { timeZone: 'UTC' }),\n    })\n    .replace(/\\./g, '');\n}\n\n/**\n * Estilo obligatorio de todo número que se refresque en vivo.\n *\n * `tabular-nums` fija el ancho de los dígitos: sin él, un `1` ocupa menos que un `8` y la cifra\n * se desplaza en cada refresco.\n *\n * <b>El tracking de las cifras grandes del KPI NO va aquí</b> —aunque este comentario lo dijera—:\n * lo decide el contenedor con `--dash-kpi-tracking`, porque el mismo componente se pinta a tres\n * tamaños (compacto, ampliado y modo presentación) y el interletraje correcto depende del tamaño.\n */\nexport const NUMERIC_STYLE = {\n  fontVariantNumeric: 'tabular-nums',\n} as const;\n\n/** @deprecated Usar {@link NUMERIC_STYLE}: son exactamente el mismo estilo. */\nexport const KPI_VALUE_STYLE = NUMERIC_STYLE;\n","import type { FetchProxyPayload, DashboardFetcher, SchemaField } from '../types';\n\nexport interface EndpointMeta {\n  generatedAt?: string;\n  period?: string;\n  rowCount?: number;\n}\n\nexport interface ProxyFetchResult {\n  data: unknown;\n  schema: { fields: SchemaField[] } | null;\n  endpointMeta: EndpointMeta | null;\n}\n\n/**\n * Solicita datos de un widget al Proxy del backend.\n * Retorna data + schema (si el endpoint devolvió envelope estándar).\n */\nexport const fetchWidgetDataProxy = async (\n  payload: FetchProxyPayload,\n  fetcher: DashboardFetcher\n): Promise<ProxyFetchResult> => {\n  const response = await fetcher<{\n    source: string;\n    timestamp: string;\n    data: unknown;\n    schema?: { fields: SchemaField[] };\n    endpointMeta?: EndpointMeta;\n  }>('/api/dashboard/proxy/fetch', {\n    method: 'POST',\n    body: payload,\n  });\n\n  // Validación defensiva: el proxy puede devolver estructura inesperada si el backend cambia\n  if (response === null || response === undefined || typeof response !== 'object') {\n    console.error('[KPI Dashboard] Proxy devolvió respuesta inválida:', response);\n    return { data: null, schema: null, endpointMeta: null };\n  }\n\n  if ((response as Record<string, unknown>).data === undefined) {\n    console.warn('[KPI Dashboard] Proxy response sin campo \"data\". Widget:', payload.widgetId);\n  }\n\n  return {\n    data: response.data ?? null,\n    schema: response.schema ?? null,\n    endpointMeta: response.endpointMeta ?? null,\n  };\n};\n\n/**\n * Invalida la caché del proxy para un widget.\n * DELETE /api/dashboard/proxy/cache/:widgetId\n */\nexport const invalidateWidgetCache = async (\n  widgetId: string,\n  fetcher: DashboardFetcher\n): Promise<void> => {\n  await fetcher(`/api/dashboard/proxy/cache/${widgetId}`, { method: 'DELETE' });\n};\n","import type { DashboardFetcher, DashboardPeriod, SchemaField } from '../types';\nimport type { EndpointMeta } from './dashboardProxy';\nimport { fetchWidgetDataProxy } from './dashboardProxy';\n\n/**\n * La entrada de caché de los datos de un widget: su clave y cómo se construye su contenido.\n *\n * <b>Por qué existe este módulo.</b> Dos consumidores piden los datos de un mismo widget: el\n * propio widget (`useWidgetFetch`) y la fuente secundaria de un KPI (`useSecondarySource`, el\n * sparkline). Comparten clave <b>a propósito</b> —si el gráfico grande ya está en pantalla, el\n * sparkline no cuesta ninguna petición— y eso los obliga a guardar exactamente lo mismo.\n *\n * Ya se rompió una vez por la FORMA (uno guardaba el array pelado y el otro el envelope) y se\n * corrigió. Pero seguía roto por el CONTENIDO, que es más difícil de ver: `useWidgetFetch`\n * aplicaba `field_mapping.rename` dentro de su `queryFn` y la fuente secundaria no, así que si el\n * sparkline ganaba la carrera el gráfico grande leía la entrada <b>sin renombrar</b> y sus\n * `valueKeys` no existían en las filas. El `queryFn` del que pierde la carrera no se ejecuta\n * nunca, así que su transformación tampoco.\n *\n * Teniendo la clave y el contenido en un solo sitio, no pueden volver a divergir.\n */\n\n/** Parámetros extra del proxy. Primitivos, como los admite su DTO. */\nexport type WidgetUserParams = Record<string, string | number | boolean>;\n\nexport interface CachedWidgetEnvelope<T = unknown> {\n  data: T;\n  schema: { fields: SchemaField[] } | null;\n  meta: EndpointMeta | null;\n}\n\n/**\n * La clave de caché de los datos de un widget.\n *\n * <b>`userParams` forma parte de la identidad de la petición</b>, porque cambia la respuesta:\n * un `{ points: 7 }` devuelve siete puntos. Sin ellos en la clave, el sparkline y el gráfico\n * grande compartían entrada pidiendo cosas distintas y ganaba el que resolviera primero.\n *\n * Cuando no hay `userParams` la clave queda IDÉNTICA a la de siempre — que es justo el objetivo:\n * compartir la entrada cuando la petición es la misma, y separarla cuando no lo es.\n */\nexport function widgetDataQueryKey(\n  widgetId: string | undefined,\n  period: DashboardPeriod,\n  userParams?: WidgetUserParams,\n): unknown[] {\n  const base = ['widget-data', widgetId, period];\n  return userParams && Object.keys(userParams).length > 0 ? [...base, userParams] : base;\n}\n\n/** Accede a un valor anidado vía dot-notation (`name.common` → `obj.name.common`). */\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n  return path.split('.').reduce<unknown>((acc, key) =>\n    acc != null && typeof acc === 'object' ? (acc as Record<string, unknown>)[key] : undefined, obj);\n}\n\n/** Aplica `field_mapping.rename`: expone cada campo del endpoint con el nombre que el widget espera. */\nexport function applyFieldMapping(data: unknown, mapping: Record<string, string>): unknown {\n  const entries = Object.entries(mapping);\n  if (entries.length === 0) return data;\n\n  if (process.env.NODE_ENV === 'development') {\n    const sample = Array.isArray(data) ? data[0] : data;\n    if (sample && typeof sample === 'object') {\n      for (const [, apiField] of entries) {\n        const topLevelField = apiField.split('.')[0];\n        if (!(topLevelField in (sample as object))) {\n          // eslint-disable-next-line no-console\n          console.warn(\n            `[KPI Dashboard] field_mapping.rename: el campo \"${apiField}\" no existe en la respuesta del endpoint. ` +\n            `Verificar que el nombre coincida exactamente con el campo devuelto por la API.`\n          );\n        }\n      }\n    }\n  }\n\n  const mapObject = (obj: Record<string, unknown>): Record<string, unknown> => {\n    const result: Record<string, unknown> = { ...obj };\n    for (const [widgetField, apiField] of entries) {\n      const val = apiField.includes('.') ? getNestedValue(obj, apiField) : obj[apiField];\n      if (val !== undefined) {\n        result[widgetField] = val;\n      }\n    }\n    return result;\n  };\n\n  if (Array.isArray(data)) {\n    return data.map(item =>\n      typeof item === 'object' && item !== null ? mapObject(item as Record<string, unknown>) : item\n    );\n  }\n  if (typeof data === 'object' && data !== null) {\n    return mapObject(data as Record<string, unknown>);\n  }\n  return data;\n}\n\n/**\n * El contenido EXACTO que se guarda bajo {@link widgetDataQueryKey}.\n *\n * Todo consumidor que comparta la clave tiene que llamar a esta función: es lo que garantiza que\n * la entrada de caché sea la misma sin importar quién gane la carrera.\n */\nexport async function fetchWidgetEnvelope<T>(\n  params: { widgetId: string; period: DashboardPeriod; userParams?: WidgetUserParams },\n  fieldMapping: Record<string, string> | undefined,\n  fetcher: DashboardFetcher,\n): Promise<CachedWidgetEnvelope<T>> {\n  const { data: raw, schema, endpointMeta } = await fetchWidgetDataProxy(\n    { widgetId: params.widgetId, period: params.period, userParams: params.userParams },\n    fetcher,\n  );\n  const mapped = fieldMapping && Object.keys(fieldMapping).length > 0\n    ? applyFieldMapping(raw, fieldMapping)\n    : raw;\n  return { data: mapped as T, schema, meta: endpointMeta };\n}\n","import type { IndicatorDirection } from './kpiDelta';\nimport type { TableColumn } from './tableColumns';\n\n/**\n * Lectura VALIDADA de `config_schema`.\n *\n * <b>El problema que resuelve.</b> `config_schema` llega del catálogo como dato sin forma, y los\n * widgets lo leían con un doble cast — `cfg as unknown as { direction?: …; format?: … }` — que\n * elude el sistema de tipos por completo. Con eso, un `direction: \"mayor\"`, un `columns` que no\n * es un array o un `criticalVolumeThreshold: \"5000\"` no producen un error localizable: producen\n * comportamiento indefinido en silencio, a veces varias capas más abajo.\n *\n * Aquí la tolerancia es <b>explícita y está en un solo sitio</b>: lo que no encaja se descarta y\n * se cae al valor por defecto, que es exactamente la degradación que el módulo ya promete para\n * los widgets sembrados que no declaran nada.\n */\n\n/** El `config_schema` de un widget, sin suponer nada de su contenido. */\nexport type WidgetConfig = Record<string, unknown> | undefined;\n\nexport function asConfig(config: unknown): WidgetConfig {\n  return config && typeof config === 'object' && !Array.isArray(config)\n    ? (config as Record<string, unknown>)\n    : undefined;\n}\n\n/** Formatos de cifra que el tablero sabe pintar. */\nconst FORMATS = ['number', 'currency', 'percent', 'integer'] as const;\nexport type ValueFormat = (typeof FORMATS)[number];\n\n/** El `format` declarado, o `undefined` si no lo declara o declara algo que no existe. */\nexport function readFormat(config: unknown): ValueFormat | undefined {\n  const value = asConfig(config)?.format;\n  return typeof value === 'string' && (FORMATS as readonly string[]).includes(value)\n    ? (value as ValueFormat)\n    : undefined;\n}\n\nconst DIRECTIONS = ['higher-is-better', 'lower-is-better', 'neutral'] as const;\n\n/**\n * La dirección deseable del indicador.\n *\n * `higher-is-better` por defecto, que es lo que hace que nada de lo ya sembrado cambie de\n * comportamiento al introducir esta propiedad.\n */\nexport function readDirection(config: unknown): IndicatorDirection {\n  const value = asConfig(config)?.direction;\n  return typeof value === 'string' && (DIRECTIONS as readonly string[]).includes(value)\n    ? (value as IndicatorDirection)\n    : 'higher-is-better';\n}\n\n/** Las columnas declaradas de una tabla, solo si son un array con la forma mínima esperada. */\nexport function readColumns(config: unknown): TableColumn[] | undefined {\n  const value = asConfig(config)?.columns;\n  if (!Array.isArray(value)) return undefined;\n  const validas = value.filter((c): c is TableColumn =>\n    Boolean(c) && typeof c === 'object'\n    && typeof (c as TableColumn).key === 'string'\n    && typeof (c as TableColumn).type === 'string');\n  return validas.length > 0 ? validas : undefined;\n}\n\n/** Un número positivo declarado en `config_schema`, o el respaldo. */\nexport function readPositiveNumber(config: unknown, key: string, fallback: number): number {\n  const value = asConfig(config)?.[key];\n  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\n/** Una cadena no vacía declarada en `config_schema`. */\nexport function readString(config: unknown, key: string): string | undefined {\n  const value = asConfig(config)?.[key];\n  return typeof value === 'string' && value.trim() !== '' ? value : undefined;\n}\n\n/** Un sub-objeto de `config_schema` (`series`, `image`), solo si de verdad es un objeto. */\nexport function readObject(config: unknown, key: string): Record<string, unknown> | undefined {\n  return asConfig(asConfig(config)?.[key]);\n}\n","import React, { Suspense, useContext, useState, useEffect, useMemo } from 'react';\nimport { useDashboardTranslation } from './i18n';\nimport { createPortal } from 'react-dom';\nimport { GripVertical, Maximize2, Minimize2, X, RefreshCw, AlertTriangle, Users } from 'lucide-react';\nimport { useIsFetching, useQueryClient } from '@tanstack/react-query';\nimport type { BaseWidgetProps } from '../components/DashboardEngine/types';\nimport type { DashboardPeriod } from './types';\nimport { WidgetErrorBoundary } from '../components/DashboardEngine/components/WidgetErrorBoundary';\nimport { WidgetSkeleton as ShapedSkeleton } from './components/WidgetSkeletons';\nimport { skeletonShapeFor } from './utils/skeletonShape';\nimport { useReducedMotion } from './utils/useReducedMotion';\nimport { DASHBOARD_LOCALE } from './utils/formatNumber';\nimport { widgetDataQueryKey } from './api/widgetEnvelope';\nimport { readPositiveNumber } from './utils/widgetConfig';\nimport { DashboardContext } from './useDashboardContext';\nimport { WidgetAccessDialog } from './access/WidgetAccessDialog';\n\ninterface WrapperProps extends BaseWidgetProps {\n  children: React.ReactNode;\n  onRemove?: (id: string) => void;\n}\n\n/**\n * Esqueleto genérico, conservado por compatibilidad.\n * @deprecated Usar `WidgetSkeleton` de `./components/WidgetSkeletons`, que respeta\n * la forma del widget. Este cae en la forma `generic`.\n */\nexport const WidgetSkeleton = () => <ShapedSkeleton shape=\"generic\" />;\n\n/**\n * Antigüedad del dato, en lenguaje relativo.\n *\n * Las claves llevan la plantilla completa (`hace {n} min` / `{n} min ago`) y no el\n * adverbio suelto: en español el \"hace\" va delante y en inglés el \"ago\" detrás, así\n * que componer la frase por partes produce \" 2 min\" en uno de los dos idiomas.\n */\nfunction formatTimestamp(ms: number, t: (key: string) => string): string {\n  if (!ms) return '';\n  const diff = Math.floor((Date.now() - ms) / 1000);\n  if (diff < 60) return t('dashboard.widget.justNow');\n  if (diff < 3600) return t('dashboard.widget.agoMinutes').replace('{n}', String(Math.floor(diff / 60)));\n  if (diff < 86400) return t('dashboard.widget.agoHours').replace('{n}', String(Math.floor(diff / 3600)));\n  return new Date(ms).toLocaleString(DASHBOARD_LOCALE, {\n    day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false,\n  });\n}\n\nexport const WidgetWrapper: React.FC<WrapperProps> = ({\n  preference,\n  definition,\n  isEditMode,\n  globalFilters,\n  onRemove,\n  children\n}) => {\n  const { t } = useDashboardTranslation();\n  const [isMaximized, setIsMaximized] = useState(false);\n  const reducedMotion = useReducedMotion();\n\n  // ── Refresh manual: observar la query del widget via cache ──\n  const queryClient = useQueryClient();\n  // Por el constructor compartido y no a mano: si la forma de la clave cambia, este observador\n  // la sigue. Escrita a mano, dejaría de encontrar la entrada sin que nada avisara.\n  // Memorizada para poder declararla en las deps del efecto sin que este se re-ejecute en cada\n  // render: sus entradas son exactamente las que ya estaban en el array de dependencias.\n  const period = globalFilters?.period as DashboardPeriod | undefined;\n  const queryKey = useMemo(\n    () => widgetDataQueryKey(definition.widget_id, period as DashboardPeriod),\n    [definition.widget_id, period],\n  );\n\n  // Reactivo: true si la query con este key está en curso\n  const isRefetching = useIsFetching({ queryKey }) > 0;\n\n  // Reactivo: timestamp + data length via suscripción al cache\n  const [dataUpdatedAt, setDataUpdatedAt] = useState(0);\n  const [dataLength, setDataLength] = useState(0);\n  const [, forceRender] = useState(0);\n  useEffect(() => {\n    let isMounted = true;\n\n    const readState = () => {\n      if (!isMounted) return;\n      const state = queryClient.getQueryState(queryKey);\n      const cachedResult = queryClient.getQueryData<{\n        data: unknown;\n        schema: unknown;\n        meta: { generatedAt?: string; rowCount?: number } | null;\n      }>(queryKey);\n\n      // Timestamp: preferir meta.generatedAt del envelope, fallback a React Query timestamp\n      const generatedAt = cachedResult?.meta?.generatedAt\n        ? new Date(cachedResult.meta.generatedAt).getTime()\n        : null;\n      const ts = generatedAt ?? (state?.dataUpdatedAt ?? 0);\n      setDataUpdatedAt(prev => ts !== prev ? ts : prev);\n\n      // Volumen: preferir rowCount del envelope (autoritativo), fallback a length del array\n      const rowCount = cachedResult?.meta?.rowCount\n        ?? (Array.isArray(cachedResult?.data) ? (cachedResult.data as unknown[]).length : 0);\n      setDataLength(rowCount);\n    };\n\n    readState();\n    const unsubscribe = queryClient.getQueryCache().subscribe(readState);\n    const tick = setInterval(() => { if (isMounted) forceRender(n => n + 1); }, 30_000);\n\n    return () => {\n      isMounted = false;\n      unsubscribe();\n      clearInterval(tick);\n    };\n  }, [queryClient, queryKey]);\n\n  // Umbral de volumen configurable por widget via config_schema. Default: 5000 registros.\n  // Validado: un `\"5000\"` en texto o un valor negativo caen al respaldo en vez de comparar basura.\n  const criticalVolume = readPositiveNumber(\n    (definition as unknown as Record<string, unknown>).config_schema,\n    'criticalVolumeThreshold',\n    5000,\n  );\n  const isHighVolume = dataLength > criticalVolume;\n\n  const handleRefresh = (e: React.MouseEvent) => {\n    e.stopPropagation();\n    queryClient.refetchQueries({ queryKey });\n  };\n\n  const handleRemove = (e: React.MouseEvent) => {\n    e.stopPropagation();\n    if (onRemove) onRemove(preference.id);\n  };\n\n  const title = (preference.config_json?.title as string) || definition.nombre;\n\n  /**\n   * Subtítulo: periodo y antigüedad del dato.\n   *\n   * El periodo baja aquí desde el cuerpo del widget, donde se repetía junto al\n   * título — \"Ventas del periodo\" arriba y \"Ventas del periodo (Semana)\" abajo.\n   * Dos líneas para decir lo mismo, robándole el espacio a la cifra.\n   */\n  const freshness = formatTimestamp(dataUpdatedAt, t);\n  const subtitle = [period, freshness].filter(Boolean).join(' · ');\n\n  /**\n   * Los tres botones del header.\n   *\n   * <b>Ocultos hasta hover, foco o táctil</b>, con `opacity` y NO con `display`: si\n   * salieran del flujo, el header cambiaría de alto al pasar el mouse y el contenido\n   * saltaría. `group-focus-within` es lo que los revela a quien navega con teclado,\n   * y `[@media(hover:none)]` lo que los deja fijos en tablet — donde no hay hover\n   * que valga y esconderlos sería esconderlos para siempre.\n   */\n  const chromeButtonClass = 'p-1 rounded transition-colors hover:text-[var(--dash-accent)]';\n\n  /**\n   * 🔴 El botón de acceso, y las tres condiciones que lo hacen aparecer.\n   *\n   * Se pinta solo si (1) el host proveyó un adaptador —sin modelo de acceso por instancia no hay\n   * nada que ofrecer—, (2) el SERVIDOR concedió el verbo correspondiente sobre ESTE widget, y (3) por\n   * tanto nunca a partir de un `isAdmin` global. `can_share` abre la pestaña de personas y `can_edit`\n   * la de política: con cualquiera de las dos el diálogo tiene contenido, sin ninguna sobra el botón.\n   *\n   * <para>Vive en el cromo de la tarjeta —oculto hasta hover, como sus vecinos— porque el sitio\n   * natural para compartir algo es la cosa misma. La pantalla de revisión, transversal, es para lo\n   * contrario: auditar lo repartido sin ir widget por widget.</para>\n   */\n  // 🔴 Se lee el contexto CRUDO y no con `useDashboardContext()`: ese hook LANZA cuando no hay\n  // provider, y la tarjeta se monta sola —en los tests del contenedor y en un host que arme piezas\n  // del tablero por separado, que el propio contexto declara soportado—. Un adaptador opcional no\n  // puede convertir el provider en obligatorio.\n  const accessAdapter = useContext(DashboardContext)?.accessAdapter;\n  const [isAccessOpen, setIsAccessOpen] = useState(false);\n  const puedeAbrirAcceso =\n    !!accessAdapter &&\n    (definition.permissions?.can_share === true || definition.permissions?.can_edit === true);\n\n  const accessButton = puedeAbrirAcceso ? (\n    <button\n      onClick={(e) => { e.stopPropagation(); setIsAccessOpen(true); }}\n      className={chromeButtonClass}\n      style={{ color: 'var(--dash-text-muted)' }}\n      title={t('dashboard.access.dialogTitle')}\n      aria-label={t('dashboard.access.dialogTitle')}\n      data-testid=\"widget-access-button\"\n    >\n      <Users className=\"w-3.5 h-3.5\" />\n    </button>\n  ) : null;\n\n  const refreshButton = (\n    <button\n      onClick={handleRefresh}\n      className={chromeButtonClass}\n      style={{ color: 'var(--dash-text-muted)' }}\n      title={t('dashboard.widget.refresh')}\n      aria-label={t('dashboard.widget.refresh')}\n    >\n      <RefreshCw className={`w-3.5 h-3.5 ${isRefetching && !reducedMotion ? 'animate-spin' : ''}`} />\n    </button>\n  );\n\n  const widgetContent = (\n    <WidgetErrorBoundary widgetId={definition.widget_id}>\n      <Suspense fallback={<ShapedSkeleton shape={skeletonShapeFor(definition.tipo)} reducedMotion={reducedMotion} />}>\n        {children}\n      </Suspense>\n    </WidgetErrorBoundary>\n  );\n\n  /**\n   * El aviso de alto volumen queda FUERA del bloque de cromo, a propósito: es una\n   * advertencia, no una acción, y una advertencia que sólo aparece en hover no\n   * advierte de nada.\n   */\n  const highVolumeBadge = isHighVolume ? (\n    <span\n      className=\"p-1 flex-shrink-0\"\n      style={{ color: 'var(--dash-danger)' }}\n      title={t('dashboard.widget.highVolume').replace('{count}', dataLength.toLocaleString(DASHBOARD_LOCALE))}\n      data-testid=\"widget-high-volume\"\n    >\n      <AlertTriangle className=\"w-3.5 h-3.5\" />\n    </span>\n  ) : null;\n\n  return (\n    <>\n      <div\n        className=\"group w-full h-full flex flex-col rounded-[12px] overflow-hidden transition-shadow duration-200 border\"\n        style={{\n          background: 'var(--dash-surface-card)',\n          borderColor: 'var(--dash-border)',\n          // Sombra mínima en reposo: sin ella la tarjeta se lee como una celda de\n          // tabla y no como un objeto. No hay `transform` en hover — una tarjeta\n          // que se mueve al pasar el mouse desordena la lectura de la grilla.\n          boxShadow: '0 1px 2px rgba(16,24,40,.04)',\n        }}\n        data-testid={`widget-card-${definition.widget_id}`}\n      >\n        {/* Cabecera */}\n        <div\n          className={`flex items-start justify-between gap-2 px-4 pt-3 pb-2 ${isEditMode ? 'cursor-move drag-handle' : ''}`}\n        >\n          <div className=\"flex items-start gap-2 overflow-hidden min-w-0\">\n            {isEditMode && (\n              <GripVertical\n                className=\"w-4 h-4 flex-shrink-0 mt-0.5\"\n                style={{ color: 'var(--dash-text-muted)' }}\n              />\n            )}\n            <div className=\"min-w-0\">\n              {/* Un solo título. El icono de info que iba aquí se retiró: no era\n                  accionable y competía con la etiqueta por el mismo renglón. */}\n              {/* 15px y semibold: a 13px/medium el titulo se perdia contra la cifra,\n                  que es lo unico que compite con el en la tarjeta. */}\n              <h3\n                className=\"text-[15px] font-semibold truncate leading-tight\"\n                style={{ color: 'var(--dash-text-primary)' }}\n                title={title}\n              >\n                {title}\n              </h3>\n              {subtitle && (\n                <p\n                  className=\"text-[11px] truncate leading-tight mt-0.5\"\n                  style={{ color: 'var(--dash-text-muted)' }}\n                  data-testid=\"widget-subtitle\"\n                >\n                  {subtitle}\n                </p>\n              )}\n            </div>\n          </div>\n\n          <div className=\"flex items-start gap-0.5 flex-shrink-0\">\n            {highVolumeBadge}\n            <div\n              className=\"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100 transition-opacity duration-[120ms] ease-out\"\n              data-testid=\"widget-chrome\"\n            >\n              {accessButton}\n              {refreshButton}\n              <button\n                onClick={(e) => { e.stopPropagation(); setIsMaximized(true); }}\n                className={chromeButtonClass}\n                style={{ color: 'var(--dash-text-muted)' }}\n                title={t('dashboard.widget.maximize')}\n                aria-label={t('dashboard.widget.maximize')}\n              >\n                <Maximize2 className=\"w-3.5 h-3.5\" />\n              </button>\n              <button\n                onClick={handleRemove}\n                className={chromeButtonClass}\n                style={{ color: 'var(--dash-text-muted)' }}\n                title={t('dashboard.widget.remove')}\n                aria-label={t('dashboard.widget.remove')}\n              >\n                <X className=\"w-3.5 h-3.5\" />\n              </button>\n            </div>\n          </div>\n        </div>\n\n        {/* Cuerpo — oculto cuando está maximizado (el portal lo muestra en fullscreen) */}\n        <div className={`flex-1 overflow-hidden relative transition-opacity duration-300 ${isRefetching ? 'opacity-60' : ''} ${isMaximized ? 'invisible' : ''}`}>\n          {widgetContent}\n        </div>\n      </div>\n\n      {/* Modal maximizado */}\n      {isMaximized && createPortal(\n        <div className=\"fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 md:p-8\">\n          <div\n            className=\"w-full h-full max-w-7xl max-h-[90vh] rounded-xl shadow-2xl flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200\"\n            style={{ background: 'var(--dash-surface-card)' }}\n          >\n            <div\n              className=\"flex items-center justify-between px-5 py-3 border-b\"\n              style={{ borderColor: 'var(--dash-border)' }}\n            >\n              <div className=\"min-w-0\">\n                <h3 className=\"text-lg font-semibold truncate\" style={{ color: 'var(--dash-text-primary)' }}>\n                  {title}\n                </h3>\n                {subtitle && (\n                  <p className=\"text-[11px] truncate mt-0.5\" style={{ color: 'var(--dash-text-muted)' }}>\n                    {subtitle}\n                  </p>\n                )}\n              </div>\n              <div className=\"flex items-center gap-2 flex-shrink-0\">\n                {highVolumeBadge}\n                {refreshButton}\n                {/* Cerrar no está aquí a propósito: borrar desde el modal deja al\n                    usuario mirando un widget que ya no existe. */}\n                <button\n                  onClick={(e) => { e.stopPropagation(); setIsMaximized(false); }}\n                  className=\"p-1.5 rounded-md transition-colors hover:text-[var(--dash-accent)]\"\n                  style={{ color: 'var(--dash-text-secondary)' }}\n                  title={t('dashboard.widget.minimize')}\n                  aria-label={t('dashboard.widget.minimize')}\n                >\n                  <Minimize2 className=\"w-5 h-5\" />\n                </button>\n              </div>\n            </div>\n            {/* `dash-expanded` sube la escala del contenido escalar y lo centra:\n                ampliar cambia la DENSIDAD, no solo el tamaño del contenedor. */}\n            <div className={`dash-expanded flex-1 overflow-auto relative p-4 transition-opacity duration-300 ${isRefetching ? 'opacity-60' : ''}`}>\n              {widgetContent}\n            </div>\n          </div>\n        </div>,\n        document.body\n      )}\n\n      {/* El diálogo de acceso. Se monta solo cuando hace falta y el host proveyó el adaptador. */}\n      {accessAdapter && isAccessOpen && (\n        <WidgetAccessDialog\n          widget={definition}\n          adapter={accessAdapter}\n          isOpen\n          onClose={() => setIsAccessOpen(false)}\n          // Cambiar el acceso puede sacar este widget del catálogo de quien lo cambió —restringirlo\n          // sin darse un grant, o exigir una clase que no tiene— así que hay que refrescar lo que la\n          // pantalla cree saber. `refetchQueries` sin clave recarga el catálogo y los datos.\n          onChanged={() => { void queryClient.refetchQueries(); }}\n        />\n      )}\n    </>\n  );\n};\n","import React from 'react';\nimport type { WidgetProps } from '../types';\nimport { getCompatibleTypes } from '../types';\nimport { WidgetWrapper } from '../WidgetWrapper';\n\n/**\n * Registro por tipo de widget (WidgetDefinition.tipo).\n * Resuelve el componente correcto según el tipo del widget en BD.\n * Para widgets custom por ID, el host puede inyectar un registro adicional\n * via la prop customWidgetRegistry de DashboardPage.\n */\nconst typeRegistry: Record<string, React.LazyExoticComponent<React.FC<WidgetProps>>> = {\n  'kpi': React.lazy(() => import('../widgets/KpiVentasHoy')),\n  'chart_line': React.lazy(() => import('../widgets/ChartLine')),\n  'chart_bar_vertical': React.lazy(() => import('../widgets/ChartVentasMensual')),\n  'chart_bar_horizontal': React.lazy(() => import('../widgets/ChartBarHorizontal')),\n  'chart_donut': React.lazy(() => import('../widgets/ChartDonut')),\n  'table': React.lazy(() => import('../widgets/TableStockCritico')),\n  'image': React.lazy(() => import('../widgets/StaticImageWidget')),\n};\n\nexport type WidgetRegistry = Record<string, React.LazyExoticComponent<React.FC<WidgetProps>>>;\n\nexport interface LazyWidgetProps extends WidgetProps {\n  onRemove?: (id: string) => void;\n  /** Registro custom del host: mapea widget_id → componente React. */\n  customWidgetRegistry?: WidgetRegistry;\n}\n\n/**\n * Componente que se encarga de resolver dinámicamente qué archivo React\n * cargar basado en el `widgetId` que viene de la BD.\n * Si el usuario tiene un override de chartType en config_json (panel de personalización),\n * se usa ese tipo siempre que sea compatible con la familia del tipo original.\n */\nexport const LazyWidget: React.FC<LazyWidgetProps> = (props) => {\n  const { definition, preference, customWidgetRegistry } = props;\n\n  // Override de tipo desde config_json del usuario (panel de personalización)\n  const overrideType = preference.config_json?.chartType as string | undefined;\n  const effectiveType = overrideType && getCompatibleTypes(definition.tipo).includes(overrideType)\n    ? overrideType\n    : definition.tipo;\n\n  const Component = customWidgetRegistry?.[definition.widget_id] ?? typeRegistry[effectiveType];\n\n  // Si el widget no está registrado en el mapa (ej. no existe el archivo), mostramos un fallback seguro\n  if (!Component) {\n    return (\n      <WidgetWrapper {...props} globalFilters={{ period: props.period }}>\n        <div className=\"flex items-center justify-center h-full p-4 text-center\">\n          <p className=\"text-sm text-gray-500\">\n            Widget <span className=\"font-semibold text-gray-700\">\"{definition.widget_id}\"</span> no disponible o archivo no encontrado.\n          </p>\n        </div>\n      </WidgetWrapper>\n    );\n  }\n\n  // Componente válido encontrado en el registro dinámico\n  return (\n    <WidgetWrapper {...props} globalFilters={{ period: props.period }}>\n      <Component {...props} />\n    </WidgetWrapper>\n  );\n};\n","import React from 'react';\nimport type { DashboardFetcher, WidgetDefinition } from './types';\nimport type { WidgetAccessAdapter } from './access/types';\nimport { DashboardContext } from './useDashboardContext';\n\n/**\n * Provider del tablero: inyecta el fetcher del host y el catálogo de widgets.\n *\n * El contexto y su hook de lectura viven en `useDashboardContext.ts` — ver el porqué allí.\n * Este módulo exporta SOLO el componente, que es lo que `react-refresh` necesita.\n */\nexport const DashboardProvider: React.FC<{\n  fetcher: DashboardFetcher;\n  catalog?: WidgetDefinition[];\n  /** Ver `DashboardContextValue.accessAdapter`. Sin él no se pinta ningún control de acceso. */\n  accessAdapter?: WidgetAccessAdapter;\n  children: React.ReactNode;\n}> = ({ fetcher, catalog, accessAdapter, children }) => (\n  <DashboardContext.Provider value={{ fetcher, catalog, accessAdapter }}>\n    {children}\n  </DashboardContext.Provider>\n);\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\n/**\n * <b>El modo presentación NO refresca los datos.</b>\n *\n * Tenía un auto-refresco global configurable, y se quitó por una razón de fondo:\n * cada widget ya se refresca solo con su propia `refresh_policy`, que es lo que le\n * puso quien lo creó. Un temporizador global dispara los ocho a la vez —una\n * estampida contra el proxy, cada una con su salto HTTP— y además pisa el ritmo que\n * cada indicador tenía configurado, que no tiene por qué ser el mismo: un stock\n * crítico y un consolidado de ventas no necesitan la misma frecuencia.\n *\n * Lo que este modo aporta es lo que el navegador no da solo: pantalla completa,\n * escala tipográfica y rotación entre categorías.\n */\n\n/** Cada cuánto rota entre categorías, cuando la rotación está activa. */\nexport const DEFAULT_ROTATE_SECONDS = 30;\n\ninterface UsePresentationModeOptions {\n  /** Se llama en cada rotación, con el índice de la siguiente categoría. */\n  onRotate?: (nextIndex: number) => void;\n  /** Cuántas categorías hay para rotar. Con menos de 2, no se rota. */\n  rotatableCount?: number;\n}\n\nexport interface PresentationMode {\n  isActive: boolean;\n  enter: () => void;\n  exit: () => void;\n  isRotating: boolean;\n  setRotating: (value: boolean) => void;\n  /** Ref del elemento que se lleva a pantalla completa. */\n  containerRef: React.RefObject<HTMLDivElement | null>;\n}\n\n/**\n * Modo presentación: el tablero a pantalla completa, para dejarlo en un monitor.\n *\n * <b>Usa la Fullscreen API del navegador y no un overlay propio.</b> El diseño pide\n * que se oculten \"navegación, breadcrumb y selector de compañía\", y esas tres cosas\n * son del HOST, no de este componente — el kit no las dibuja ni sabe que existen.\n * Pantalla completa sobre el contenedor del tablero las tapa todas sin que el host\n * tenga que cooperar en nada, y `Esc` sale de forma nativa.\n *\n * Funciona porque el host integra por single-spa y comparte el documento del shell.\n * Bajo una integración por iframe haría falta `allow=\"fullscreen\"` en el iframe, que\n * es una decisión del host; en ese caso `enter()` falla y el modo simplemente no se\n * activa, sin romper nada.\n */\nexport function usePresentationMode({\n  onRotate,\n  rotatableCount = 0,\n}: UsePresentationModeOptions = {}): PresentationMode {\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  const [isActive, setIsActive] = useState(false);\n  const [isRotating, setRotating] = useState(false);\n\n  const enter = useCallback(() => {\n    const element = containerRef.current;\n    if (!element?.requestFullscreen) {\n      // Sin soporte (o denegado por el contenedor): no se activa, y no se rompe nada.\n      return;\n    }\n    element.requestFullscreen().catch(() => {\n      /* El navegador puede rechazarla; el estado lo corrige el listener de abajo. */\n    });\n  }, []);\n\n  const exit = useCallback(() => {\n    if (document.fullscreenElement) void document.exitFullscreen().catch(() => {});\n  }, []);\n\n  /**\n   * El estado lo manda el NAVEGADOR, no nuestro botón: el usuario puede salir con\n   * `Esc` o con F11 sin pasar por la interfaz, y si guardáramos el estado por\n   * nuestra cuenta quedaría desincronizado.\n   */\n  useEffect(() => {\n    const onChange = () => setIsActive(document.fullscreenElement === containerRef.current);\n    document.addEventListener('fullscreenchange', onChange);\n    return () => document.removeEventListener('fullscreenchange', onChange);\n  }, []);\n\n  /** Rotación entre categorías. Con menos de dos no hay nada que rotar. */\n  useEffect(() => {\n    if (!isActive || !isRotating || !onRotate || rotatableCount < 2) return;\n\n    let index = 0;\n    const timer = setInterval(() => {\n      index = (index + 1) % rotatableCount;\n      onRotate(index);\n    }, DEFAULT_ROTATE_SECONDS * 1000);\n\n    return () => clearInterval(timer);\n  }, [isActive, isRotating, onRotate, rotatableCount]);\n\n  return { isActive, enter, exit, isRotating, setRotating, containerRef };\n}\n","import React, { useState, useMemo, useEffect, useCallback, useRef } from 'react';\nimport { LayoutTemplate, Loader2, Layers, Columns, LayoutGrid, AlertTriangle, Pencil, Monitor, Minimize2 } from 'lucide-react';\nimport { useWidgetEngine } from './hooks/useWidgetEngine';\nimport { useDashboardLayout } from './hooks/useDashboardLayout';\nimport { DashboardGrid } from './DashboardGrid';\nimport { WidgetManagerPanel } from './components/WidgetManagerPanel';\nimport { CustomizationWithSchema } from './components/WidgetCustomizationPanel';\nimport { findFirstAvailablePosition } from '../components/DashboardEngine/utils/gridEngine';\nimport { deleteWidget as deleteWidgetAPI } from './api/dashboardCatalog';\nimport type { DashboardPeriod, WidgetDefinition, UserWidgetPreference, DashboardFetcher } from './types';\nimport { LazyWidget } from './components/LazyWidget';\nimport type { WidgetRegistry } from './components/LazyWidget';\nimport { DashboardProvider } from './DashboardContext';\nimport type { WidgetAccessAdapter } from './access/types';\nimport { useDashboardTranslation } from './i18n';\nimport { usePresentationMode } from './utils/usePresentationMode';\nimport { DashboardCompanySelector, type DashboardCompany } from './components/DashboardCompanySelector';\nimport type { DashboardVocabularyTerm } from './types';\n\n/**\n * Clave que agrupa los widgets sin categoría. Es una CLAVE, no un texto: antes era el literal\n * `'Otros'`, que se pintaba igual en inglés porque nunca pasó por el motor de traducción.\n *\n * Vive en el módulo y no dentro del componente: es una constante, y declararla en el cuerpo la\n * recreaba en cada render y la dejaba fuera de las deps de los `useMemo` que la usan.\n */\nconst UNCATEGORIZED = '__uncategorized__';\n\ninterface DashboardPageProps {\n  /** Fetcher del host con autenticación y headers incluidos. */\n  fetcher: DashboardFetcher;\n  /** ID del usuario autenticado (del JWT del host). */\n  userId: string;\n  /** Roles del usuario autenticado (del JWT del host). */\n  userRoles: string[];\n  /** Muestra el selector de periodo (Hoy/Semana/Mes). Default false. */\n  showPeriodSelector?: boolean;\n  /** Permite crear widgets con endpoints externos en el Builder. Default false. */\n  showExternalEndpoints?: boolean;\n  /**\n   * Si la puerta del Constructor existe, separada de si ofrece fuentes externas. Sin valor cae a\n   * `showExternalEndpoints` — ningún host cambia de conducta. Ver `WidgetManagerPanel`.\n   */\n  showWidgetBuilder?: boolean;\n  /** Registro custom del host: mapea widget_id → componente React para widgets específicos. */\n  customWidgetRegistry?: WidgetRegistry;\n  /** Orden preferido de categorías en la vista cascada. Las no listadas van al final alfabéticamente. */\n  categoryOrder?: string[];\n  /**\n   * Vocabulario de segmentación que el Widget Builder ofrece al administrador, y que se guarda en\n   * `roles_permitidos` del widget.\n   *\n   * Debe ser EL MISMO que el backend del host entrega como `roles`: el catálogo se filtra cruzando\n   * ambos, así que si divergen el widget queda invisible para todos —incluido quien lo creó— sin\n   * error ni log.\n   *\n   * <b>Si se omite, la lista sale VACÍA</b> y el Widget Builder lo dice. Antes caía a\n   * `admin | ventas | compras | inventario` —el vocabulario de Siesa Comercial—, y un host de\n   * Financiero o Nómina terminaba segmentando con módulos que no son suyos, sin ningún aviso.\n   *\n   * El `id` es lo que se persiste: puede ser el código de permiso del RBAC del host.\n   */\n  /**\n   * 🔴 **RETIRADO el 2026-09-14 (F3.b.5).** Ver `WidgetManagerPanel`. El Constructor ya no pregunta\n   * la vertical, así que esta prop no llegaba a ningún sitio.\n   */\n  /**\n   * Vocabulario de categorías del host. `{ id, label }`: el `id` se persiste en `categoria` del\n   * widget y el `label` es lo que se pinta — esa separación es lo que permite traducirlas.\n   *\n   * Admite `string[]` por compatibilidad: cada elemento se toma como `id` y `label` a la vez, que\n   * es exactamente lo que hacía antes.\n   */\n  availableCategories?: Array<string | DashboardVocabularyTerm>;\n  /**\n   * Si el usuario administra el catálogo: puede borrar widgets que no sean semilla y —con\n   * `showExternalEndpoints`— conectar APIs externas.\n   *\n   * <b>Lo decide el host, y por eso es una prop.</b> Hasta ahora el kit lo deducía buscando el\n   * literal `'admin'` dentro de `userRoles`, que es justo lo que el resto de este módulo dejó de\n   * hacer: un host cuyo rol de administración se llame `nomina_admin` o `administrador` no lo\n   * activaba nunca. Y era una mina para el propio Comercial: el día que los ids pasen a ser códigos\n   * de permiso (`…dashboard.admin`), el literal deja de coincidir y el Widget Builder pierde sus\n   * funciones de administración <b>sin ningún error</b>.\n   *\n   * Si se omite, se conserva la deducción anterior por compatibilidad.\n   */\n  isAdmin?: boolean;\n\n  /**\n   * Capacidad de crear y editar definiciones de widget. Es lo que abre el Widget Builder.\n   *\n   * 🔴 Se separa de `isAdmin` porque son dos preguntas distintas y estaban colapsadas: un host\n   * cuyo backend gatea la escritura con una capacidad propia —y no con el permiso de\n   * administración— tenía la capacidad **inerte en la pantalla**, con el botón ausente para quien\n   * el API sí autorizaba. Sin valor cae a `isAdmin` y nada cambia.\n   */\n  canWriteWidgets?: boolean;\n\n  /**\n   * Capacidad de cambiar la EXPOSICION de un widget: a quien alcanza (`es_privado`,\n   * `roles_permitidos`) y con que autoridad se pide su dato (`is_internal`).\n   *\n   * 🔴 Separada tambien de `isAdmin`, y por un motivo mas duro que el de escribir: el backend la\n   * exige en el PATCH del catalogo, asi que un asistente que ofrezca el paso de permisos a quien no\n   * la tiene acaba en 403 -y, en la version anterior, mandaba `es_privado: true` sin decirlo y\n   * volvia privado un widget de modulo-. Sin valor cae a `isAdmin`.\n   */\n  canPublishWidgets?: boolean;\n\n  /**\n   * 🔴 El adaptador del **diálogo de acceso** por widget: quién ve este indicador y qué exige para\n   * verse. **Opcional**: sin él no se pinta ningún control de acceso y el tablero queda como estaba.\n   *\n   * <para>El kit no habla HTTP — recibe las operaciones y las llama. Quien las implementa contra su\n   * API vive en el host, igual que `IWidgetAccessPolicy` en el backend del componente: el modelo de\n   * acceso es del host, el formulario es del kit. Y todo lo que el diálogo ofrece sale de las\n   * capacidades que el adaptador declara, así que un host con un modelo más pequeño obtiene un\n   * formulario más pequeño en vez de casillas que su backend va a rechazar.</para>\n   */\n  accessAdapter?: WidgetAccessAdapter;\n  /**\n   * Titulo de la pantalla. El kit trae uno neutro (\"Tablero de indicadores\"); un host que quiera\n   * llamarlo por su producto lo declara aqui — el kit no puede saber si es Comercial, Financiero o\n   * Nomina, y hasta ahora decia \"Dashboard Comercial\" para todos.\n   */\n  title?: string;\n  /**\n   * Compañías entre las que el usuario puede cambiar.\n   *\n   * <b>Sin esta prop el tablero no dibuja selector</b>, y el host queda como estaba:\n   * puede seguir poniendo el suyo por fuera. Es lo que permite adoptarlo sin migrar\n   * de golpe.\n   *\n   * El tablero <b>no gestiona el alcance</b>: lo pinta y avisa del cambio. Quién es\n   * la compañía activa, cómo se persiste y qué cabecera se envía siguen siendo del\n   * host, que es quien tiene el contexto de sesión.\n   */\n  companies?: DashboardCompany[];\n  /** La compañía activa. La decide el host — ver la advertencia de abajo. */\n  selectedCompanyId?: string | null;\n  /**\n   * Se llama al elegir una compañía distinta.\n   *\n   * ⚠️ <b>El tablero NUNCA preselecciona por su cuenta.</b> Si no llega\n   * `selectedCompanyId`, el chip muestra su texto de marcador y no se dispara nada.\n   *\n   * Es la lección de `MasterCrud`: allí el kit preseleccionaba una compañía por\n   * defecto y <b>no</b> emitía el evento para esa elección silenciosa, así que host\n   * y kit discrepaban sobre cuál era la activa — y hubo que agregar\n   * `isSelectedByDefault` para salir del lío. Aquí no puede pasar: el kit no elige.\n   */\n  onCompanyChange?: (company: DashboardCompany) => void;\n  /**\n   * Opciones visibles pero no elegibles, con su motivo.\n   * `{ '000': 'Las compañías habilitadas manejan monedas distintas' }`\n   */\n  companyDisabledReasons?: Record<string, string>;\n}\n\nexport const DashboardPage: React.FC<DashboardPageProps> = ({\n  fetcher,\n  userId,\n  userRoles,\n  showPeriodSelector = false,\n  showExternalEndpoints = false,\n  showWidgetBuilder,\n  customWidgetRegistry,\n  categoryOrder,\n  availableCategories,\n  title,\n  isAdmin,\n  canWriteWidgets,\n  canPublishWidgets,\n  accessAdapter,\n  companies,\n  selectedCompanyId,\n  onCompanyChange,\n  companyDisabledReasons,\n}) => {\n  const { t } = useDashboardTranslation();\n\n  /** Acepta las dos formas de `availableCategories` y deja una sola por dentro. */\n  const categoryTerms = useMemo<DashboardVocabularyTerm[]>(\n    () => (availableCategories ?? []).map(c => (typeof c === 'string' ? { id: c, label: c } : c)),\n    [availableCategories],\n  );\n\n  /**\n   * Clave → etiqueta visible. Si el host no declaró la categoría, se pinta la clave tal cual: es\n   * lo que hacía antes y mantiene legibles los widgets creados con el modelo viejo, donde la clave\n   * ERA el texto.\n   */\n  const categoryLabel = useCallback(\n    (id: string) =>\n      id === UNCATEGORIZED\n        ? t('dashboard.category.uncategorized')\n        : categoryTerms.find(c => c.id === id)?.label ?? id,\n    [categoryTerms, t],\n  );\n\n  /** Solo los ids: es lo que consumen el Builder y el panel de personalización. */\n\n  // 1. Motor Global (Catálogo, Perfil, Filtros)\n  const esAdminDelCatalogo = isAdmin ?? userRoles.some(r => r.toLowerCase() === 'admin');\n  const engine = useWidgetEngine({ userId, userRoles, fetcher, isAdmin: esAdminDelCatalogo });\n\n  // 2. Layout Local (Sincronizado con BD vía Debounce)\n  const layoutManager = useDashboardLayout({\n    userId,\n    initialLayout: engine.initialLayout,\n    period: engine.period,\n    fetcher,\n  });\n\n  const [isManagerOpen, setIsManagerOpen] = useState(false);\n  const [customizingWidget, setCustomizingWidget] = useState<{\n    widget: WidgetDefinition;\n    preference?: UserWidgetPreference;\n  } | null>(null);\n  /**\n   * Las tres formas de organizar el tablero.\n   *\n   *  cascade  una seccion por categoria, una debajo de otra — todo de un vistazo\n   *  tabs     una pestana por categoria — para trabajar concentrado en un modulo\n   *  board    una sola grilla, sin encabezados — la vista de direccion\n   *\n   * `board` es nueva. NO reemplaza a la cascada: sustituirla habria borrado la\n   * segmentacion visual por modulo, que es lo que hace visible el trabajo de\n   * permisos — quien tiene ventas ve ventas.\n   */\n  const [viewMode, setViewMode] = useState<'cascade' | 'tabs' | 'board'>('cascade');\n  // Vacio: la primera categoria REAL lo corrige en el efecto de abajo. Antes arrancaba en\n  // 'Ventas', que en un host de Financiero o Nomina no existe — se auto-corregia, pero dejaba una\n  // categoria de otro producto escrita en el estado inicial de una libreria compartida.\n  const [activeTab, setActiveTab] = useState<string>('');\n  const [pendingRemoveId, setPendingRemoveId] = useState<string | null>(null);\n\n  // --- Lógica de Agrupación por Categorías ---\n  const layoutByCategory = useMemo(() => {\n    const groups: Record<string, UserWidgetPreference[]> = {};\n    \n    layoutManager.layout.forEach(pref => {\n      const def = engine.catalog.find(c => c.widget_id === pref.widget_id);\n      if (def) {\n        const cat = def.categoria || UNCATEGORIZED;\n        if (!groups[cat]) groups[cat] = [];\n        groups[cat].push(pref);\n      }\n    });\n    \n    return groups;\n  }, [layoutManager.layout, engine.catalog]);\n\n  const sortedCategories = useMemo(() => {\n    const categories = Object.keys(layoutByCategory);\n    // Sin `categoryOrder` no hay prioridad: se pintan alfabeticamente. El fallback anterior era\n    // ['Ventas','Compras','Inventario'] — inofensivo (se filtra por las que existen) pero era\n    // vocabulario de Comercial dentro del kit.\n    const prioritized = (categoryOrder ?? []).filter(c => categories.includes(c));\n    categories.sort().forEach(c => { if (!prioritized.includes(c)) prioritized.push(c); });\n    return prioritized;\n  }, [layoutByCategory, categoryOrder]);\n\n  /**\n   * Modo presentación: el tablero a pantalla completa, para dejarlo en un monitor.\n   *\n   * Usa la Fullscreen API y no un overlay propio porque lo que hay que ocultar\n   * —navegación, breadcrumb, selector de compañía— es del HOST, no de este\n   * componente: el kit no los dibuja ni sabe que existen. Ver `usePresentationMode`.\n   */\n  /** Las categorías, por referencia, para que la rotación no reinicie su temporizador\n      en cada render — depender del array lo recrearía constantemente. */\n  const categoriesRef = useRef<string[]>([]);\n  categoriesRef.current = sortedCategories;\n\n  const handleRotate = useCallback((index: number) => {\n    const next = categoriesRef.current[index];\n    if (next) {\n      setViewMode('tabs');\n      setActiveTab(next);\n    }\n  }, []);\n\n  /**\n   * Layout de la vista de tablero único.\n   *\n   * <b>Se recalculan las posiciones, no se reutilizan las guardadas.</b> Las\n   * coordenadas persistidas se calcularon POR CATEGORÍA, y cada categoría empieza en\n   * `y = 0`: juntarlas en una sola grilla dejaba widgets superpuestos y huecos\n   * enormes entre bloques que en su categoría eran contiguos.\n   *\n   * Aquí se reordena en el orden en que el usuario los tiene y se acomodan de\n   * izquierda a derecha, saltando de fila cuando no cabe el siguiente. La compactación\n   * vertical de la grilla termina de cerrar los huecos.\n   *\n   * <b>Y se descartan las preferencias sin definición en el catálogo</b>, en vez de\n   * pintar \"Widget desconocido\": eso pasa cuando un widget se desactiva del catálogo\n   * o el usuario pierde el permiso que lo concedía, y en los dos casos lo correcto es\n   * que desaparezca en silencio — no dejar una lápida en el tablero.\n   */\n  const boardLayout = useMemo(() => {\n    const COLS = 12;\n    let x = 0;\n    let y = 0;\n    let rowHeight = 0;\n\n    return layoutManager.layout\n      .filter(pref => engine.catalog.some(c => c.widget_id === pref.widget_id))\n      .map(pref => {\n        const w = Math.min(pref.col_span || 3, COLS);\n        if (x + w > COLS) {\n          x = 0;\n          y += rowHeight || 1;\n          rowHeight = 0;\n        }\n        const placed = { ...pref, pos_x: x, pos_y: y };\n        x += w;\n        rowHeight = Math.max(rowHeight, pref.row_span || 1);\n        return placed;\n      });\n  }, [layoutManager.layout, engine.catalog]);\n\n  const presentation = usePresentationMode({\n    onRotate: handleRotate,\n    rotatableCount: sortedCategories.length,\n  });\n\n  // Categorías únicas del catálogo completo (para el panel de personalización)\n  const catalogCategories = useMemo(() =>\n    [...new Set(engine.catalog.map(w => w.categoria).filter(Boolean))].sort(),\n    [engine.catalog]\n  );\n\n  useEffect(() => {\n    if (sortedCategories.length > 0 && !sortedCategories.includes(activeTab)) {\n      setActiveTab(sortedCategories[0]);\n    }\n  }, [sortedCategories, activeTab]);\n\n  const handleCategoryLayoutChange = (category: string, newCategoryLayout: UserWidgetPreference[]) => {\n    const otherCategoriesLayout = layoutManager.layout.filter(pref => {\n      const def = engine.catalog.find(c => c.widget_id === pref.widget_id);\n      const cat = def ? (def.categoria || UNCATEGORIZED) : UNCATEGORIZED;\n      return cat !== category;\n    });\n    layoutManager.updateLayout([...otherCategoriesLayout, ...newCategoryLayout]);\n  };\n\n  // Manejador para quitar un widget — solicita confirmación antes de eliminar\n  const handleRemoveWidget = (instanceId: string) => {\n    setPendingRemoveId(instanceId);\n  };\n\n  const confirmRemove = () => {\n    if (pendingRemoveId) {\n      layoutManager.updateLayout(layoutManager.layout.filter(w => w.id !== pendingRemoveId));\n      setPendingRemoveId(null);\n    }\n  };\n\n\n  if (engine.isLoading) {\n    return (\n      <div\n        className=\"flex flex-col items-center justify-center min-h-screen\"\n        style={{ background: 'var(--dash-surface-page)' }}\n      >\n        <Loader2 className=\"w-8 h-8 animate-spin mb-4\" style={{ color: 'var(--dash-accent)' }} />\n        <p className=\"font-medium\" style={{ color: 'var(--dash-text-secondary)' }}>{t('dashboard.chrome.loading')}</p>\n      </div>\n    );\n  }\n\n  if (engine.initError) {\n    return (\n      <div\n        className=\"flex flex-col items-center justify-center min-h-screen p-8\"\n        style={{ background: 'var(--dash-surface-page)' }}\n      >\n        <AlertTriangle className=\"w-12 h-12 mb-4\" style={{ color: 'var(--dash-danger)' }} />\n        <h2 className=\"text-lg font-semibold mb-2\" style={{ color: 'var(--dash-text-primary)' }}>{t('dashboard.chrome.loadError')}</h2>\n        <p className=\"text-sm text-center max-w-md\" style={{ color: 'var(--dash-text-secondary)' }}>{engine.initError}</p>\n        <button\n          onClick={() => window.location.reload()}\n          className=\"mt-6 px-4 py-2 text-white text-sm font-medium rounded-lg transition-opacity hover:opacity-90\"\n          style={{ background: 'var(--dash-accent)' }}\n        >\n          {t('dashboard.chrome.retry')}\n        </button>\n      </div>\n    );\n  }\n\n  return (\n    <DashboardProvider fetcher={fetcher} catalog={engine.catalog} accessAdapter={accessAdapter}>\n    <div\n      ref={presentation.containerRef}\n      className={`min-h-screen overflow-x-hidden relative ${presentation.isActive ? 'dash-presentation' : ''}`}\n      /*\n        Los tokens van INLINE y no en una clase: `bg-[#F4F6F8]` se emite en `@layer utilities` y\n        `.dash-presentation` vive en `@layer base`, así que la utilidad ganaba siempre y el fondo\n        del tablero se quedaba claro en modo oscuro (y la declaración `background` de\n        `.dash-presentation` era código muerto).\n      */\n      style={{ background: 'var(--dash-surface-page)', color: 'var(--dash-text-primary)' }}\n    >\n      {/* 1. Topbar Estricta según PRD */}\n      {/*\n        Alto MINIMO, no fijo: con el chip de compania bajo el titulo, 64px no dan\n        y el chip queda pegado al borde inferior. Con min-h la barra crece solo\n        cuando hay chip, y se ve igual que antes cuando no lo hay.\n      */}\n      <header\n        className=\"sticky top-0 z-40 border-b shadow-sm min-h-[64px] py-2.5 px-6 flex items-center justify-between gap-4\"\n        style={{ background: 'var(--dash-surface-card)', borderColor: 'var(--dash-border)' }}\n      >\n        <div className=\"flex items-center gap-4\">\n          <div\n            className=\"w-8 h-8 rounded-lg flex items-center justify-center\"\n            style={{ background: 'var(--dash-accent)' }}\n          >\n            <LayoutTemplate className=\"w-5 h-5 text-white\" />\n          </div>\n          <div className=\"flex flex-col gap-2 py-1.5\">\n            <h1 className=\"text-xl font-bold tracking-tight\">{title ?? t('dashboard.chrome.title')}</h1>\n            {/*\n              El chip va BAJO el título, dentro de la barra del tablero — no en una\n              franja propia por encima de la pantalla. Es el mismo control que el\n              maestro de Ítems, para que cambiar de compañía sea el mismo gesto en\n              las dos pantallas.\n\n              Sólo aparece si el host pasa compañías: sin la prop, el tablero se\n              comporta como antes y el host puede seguir con el suyo por fuera.\n            */}\n            {companies && companies.length > 0 && onCompanyChange && (\n              <DashboardCompanySelector\n                companies={companies}\n                selectedCompanyId={selectedCompanyId}\n                onCompanyChange={onCompanyChange}\n                optionDisabledReasons={companyDisabledReasons}\n              />\n            )}\n          </div>\n          \n          {layoutManager.isSaving && (\n            <span\n              className=\"ml-4 flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded-full\"\n              style={{ color: 'var(--dash-text-secondary)', background: 'var(--dash-surface-page)' }}\n            >\n              <Loader2 className=\"w-3 h-3 animate-spin\" /> {t('dashboard.chrome.saving')}\n            </span>\n          )}\n        </div>\n\n        <div className=\"flex items-center gap-4\">\n          {/*\n            Selector de vista — solo si hay MAS DE UNA categoria con widgets.\n\n            Con un solo modulo activo las tres vistas producen exactamente la misma\n            pantalla, y un control que no cambia nada es ruido.\n          */}\n          {sortedCategories.length > 1 && (\n            <>\n              <div className=\"flex items-center p-1 rounded-lg\" style={{ background: 'var(--dash-surface-page)' }}>\n                {([\n                  ['cascade', Layers, 'dashboard.chrome.viewCascade'],\n                  ['tabs', Columns, 'dashboard.chrome.viewTabs'],\n                  ['board', LayoutGrid, 'dashboard.chrome.viewBoard'],\n                ] as const).map(([mode, Icon, labelKey]) => (\n                  <button\n                    key={mode}\n                    onClick={() => setViewMode(mode)}\n                    className=\"p-1.5 rounded transition-all\"\n                    style={viewMode === mode\n                      ? { background: 'var(--dash-surface-card)', color: 'var(--dash-accent)', boxShadow: '0 1px 2px rgba(16,24,40,.06)' }\n                      : { color: 'var(--dash-text-muted)' }}\n                    title={t(labelKey)}\n                    aria-pressed={viewMode === mode}\n                  >\n                    <Icon className=\"w-4 h-4\" />\n                  </button>\n                ))}\n              </div>\n\n              <div className=\"w-px h-8 mx-1\" style={{ background: 'var(--dash-border)' }}></div>\n            </>\n          )}\n\n          {/* Modo presentación */}\n          {presentation.isActive ? (\n            <div className=\"flex items-center gap-3\">\n              {/*\n                Sin selector de frecuencia: cada widget ya se refresca con su propia\n                `refresh_policy`. Un temporizador global dispararia los ocho a la vez\n                y pisaria el ritmo que cada indicador tiene configurado.\n              */}\n              {sortedCategories.length > 1 && (\n                <label className=\"flex items-center gap-1.5 text-xs\" style={{ color: 'var(--dash-text-secondary)' }}>\n                  <input\n                    type=\"checkbox\"\n                    checked={presentation.isRotating}\n                    onChange={e => presentation.setRotating(e.target.checked)}\n                  />\n                  {t('dashboard.presentation.rotate')}\n                </label>\n              )}\n\n              <button\n                onClick={presentation.exit}\n                className=\"p-1.5 rounded transition-colors\"\n                style={{ color: 'var(--dash-text-secondary)' }}\n                title={t('dashboard.presentation.exit')}\n                aria-label={t('dashboard.presentation.exit')}\n              >\n                <Minimize2 className=\"w-4 h-4\" />\n              </button>\n            </div>\n          ) : (\n            <button\n              onClick={presentation.enter}\n              className=\"p-1.5 rounded transition-colors\"\n              style={{ color: 'var(--dash-text-muted)' }}\n              title={t('dashboard.presentation.enter')}\n              aria-label={t('dashboard.presentation.enter')}\n            >\n              <Monitor className=\"w-4 h-4\" />\n            </button>\n          )}\n\n          {/* Selector de Tiempo (Filtro Global) */}\n          {showPeriodSelector && (\n            <div className=\"p-1 rounded-lg flex items-center\" style={{ background: 'var(--dash-surface-page)' }}>\n              {(['Hoy', 'Semana', 'Mes'] as DashboardPeriod[]).map(p => (\n                <button\n                  key={p}\n                  onClick={() => engine.setPeriod(p)}\n                  className=\"px-4 py-1.5 text-sm font-medium rounded-md transition-all\"\n                  style={engine.period === p\n                    ? { background: 'var(--dash-surface-card)', color: 'var(--dash-accent)', boxShadow: '0 1px 2px rgba(16,24,40,.06)' }\n                    : { color: 'var(--dash-text-muted)' }}\n                >\n                  {p}\n                </button>\n              ))}\n            </div>\n          )}\n\n          <div className=\"w-px h-8 mx-2\" style={{ background: 'var(--dash-border)' }}></div>\n\n          {/* Botón Editar — abre sidebar (= activa edit mode) */}\n          <button\n            onClick={() => setIsManagerOpen(true)}\n            className=\"flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm border transition-colors hover:opacity-90\"\n            style={isManagerOpen\n              ? { background: 'var(--dash-accent)', borderColor: 'var(--dash-accent)', color: '#ffffff' }\n              : { background: 'var(--dash-surface-card)', borderColor: 'var(--dash-border-strong)', color: 'var(--dash-text-primary)' }}\n          >\n            <Pencil className=\"w-4 h-4\" /> {t('dashboard.chrome.edit')}\n          </button>\n        </div>\n      </header>\n\n      {/* Banner de Modo Edición — visible cuando el sidebar está abierto */}\n      {isManagerOpen && (\n        <div\n          className=\"border-b px-6 py-2 flex items-center justify-center\"\n          style={{ background: 'var(--dash-bg-accent)', borderColor: 'var(--dash-border)' }}\n        >\n          <p className=\"text-sm font-medium\" style={{ color: 'var(--dash-accent)' }}>\n            {t('dashboard.chrome.editModeHint')}\n          </p>\n        </div>\n      )}\n\n      {/* Menú de Pestañas (SubHeader) */}\n      {viewMode === 'tabs' && sortedCategories.length > 0 && (\n        <div\n          className=\"px-6 pt-4 border-b flex gap-6\"\n          style={{ background: 'var(--dash-surface-card)', borderColor: 'var(--dash-border)' }}\n        >\n          {sortedCategories.map(cat => (\n            <button\n              key={cat}\n              onClick={() => setActiveTab(cat)}\n              className=\"pb-3 font-bold text-sm tracking-wide transition-colors border-b-2\"\n              style={activeTab === cat\n                ? { borderColor: 'var(--dash-accent)', color: 'var(--dash-accent)' }\n                : { borderColor: 'transparent', color: 'var(--dash-text-muted)' }}\n            >\n              {categoryLabel(cat).toUpperCase()}\n            </button>\n          ))}\n        </div>\n      )}\n\n      {/* 2. Contenido Principal (Grid) */}\n      <main className={`p-6 transition-all duration-300 ${isManagerOpen ? 'mr-[348px]' : ''}`}>\n        {/*\n          Vista de tablero unico: una sola grilla con TODO, sin encabezados de\n          categoria. El layout se guarda igual que en las otras vistas — es la\n          misma coleccion de preferencias, presentada junta.\n        */}\n        {viewMode === 'board' && boardLayout.length > 0 && (\n          <DashboardGrid\n            layout={boardLayout}\n            catalog={engine.catalog}\n            isEditMode={isManagerOpen}\n            globalFilters={{ period: engine.period }}\n            onLayoutChange={layoutManager.updateLayout}\n            onRemoveWidget={handleRemoveWidget}\n            renderWidget={(pref, def, editMode, filters, onRemove) => (\n              <LazyWidget\n                preference={pref}\n                definition={def}\n                isEditMode={editMode}\n                period={filters.period as DashboardPeriod}\n                onRemove={onRemove}\n                customWidgetRegistry={customWidgetRegistry}\n              />\n            )}\n          />\n        )}\n\n        {viewMode !== 'board' && sortedCategories.map(category => {\n          // Si estamos en modo tabs y no es la activa, no renderizamos su grid\n          if (viewMode === 'tabs' && category !== activeTab) return null;\n\n          const categoryLayout = layoutByCategory[category];\n\n          return (\n            <div key={category} className=\"mb-10\">\n              {viewMode === 'cascade' && (\n                <h2\n                  className=\"text-sm font-bold mb-4 uppercase tracking-wider pl-3 border-l-4 flex items-center gap-2\"\n                  style={{ color: 'var(--dash-accent)', borderColor: 'var(--dash-accent)' }}\n                >\n                  <span className=\"font-normal\" style={{ color: 'var(--dash-text-muted)' }}>|</span> {categoryLabel(category)}\n                </h2>\n              )}\n              \n              <DashboardGrid\n                layout={categoryLayout}\n                catalog={engine.catalog}\n                isEditMode={isManagerOpen}\n                globalFilters={{ period: engine.period }}\n                onLayoutChange={(newLayout) => handleCategoryLayoutChange(category, newLayout)}\n                onRemoveWidget={handleRemoveWidget}\n                renderWidget={(pref, def, editMode, filters, onRemove) => (\n                  <LazyWidget\n                    preference={pref}\n                    definition={def}\n                    isEditMode={editMode}\n                    period={filters.period as DashboardPeriod}\n                    onRemove={onRemove}\n                    customWidgetRegistry={customWidgetRegistry}\n                  />\n                )}\n              />\n            </div>\n          );\n        })}\n\n        {sortedCategories.length === 0 && (\n          <div\n            className=\"flex flex-col items-center justify-center mt-20 p-8 border border-dashed rounded-xl max-w-md mx-auto\"\n            style={{ background: 'var(--dash-surface-card)', borderColor: 'var(--dash-border-strong)', color: 'var(--dash-text-secondary)' }}\n          >\n            <LayoutTemplate className=\"w-12 h-12 mb-4\" style={{ color: 'var(--dash-text-muted)' }} />\n            <h3 className=\"font-semibold mb-1\" style={{ color: 'var(--dash-text-primary)' }}>{t('dashboard.chrome.empty')}</h3>\n            <p className=\"text-center text-sm\">{t('dashboard.chrome.emptyHint')}</p>\n          </div>\n        )}\n      </main>\n\n      {/* 3. Panel Lateral (Catálogo) */}\n      <WidgetManagerPanel\n        // 🔴 F3 — los TÉRMINOS, no los ids. Antes viajaban `categoryIds`, y con eso el Constructor\n        // perdía dos cosas en el salto: la etiqueta traducida (pintaba la clave, que en Comercial\n        // coincide por casualidad) y —lo que importa— la VERTICAL. Sin ella no hay nada que derivar.\n        availableCategories={categoryTerms}\n        isOpen={isManagerOpen}\n        catalog={engine.catalog}\n        currentLayout={layoutManager.layout}\n        isAdmin={esAdminDelCatalogo}\n        canWriteWidgets={canWriteWidgets}\n        canPublishWidgets={canPublishWidgets}\n        userRoles={userRoles}\n        userId={userId}\n        showExternalEndpoints={showExternalEndpoints}\n        showWidgetBuilder={showWidgetBuilder}\n        onClose={() => setIsManagerOpen(false)}\n        onRequestAdd={(widget) => {\n          setCustomizingWidget({ widget, preference: undefined });\n          setIsManagerOpen(false);\n        }}\n        onRequestModify={(widget, preference) => {\n          setCustomizingWidget({ widget, preference });\n          setIsManagerOpen(false);\n        }}\n        onRemoveWidget={handleRemoveWidget}\n        onWidgetCreated={(newDef) => {\n          engine.addToCatalog(newDef);\n          // Si es privado, agregar directamente al layout del usuario\n          if (newDef.es_privado) {\n            const pos = findFirstAvailablePosition(\n              layoutByCategory[newDef.categoria] ?? [],\n              newDef.cols_default,\n              newDef.altura_default\n            );\n            layoutManager.updateLayout([...layoutManager.layout, {\n              id: `inst_${crypto.randomUUID()}`,\n              user_id: userId,\n              widget_id: newDef.widget_id,\n              activo: true,\n              orden: layoutManager.layout.length + 1,\n              col_span: newDef.cols_default,\n              /**\n               * `altura_default` del catálogo está expresado en filas de `LEGACY_ROW_HEIGHT`\n               * (148 px), así que la preferencia nace SIN sello y `migrateLayout` la convierte\n               * como a cualquier otra heredada. El día que el catálogo pase a las filas de\n               * `ROW_HEIGHT` (80 px), aquí hay que estampar `layoutVersion: LAYOUT_VERSION`.\n               */\n              row_span: newDef.altura_default,\n              pos_x: pos.x,\n              pos_y: pos.y,\n              modificado_en: new Date().toISOString(),\n            }]);\n          }\n        }}\n        onWidgetUpdated={(updatedDef) => {\n          engine.updateInCatalog(updatedDef);\n        }}\n        onDeleteWidget={async (widgetId) => {\n          await deleteWidgetAPI(widgetId, fetcher);\n          engine.removeFromCatalog(widgetId);\n          const cleaned = layoutManager.layout.filter(p => p.widget_id !== widgetId);\n          if (cleaned.length !== layoutManager.layout.length) {\n            layoutManager.updateLayout(cleaned);\n          }\n        }}\n      />\n\n      {/* 4. Panel de Personalización unificado (agregar o modificar) */}\n      {customizingWidget && (\n        <CustomizationWithSchema\n          widget={customizingWidget.widget}\n          preference={customizingWidget.preference}\n          availableCategories={catalogCategories}\n          period={engine.period}\n          onConfirm={(overrides) => {\n            if (customizingWidget.preference) {\n              // Modo personalize: actualizar config_json de la preferencia existente\n              const updated = layoutManager.layout.map(p =>\n                p.id === customizingWidget.preference!.id\n                  ? { ...p, config_json: Object.keys(overrides).length > 0 ? overrides : undefined }\n                  : p\n              );\n              layoutManager.updateLayout(updated);\n              setCustomizingWidget(null);\n            } else {\n              // Modo add: crear nueva instancia en el layout\n              const def = customizingWidget.widget;\n              const cols = (overrides.cols_default as number) ?? def.cols_default;\n              const pos = findFirstAvailablePosition(\n                layoutByCategory[def.categoria] ?? [],\n                cols,\n                def.altura_default\n              );\n              layoutManager.updateLayout([...layoutManager.layout, {\n                id: `inst_${crypto.randomUUID()}`,\n                user_id: userId,\n                widget_id: def.widget_id,\n                activo: true,\n                orden: layoutManager.layout.length + 1,\n                col_span: cols,\n                // Ver la nota de `onWidgetCreated`: `altura_default` está en filas de 148 px.\n                row_span: def.altura_default,\n                pos_x: pos.x,\n                pos_y: pos.y,\n                config_json: Object.keys(overrides).length > 0 ? overrides : undefined,\n                modificado_en: new Date().toISOString(),\n              }]);\n              setCustomizingWidget(null);\n              setIsManagerOpen(true);   // volver al catálogo para seguir agregando\n            }\n          }}\n          onRestore={customizingWidget.preference ? () => {\n            const restored = layoutManager.layout.map(p =>\n              p.id === customizingWidget.preference!.id\n                // \"Restaurar\" borra los overrides del usuario, NO el sello de layout: si se\n                // fuera con ellos, la migración volvería a convertir un row_span ya convertido.\n                ? { ...p, config_json: p.config_json?.layoutVersion !== undefined\n                      ? { layoutVersion: p.config_json.layoutVersion }\n                      : undefined }\n                : p\n            );\n            layoutManager.updateLayout(restored);\n            setCustomizingWidget(null);\n          } : undefined}\n          onClose={() => {\n            const wasAdd = !customizingWidget.preference;\n            setCustomizingWidget(null);\n            if (wasAdd) setIsManagerOpen(true);  // volver al catálogo si era modo add\n          }}\n        />\n      )}\n\n      {/*\n        5. Confirmación de quitar un widget.\n\n        <b>Baja de tono, a propósito.</b> Usaba el lenguaje de \"vas a destruir\n        datos\" —círculo rojo, triángulo de alerta, botón rojo, \"no se puede\n        deshacer\"— para una acción que sólo esconde un widget del tablero PROPIO\n        del usuario y que se revierte desde el catálogo en dos clics. La gravedad\n        era falsa, y una alarma que no corresponde enseña a ignorar las que sí.\n\n        Se conserva la confirmación (quitar sigue siendo un clic sin vuelta atrás\n        inmediata). Lo que se retira es el rojo, el icono de alerta y el texto que\n        prometía un daño que no existe.\n\n        Y deja de estar a medio traducir: el párrafo y los dos botones estaban\n        cableados en español mientras el título usaba `t()`.\n      */}\n      {pendingRemoveId && (\n        <div className=\"fixed inset-0 z-[70] flex items-center justify-center bg-gray-900/40 backdrop-blur-sm p-4\">\n          <div\n            className=\"rounded-xl shadow-2xl w-full max-w-sm p-6 animate-in fade-in zoom-in duration-150\"\n            style={{ background: 'var(--dash-surface-card)' }}\n            role=\"dialog\"\n            aria-modal=\"true\"\n          >\n            <h3 className=\"text-base font-medium mb-1\" style={{ color: 'var(--dash-text-primary)' }}>\n              {t('dashboard.confirm.removeQuestion')}\n            </h3>\n            <p className=\"text-sm mb-6\" style={{ color: 'var(--dash-text-secondary)' }}>\n              {t('dashboard.confirm.removeBody')}\n            </p>\n            <div className=\"flex items-center justify-end gap-3\">\n              <button\n                onClick={() => setPendingRemoveId(null)}\n                className=\"px-4 py-2 text-sm font-medium rounded-lg transition-colors hover:opacity-80\"\n                style={{ color: 'var(--dash-text-secondary)', background: 'var(--dash-surface-page)' }}\n              >\n                {t('dashboard.confirm.cancel')}\n              </button>\n              <button\n                onClick={confirmRemove}\n                className=\"px-4 py-2 text-sm font-medium text-white rounded-lg transition-colors hover:opacity-90\"\n                style={{ background: 'var(--dash-accent)' }}\n              >\n                {t('dashboard.confirm.removeAction')}\n              </button>\n            </div>\n          </div>\n        </div>\n      )}\n    </div>\n    </DashboardProvider>\n  );\n};\n\n","/**\n * Typed HTTP wrappers for the form-caches backend API.\n *\n * Mirrors Architecture §9.5. `createFormCacheApi` receives the consumer's\n * httpClient so auth headers and base URL are fully controlled by the caller.\n */\n\nimport type { HttpClient, FormCacheDTO } from './FormCacheSelector.types';\n\n/**\n * TanStack Query key factory for form-cache resources.\n *\n * Always invoke `formCacheKeys.all(cacheId)` instead of hardcoding the key\n * tuple in components — it keeps invalidation calls in sync.\n */\nexport const formCacheKeys = {\n  all: (cacheId: string) => ['form-caches', cacheId] as const,\n};\n\nexport function createFormCacheApi(client: HttpClient) {\n  return {\n    /**\n     * List all form-cache entries for the given `cacheId` and the current user.\n     *\n     * `cacheId` is URL-encoded so it can safely contain `/`, `?`, `#`, etc.\n     */\n    getAllByUser: (cacheId: string): Promise<FormCacheDTO[]> =>\n      client.get(`/form-caches/${encodeURIComponent(cacheId)}`),\n\n    /**\n     * Fetch a single entry by id. Returns `unknown` because the persisted JSON\n     * shape depends on `TFilter` and is validated by `safeParse` at the call site.\n     */\n    getById: (id: string): Promise<unknown> =>\n      client.get(`/form-caches/entries/${id}`),\n\n    upsert: (payload: {\n      cacheId: string;\n      name: string;\n      filter: unknown;\n    }): Promise<{ id: string }> => client.post('/form-caches', payload),\n\n    updateLastInUse: (id: string): Promise<boolean> =>\n      client.patch(`/form-caches/entries/${id}/last-in-use`),\n\n    delete: (id: string): Promise<boolean> =>\n      client.delete(`/form-caches/entries/${id}`),\n\n    rename: (id: string, newName: string): Promise<boolean> =>\n      client.patch(`/form-caches/entries/${id}/rename`, { newName }),\n  };\n}\n\nexport type FormCacheApi = ReturnType<typeof createFormCacheApi>;\n","/**\n * Pure utilities for the FormCacheSelector component.\n *\n * Mirrors Architecture §9.6.\n */\n\nimport type { FormCacheDTO } from './FormCacheSelector.types';\n\n/**\n * Lenient field-level merge that restores a stored filter without ever\n * throwing — the resilience strategy for schema drift (FR-FFCS-011, FFCS-D006).\n *\n * Algorithm:\n *   1. If `rawJson` is null/undefined/non-object/array → return a fresh copy\n *      of `emptyFilter`.\n *   2. For every key declared in `emptyFilter`, copy `rawJson[key]` only when\n *      `typeof rawJson[key] === typeof emptyFilter[key]` — otherwise keep the\n *      default value.\n *\n * The function never mutates `emptyFilter`; callers may pass a frozen object.\n *\n * @typeParam TFilter - The expected filter shape (drives the key set).\n * @param rawJson - The opaque JSON value retrieved from the backend.\n * @param emptyFilter - Default values used for missing or type-mismatched keys.\n * @returns A new object with the same keys as `emptyFilter`.\n */\nexport function safeParse<TFilter extends Record<string, unknown>>(\n  rawJson: unknown,\n  emptyFilter: TFilter,\n): TFilter {\n  if (\n    rawJson === null ||\n    rawJson === undefined ||\n    typeof rawJson !== 'object' ||\n    Array.isArray(rawJson)\n  ) {\n    return { ...emptyFilter };\n  }\n\n  const raw = rawJson as Record<string, unknown>;\n  const result = { ...emptyFilter };\n\n  for (const key of Object.keys(emptyFilter)) {\n    if (key in raw) {\n      // `typeof null === \"object\"` is a JS quirk: nullable fields in emptyFilter\n      // would never match a stored string/number value under a strict typeof check.\n      // Accept the stored value when either side is null, or when types match.\n      const emptyType = typeof emptyFilter[key];\n      const rawType = typeof raw[key];\n      if (emptyType === rawType || emptyFilter[key] === null || raw[key] === null) {\n        (result as Record<string, unknown>)[key] = raw[key];\n      }\n    }\n  }\n\n  return result;\n}\n\n/**\n * Returns a new array of caches sorted alphabetically by `name` (FR-FFCS-012).\n *\n * Uses `localeCompare` with `sensitivity: 'base'` so:\n *   - sorting is case-insensitive (\"apple\" < \"Banana\"),\n *   - accented Spanish characters are ordered correctly (e.g. \"Año\" before\n *     \"Beneficios\") instead of the broken codepoint order a default `<`\n *     comparator would produce.\n *\n * Pure — never mutates the input array.\n */\nexport function sortCaches(caches: FormCacheDTO[]): FormCacheDTO[] {\n  return [...caches].sort((a, b) =>\n    a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),\n  );\n}\n","/**\n * Zod validation schema for the FormCacheSelector save dialog.\n *\n * Exposed as a hook (`useFormCacheSelectorSchema`) so error messages can be\n * resolved through `react-i18next`. Per the Siesa I18N-RULE-004 rule, all\n * validation messages MUST flow through `t(...)` — hardcoded English strings\n * are forbidden.\n *\n * NOTE: the document defining I18N-RULE-004 is NOT in this repository — only this\n * citation and the one in `MasterPatternView/engine/validationEngine.ts`. If the\n * rule turns out to fix a key-naming convention, it prevails over the prefixes\n * this kit chose. Tracked in `docs/i18n-masterdocument-deuda.md` (point 4).\n */\n\nimport { useTranslation } from 'react-i18next';\nimport { z } from 'zod';\n\n/**\n * Returns a Zod schema for the \"save form-cache entry\" dialog. The schema\n * validates only the user-supplied `name` field (1..50 chars).\n *\n * Must be called from within a React component tree because it uses\n * `useTranslation`.\n */\nexport function useFormCacheSelectorSchema() {\n  const { t } = useTranslation('form-cache-selector');\n\n  return z.object({\n    name: z\n      .string()\n      .min(1, { message: t('validation.name.required') })\n      .max(50, { message: t('validation.name.maxLength', { max: 50 }) }),\n  });\n}\n","/**\n * `useFormCacheSelector` — server-state coordinator for the FormCacheSelector\n * component.\n *\n * Implements the mount-time auto-restore flow described in Architecture §9.4:\n *\n *   1. Fetch GetAllByUser via TanStack Query.\n *   2. On success:\n *      a. If any record has lastInUse === true → fetch GetById, run safeParse,\n *         call onSelected(restoredFilter, true).\n *      b. Else → call onSelected(emptyFilter, false).\n *   3. On error → call onSelected(emptyFilter, false) (NFR-FFCS-STB-002).\n *\n * The mount-time call to `onSelected` MUST fire exactly once (FR-FFCS-011).\n * A `useRef` flag guards against duplicate fires when:\n *   - React 18 StrictMode invokes effects twice in development.\n *   - The query refetches because of focus / network reconnect.\n *   - Parent re-renders cause the effect dependency array to re-evaluate.\n *\n * In S013 the hook gains its first real mutation (`handleUpsert`):\n *   - Sets `isMutating` while the request is in-flight.\n *   - On 200: pessimistically updates the local `caches` list using the\n *     server-returned `id`, switches `activeId`, surfaces a success message\n *     that auto-dismisses after 3 s (D-UX-006).\n *   - On 409: routes the error into `saveNameError` (rendered inline in\n *     SaveDialog) — the global error banner stays clear.\n *   - On other errors: routes the error into `errorMessage` (global banner)\n *     and leaves the dialog open.\n *\n * The auto-dismiss timer is cleaned up in a `useEffect` return so toggling\n * `successMessage` mid-life cancels any stale timer and unmounting cancels\n * the pending one (R-001 / no setState-after-unmount warnings).\n *\n * In S014 the hook gains `handleRename` plus the `renameDialogOpen` /\n * `renameError` state used by the RenameDialog subcomponent:\n *   - On 200: list updates in-place (`id` unchanged, only `name` changes), the\n *     dialog closes, success banner fires.\n *   - On 409: `renameError` is set so the dialog renders inline conflict text\n *     and stays open — the user can edit the name and retry.\n *   - On 404 / other errors: dialog closes and the global error banner is set.\n *\n * In S015 the hook gains `handleDelete` plus the `deleteDialogOpen` /\n * `deletingCacheName` state used by the DeleteDialog subcomponent:\n *   - `openDeleteDialog()` snapshots the active cache name (R-001) so the\n *     dialog title cannot drift mid-confirmation.\n *   - On 200: the entry is removed from the local `caches` list. If it was\n *     the active cache, `activeId` resets to null AND `onSelected(emptyFilter,\n *     false)` fires AFTER the local state update (R-002) so the parent form\n *     observes a consistent local state.\n *   - On error: dialog closes and the global error banner shows the message.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport { useTranslation } from 'react-i18next';\nimport { createFormCacheApi, formCacheKeys } from './FormCacheSelector.api';\nimport { safeParse } from './FormCacheSelector.utils';\nimport type { FormCacheDTO, FormCacheSelectorProps, HttpClient } from './FormCacheSelector.types';\n\n/** i18n key surfaced in `saveNameError` when the backend responds with 409. */\nconst NAME_CONFLICT_KEY = 'errors.nameAlreadyExists';\n\n/** Payload for the in-tree toast rendered via createPortal in FormCacheSelector. */\nexport interface ToastPayload {\n  text: string;\n  color: 'green' | 'red';\n}\n\nexport interface UseFormCacheSelectorResult<TFilter> {\n  caches: FormCacheDTO[];\n  activeId: string | null;\n  isLoading: boolean;\n  isMutating: boolean;\n  /** Save dialog open state — exposed so the root component can render it. */\n  saveDialogOpen: boolean;\n  /** Setter for `saveDialogOpen` so the root component can open / close it. */\n  setSaveDialogOpen: (open: boolean) => void;\n  /** i18n key for an inline 409 error inside the save dialog (or null). */\n  saveNameError: string | null;\n  /** Clears `saveNameError` — called as the user edits the name input. */\n  clearSaveNameError: () => void;\n  /** Rename dialog open state — exposed so the root component can render it. */\n  renameDialogOpen: boolean;\n  /** Setter for `renameDialogOpen` so the root component can open / close it. */\n  setRenameDialogOpen: (open: boolean) => void;\n  /** i18n key for an inline 409 error inside the rename dialog (or null). */\n  renameError: string | null;\n  /** Clears `renameError` — called as the user edits the rename input. */\n  clearRenameError: () => void;\n  /** Delete dialog open state — exposed so the root component can render it. */\n  deleteDialogOpen: boolean;\n  /** Setter for `deleteDialogOpen` so the root component can dismiss it. */\n  setDeleteDialogOpen: (open: boolean) => void;\n  /**\n   * Cache name snapshot taken when the delete dialog was opened (R-001). The\n   * dialog renders this verbatim so a concurrent rename can't relabel the\n   * confirmation mid-flow.\n   */\n  deletingCacheName: string;\n  /**\n   * Opens the DeleteDialog and snapshots the current active cache name. Use\n   * this from the Delete button click handler instead of `setDeleteDialogOpen`\n   * directly so the snapshot stays in sync with the open state.\n   */\n  openDeleteDialog: () => void;\n  /** Active toast to render via createPortal (null = no toast). */\n  activeToast: ToastPayload | null;\n  handleSelectNoFilter: () => void;\n  handleSelectCache: (cache: FormCacheDTO) => Promise<void>;\n  handleUpsert: (name: string) => Promise<void>;\n  handleUpdateLastInUse: (id: string) => Promise<void>;\n  handleDelete: () => Promise<void>;\n  handleRename: (newName: string) => Promise<void>;\n  setActiveId: (id: string | null) => void;\n}\n\nexport function useFormCacheSelector<TFilter>(\n  cacheId: string,\n  filter: TFilter,\n  onSelected: FormCacheSelectorProps<TFilter>['onSelected'],\n  httpClient: HttpClient,\n): UseFormCacheSelectorResult<TFilter> {\n  const { t } = useTranslation('form-cache-selector');\n\n  // ── API client (memoized so mutations always use the same reference) ──────\n  const api = useMemo(() => createFormCacheApi(httpClient), [httpClient]);\n\n  // ── Local UI state ───────────────────────────────────────────────────────\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [isMutating, setIsMutating] = useState(false);\n  const [saveDialogOpen, setSaveDialogOpen] = useState(false);\n  const [saveNameError, setSaveNameError] = useState<string | null>(null);\n  const [renameDialogOpen, setRenameDialogOpen] = useState(false);\n  const [renameError, setRenameError] = useState<string | null>(null);\n  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);\n  const [deletingCacheName, setDeletingCacheName] = useState('');\n  const [caches, setCaches] = useState<FormCacheDTO[]>([]);\n  const [activeToast, setActiveToast] = useState<ToastPayload | null>(null);\n\n  // ── Toast auto-dismiss ───────────────────────────────────────────────────\n  // Clears the toast after 5 s. The cleanup cancels any pending timer so rapid\n  // mutations don't stack overlapping dismissals.\n  useEffect(() => {\n    if (!activeToast) return;\n    const id = setTimeout(() => setActiveToast(null), 5000);\n    return () => clearTimeout(id);\n  }, [activeToast]);\n\n  // ── Live filter ref ──────────────────────────────────────────────────────\n  // The `filter` prop is the live form state. We keep a ref so async mutation\n  // handlers always read the latest value at the moment they execute, not the\n  // value captured when the closure was created (R-003).\n  const filterRef = useRef<TFilter>(filter);\n  useEffect(() => {\n    filterRef.current = filter;\n  }, [filter]);\n\n  // ── Mount-time empty-filter snapshot ─────────────────────────────────────\n  // The architecture references an `emptyTFilter` template for fallbacks. We\n  // capture the prop value at mount time — a stable reference that the\n  // consumer is expected to provide as a \"zeroed\" version of TFilter. The ref\n  // guarantees subsequent live mutations of `filter` cannot corrupt the\n  // fallback used by safeParse / onSelected.\n  const emptyFilterRef = useRef<TFilter>(filter);\n\n  // ── Exactly-once mount call guard ────────────────────────────────────────\n  // Set to true the first time the auto-restore effect fires onSelected,\n  // ensuring StrictMode / refetch / re-render cannot trigger a second call.\n  const hasRestoredRef = useRef(false);\n\n  // ── GetAllByUser ─────────────────────────────────────────────────────────\n  const queryKey = useMemo(() => formCacheKeys.all(cacheId), [cacheId]);\n  const {\n    data,\n    isLoading,\n    isError,\n    error,\n  } = useQuery<FormCacheDTO[]>({\n    queryKey,\n    queryFn: () => api.getAllByUser(cacheId),\n    enabled: cacheId.length > 0,\n  });\n\n  // Keep the local `caches` state in sync with the server data. Mutations\n  // (upsert / delete / rename) work against this local copy so the UI can\n  // update without forcing a full GetAllByUser refetch.\n  useEffect(() => {\n    if (data) setCaches(data);\n  }, [data]);\n\n  // ── Mount-time auto-restore effect ───────────────────────────────────────\n  useEffect(() => {\n    if (hasRestoredRef.current) return;\n\n    // Loading: wait until the query resolves one way or the other.\n    if (isLoading) return;\n\n    if (isError) {\n      hasRestoredRef.current = true;\n      // NFR-FFCS-STB-002: surface via toast but never block parent form.\n      const message = error instanceof Error ? error.message : 'unknown';\n      console.warn('[FormCacheSelector] GetAllByUser failed:', message);\n      setActiveToast({ text: message, color: 'red' });\n      void onSelected(emptyFilterRef.current, false);\n      return;\n    }\n\n    if (!data) return;\n\n    const lastInUseItem = data.find((c) => c.lastInUse === true);\n    hasRestoredRef.current = true;\n\n    if (lastInUseItem) {\n      // GetById → safeParse → onSelected(parsed, true) → setActiveId on accept.\n      // The double cast through `unknown` is a deliberate, narrow widening:\n      // safeParse is parametric over `Record<string, unknown>` (the JSON shape\n      // it can introspect with `typeof`), but the consumer's TFilter is opaque\n      // here. The cast is sound because:\n      //   - `emptyFilterRef.current` IS the consumer's TFilter at runtime.\n      //   - safeParse never adds keys not present in emptyFilter.\n      //   - The returned object structurally matches TFilter.\n      const emptyAsRecord = emptyFilterRef.current as unknown as Record<string, unknown>;\n\n      api\n        .getById(lastInUseItem.id)\n        .then((rawJson) => safeParse(rawJson, emptyAsRecord))\n        .then((restored) => onSelected(restored as unknown as TFilter, true))\n        .then(() => {\n          // R-001: always mark the lastInUse item as active regardless of\n          // whether the consumer accepted the filter into its form state. The\n          // component's selection state (dropdown highlight) reflects what the\n          // server says was last used, independent of the consumer's veto.\n          setActiveId(lastInUseItem.id);\n        })\n        .catch((err) => {\n          console.warn(\n            '[FormCacheSelector] GetById failed during auto-restore:',\n            err,\n          );\n          void onSelected(emptyFilterRef.current, false);\n        });\n    } else {\n      // No lastInUse → empty fallback, no GetById call.\n      void onSelected(emptyFilterRef.current, false);\n    }\n    // We intentionally exclude `onSelected` from the dependency array because\n    // the consumer is not required to wrap it in useCallback — and the\n    // hasRestoredRef guard already prevents double fires.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [data, isLoading, isError, error]);\n\n  // ── Mutation handlers — S012 implements select; S013-S015 the rest ────────\n  /**\n   * \"Sin filtros\" pseudo-option click (S012, AC-007).\n   * - Clears `activeId` so the dropdown UI shows no Check.\n   * - Calls `onSelected(emptyFilter, false)` so the parent form resets to its\n   *   zeroed state.\n   * - Does NOT call any backend API (no `lastInUse` row to clear server-side).\n   */\n  const handleSelectNoFilter = () => {\n    setActiveId(null);\n    void onSelected(emptyFilterRef.current, false);\n  };\n\n  /**\n   * Named cache click (S012, AC-006).\n   *\n   * Pipeline:\n   *   0. Optimistic: set `activeId = cache.id` immediately so the trigger\n   *        reflects the click at once (R-001 — instant visual feedback).\n   *   1. `api.getById(cache.id)` → raw JSON.\n   *   2. `safeParse(rawJson, emptyFilter)` → typed TFilter (never throws).\n   *   3. `onSelected(restored, true)` → consumer decides whether to accept.\n   *   4. If consumer returns `true`:\n   *        - fire-and-forget `api.updateLastInUse(cache.id)` (R-003)\n   *          — UX §7.3 lastInUse update timing: backend write does NOT block\n   *          the parent form update.\n   *\n   * Any failure in steps 1-3 falls through to the catch block, which:\n   *   - Reverts `activeId` to `null` (\"Sin filtros\") — consistent with the\n   *     `onSelected(emptyFilter, false)` call that follows (R-001: trigger\n   *     must match form state).\n   *   - Calls `onSelected(emptyFilter, false)` so the parent form is left in\n   *     a known (empty) state rather than partially-restored garbage.\n   *   - Surfaces the error via `setActiveToast`.\n   */\n  const handleSelectCache = async (cache: FormCacheDTO): Promise<void> => {\n    // R-001: optimistic update — give instant visual feedback on click.\n    // Reverted in the catch block if the pipeline fails.\n    setActiveId(cache.id);\n    try {\n      const rawJson = await api.getById(cache.id);\n      const emptyAsRecord = emptyFilterRef.current as unknown as Record<\n        string,\n        unknown\n      >;\n      const restored = safeParse(rawJson, emptyAsRecord) as unknown as TFilter;\n      const shouldUpdate = await onSelected(restored, true);\n      if (shouldUpdate) {\n        // Fire-and-forget: do NOT await. Failure is non-fatal — the user still\n        // got the restored filter; the only loss is \"last used\" stickiness on\n        // their next visit.\n        void api.updateLastInUse(cache.id).catch((err) => {\n          console.warn(\n            '[FormCacheSelector] updateLastInUse failed (non-fatal):',\n            err,\n          );\n        });\n      }\n    } catch (err) {\n      const message = err instanceof Error ? err.message : 'unknown';\n      console.warn('[FormCacheSelector] handleSelectCache failed:', message);\n      // R-001: revert trigger to \"Sin filtros\" — consistent with the\n      // onSelected(emptyFilter, false) call below that resets the form.\n      // Use functional update to avoid reverting a concurrent selection.\n      setActiveId((prev) => (prev === cache.id ? null : prev));\n      setActiveToast({ text: message, color: 'red' });\n      void onSelected(emptyFilterRef.current, false);\n    }\n  };\n\n  /**\n   * Save / Upsert handler (S013, FR-FFCS-015 / FR-FFCS-016).\n   *\n   * Single entry point for both \"save new\" and \"save overwrite\":\n   *   - Save new: parent calls with the dialog-supplied name; the API\n   *     creates a fresh row and returns its id.\n   *   - Save overwrite: parent calls with the active cache's existing name;\n   *     the API recognises the name + cacheId + userId tuple and updates the\n   *     existing row's filter JSON, returning the same id.\n   *\n   * Update strategy: pessimistic (R-002). We wait for the server-returned id\n   * before touching local state because:\n   *   - Save-new needs the id to set `activeId` correctly.\n   *   - Optimistic insertion would require a synthetic id and roll-back logic\n   *     for the rare 5xx case.\n   *   - The latency on a write is small enough that the spinner UX is fine.\n   *\n   * Filter freshness: we read `filterRef.current` at call time — NOT a\n   * stale closure capture from when `handleUpsert` was last memoised. This\n   * matters when the user keeps editing the form while the dialog is open.\n   */\n  const handleUpsert = async (name: string): Promise<void> => {\n    setIsMutating(true);\n    setSaveNameError(null);\n    try {\n      const response = await api.upsert({\n        cacheId,\n        name,\n        filter: filterRef.current as unknown,\n      });\n\n      // Update the local list pessimistically using the server-returned id.\n      // - If the id already exists locally → it's an overwrite: update name +\n      //   flip lastInUse to true on this row, false on every other row.\n      // - Otherwise → it's a new row: append it and clear lastInUse on others.\n      setCaches((prev) => {\n        const existing = prev.find((c) => c.id === response.id);\n        if (existing) {\n          return prev.map((c) =>\n            c.id === response.id\n              ? { ...c, name, lastInUse: true }\n              : { ...c, lastInUse: false },\n          );\n        }\n        return [\n          ...prev.map((c) => ({ ...c, lastInUse: false })),\n          { id: response.id, name, lastInUse: true },\n        ];\n      });\n\n      setActiveId(response.id);\n      setSaveDialogOpen(false);\n      setActiveToast({ text: t('messages.saved'), color: 'green' });\n    } catch (err) {\n      const message = err instanceof Error ? err.message : 'unknown';\n      // 409 → inline conflict in the dialog. Anything else → toast error.\n      if (message.includes('409')) {\n        setSaveNameError(NAME_CONFLICT_KEY);\n      } else {\n        setActiveToast({ text: message, color: 'red' });\n      }\n    } finally {\n      setIsMutating(false);\n    }\n  };\n\n  const handleUpdateLastInUse = async (_id: string): Promise<void> => {\n    /* implemented in S013 — covered by handleSelectCache fire-and-forget */\n  };\n  /**\n   * Delete handler (S015, FR-FFCS-018).\n   *\n   * Pipeline:\n   *   1. Guard: a delete without an active id is a no-op (the button is\n   *      hidden in that state, but the guard is defensive — Delete is only\n   *      offered when a named cache is selected).\n   *   2. `api.delete(activeId)` — backend returns true on 200.\n   *   3. On 200: remove the entry from the local list. R-002: the local\n   *      state updates (caches filter, dialog close, activeId = null) MUST\n   *      complete BEFORE `onSelected(emptyFilter, false)` is called so the\n   *      parent form sees a consistent component state when its onSelected\n   *      callback fires.\n   *   4. On 404 or generic error: close the dialog and surface the message\n   *      via the global error banner. 404 here means the row was already\n   *      deleted out from under us by another tab — there is nothing to\n   *      retry, so closing is the correct UX.\n   */\n  const handleDelete = async (): Promise<void> => {\n    if (!activeId) return;\n    const deletedId = activeId;\n    setIsMutating(true);\n    try {\n      await api.delete(deletedId);\n      // R-002: local state updates BEFORE the onSelected callback fires.\n      setCaches((prev) => prev.filter((c) => c.id !== deletedId));\n      setDeleteDialogOpen(false);\n      setActiveId(null);\n      setActiveToast({ text: t('messages.deleted'), color: 'green' });\n      void onSelected(emptyFilterRef.current, false);\n    } catch (err) {\n      const message = err instanceof Error ? err.message : 'unknown';\n      setDeleteDialogOpen(false);\n      setActiveToast({ text: message, color: 'red' });\n    } finally {\n      setIsMutating(false);\n    }\n  };\n\n  /**\n   * Opens the DeleteDialog and snapshots the current active cache's name\n   * (R-001). The snapshot is read by the dialog's confirmation text so a\n   * concurrent rename mid-confirmation cannot change the displayed name.\n   */\n  const openDeleteDialog = useCallback(() => {\n    const name =\n      activeId !== null\n        ? (caches.find((c) => c.id === activeId)?.name ?? '')\n        : '';\n    setDeletingCacheName(name);\n    setDeleteDialogOpen(true);\n  }, [activeId, caches]);\n\n  /**\n   * Rename handler (S014, FR-FFCS-017).\n   *\n   * Pipeline:\n   *   1. Guard: a rename without an active id is a no-op (the button is hidden\n   *      in that state, but the guard is defensive).\n   *   2. `api.rename(activeId, newName)` — backend returns true on 200.\n   *   3. On 200: in-place list update — same `id`, new `name`, `lastInUse`\n   *      untouched. Dialog closes. The selector trigger label re-renders with\n   *      the new name automatically because it reads `caches.find(...).name`.\n   *   4. On 409 (FFCS-100): `renameError` is set; dialog stays open so the\n   *      user can fix the name and retry. The global banner is left clear.\n   *   5. On 404 / other errors: dialog closes, global banner shows the message.\n   *      404 specifically means the row was deleted out from under us by\n   *      another tab — there is nothing to retry, so closing is the correct UX.\n   */\n  const handleRename = async (newName: string): Promise<void> => {\n    if (!activeId) return;\n    setIsMutating(true);\n    setRenameError(null);\n    try {\n      await api.rename(activeId, newName);\n      setCaches((prev) =>\n        prev.map((c) => (c.id === activeId ? { ...c, name: newName } : c)),\n      );\n      setRenameDialogOpen(false);\n      setActiveToast({ text: t('messages.renamed'), color: 'green' });\n    } catch (err) {\n      const message = err instanceof Error ? err.message : 'unknown';\n      if (message.includes('409')) {\n        // Inline conflict — keep dialog open.\n        setRenameError(NAME_CONFLICT_KEY);\n      } else {\n        // 404 or generic — close dialog + toast error.\n        setRenameDialogOpen(false);\n        setActiveToast({ text: message, color: 'red' });\n      }\n    } finally {\n      setIsMutating(false);\n    }\n  };\n\n  const clearSaveNameError = useCallback(() => {\n    setSaveNameError(null);\n  }, []);\n\n  const clearRenameError = useCallback(() => {\n    setRenameError(null);\n  }, []);\n\n  return {\n    caches,\n    activeId,\n    isLoading,\n    isMutating,\n    saveDialogOpen,\n    setSaveDialogOpen,\n    saveNameError,\n    clearSaveNameError,\n    renameDialogOpen,\n    setRenameDialogOpen,\n    renameError,\n    clearRenameError,\n    deleteDialogOpen,\n    setDeleteDialogOpen,\n    deletingCacheName,\n    openDeleteDialog,\n    activeToast,\n    handleSelectNoFilter,\n    handleSelectCache,\n    handleUpsert,\n    handleUpdateLastInUse,\n    handleDelete,\n    handleRename,\n    setActiveId,\n  };\n}\n","/**\n * Wrapper shim around `radix-ui` Popover.\n *\n * Exists so consuming code imports a stable symbol from `lib/ui/popover` —\n * insulating the FormCacheSelector from a future swap to a different popover\n * primitive (e.g. when Siesa UI Kit eventually ships one). It also gives unit\n * tests a single, easy `vi.mock` seam.\n *\n * `PopoverContent` wraps `PopoverPrimitive.Content` in an explicit\n * `PopoverPrimitive.Portal` so the panel is portalled to `document.body`.\n * Radix v1 does NOT do this automatically — without the Portal the panel\n * renders in-flow and stacking/z-index break.\n */\n\nimport * as React from 'react';\nimport { Popover as PopoverPrimitive } from 'radix-ui';\n\nexport const Popover = PopoverPrimitive.Root;\nexport const PopoverTrigger = PopoverPrimitive.Trigger;\nexport const PopoverAnchor = PopoverPrimitive.Anchor;\nexport const PopoverPortal = PopoverPrimitive.Portal;\nexport const PopoverClose = PopoverPrimitive.Close;\n\nexport const PopoverContent = React.forwardRef<\n  React.ElementRef<typeof PopoverPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className = '', align = 'start', sideOffset = 4, ...props }, ref) => (\n  <PopoverPrimitive.Portal>\n    <PopoverPrimitive.Content\n      ref={ref}\n      align={align}\n      sideOffset={sideOffset}\n      className={`z-50 min-w-[12rem] overflow-hidden rounded-md border border-gray-200 bg-white text-gray-900 shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out ${className}`}\n      {...props}\n    />\n  </PopoverPrimitive.Portal>\n));\nPopoverContent.displayName = 'PopoverContent';\n","var U=1,Y=.9,H=.8,J=.17,p=.1,u=.999,$=.9999;var k=.99,m=/[\\\\\\/_+.#\"@\\[\\(\\{&]/,B=/[\\\\\\/_+.#\"@\\[\\(\\{&]/g,K=/[\\s-]/,X=/[\\s-]/g;function G(_,C,h,P,A,f,O){if(f===C.length)return A===_.length?U:k;var T=`${A},${f}`;if(O[T]!==void 0)return O[T];for(var L=P.charAt(f),c=h.indexOf(L,A),S=0,E,N,R,M;c>=0;)E=G(_,C,h,P,c+1,f+1,O),E>S&&(c===A?E*=U:m.test(_.charAt(c-1))?(E*=H,R=_.slice(A,c-1).match(B),R&&A>0&&(E*=Math.pow(u,R.length))):K.test(_.charAt(c-1))?(E*=Y,M=_.slice(A,c-1).match(X),M&&A>0&&(E*=Math.pow(u,M.length))):(E*=J,A>0&&(E*=Math.pow(u,c-A))),_.charAt(c)!==C.charAt(f)&&(E*=$)),(E<p&&h.charAt(c-1)===P.charAt(f+1)||P.charAt(f+1)===P.charAt(f)&&h.charAt(c-1)!==P.charAt(f))&&(N=G(_,C,h,P,c+1,f+2,O),N*p>E&&(E=N*p)),E>S&&(S=E),c=h.indexOf(L,c+1);return O[T]=S,S}function D(_){return _.toLowerCase().replace(X,\" \")}function W(_,C,h){return _=h&&h.length>0?`${_+\" \"+h.join(\" \")}`:_,G(_,C,D(_),D(C),0,0,{})}export{W as a};\n","\"use client\";import{a as ae}from\"./chunk-NZJY6EH4.mjs\";import*as w from\"@radix-ui/react-dialog\";import*as t from\"react\";import{Primitive as D}from\"@radix-ui/react-primitive\";import{useId as H}from\"@radix-ui/react-id\";import{composeRefs as G}from\"@radix-ui/react-compose-refs\";var N='[cmdk-group=\"\"]',Y='[cmdk-group-items=\"\"]',be='[cmdk-group-heading=\"\"]',le='[cmdk-item=\"\"]',ce=`${le}:not([aria-disabled=\"true\"])`,Z=\"cmdk-item-select\",T=\"data-value\",Re=(r,o,n)=>ae(r,o,n),ue=t.createContext(void 0),K=()=>t.useContext(ue),de=t.createContext(void 0),ee=()=>t.useContext(de),fe=t.createContext(void 0),me=t.forwardRef((r,o)=>{let n=L(()=>{var e,a;return{search:\"\",value:(a=(e=r.value)!=null?e:r.defaultValue)!=null?a:\"\",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),u=L(()=>new Set),c=L(()=>new Map),d=L(()=>new Map),f=L(()=>new Set),p=pe(r),{label:b,children:m,value:R,onValueChange:x,filter:C,shouldFilter:S,loop:A,disablePointerSelection:ge=!1,vimBindings:j=!0,...O}=r,$=H(),q=H(),_=H(),I=t.useRef(null),v=ke();k(()=>{if(R!==void 0){let e=R.trim();n.current.value=e,E.emit()}},[R]),k(()=>{v(6,ne)},[]);let E=t.useMemo(()=>({subscribe:e=>(f.current.add(e),()=>f.current.delete(e)),snapshot:()=>n.current,setState:(e,a,s)=>{var i,l,g,y;if(!Object.is(n.current[e],a)){if(n.current[e]=a,e===\"search\")J(),z(),v(1,W);else if(e===\"value\"){if(document.activeElement.hasAttribute(\"cmdk-input\")||document.activeElement.hasAttribute(\"cmdk-root\")){let h=document.getElementById(_);h?h.focus():(i=document.getElementById($))==null||i.focus()}if(v(7,()=>{var h;n.current.selectedItemId=(h=M())==null?void 0:h.id,E.emit()}),s||v(5,ne),((l=p.current)==null?void 0:l.value)!==void 0){let h=a!=null?a:\"\";(y=(g=p.current).onValueChange)==null||y.call(g,h);return}}E.emit()}},emit:()=>{f.current.forEach(e=>e())}}),[]),U=t.useMemo(()=>({value:(e,a,s)=>{var i;a!==((i=d.current.get(e))==null?void 0:i.value)&&(d.current.set(e,{value:a,keywords:s}),n.current.filtered.items.set(e,te(a,s)),v(2,()=>{z(),E.emit()}))},item:(e,a)=>(u.current.add(e),a&&(c.current.has(a)?c.current.get(a).add(e):c.current.set(a,new Set([e]))),v(3,()=>{J(),z(),n.current.value||W(),E.emit()}),()=>{d.current.delete(e),u.current.delete(e),n.current.filtered.items.delete(e);let s=M();v(4,()=>{J(),(s==null?void 0:s.getAttribute(\"id\"))===e&&W(),E.emit()})}),group:e=>(c.current.has(e)||c.current.set(e,new Set),()=>{d.current.delete(e),c.current.delete(e)}),filter:()=>p.current.shouldFilter,label:b||r[\"aria-label\"],getDisablePointerSelection:()=>p.current.disablePointerSelection,listId:$,inputId:_,labelId:q,listInnerRef:I}),[]);function te(e,a){var i,l;let s=(l=(i=p.current)==null?void 0:i.filter)!=null?l:Re;return e?s(e,n.current.search,a):0}function z(){if(!n.current.search||p.current.shouldFilter===!1)return;let e=n.current.filtered.items,a=[];n.current.filtered.groups.forEach(i=>{let l=c.current.get(i),g=0;l.forEach(y=>{let h=e.get(y);g=Math.max(h,g)}),a.push([i,g])});let s=I.current;V().sort((i,l)=>{var h,F;let g=i.getAttribute(\"id\"),y=l.getAttribute(\"id\");return((h=e.get(y))!=null?h:0)-((F=e.get(g))!=null?F:0)}).forEach(i=>{let l=i.closest(Y);l?l.appendChild(i.parentElement===l?i:i.closest(`${Y} > *`)):s.appendChild(i.parentElement===s?i:i.closest(`${Y} > *`))}),a.sort((i,l)=>l[1]-i[1]).forEach(i=>{var g;let l=(g=I.current)==null?void 0:g.querySelector(`${N}[${T}=\"${encodeURIComponent(i[0])}\"]`);l==null||l.parentElement.appendChild(l)})}function W(){let e=V().find(s=>s.getAttribute(\"aria-disabled\")!==\"true\"),a=e==null?void 0:e.getAttribute(T);E.setState(\"value\",a||void 0)}function J(){var a,s,i,l;if(!n.current.search||p.current.shouldFilter===!1){n.current.filtered.count=u.current.size;return}n.current.filtered.groups=new Set;let e=0;for(let g of u.current){let y=(s=(a=d.current.get(g))==null?void 0:a.value)!=null?s:\"\",h=(l=(i=d.current.get(g))==null?void 0:i.keywords)!=null?l:[],F=te(y,h);n.current.filtered.items.set(g,F),F>0&&e++}for(let[g,y]of c.current)for(let h of y)if(n.current.filtered.items.get(h)>0){n.current.filtered.groups.add(g);break}n.current.filtered.count=e}function ne(){var a,s,i;let e=M();e&&(((a=e.parentElement)==null?void 0:a.firstChild)===e&&((i=(s=e.closest(N))==null?void 0:s.querySelector(be))==null||i.scrollIntoView({block:\"nearest\"})),e.scrollIntoView({block:\"nearest\"}))}function M(){var e;return(e=I.current)==null?void 0:e.querySelector(`${le}[aria-selected=\"true\"]`)}function V(){var e;return Array.from(((e=I.current)==null?void 0:e.querySelectorAll(ce))||[])}function X(e){let s=V()[e];s&&E.setState(\"value\",s.getAttribute(T))}function Q(e){var g;let a=M(),s=V(),i=s.findIndex(y=>y===a),l=s[i+e];(g=p.current)!=null&&g.loop&&(l=i+e<0?s[s.length-1]:i+e===s.length?s[0]:s[i+e]),l&&E.setState(\"value\",l.getAttribute(T))}function re(e){let a=M(),s=a==null?void 0:a.closest(N),i;for(;s&&!i;)s=e>0?we(s,N):De(s,N),i=s==null?void 0:s.querySelector(ce);i?E.setState(\"value\",i.getAttribute(T)):Q(e)}let oe=()=>X(V().length-1),ie=e=>{e.preventDefault(),e.metaKey?oe():e.altKey?re(1):Q(1)},se=e=>{e.preventDefault(),e.metaKey?X(0):e.altKey?re(-1):Q(-1)};return t.createElement(D.div,{ref:o,tabIndex:-1,...O,\"cmdk-root\":\"\",onKeyDown:e=>{var s;(s=O.onKeyDown)==null||s.call(O,e);let a=e.nativeEvent.isComposing||e.keyCode===229;if(!(e.defaultPrevented||a))switch(e.key){case\"n\":case\"j\":{j&&e.ctrlKey&&ie(e);break}case\"ArrowDown\":{ie(e);break}case\"p\":case\"k\":{j&&e.ctrlKey&&se(e);break}case\"ArrowUp\":{se(e);break}case\"Home\":{e.preventDefault(),X(0);break}case\"End\":{e.preventDefault(),oe();break}case\"Enter\":{e.preventDefault();let i=M();if(i){let l=new Event(Z);i.dispatchEvent(l)}}}}},t.createElement(\"label\",{\"cmdk-label\":\"\",htmlFor:U.inputId,id:U.labelId,style:Te},b),B(r,e=>t.createElement(de.Provider,{value:E},t.createElement(ue.Provider,{value:U},e))))}),he=t.forwardRef((r,o)=>{var _,I;let n=H(),u=t.useRef(null),c=t.useContext(fe),d=K(),f=pe(r),p=(I=(_=f.current)==null?void 0:_.forceMount)!=null?I:c==null?void 0:c.forceMount;k(()=>{if(!p)return d.item(n,c==null?void 0:c.id)},[p]);let b=ve(n,u,[r.value,r.children,u],r.keywords),m=ee(),R=P(v=>v.value&&v.value===b.current),x=P(v=>p||d.filter()===!1?!0:v.search?v.filtered.items.get(n)>0:!0);t.useEffect(()=>{let v=u.current;if(!(!v||r.disabled))return v.addEventListener(Z,C),()=>v.removeEventListener(Z,C)},[x,r.onSelect,r.disabled]);function C(){var v,E;S(),(E=(v=f.current).onSelect)==null||E.call(v,b.current)}function S(){m.setState(\"value\",b.current,!0)}if(!x)return null;let{disabled:A,value:ge,onSelect:j,forceMount:O,keywords:$,...q}=r;return t.createElement(D.div,{ref:G(u,o),...q,id:n,\"cmdk-item\":\"\",role:\"option\",\"aria-disabled\":!!A,\"aria-selected\":!!R,\"data-disabled\":!!A,\"data-selected\":!!R,onPointerMove:A||d.getDisablePointerSelection()?void 0:S,onClick:A?void 0:C},r.children)}),Ee=t.forwardRef((r,o)=>{let{heading:n,children:u,forceMount:c,...d}=r,f=H(),p=t.useRef(null),b=t.useRef(null),m=H(),R=K(),x=P(S=>c||R.filter()===!1?!0:S.search?S.filtered.groups.has(f):!0);k(()=>R.group(f),[]),ve(f,p,[r.value,r.heading,b]);let C=t.useMemo(()=>({id:f,forceMount:c}),[c]);return t.createElement(D.div,{ref:G(p,o),...d,\"cmdk-group\":\"\",role:\"presentation\",hidden:x?void 0:!0},n&&t.createElement(\"div\",{ref:b,\"cmdk-group-heading\":\"\",\"aria-hidden\":!0,id:m},n),B(r,S=>t.createElement(\"div\",{\"cmdk-group-items\":\"\",role:\"group\",\"aria-labelledby\":n?m:void 0},t.createElement(fe.Provider,{value:C},S))))}),ye=t.forwardRef((r,o)=>{let{alwaysRender:n,...u}=r,c=t.useRef(null),d=P(f=>!f.search);return!n&&!d?null:t.createElement(D.div,{ref:G(c,o),...u,\"cmdk-separator\":\"\",role:\"separator\"})}),Se=t.forwardRef((r,o)=>{let{onValueChange:n,...u}=r,c=r.value!=null,d=ee(),f=P(m=>m.search),p=P(m=>m.selectedItemId),b=K();return t.useEffect(()=>{r.value!=null&&d.setState(\"search\",r.value)},[r.value]),t.createElement(D.input,{ref:o,...u,\"cmdk-input\":\"\",autoComplete:\"off\",autoCorrect:\"off\",spellCheck:!1,\"aria-autocomplete\":\"list\",role:\"combobox\",\"aria-expanded\":!0,\"aria-controls\":b.listId,\"aria-labelledby\":b.labelId,\"aria-activedescendant\":p,id:b.inputId,type:\"text\",value:c?r.value:f,onChange:m=>{c||d.setState(\"search\",m.target.value),n==null||n(m.target.value)}})}),Ce=t.forwardRef((r,o)=>{let{children:n,label:u=\"Suggestions\",...c}=r,d=t.useRef(null),f=t.useRef(null),p=P(m=>m.selectedItemId),b=K();return t.useEffect(()=>{if(f.current&&d.current){let m=f.current,R=d.current,x,C=new ResizeObserver(()=>{x=requestAnimationFrame(()=>{let S=m.offsetHeight;R.style.setProperty(\"--cmdk-list-height\",S.toFixed(1)+\"px\")})});return C.observe(m),()=>{cancelAnimationFrame(x),C.unobserve(m)}}},[]),t.createElement(D.div,{ref:G(d,o),...c,\"cmdk-list\":\"\",role:\"listbox\",tabIndex:-1,\"aria-activedescendant\":p,\"aria-label\":u,id:b.listId},B(r,m=>t.createElement(\"div\",{ref:G(f,b.listInnerRef),\"cmdk-list-sizer\":\"\"},m)))}),xe=t.forwardRef((r,o)=>{let{open:n,onOpenChange:u,overlayClassName:c,contentClassName:d,container:f,...p}=r;return t.createElement(w.Root,{open:n,onOpenChange:u},t.createElement(w.Portal,{container:f},t.createElement(w.Overlay,{\"cmdk-overlay\":\"\",className:c}),t.createElement(w.Content,{\"aria-label\":r.label,\"cmdk-dialog\":\"\",className:d},t.createElement(me,{ref:o,...p}))))}),Ie=t.forwardRef((r,o)=>P(u=>u.filtered.count===0)?t.createElement(D.div,{ref:o,...r,\"cmdk-empty\":\"\",role:\"presentation\"}):null),Pe=t.forwardRef((r,o)=>{let{progress:n,children:u,label:c=\"Loading...\",...d}=r;return t.createElement(D.div,{ref:o,...d,\"cmdk-loading\":\"\",role:\"progressbar\",\"aria-valuenow\":n,\"aria-valuemin\":0,\"aria-valuemax\":100,\"aria-label\":c},B(r,f=>t.createElement(\"div\",{\"aria-hidden\":!0},f)))}),_e=Object.assign(me,{List:Ce,Item:he,Input:Se,Group:Ee,Separator:ye,Dialog:xe,Empty:Ie,Loading:Pe});function we(r,o){let n=r.nextElementSibling;for(;n;){if(n.matches(o))return n;n=n.nextElementSibling}}function De(r,o){let n=r.previousElementSibling;for(;n;){if(n.matches(o))return n;n=n.previousElementSibling}}function pe(r){let o=t.useRef(r);return k(()=>{o.current=r}),o}var k=typeof window==\"undefined\"?t.useEffect:t.useLayoutEffect;function L(r){let o=t.useRef();return o.current===void 0&&(o.current=r()),o}function P(r){let o=ee(),n=()=>r(o.snapshot());return t.useSyncExternalStore(o.subscribe,n,n)}function ve(r,o,n,u=[]){let c=t.useRef(),d=K();return k(()=>{var b;let f=(()=>{var m;for(let R of n){if(typeof R==\"string\")return R.trim();if(typeof R==\"object\"&&\"current\"in R)return R.current?(m=R.current.textContent)==null?void 0:m.trim():c.current}})(),p=u.map(m=>m.trim());d.value(r,f,p),(b=o.current)==null||b.setAttribute(T,f),c.current=f}),c}var ke=()=>{let[r,o]=t.useState(),n=L(()=>new Map);return k(()=>{n.current.forEach(u=>u()),n.current=new Map},[r]),(u,c)=>{n.current.set(u,c),o({})}};function Me(r){let o=r.type;return typeof o==\"function\"?o(r.props):\"render\"in o?o.render(r.props):r}function B({asChild:r,children:o},n){return r&&t.isValidElement(o)?t.cloneElement(Me(o),{ref:o.ref},n(o.props.children)):n(o)}var Te={position:\"absolute\",width:\"1px\",height:\"1px\",padding:\"0\",margin:\"-1px\",overflow:\"hidden\",clip:\"rect(0, 0, 0, 0)\",whiteSpace:\"nowrap\",borderWidth:\"0\"};export{_e as Command,xe as CommandDialog,Ie as CommandEmpty,Ee as CommandGroup,Se as CommandInput,he as CommandItem,Ce as CommandList,Pe as CommandLoading,me as CommandRoot,ye as CommandSeparator,Re as defaultFilter,P as useCommandState};\n","/**\n * Thin wrapper shim around `cmdk` (the shadcn `Command` primitive).\n *\n * Re-exports the named subcomponents so the FormCacheSelector imports them\n * from `lib/ui/command`. Lets tests mock a single module instead of cmdk's\n * internals, and decouples future swaps to a Kit-provided combobox.\n *\n * All exports are forwardRef wrappers that apply shadcn-style Tailwind classes\n * so the combobox renders with correct padding, hover/selected states, and\n * scroll containment out of the box — matching the standard shadcn spec.\n */\n\nimport * as React from 'react';\nimport { Command as CommandPrimitive } from 'cmdk';\nimport { Search } from 'lucide-react';\n\nexport const Command = CommandPrimitive;\n\nexport const CommandList = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>\n>(({ className = '', ...props }, ref) => (\n  <CommandPrimitive.List\n    ref={ref}\n    className={['max-h-[300px] overflow-y-auto overflow-x-hidden', className].filter(Boolean).join(' ')}\n    {...props}\n  />\n));\nCommandList.displayName = 'CommandList';\n\nexport const CommandEmpty = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Empty>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>\n>(({ className = '', ...props }, ref) => (\n  <CommandPrimitive.Empty\n    ref={ref}\n    className={['py-6 text-center text-sm text-gray-500', className].filter(Boolean).join(' ')}\n    {...props}\n  />\n));\nCommandEmpty.displayName = 'CommandEmpty';\n\nexport const CommandGroup = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Group>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>\n>(({ className = '', ...props }, ref) => (\n  <CommandPrimitive.Group\n    ref={ref}\n    className={['overflow-hidden p-1 text-gray-900', className].filter(Boolean).join(' ')}\n    {...props}\n  />\n));\nCommandGroup.displayName = 'CommandGroup';\n\nexport const CommandItem = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>\n>(({ className = '', ...props }, ref) => (\n  <CommandPrimitive.Item\n    ref={ref}\n    className={['relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-gray-100', className].filter(Boolean).join(' ')}\n    {...props}\n  />\n));\nCommandItem.displayName = 'CommandItem';\n\nexport const CommandSeparator = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>\n>(({ className = '', ...props }, ref) => (\n  <CommandPrimitive.Separator\n    ref={ref}\n    className={['-mx-1 h-px bg-gray-200', className].filter(Boolean).join(' ')}\n    {...props}\n  />\n));\nCommandSeparator.displayName = 'CommandSeparator';\n\nexport const CommandInput = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Input>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>\n>(({ className = '', ...props }, ref) => (\n  <div className=\"flex items-center border-b px-3\" cmdk-input-wrapper=\"\">\n    <Search className=\"mr-2 h-4 w-4 shrink-0 text-gray-400\" aria-hidden=\"true\" />\n    <CommandPrimitive.Input\n      ref={ref}\n      className={['flex h-9 w-full bg-transparent py-2 text-sm outline-none placeholder:text-gray-400 disabled:cursor-not-allowed disabled:opacity-50', className].filter(Boolean).join(' ')}\n      {...props}\n    />\n  </div>\n));\nCommandInput.displayName = 'CommandInput';\n","/**\n * `<CacheSelector>` — the dropdown UI subcomponent of FormCacheSelector.\n *\n * Architecture §9.8 / UX §5.2 States 3-5 / §5.3 Component Composition.\n *\n * Composition:\n *   - shadcn `Popover` (D-UX-001 — Kit has no combobox primitive).\n *   - shadcn `Command` for accessible keyboard navigation + free-text search.\n *   - lucide-react `Check` and `ChevronDown` icons.\n *\n * Behavior:\n *   - \"Sin filtros\" pseudo-option always appears first (FR-FFCS-012). Its\n *     `value` is the reserved sentinel `__no_filter__` (R-002) — a string that\n *     can never collide with a user-chosen cache name.\n *   - Named caches are sorted alphabetically (case-insensitive, locale-aware)\n *     via `sortCaches`.\n *   - The active item shows a `Check` icon as prefix; inactive items reserve\n *     equivalent left padding so layout stays aligned.\n *   - `aria-expanded` on the trigger button (AC-009).\n *   - `aria-selected` on each `CommandItem` (AC-010).\n *\n * The actual side effects (GetById, safeParse, onSelected, UpdateLastInUse)\n * live in the parent hook's `handleSelectCache` / `handleSelectNoFilter` —\n * this component is a pure UI shell that forwards user clicks.\n */\n\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Check, ChevronDown } from 'lucide-react';\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from '../lib/ui/popover';\nimport {\n  Command,\n  CommandEmpty,\n  CommandGroup,\n  CommandInput,\n  CommandItem,\n  CommandList,\n} from '../lib/ui/command';\nimport { sortCaches } from '../FormCacheSelector.utils';\nimport type { FormCacheDTO } from '../FormCacheSelector.types';\n\n/** Reserved CommandItem value for the \"Sin filtros\" pseudo-option (R-002). */\nconst NO_FILTER_VALUE = '__no_filter__';\n\nexport interface CacheSelectorProps {\n  /** Caches to display in the dropdown — already deduplicated by the hook. */\n  caches: FormCacheDTO[];\n  /** Currently-selected cache id, or `null` when \"Sin filtros\" is active. */\n  activeId: string | null;\n  /** Click handler for a named cache item. May reject; errors are swallowed. */\n  onSelectCache: (cache: FormCacheDTO) => Promise<void>;\n  /** Click handler for the \"Sin filtros\" pseudo-option. */\n  onSelectNoFilter: () => void;\n  /** Localized label for the \"Sin filtros\" pseudo-option. */\n  noFilterLabel: string;\n}\n\nexport function CacheSelector({\n  caches,\n  activeId,\n  onSelectCache,\n  onSelectNoFilter,\n  noFilterLabel,\n}: CacheSelectorProps) {\n  const { t } = useTranslation('form-cache-selector');\n  const [open, setOpen] = useState(false);\n\n  const sorted = sortCaches(caches);\n  const activeName =\n    caches.find((c) => c.id === activeId)?.name ?? noFilterLabel;\n\n  const handleSelectCacheClick = (cache: FormCacheDTO) => {\n    // Fire-and-swallow: the parent handler may reject (e.g. GetById 404).\n    // That failure is reported via the error banner, not by re-throwing into\n    // React's render loop.\n    void onSelectCache(cache).catch(() => {\n      /* parent handler is responsible for surfacing this error */\n    });\n    setOpen(false);\n  };\n\n  const handleSelectNoFilterClick = () => {\n    onSelectNoFilter();\n    setOpen(false);\n  };\n\n  return (\n    <Popover open={open} onOpenChange={setOpen}>\n      <PopoverTrigger asChild>\n        <button\n          type=\"button\"\n          aria-expanded={open}\n          data-testid=\"cache-selector-trigger\"\n          className=\"inline-flex h-9 items-center justify-between gap-2 px-3 border border-gray-300 rounded-md text-sm w-full bg-white hover:border-gray-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-1\"\n        >\n          <span>{activeName}</span>\n          <ChevronDown className=\"h-4 w-4 shrink-0 text-gray-500\" aria-hidden=\"true\" />\n        </button>\n      </PopoverTrigger>\n      <PopoverContent>\n        <Command>\n          <CommandInput\n            placeholder={t('selector.searchPlaceholder')}\n            data-testid=\"cache-selector-search\"\n          />\n          <CommandList>\n            <CommandEmpty>{t('selector.noResults')}</CommandEmpty>\n            <CommandGroup>\n              <CommandItem\n                value={NO_FILTER_VALUE}\n                data-testid=\"cache-item-no-filter\"\n                onSelect={handleSelectNoFilterClick}\n                aria-selected={activeId === null}\n              >\n                {activeId === null ? (\n                  <Check data-testid=\"check-icon-no-filter\" />\n                ) : (\n                  <span className=\"inline-block w-4\" aria-hidden=\"true\" />\n                )}\n                <span>{noFilterLabel}</span>\n              </CommandItem>\n              {sorted.map((cache) => (\n                <CommandItem\n                  key={cache.id}\n                  value={cache.name}\n                  data-testid={`cache-item-${cache.id}`}\n                  onSelect={() => handleSelectCacheClick(cache)}\n                  aria-selected={activeId === cache.id}\n                >\n                  {activeId === cache.id ? (\n                    <Check data-testid={`check-icon-${cache.id}`} />\n                  ) : (\n                    <span className=\"inline-block w-4\" aria-hidden=\"true\" />\n                  )}\n                  <span>{cache.name}</span>\n                </CommandItem>\n              ))}\n            </CommandGroup>\n          </CommandList>\n        </Command>\n      </PopoverContent>\n    </Popover>\n  );\n}\n","/**\n * Radix-backed Dialog primitives.\n *\n * Replaces the earlier plain-DOM stub. The library owns its dialog rendering —\n * consumers do NOT need to override this via Vite alias.\n *\n * Consumers must provide an auth-aware `httpClient` prop to FormCacheSelector.\n */\n\nimport { Dialog as DialogPrimitive } from 'radix-ui';\nimport type { ReactNode, ComponentPropsWithoutRef, ElementRef } from 'react';\nimport * as React from 'react';\n\nexport interface DialogProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  children: ReactNode;\n}\n\nexport function Dialog({ open, onOpenChange, children }: DialogProps) {\n  return (\n    <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>\n      {children}\n    </DialogPrimitive.Root>\n  );\n}\n\nexport interface DialogContentProps {\n  children: ReactNode;\n  className?: string;\n}\n\nexport function DialogContent({ children, ...props }: DialogContentProps & Record<string, unknown>) {\n  return (\n    <DialogPrimitive.Portal>\n      <DialogPrimitive.Overlay className=\"fixed inset-0 z-50 bg-black/50\" />\n      <DialogPrimitive.Content className=\"fixed left-1/2 top-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-6 shadow-xl\" {...props}>\n        {children}\n      </DialogPrimitive.Content>\n    </DialogPrimitive.Portal>\n  );\n}\n\nexport interface DialogHeaderProps {\n  children: ReactNode;\n}\n\nexport function DialogHeader({ children }: DialogHeaderProps) {\n  return <div className=\"mb-4\">{children}</div>;\n}\n\nexport interface DialogTitleProps {\n  children: ReactNode;\n}\n\nexport function DialogTitle({ children }: DialogTitleProps) {\n  return (\n    <DialogPrimitive.Title className=\"text-lg font-semibold text-neutral-900\">\n      {children}\n    </DialogPrimitive.Title>\n  );\n}\n\nexport interface DialogDescriptionProps {\n  children: ReactNode;\n}\n\nexport function DialogDescription({ children }: DialogDescriptionProps) {\n  return (\n    <DialogPrimitive.Description className=\"text-sm text-neutral-500\">\n      {children}\n    </DialogPrimitive.Description>\n  );\n}\n\nexport interface DialogFooterProps {\n  children: ReactNode;\n}\n\nexport function DialogFooter({ children }: DialogFooterProps) {\n  return <div className=\"mt-6 flex justify-end gap-2\">{children}</div>;\n}\n\nexport const DialogClose = React.forwardRef<\n  ElementRef<typeof DialogPrimitive.Close>,\n  ComponentPropsWithoutRef<typeof DialogPrimitive.Close>\n>(({ className = '', ...props }, ref) => (\n  <DialogPrimitive.Close\n    ref={ref}\n    className={['rounded-sm opacity-70 hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400', className].filter(Boolean).join(' ')}\n    {...props}\n  />\n));\nDialogClose.displayName = 'DialogClose';\n","/**\n * `<SaveDialog>` — name-input dialog for the \"Save New\" flow.\n *\n * Architecture §9.4 / UX §5.2 State 6 / Story FFCS-FFCS-E003-S013.\n *\n * Composition:\n *   - `lib/ui/dialog` shim (kept aligned with the shadcn Dialog API).\n *   - Siesa UI Kit `Input` (label, placeholder, error state built-in).\n *   - Siesa UI Kit `Button` for Cancel (outline) and Save (filled).\n *   - lucide-react `Loader2` spinner while a mutation is in-flight.\n *   - lucide-react `X` for the close button.\n *   - `useFormCacheSelectorSchema` — Zod schema with i18n-bound messages.\n *\n * Behavior:\n *   - Auto-focused, single-line text input. Max length is 51 to allow Zod to\n *     report the over-50 error rather than silently truncating.\n *   - Character counter rendered as `{n} / 50` right-aligned below the input.\n *   - On submit:\n *       1. Run Zod validation locally — show inline error and short-circuit\n *          if invalid.\n *       2. Call `onSubmit(name)`. The parent hook handles the API call,\n *          409 surfacing, success banner, and dialog dismissal.\n *   - When the user types, both the local validation error and any server\n *     error (e.g. 409) are cleared so the user can retry without confusion.\n *   - `serverError` is a translation key supplied by the parent (e.g.\n *     `errors.nameAlreadyExists`). The dialog renders it through `t(...)`.\n */\n\nimport { useState, useEffect, type FormEvent } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Loader2, X } from 'lucide-react';\nimport { Button } from '@components/Button/Button';\nimport { Input } from '@components/Input/Input';\nimport {\n  Dialog,\n  DialogClose,\n  DialogContent,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from '../lib/ui/dialog';\nimport { useFormCacheSelectorSchema } from '../FormCacheSelector.schema';\n\nexport interface SaveDialogProps {\n  /** Whether the dialog is currently visible. Controlled by the parent. */\n  open: boolean;\n  /** Toggle handler — invoked when the dialog wants to close (e.g. cancel). */\n  onOpenChange: (open: boolean) => void;\n  /**\n   * Submit handler. Receives the trimmed user-supplied name. The parent is\n   * responsible for the actual upsert call, the 409 → serverError mapping,\n   * and dismissing the dialog on success.\n   */\n  onSubmit: (name: string) => Promise<void>;\n  /** True while any mutation is in-flight — disables submit, shows spinner. */\n  isMutating: boolean;\n  /**\n   * Translation key for a server-side error (typically a 409 conflict) to\n   * render inline. `null` when there is no server error to show.\n   */\n  serverError: string | null;\n  /** Clears the server error — called as the user starts editing the input. */\n  onServerErrorClear: () => void;\n}\n\nexport function SaveDialog({\n  open,\n  onOpenChange,\n  onSubmit,\n  isMutating,\n  serverError,\n  onServerErrorClear,\n}: SaveDialogProps) {\n  const { t } = useTranslation('form-cache-selector');\n  const schema = useFormCacheSelectorSchema();\n\n  const [name, setName] = useState('');\n  const [localError, setLocalError] = useState<string | null>(null);\n\n  useEffect(() => {\n    if (!open) {\n      setName('');\n      setLocalError(null);\n    }\n  }, [open]);\n\n  const handleChange = (value: string) => {\n    setName(value);\n    if (localError !== null) setLocalError(null);\n    if (serverError !== null) onServerErrorClear();\n  };\n\n  const runSubmit = async () => {\n    const trimmed = name.trim();\n    const result = schema.safeParse({ name: trimmed });\n    if (!result.success) {\n      const firstIssue = result.error.issues[0];\n      setLocalError(firstIssue?.message ?? t('validation.name.required'));\n      return;\n    }\n    setLocalError(null);\n    await onSubmit(trimmed);\n  };\n\n  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    await runSubmit();\n  };\n\n  const errorMessage =\n    localError !== null\n      ? localError\n      : serverError !== null\n        ? t(serverError)\n        : null;\n\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent data-testid=\"save-dialog\">\n        <DialogHeader>\n          <div className=\"flex items-start justify-between gap-4\">\n            <DialogTitle>{t('saveDialog.title')}</DialogTitle>\n            <DialogClose data-testid=\"save-dialog-close\">\n              <X className=\"h-4 w-4\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">{t('saveDialog.cancel')}</span>\n            </DialogClose>\n          </div>\n        </DialogHeader>\n        <form onSubmit={handleSubmit} className=\"mt-4\">\n          <Input\n            autoFocus\n            data-testid=\"save-dialog-name-input\"\n            label={t('saveDialog.nameLabel')}\n            placeholder={t('saveDialog.namePlaceholder')}\n            value={name}\n            onChange={(e) => handleChange(e.target.value)}\n            maxLength={51}\n            required\n            error={errorMessage !== null}\n          />\n          <div className=\"mt-1 flex items-start justify-between text-xs\">\n            {errorMessage !== null ? (\n              <span role=\"alert\" data-testid=\"save-dialog-error\" className=\"text-red-600\">\n                {errorMessage}\n              </span>\n            ) : (\n              <span />\n            )}\n            <span data-testid=\"char-counter\" className=\"text-gray-400\">\n              {name.length} / 50\n            </span>\n          </div>\n          <DialogFooter>\n            <Button\n              htmlType=\"button\"\n              type=\"outline\"\n              size=\"sm\"\n              data-testid=\"save-dialog-cancel\"\n              onClick={() => onOpenChange(false)}\n              disabled={isMutating}\n            >\n              {t('saveDialog.cancel')}\n            </Button>\n            <Button\n              htmlType=\"button\"\n              size=\"sm\"\n              data-testid=\"save-dialog-submit\"\n              disabled={isMutating}\n              onClick={() => { void runSubmit(); }}\n              leftIcon={\n                isMutating ? (\n                  <Loader2 className=\"h-4 w-4 animate-spin\" data-testid=\"save-spinner\" />\n                ) : undefined\n              }\n            >\n              {t('saveDialog.submit')}\n            </Button>\n          </DialogFooter>\n        </form>\n      </DialogContent>\n    </Dialog>\n  );\n}\n","/**\n * `<RenameDialog>` — name-input dialog for the \"Rename existing cache\" flow.\n *\n * Architecture §9.8 / UX §5.2 State 7 / Story FFCS-FFCS-E003-S014.\n *\n * Composition:\n *   - `lib/ui/dialog` shim (Radix-backed, canonical implementation).\n *   - Siesa UI Kit `Input` (label, error state built-in).\n *   - Siesa UI Kit `Button` for Cancel (outline) and Rename (filled).\n *   - lucide-react `Loader2` spinner while a mutation is in-flight.\n *   - lucide-react `X` for the close button.\n *   - `useFormCacheSelectorSchema` — Zod schema with i18n-bound messages.\n *\n * Behavior:\n *   - When opened, the input is pre-filled with `currentName` and focused.\n *     Re-initialisation happens on every false → true transition of `open`\n *     (R-001) — guarantees a stale value never bleeds in.\n *   - Character counter rendered as `{n} / 50` right-aligned below the input.\n *   - On submit:\n *       1. Run Zod validation locally — show inline error and short-circuit\n *          if invalid.\n *       2. Call `onSubmit(name)`. The parent hook handles the API call,\n *          409 surfacing, success banner, and dialog dismissal.\n *   - When the user types, both the local validation error and any server\n *     error (e.g. 409) are cleared so the user can retry without confusion.\n *   - `serverError` is a translation key supplied by the parent (e.g.\n *     `errors.nameAlreadyExists`). The dialog renders it through `t(...)`.\n */\n\nimport {\n  useEffect,\n  useRef,\n  useState,\n  type FormEvent,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Loader2, X } from 'lucide-react';\nimport { Button } from '@components/Button/Button';\nimport { Input } from '@components/Input/Input';\nimport {\n  Dialog,\n  DialogClose,\n  DialogContent,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from '../lib/ui/dialog';\nimport { useFormCacheSelectorSchema } from '../FormCacheSelector.schema';\n\nexport interface RenameDialogProps {\n  /** Whether the dialog is currently visible. Controlled by the parent. */\n  open: boolean;\n  /** Toggle handler — invoked when the dialog wants to close (e.g. cancel). */\n  onOpenChange: (open: boolean) => void;\n  /** Current cache name — pre-fills the input every time the dialog opens. */\n  currentName: string;\n  /**\n   * Submit handler. Receives the trimmed user-supplied name. The parent is\n   * responsible for the actual rename call, the 409 → serverError mapping,\n   * and dismissing the dialog on success / 404.\n   */\n  onSubmit: (name: string) => Promise<void>;\n  /** True while any mutation is in-flight — disables submit, shows spinner. */\n  isMutating: boolean;\n  /**\n   * Translation key for a server-side error (typically a 409 conflict) to\n   * render inline. `null` when there is no server error to show.\n   */\n  serverError: string | null;\n  /** Clears the server error — called as the user starts editing the input. */\n  onServerErrorClear: () => void;\n}\n\nexport function RenameDialog({\n  open,\n  onOpenChange,\n  currentName,\n  onSubmit,\n  isMutating,\n  serverError,\n  onServerErrorClear,\n}: RenameDialogProps) {\n  const { t } = useTranslation('form-cache-selector');\n  const schema = useFormCacheSelectorSchema();\n\n  const [name, setName] = useState(currentName);\n  const [localError, setLocalError] = useState<string | null>(null);\n  const inputRef = useRef<HTMLInputElement | null>(null);\n\n  // Re-initialise the input from `currentName` whenever the dialog opens\n  // (R-001). Clear any stale server error so a previous 409 doesn't bleed\n  // into a fresh open. Defer focus + select to the next microtask so the\n  // input is mounted (R-003).\n  useEffect(() => {\n    if (open) {\n      setName(currentName);\n      setLocalError(null);\n      if (serverError !== null) onServerErrorClear();\n      queueMicrotask(() => {\n        inputRef.current?.focus();\n        inputRef.current?.select();\n      });\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, currentName]);\n\n  const handleChange = (value: string) => {\n    setName(value);\n    if (localError !== null) setLocalError(null);\n    if (serverError !== null) onServerErrorClear();\n  };\n\n  const runSubmit = async () => {\n    const trimmed = name.trim();\n    const result = schema.safeParse({ name: trimmed });\n    if (!result.success) {\n      const firstIssue = result.error.issues[0];\n      setLocalError(firstIssue?.message ?? t('validation.name.required'));\n      return;\n    }\n    setLocalError(null);\n    await onSubmit(trimmed);\n  };\n\n  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    await runSubmit();\n  };\n\n  const errorMessage =\n    localError !== null\n      ? localError\n      : serverError !== null\n        ? t(serverError)\n        : null;\n\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent data-testid=\"rename-dialog\">\n        <DialogHeader>\n          <div className=\"flex items-start justify-between gap-4\">\n            <DialogTitle>{t('renameDialog.title')}</DialogTitle>\n            <DialogClose data-testid=\"rename-dialog-close\">\n              <X className=\"h-4 w-4\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">{t('renameDialog.cancel')}</span>\n            </DialogClose>\n          </div>\n        </DialogHeader>\n        <form onSubmit={handleSubmit} className=\"mt-4\">\n          <Input\n            ref={inputRef}\n            autoFocus\n            data-testid=\"rename-dialog-input\"\n            label={t('renameDialog.nameLabel')}\n            value={name}\n            onChange={(e) => handleChange(e.target.value)}\n            maxLength={51}\n            required\n            error={errorMessage !== null}\n          />\n          <div className=\"mt-1 flex items-start justify-between text-xs\">\n            {errorMessage !== null ? (\n              <span role=\"alert\" data-testid=\"rename-dialog-error\" className=\"text-red-600\">\n                {errorMessage}\n              </span>\n            ) : (\n              <span />\n            )}\n            <span data-testid=\"rename-char-counter\" className=\"text-gray-400\">\n              {name.length} / 50\n            </span>\n          </div>\n          <DialogFooter>\n            <Button\n              htmlType=\"button\"\n              type=\"outline\"\n              size=\"sm\"\n              data-testid=\"rename-dialog-cancel\"\n              onClick={() => onOpenChange(false)}\n              disabled={isMutating}\n            >\n              {t('renameDialog.cancel')}\n            </Button>\n            <Button\n              htmlType=\"button\"\n              size=\"sm\"\n              data-testid=\"rename-dialog-submit\"\n              disabled={isMutating}\n              onClick={() => { void runSubmit(); }}\n              leftIcon={\n                isMutating ? (\n                  <Loader2 className=\"h-4 w-4 animate-spin\" data-testid=\"rename-spinner\" />\n                ) : undefined\n              }\n            >\n              {t('renameDialog.submit')}\n            </Button>\n          </DialogFooter>\n        </form>\n      </DialogContent>\n    </Dialog>\n  );\n}\n","import { Loader2, AlertTriangle, X } from 'lucide-react';\nimport { useTranslation } from 'react-i18next';\nimport { Button } from '@components/Button/Button';\nimport {\n  Dialog,\n  DialogClose,\n  DialogContent,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from '../lib/ui/dialog';\n\nexport interface DeleteDialogProps {\n  /** Whether the dialog is currently visible. Controlled by the parent. */\n  open: boolean;\n  /** Toggle handler — invoked when the dialog wants to close (e.g. cancel). */\n  onOpenChange: (open: boolean) => void;\n  /**\n   * Snapshot of the active cache name at dialog-open time (R-001). The parent\n   * captures it via `openDeleteDialog` and freezes it for the lifetime of the\n   * dialog so a concurrent rename does not change the displayed name.\n   */\n  cacheName: string;\n  /**\n   * Confirm handler — runs the delete mutation in the parent hook. The dialog\n   * does NOT close itself on confirm; the parent dismisses it as part of the\n   * mutation's success / failure branches.\n   */\n  onConfirm: () => Promise<void>;\n  /** True while any mutation is in-flight — disables buttons, shows spinner. */\n  isMutating: boolean;\n}\n\nexport function DeleteDialog({\n  open,\n  onOpenChange,\n  cacheName,\n  onConfirm,\n  isMutating,\n}: DeleteDialogProps) {\n  const { t } = useTranslation('form-cache-selector');\n\n  const handleConfirm = async () => {\n    await onConfirm();\n  };\n\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent data-testid=\"delete-dialog\">\n        <DialogHeader>\n          <div className=\"flex items-start justify-between gap-4\">\n            <div className=\"flex items-center gap-3\">\n              <div className=\"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-amber-100\">\n                <AlertTriangle\n                  data-testid=\"alert-triangle-icon\"\n                  className=\"h-5 w-5 text-amber-600\"\n                />\n              </div>\n              <DialogTitle>{t('deleteDialog.title')}</DialogTitle>\n            </div>\n            <DialogClose data-testid=\"delete-dialog-close\">\n              <X className=\"h-4 w-4\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">{t('deleteDialog.closeButton')}</span>\n            </DialogClose>\n          </div>\n        </DialogHeader>\n        <div className=\"mt-4 space-y-1\">\n          <p data-testid=\"delete-confirm-text\" className=\"text-sm text-neutral-500\">\n            {t('deleteDialog.confirm', { name: cacheName })}\n          </p>\n          <p data-testid=\"delete-warning-text\" className=\"text-sm text-neutral-500\">\n            {t('deleteDialog.warning')}\n          </p>\n        </div>\n        <DialogFooter>\n          <Button\n            htmlType=\"button\"\n            type=\"outline\"\n            size=\"sm\"\n            autoFocus\n            data-testid=\"delete-dialog-cancel\"\n            onClick={() => onOpenChange(false)}\n            disabled={isMutating}\n          >\n            {t('deleteDialog.cancel')}\n          </Button>\n          <Button\n            htmlType=\"button\"\n            type=\"plain\"\n            size=\"sm\"\n            style={{ backgroundColor: 'var(--color-error-border)', color: 'white' }}\n            data-testid=\"delete-dialog-confirm\"\n            onClick={() => { void handleConfirm(); }}\n            disabled={isMutating}\n            leftIcon={\n              isMutating ? (\n                <Loader2 className=\"h-4 w-4 animate-spin\" data-testid=\"delete-spinner\" />\n              ) : undefined\n            }\n          >\n            {t('deleteDialog.confirmButton')}\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n","/**\n * `<FormCacheSelector>` — root component for the FormCacheSelector library.\n *\n * In this story (S015) the component adds:\n *   - A Delete icon button visible only when a cache is active (FR-FFCS-018).\n *     Desktop: standalone Trash2 button styled with `text-red-600`.\n *     Mobile: entry inside the overflow `DropdownMenu` next to Rename — also\n *     styled with `text-red-600` so the destructive intent is consistent\n *     across breakpoints (R-003).\n *   - The `DeleteDialog` wired into the hook's `deleteDialogOpen` /\n *     `deletingCacheName` / `handleDelete` API. The hook's `openDeleteDialog`\n *     helper is what the buttons invoke — it snapshots the active cache name\n *     before opening so the dialog title is frozen for the lifetime of the\n *     confirmation (R-001).\n *\n * Earlier stories established:\n *   - Developer-facing assertions for `cacheId` and `filter` (FR-FFCS-019).\n *   - Loading skeleton render branch while GetAllByUser is in-flight.\n *   - Wiring to `useFormCacheSelector` so the mount-time auto-restore flow\n *     fires `onSelected` exactly once.\n *   - Save button + SaveDialog (S013).\n *   - Rename icon button (desktop) + DropdownMenu entry (mobile) + RenameDialog (S014).\n */\n\nimport { useImperativeHandle, type Ref } from 'react';\nimport { Loader2, Pencil, Save, Trash2 } from 'lucide-react';\nimport { useTranslation } from 'react-i18next';\nimport { createPortal } from 'react-dom';\nimport { Button } from '@components/Button/Button';\nimport { toast } from '@components/Toast';\nimport { useFormCacheSelector } from './FormCacheSelector.hooks';\nimport { CacheSelector } from './subcomponents/CacheSelector';\nimport { SaveDialog } from './subcomponents/SaveDialog';\nimport { RenameDialog } from './subcomponents/RenameDialog';\nimport { DeleteDialog } from './subcomponents/DeleteDialog';\nimport type { FormCacheSelectorHandle, FormCacheSelectorProps } from './FormCacheSelector.types';\n\nexport function FormCacheSelector<TFilter>(\n  props: FormCacheSelectorProps<TFilter> & { ref?: Ref<FormCacheSelectorHandle> },\n) {\n  const { ref, cacheId, filter, onSelected, httpClient } = props;\n  const { t } = useTranslation('form-cache-selector');\n\n  // ── Developer assertions (FR-FFCS-019) ───────────────────────────────────\n  // These are contract violations by the consuming developer — surface them\n  // loudly via console.error + throw so they fail builds in CI and crash\n  // visibly in development. They are NOT user-facing errors.\n  if (!cacheId || cacheId.length === 0) {\n    const message = '[FormCacheSelector] cacheId must be a non-empty string';\n    console.error(message);\n    throw new Error(message);\n  }\n  if (filter === null || filter === undefined) {\n    const message = '[FormCacheSelector] filter must not be null or undefined';\n    console.error(message);\n    throw new Error(message);\n  }\n\n  const {\n    caches,\n    activeId,\n    isLoading,\n    isMutating,\n    saveDialogOpen,\n    setSaveDialogOpen,\n    saveNameError,\n    clearSaveNameError,\n    renameDialogOpen,\n    setRenameDialogOpen,\n    renameError,\n    clearRenameError,\n    deleteDialogOpen,\n    setDeleteDialogOpen,\n    deletingCacheName,\n    openDeleteDialog,\n    activeToast,\n    handleSelectCache,\n    handleSelectNoFilter,\n    handleUpsert,\n    handleRename,\n    handleDelete,\n    setActiveId,\n  } = useFormCacheSelector<TFilter>(cacheId, filter, onSelected, httpClient);\n\n  useImperativeHandle(ref, () => ({ clearSelection: () => setActiveId(null) }), [setActiveId]);\n\n  // ── Loading skeleton (UX §5.2 State 1) ───────────────────────────────────\n  if (isLoading) {\n    return (\n      <div\n        data-testid=\"form-cache-skeleton\"\n        className=\"animate-pulse h-8 w-full rounded bg-gray-200\"\n        role=\"status\"\n        aria-label={t('selector.loadingAriaLabel')}\n      />\n    );\n  }\n\n  /**\n   * Save button click coordinator (FR-FFCS-015 / FR-FFCS-016).\n   *\n   * - When a cache is active: overwrite path (silent, no dialog). We look up\n   *   the cache name from the local list and call `handleUpsert` directly.\n   *   D-UX-007: the overwrite is non-destructive (user is overwriting their\n   *   own state), so no confirmation is required.\n   * - When no cache is active: open the SaveDialog so the user can supply a\n   *   name. The dialog itself calls `handleUpsert` with the user's input.\n   */\n  const handleSaveClick = () => {\n    if (activeId !== null) {\n      const activeCache = caches.find((c) => c.id === activeId);\n      // If the active id has somehow drifted from the local list (race with a\n      // refetch), fall back to opening the dialog instead of sending an empty\n      // name to the server.\n      if (activeCache) {\n        void handleUpsert(activeCache.name);\n        return;\n      }\n    }\n    setSaveDialogOpen(true);\n  };\n\n  // ── Active cache lookup for rename pre-fill ──────────────────────────────\n  // The trigger label and rename dialog both read from this. When `activeId`\n  // is null the rename affordances are hidden, so we fall back to '' safely.\n  const activeCache =\n    activeId !== null ? caches.find((c) => c.id === activeId) : undefined;\n  const activeName = activeCache?.name ?? '';\n\n  const openRenameDialog = () => setRenameDialogOpen(true);\n\n  // ── Main render — dropdown selector + action buttons + dialogs ───────────\n  // i18n wiring lands in a follow-up integration story; for now we ship the\n  // canonical Spanish copy hardcoded at the boundary so the component is\n  // useful end-to-end.\n  return (\n    <div data-testid=\"form-cache-selector\" className=\"flex flex-col gap-1.5\">\n      {/* ── Button row: selector + save + rename/delete/more ────────────── */}\n      <div className=\"flex items-center gap-1.5\">\n        <div className=\"flex-1 min-w-0\">\n          <CacheSelector\n            caches={caches}\n            activeId={activeId}\n            onSelectCache={handleSelectCache}\n            onSelectNoFilter={handleSelectNoFilter}\n            noFilterLabel={t('selector.noFilter')}\n          />\n        </div>\n        <Button\n          htmlType=\"button\"\n          iconOnly\n          type=\"outline\"\n          size=\"sm\"\n          leftIcon={isMutating ? <Loader2 className=\"h-4 w-4 animate-spin\" data-testid=\"save-spinner\" /> : <Save className=\"h-4 w-4\" data-testid=\"save-icon\" />}\n          disabled={isMutating}\n          ariaLabel={t('selector.saveAriaLabel')}\n          onClick={handleSaveClick}\n          data-testid=\"form-cache-save-btn\"\n        />\n        {activeId !== null && (\n          <>\n            <Button\n              htmlType=\"button\"\n              iconOnly\n              type=\"outline\"\n              size=\"sm\"\n              leftIcon={<Pencil className=\"h-4 w-4\" data-testid=\"pencil-icon\" />}\n              disabled={isMutating}\n              ariaLabel={t('selector.renameAriaLabel')}\n              onClick={openRenameDialog}\n              data-testid=\"form-cache-rename-btn\"\n            />\n            <Button\n              htmlType=\"button\"\n              iconOnly\n              type=\"outline\"\n              size=\"sm\"\n              className=\"text-red-600 hover:text-red-600\"\n              leftIcon={<Trash2 className=\"h-4 w-4\" data-testid=\"trash-icon\" />}\n              disabled={isMutating}\n              ariaLabel={t('selector.deleteAriaLabel')}\n              onClick={openDeleteDialog}\n              data-testid=\"form-cache-delete-btn\"\n            />\n          </>\n        )}\n      </div>\n      <SaveDialog\n        open={saveDialogOpen}\n        onOpenChange={setSaveDialogOpen}\n        onSubmit={handleUpsert}\n        isMutating={isMutating}\n        serverError={saveNameError}\n        onServerErrorClear={clearSaveNameError}\n      />\n      <RenameDialog\n        open={renameDialogOpen}\n        onOpenChange={setRenameDialogOpen}\n        currentName={activeName}\n        onSubmit={handleRename}\n        isMutating={isMutating}\n        serverError={renameError}\n        onServerErrorClear={clearRenameError}\n      />\n      <DeleteDialog\n        open={deleteDialogOpen}\n        onOpenChange={setDeleteDialogOpen}\n        cacheName={deletingCacheName}\n        onConfirm={handleDelete}\n        isMutating={isMutating}\n      />\n      {activeToast && (() => {\n        const { text, color } = activeToast;\n        const toastType = color === 'red' ? 'error' : color === 'green' ? 'success' : 'info';\n\n        setTimeout(() => {\n          if (toastType === 'error') {\n            toast.error(text);\n          } else if (toastType === 'success') {\n            toast.success(text);\n          } else {\n            toast(text);\n          }\n        }, 0);\n\n        return null;\n      })()\n      }\n    </div>\n  );\n}\n","import React from 'react';\nimport {\n  BuildingOfficeIcon as HeroBuildingOffice,\n  DocumentTextIcon as HeroDocumentText,\n  MapPinIcon as HeroMapPin,\n  CalendarIcon as HeroCalendar,\n  HashtagIcon as HeroHashtag,\n} from '@heroicons/react/24/outline';\n\nexport const BuildingOfficeIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroBuildingOffice className={className} aria-hidden=\"true\" />\n);\n\nexport const DocumentTextIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroDocumentText className={className} aria-hidden=\"true\" />\n);\n\nexport const MapPinIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroMapPin className={className} aria-hidden=\"true\" />\n);\n\nexport const CalendarIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroCalendar className={className} aria-hidden=\"true\" />\n);\n\nexport const HashtagIcon: React.FC<{ className?: string }> = ({ className = 'size-5' }) => (\n  <HeroHashtag className={className} aria-hidden=\"true\" />\n);\n","import React from 'react';\nimport type { PanelCompanyProps } from './PanelCompany.types';\nimport { BuildingOfficeIcon } from './icons';\n\n/**\n * PanelCompany from the Siesa design system\n *\n * Panel horizontal para mostrar la información principal de la compañía y detalles\n * del documento actual. Contiene secciones separadas por divisores verticales.\n *\n * Implemented best practices:\n * - Modifier order: {responsive}:{dark}:{state}:{utility}\n * - Dark mode with 'class' strategy (darkMode: 'class')\n * - Color tokens consistent with documentation\n * - Type safety with strict TypeScript\n *\n * @see docs/colors.md - Color system\n * @see docs/spacing.md - Spacing system\n *\n * @example\n * ```tsx\n * <PanelCompany\n *   companyName=\"Empresa Demo\"\n *   companyId=\"NIT: 900.123.456-7\"\n *   fields={[...]}\n * />\n * ```\n */\nexport const PanelCompany: React.FC<PanelCompanyProps> = ({\n  companyName,\n  companyId,\n  fields,\n  className = '',\n}) => {\n  return (\n    <div\n      className={[\n        'flex',\n        'flex-row',\n        'items-stretch',\n        'border',\n        'border-border-primary',\n        'bg-bg-primary',\n        'rounded-xl',\n        'overflow-hidden',\n        'dark:border-dark-border-primary',\n        'dark:bg-dark-bg-primary',\n        className,\n      ]\n        .join(' ')\n        .replace(/\\s+/g, ' ')\n        .trim()}\n    >\n      {/* Primera sección: Header de la compañía */}\n      <div className=\"flex shrink-0 items-center gap-2 bg-gradient-to-r from-tertiary-600 to-tertiary-800 p-2 dark:from-tertiary-600 dark:to-tertiary-800\">\n        <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-50 dark:bg-dark-bg-custom\">\n          <BuildingOfficeIcon className=\"size-5 text-primary-600 dark:text-dark-content-primary\" />\n        </div>\n        <div className=\"flex flex-col justify-center\">\n          <span className=\"text-xs leading-tight text-primary-50 dark:text-primary-50\">\n            {companyName}\n          </span>\n          <span className=\"text-xs font-bold leading-tight text-zinc-100 dark:text-zinc-100\">\n            {companyId}\n          </span>\n        </div>\n      </div>\n\n      {/* Otras secciones */}\n      {fields.map((field, index) => (\n        <React.Fragment key={index}>\n          {/* Divisor vertical */}\n          <div className=\"w-px shrink-0 bg-border-primary dark:bg-dark-border-primary\" />\n\n          {/* Contenido del campo */}\n          <div\n            className={`flex flex-1 items-center gap-2 ${\n              field.isDocument ? 'p-2' : 'px-4 py-3'\n            }`}\n          >\n            <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-bg-primary dark:bg-dark-bg-primary\">\n              {React.isValidElement(field.icon) ? (\n                React.cloneElement(field.icon as React.ReactElement<{ className?: string }>, {\n                  className: 'size-5 text-primary-600 dark:text-primary-300',\n                })\n              ) : (\n                field.icon\n              )}\n            </div>\n            <div className=\"flex flex-col justify-center gap-0.5\">\n              <span className=\"text-xs leading-tight text-content-secondary dark:text-dark-content-secondary\">\n                {field.label}\n              </span>\n              <span className=\"text-sm font-bold leading-tight text-content-primary dark:text-dark-content-primary\">\n                {field.value}\n              </span>\n            </div>\n          </div>\n        </React.Fragment>\n      ))}\n    </div>\n  );\n};\n"],"names":["r","f","n","o","clsx","falsyToString","value","cx","cva","base","config","props","_config_compoundVariants","variants","defaultVariants","getVariantClassNames","variant","variantProp","defaultVariantProp","variantKey","propsWithoutUndefined","acc","param","key","getCompoundVariantClassNames","cvClass","cvClassName","compoundVariantOptions","inputs","buttonVariants","iconSizeClasses","Button","type","color","size","iconOnly","leftIcon","rightIcon","children","disabled","className","onClick","htmlType","fullWidth","ariaLabel","badge","badgeCount","rest","renderIcon","icon","jsx","renderContent","jsxs","Fragment","renderBadge","concatArrays","array1","array2","combinedArray","i","createClassValidatorObject","classGroupId","validator","createClassPartObject","nextPart","validators","CLASS_PART_SEPARATOR","EMPTY_CONFLICTS","ARBITRARY_PROPERTY_PREFIX","createClassGroupUtils","classMap","createClassMap","conflictingClassGroups","conflictingClassGroupModifiers","getGroupIdForArbitraryProperty","classParts","startIndex","getGroupRecursive","hasPostfixModifier","modifierConflicts","baseConflicts","classPartObject","currentClassPart","nextClassPartObject","result","classRest","validatorsLength","validatorObj","content","colonIndex","property","theme","classGroups","processClassGroups","group","processClassesRecursively","classGroup","len","classDefinition","processClassDefinition","processStringDefinition","processFunctionDefinition","processObjectDefinition","classPartObjectToEdit","getPart","isThemeGetter","entries","path","current","parts","part","next","func","createLruCache","maxCacheSize","cacheSize","cache","previousCache","update","IMPORTANT_MODIFIER","MODIFIER_SEPARATOR","EMPTY_MODIFIERS","createResultObject","modifiers","hasImportantModifier","baseClassName","maybePostfixModifierPosition","isExternal","createParseClassName","prefix","experimentalParseClassName","parseClassName","bracketDepth","parenDepth","modifierStart","postfixModifierPosition","index","currentCharacter","baseClassNameWithImportantModifier","fullPrefix","parseClassNameOriginal","createSortModifiers","modifierWeights","mod","currentSegment","modifier","isArbitrary","isOrderSensitive","createConfigUtils","SPLIT_CLASSES_REGEX","mergeClassList","classList","configUtils","getClassGroupId","getConflictingClassGroupIds","sortModifiers","classGroupsInConflict","classNames","originalClassName","variantModifier","modifierId","classId","conflictGroups","twJoin","classLists","argument","resolvedValue","string","toValue","mix","k","createTailwindMerge","createConfigFirst","createConfigRest","cacheGet","cacheSet","functionToCall","initTailwindMerge","previousConfig","createConfigCurrent","tailwindMerge","cachedResult","args","fallbackThemeArr","fromTheme","themeGetter","arbitraryValueRegex","arbitraryVariableRegex","fractionRegex","tshirtUnitRegex","lengthUnitRegex","colorFunctionRegex","shadowRegex","imageRegex","isFraction","isNumber","isInteger","isPercent","isTshirtSize","isAny","isLengthOnly","isNever","isShadow","isImage","isAnyNonArbitrary","isArbitraryValue","isArbitraryVariable","isArbitrarySize","getIsArbitraryValue","isLabelSize","isArbitraryLength","isLabelLength","isArbitraryNumber","isLabelNumber","isArbitraryPosition","isLabelPosition","isArbitraryImage","isLabelImage","isArbitraryShadow","isLabelShadow","isArbitraryVariableLength","getIsArbitraryVariable","isArbitraryVariableFamilyName","isLabelFamilyName","isArbitraryVariablePosition","isArbitraryVariableSize","isArbitraryVariableImage","isArbitraryVariableShadow","testLabel","testValue","shouldMatchNoLabel","label","getDefaultConfig","themeColor","themeFont","themeText","themeFontWeight","themeTracking","themeLeading","themeBreakpoint","themeContainer","themeSpacing","themeRadius","themeShadow","themeInsetShadow","themeTextShadow","themeDropShadow","themeBlur","themePerspective","themeAspect","themeEase","themeAnimate","scaleBreak","scalePosition","scalePositionWithArbitrary","scaleOverflow","scaleOverscroll","scaleUnambiguousSpacing","scaleInset","scaleGridTemplateColsRows","scaleGridColRowStartAndEnd","scaleGridColRowStartOrEnd","scaleGridAutoColsRows","scaleAlignPrimaryAxis","scaleAlignSecondaryAxis","scaleMargin","scaleSizing","scaleColor","scaleBgPosition","scaleBgRepeat","scaleBgSize","scaleGradientStopPosition","scaleRadius","scaleBorderWidth","scaleLineStyle","scaleBlendMode","scaleMaskImagePosition","scaleBlur","scaleRotate","scaleScale","scaleSkew","scaleTranslate","twMerge","cn","ButtonGroup","options","onChange","option","isFirst","isLast","isSelected","isDisabled","isIconOnly","iconPos","iconElement","labelElement","labelVariants","inputVariants","iconSizeMap","Input","React","description","helperText","errorMessage","id","inputSize","actionText","ref","generatedId","inputId","Textarea","forwardRef","error","textareaSize","resize","rows","useState","textareaId","sizeClasses","Checkbox","providedId","invalid","labelPosition","indeterminate","fallbackId","useId","inputRef","isError","textSizes","containerClasses","boxClasses","composeEventHandlers","originalEventHandler","ourEventHandler","checkForDefaultPrevented","event","setRef","composeRefs","refs","node","hasCleanup","cleanups","cleanup","useComposedRefs","createContext2","rootComponentName","defaultContext","Context","Provider","context","useContext2","consumerName","createContextScope","scopeName","createContextScopeDeps","defaultContexts","createContext3","BaseContext","scope","createScope","scopeContexts","contexts","composeContextScopes","scopes","baseScope","scopeHooks","createScope2","overrideScopes","nextScopes","nextScopes2","useScope","currentScope","createSlot","ownerName","SlotClone","createSlotClone","Slot2","forwardedRef","slotProps","childrenArray","slottable","isSlottable","newElement","newChildren","child","childrenRef","getElementRef","props2","mergeProps","SLOTTABLE_IDENTIFIER","childProps","overrideProps","propName","slotPropValue","childPropValue","element","getter","mayWarn","NODES","Primitive","primitive","Slot","Node","asChild","primitiveProps","Comp","dispatchDiscreteCustomEvent","target","ReactDOM","createCollection","name","PROVIDER_NAME","createCollectionContext","createCollectionScope","CollectionProviderImpl","useCollectionContext","CollectionProvider","itemMap","COLLECTION_SLOT_NAME","CollectionSlotImpl","CollectionSlot","composedRefs","ITEM_SLOT_NAME","ITEM_DATA_ATTR","CollectionItemSlotImpl","CollectionItemSlot","itemData","useCollection","collectionNode","orderedNodes","a","b","useLayoutEffect2","useReactId","count","deterministicId","setId","useLayoutEffect","reactId","useCallbackRef","callback","callbackRef","useInsertionEffect","useControllableState","prop","defaultProp","caller","uncontrolledProp","setUncontrolledProp","onChangeRef","useUncontrolledState","isControlled","isControlledRef","wasControlled","setValue","nextValue","value2","isFunction","prevValueRef","DirectionContext","useDirection","localDir","globalDir","ENTRY_FOCUS","EVENT_OPTIONS","GROUP_NAME","Collection","createRovingFocusGroupContext","createRovingFocusGroupScope","RovingFocusProvider","useRovingFocusContext","RovingFocusGroup","RovingFocusGroupImpl","__scopeRovingFocusGroup","orientation","loop","dir","currentTabStopIdProp","defaultCurrentTabStopId","onCurrentTabStopIdChange","onEntryFocus","preventScrollOnEntryFocus","groupProps","direction","currentTabStopId","setCurrentTabStopId","isTabbingBackOut","setIsTabbingBackOut","handleEntryFocus","getItems","isClickFocusRef","focusableItemsCount","setFocusableItemsCount","tabStopId","prevCount","isKeyboardFocus","entryFocusEvent","items","item","activeItem","currentItem","candidateNodes","focusFirst","ITEM_NAME","RovingFocusGroupItem","focusable","active","itemProps","autoId","isCurrentTabStop","onFocusableItemAdd","onFocusableItemRemove","focusIntent","getFocusIntent","currentIndex","wrapArray","MAP_KEY_TO_FOCUS_INTENT","getDirectionAwareKey","candidates","preventScroll","PREVIOUSLY_FOCUSED_ELEMENT","candidate","array","_","Root","Item","useSize","setSize","resizeObserver","entry","width","height","borderSizeEntry","borderSize","usePrevious","useStateMachine","initialState","machine","state","Presence","present","presence","usePresence","React2","setNode","stylesRef","prevPresentRef","prevAnimationNameRef","send","currentAnimationName","getAnimationName","styles","wasPresent","prevAnimationName","timeoutId","ownerWindow","handleAnimationEnd","isCurrentAnimation","currentFillMode","handleAnimationStart","node2","RADIO_NAME","createRadioContext","createRadioScope","RadioProvider","useRadioContext","Radio","__scopeRadio","checked","required","onCheck","form","radioProps","button","setButton","hasConsumerStoppedPropagationRef","isFormControl","getState","RadioBubbleInput","INDICATOR_NAME","RadioIndicator","forceMount","indicatorProps","BUBBLE_INPUT_NAME","control","bubbles","prevChecked","controlSize","input","inputProto","setChecked","ARROW_KEYS","RADIO_GROUP_NAME","createRadioGroupContext","createContextScope2","useRovingFocusGroupScope","useRadioScope","RadioGroupProvider","useRadioGroupContext","RadioGroup","__scopeRadioGroup","defaultValue","valueProp","onValueChange","rovingFocusGroupScope","jsx2","RovingFocusGroup.Root","Primitive2","RadioGroupItem","radioScope","useComposedRefs2","isArrowKeyPressedRef","handleKeyDown","handleKeyUp","RovingFocusGroup.Item","composeEventHandlers2","INDICATOR_NAME2","RadioGroupIndicator","Root2","Item2","Indicator","RadioGroupPrimitive.Root","iconSizes","labelSizes","radioItem","RadioGroupPrimitive.Item","RadioGroupPrimitive.Indicator","Circle","SWITCH_NAME","createSwitchContext","SwitchProvider","useSwitchContext","Switch","__scopeSwitch","checkedProp","defaultChecked","onCheckedChange","switchProps","SwitchBubbleInput","THUMB_NAME","SwitchThumb","thumbProps","Thumb","switchVariants","thumbVariants","isInvalid","switchId","switchElement","SwitchPrimitives.Root","SwitchPrimitives.Thumb","labelContainer","isReversed","Avatar","src","alt","shape","status","statusRingWidth","statusRingColor","imageError","setImageError","getInitials","shapeClasses","statusColors","statusSizes","statusDotClasses","contentClasses","Divider","finalClasses","DescriptionList","term","details","baseClasses","columnClasses","ArchiveBoxIcon","title","titleId","svgRef","ForwardRef","ArrowDownTrayIcon","ArrowLeftStartOnRectangleIcon","ArrowLeftIcon","ArrowPathIcon","ArrowRightOnRectangleIcon","ArrowUpTrayIcon","ArrowUturnLeftIcon","ArrowsPointingInIcon","ArrowsPointingOutIcon","Bars3Icon","BellIcon","BuildingOffice2Icon","BuildingOfficeIcon","CalendarIcon","CheckCircleIcon","CheckIcon","ChevronDownIcon","ChevronLeftIcon","ChevronRightIcon","ClockIcon","CloudArrowUpIcon","ComputerDesktopIcon","CreditCardIcon","CubeIcon","DocumentArrowDownIcon","DocumentDuplicateIcon","DocumentTextIcon","DocumentIcon","EllipsisVerticalIcon","ExclamationCircleIcon","ExclamationTriangleIcon","EyeIcon","FilmIcon","FunnelIcon","GlobeAltIcon","InformationCircleIcon","LinkIcon","ListBulletIcon","LockClosedIcon","LockOpenIcon","MagnifyingGlassIcon","MinusCircleIcon","MoonIcon","MusicalNoteIcon","NoSymbolIcon","PencilSquareIcon","PencilIcon","PhotoIcon","PlusIcon","PrinterIcon","ShoppingBagIcon","ShoppingCartIcon","Squares2X2Icon","TrashIcon","UserIcon","XCircleIcon","XMarkIcon","AlertDialog","isOpen","inline","align","fullWidthButtons","fullWidthButtonsDirection","hideCancel","showCloseButton","actions","onCancel","onConfirm","cancelText","confirmText","isProcess","preventCloseOnOverlayClick","buttonsContainerClasses","actionButtons","handleClose","isCentered","getIconByType","iconClasses","PanelContent","Dialog","Transition","Alert","badgeColors","Badge","colors","existingClassName","cloneElement","isInteractive","Card","CardHeader","CardTitle","CardDescription","CardAction","CardContent","CardFooter","MinusIcon","inputSizeClassMap","iconSizeClassMap","InputNumber","min","max","step","readOnly","showControls","setRefs","internalValue","setInternalValue","triggerChange","newVal","handleIncrement","e","nextVal","handleDecrement","handleChange","NavigationRailItem","selected","onMouseEnter","onMouseLeave","showLabelText","showIcon","iconContainerClasses","labelClasses","Dropdown","controlledOpen","onOpenChange","menuClassName","placeholder","renderTrigger","internalOpen","setInternalOpen","menuCoords","setMenuCoords","dropdownRef","useRef","menuRef","calculateMenuPosition","useCallback","triggerRect","viewportWidth","viewportHeight","menuMinWidth","top","left","estimatedHeight","useEffect","handleToggle","newOpen","handleClickOutside","handleItemClick","renderMenu","style","menuClasses","createPortal","DropdownDivider","DropdownHeading","DropdownItem","triggerClasses","isFullWidth","shortcut","itemClasses","headingClasses","dividerClasses","DropdownItemCollapsible","defaultOpen","isCollapsible","showHeading","headingLabel","showDivider","badgeColor","stickyHeader","setIsOpen","handleHeaderClick","handleChildClick","CogIcon","XIcon","iconMap","getIcon","iconName","IconComponent","DropdownItemHeading","showDescription","actionLabel","showAction","onActionClick","Notification","colorClasses","dynamicAriaLabel","displayCount","ArrowRightIcon","Pagination","currentPage","totalPages","onPageChange","backText","nextText","siblingCount","showBackButton","showNextButton","paginationRange","useMemo","totalBlocks","leftSiblingIndex","rightSiblingIndex","shouldShowLeftDots","shouldShowRightDots","firstPageIndex","lastPageIndex","leftItemCount","rightItemCount","rightRange","middleRange","handlePageChange","page","PageButton","isActive","buttonAriaLabel","isDots","buttonClasses","ChevronUpDownIcon","hasWindow","getNodeName","isNode","getWindow","_node$ownerDocument","getDocumentElement","_ref","isElement","isHTMLElement","isShadowRoot","invalidOverflowDisplayValues","isOverflowElement","overflow","overflowX","overflowY","display","getComputedStyle","tableElements","isTableElement","topLayerSelectors","isTopLayer","selector","transformProperties","willChangeValues","containValues","isContainingBlock","elementOrCss","webkit","isWebKit","css","getContainingBlock","currentNode","getParentNode","isLastTraversableNode","lastTraversableNodeNames","getNodeScroll","getNearestOverflowAncestor","parentNode","getOverflowAncestors","list","traverseIframes","_node$ownerDocument2","scrollableAncestor","isBody","win","frameElement","getFrameElement","sides","round","floor","createCoords","v","oppositeSideMap","oppositeAlignmentMap","clamp","start","end","evaluate","getSide","placement","getAlignment","getOppositeAxis","axis","getAxisLength","yAxisSides","getSideAxis","getAlignmentAxis","getAlignmentSides","rects","rtl","alignment","alignmentAxis","length","mainAlignmentSide","getOppositePlacement","getExpandedPlacements","oppositePlacement","getOppositeAlignmentPlacement","lrPlacement","rlPlacement","tbPlacement","btPlacement","getSideList","side","isStart","getOppositeAxisPlacements","flipAlignment","expandPaddingObject","padding","getPaddingObject","rectToClientRect","rect","x","y","isClient","noop","SafeReact","useSafeInsertionEffect","fn","useEffectEvent","_len","_key","computeCoordsFromPlacement","reference","floating","sideAxis","alignLength","isVertical","commonX","commonY","commonAlign","coords","computePosition","strategy","middleware","platform","validMiddleware","statefulPlacement","middlewareData","resetCount","nextX","nextY","data","reset","detectOverflow","_await$platform$isEle","elements","boundary","rootBoundary","elementContext","altBoundary","paddingObject","clippingClientRect","offsetParent","offsetScale","elementClientRect","arrow","arrowDimensions","isYAxis","minProp","maxProp","clientProp","endDiff","startDiff","arrowOffsetParent","clientSize","centerToReference","largestPossiblePadding","minPadding","maxPadding","min$1","center","offset","shouldAddOffset","alignmentOffset","flip","_middlewareData$arrow","_middlewareData$flip","initialPlacement","checkMainAxis","checkCrossAxis","specifiedFallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","detectOverflowOptions","initialSideAxis","isBasePlacement","fallbackPlacements","hasFallbackAxisSideDirection","placements","overflows","overflowsData","_middlewareData$flip2","_overflowsData$filter","nextIndex","nextPlacement","d","resetPlacement","_overflowsData$filter2","currentSideAxis","getSideOffsets","isAnySideFullyClipped","hide","offsets","originSides","convertValueToCoords","mainAxisMulti","crossAxisMulti","rawValue","mainAxis","crossAxis","_middlewareData$offse","diffCoords","shift","limiter","mainAxisCoord","crossAxisCoord","minSide","maxSide","limitedCoords","limitShift","rawOffset","computedOffset","limitMin","limitMax","_middlewareData$offse2","isOriginSide","_state$middlewareData","_state$middlewareData2","apply","heightSide","widthSide","maximumClippingHeight","maximumClippingWidth","overflowAvailableHeight","overflowAvailableWidth","noShift","availableHeight","availableWidth","xMin","xMax","yMin","yMax","nextDimensions","getCssDimensions","getComputedStyle$1","hasOffset","offsetWidth","offsetHeight","shouldFallback","unwrapElement","getScale","domElement","$","noOffsets","getVisualOffsets","shouldAddVisualOffsets","isFixed","floatingOffsetParent","getBoundingClientRect","includeScale","isFixedStrategy","clientRect","scale","visualOffsets","offsetWin","currentWin","currentIFrame","iframeScale","iframeRect","getWindowScrollBarX","leftScroll","getHTMLOffset","documentElement","scroll","htmlRect","convertOffsetParentRelativeRectToViewportRelativeRect","topLayer","isOffsetParentAnElement","offsetRect","htmlOffset","getClientRects","getDocumentRect","html","body","SCROLLBAR_MAX","getViewportRect","visualViewport","visualViewportBased","windowScrollbarX","doc","bodyStyles","bodyMarginInline","clippingStableScrollbarWidth","absoluteOrFixed","getInnerBoundingClientRect","getClientRectFromClippingAncestor","clippingAncestor","hasFixedPositionAncestor","stopNode","getClippingElementAncestors","el","currentContainingBlockComputedStyle","elementIsFixed","computedStyle","currentNodeIsContaining","ancestor","getClippingRect","clippingAncestors","firstClippingAncestor","clippingRect","accRect","getDimensions","getRectRelativeToOffsetParent","setLeftRTLScrollbarOffset","isStaticPositioned","getTrueOffsetParent","polyfill","rawOffsetParent","getOffsetParent","svgOffsetParent","getElementRects","getOffsetParentFn","getDimensionsFn","floatingDimensions","isRTL","rectsAreEqual","observeMove","onMove","io","root","_io","refresh","skip","threshold","elementRectForRootMargin","insetTop","insetRight","insetBottom","insetLeft","isFirstUpdate","handleObserve","ratio","autoUpdate","ancestorScroll","ancestorResize","elementResize","layoutShift","animationFrame","referenceEl","ancestors","cleanupIo","reobserveFrame","firstEntry","_resizeObserver","frameId","prevRefRect","frameLoop","nextRefRect","_resizeObserver2","offset$1","shift$1","flip$1","size$1","hide$1","arrow$1","limitShift$1","mergedOptions","platformWithCache","computePosition$1","deepEqual","keys","getDPR","roundByDPR","dpr","useLatestRef","useFloating","externalReference","externalFloating","transform","whileElementsMounted","open","setData","latestMiddleware","setLatestMiddleware","_reference","_setReference","_floating","_setFloating","setReference","referenceRef","setFloating","floatingRef","floatingEl","dataRef","hasWhileElementsMounted","whileElementsMountedRef","platformRef","openRef","fullData","isMountedRef","floatingStyles","initialStyles","isRef","arrow$2","deps","serverHandoffComplete","genId","useFloatingId","useModernLayoutEffect","devMessageSet","_devMessageSet3","_len2","messages","_key2","message","_devMessageSet4","createEventEmitter","map","_map$get","listener","_map$get2","FloatingNodeContext","FloatingTreeContext","useFloatingParentNodeId","_React$useContext","useFloatingTree","useFloatingRootContext","onOpenChangeProp","elementsProp","floatingId","events","nested","optionDomReference","positionReference","setPositionReference","reason","nodeId","internalRootContext","rootContext","computedElements","_domReference","setDomReference","_setPositionReference","domReference","domReferenceRef","tree","position","useFloating$1","computedPositionReference","useFloatingDropdown","offsetPx","enabled","Select","showLabel","menuHeader","onBlur","selectSize","startIcon","menuPosition","setSelected","opt","isDisabledState","floatingRefs","setFloatingPanelRef","Listbox","NavigationRail","showFab","fabIcon","onFabClick","fabAriaLabel","selectedId","onItemSelect","wrapperClasses","itemsContainerClasses","fabClasses","NavigationRailPanel","heading","showSearch","search","sections","panelClassName","searchValue","setSearchValue","handleSearchChange","containerStyle","panelStyle","section","sectionIndex","itemIndex","NavigationRailPanelItem","HeroChevronRight","HeroChevronLeft","HeroClockOutline","HeroSearch","NavigationRailTypes","collapsed","showRecentButton","showSearchButton","onCollapsedChange","onItemClick","onItemHover","labels","onSearch","searchQuery","setSearchQuery","isSearchPanelOpen","setIsSearchPanelOpen","panelRef","searchButtonRef","finalLabels","handleCollapsedToggle","handleSearchButtonClick","handleItemHover","handleInputSearchChange","panelItems","idx","NavigationRailItemComponent","HeroMagnifyingGlass","NavigationRailGroup","onStateChange","t","def","showPanel","setShowPanel","panelType","setPanelType","hoveredItem","setHoveredItem","hideTimeoutRef","isCollapsed","handleCollapsedChange","commercialItem","handleItemHoverFromRail","handleItemMouseLeave","handlePanelMouseEnter","handlePanelMouseLeave","railItems","ChevronUpIcon","ChevronsLeftIcon","ChevronsRightIcon","TableHeader","column","sortable","sorted","sortDirection","onSort","headerBand","dense","sortableClasses","alignClasses","spanAlignClasses","titleBand","conBanda","stickyClasses","combinedClasses","rawClasses","TableCell","isStriped","rowIndex","isStickyRight","clickable","accentHover","bgClass","roundedClasses","hoverBgClass","accentBorderClass","showPageNumbers","previousLabel","nextLabel","pageSize","pageSizeOptions","onPageSizeChange","totalRecords","perPageLabel","recordsLabel","goToPageLabel","goToPageAriaLabel","firstPageLabel","lastPageLabel","goToValue","setGoToValue","showExtras","multiPage","MAX_NUMEROS_VISIBLES","pageNumbers","handleGoTo","formControlCls","navIconBtnCls","navNumBtnCls","navSection","Table","columns","showBorder","showShadow","showPadding","onRowClick","onRowDoubleClick","disableRowTextSelection","suppressRowClickOnDoubleClick","doubleClickDelay","externalSortColumn","externalSortDirection","emptyMessage","loading","loadingRows","pagination","isRowSelected","minGridHeight","internalSortColumn","setInternalSortColumn","internalSortDirection","setInternalSortDirection","sortColumn","handleSort","columnAccessor","newDirection","hasRowClick","hasRowDoubleClick","isRowInteractive","deferRowClick","rowTextSelectionOff","rowSelectNoneClass","pendingClickTimers","timers","timer","handleRowClick","row","selection","previous","handleRowDoubleClick","pending","handleRowKeyActivate","getCellValue","accessor","tableGridClasses","c","widthStr","colIndex","isClickable","HeroComputerDesktopIcon","HeroExclamationCircleIcon","MARCADOR","interpolate","text","arg","marcador","nombre","valor","resolveTranslation","translated","DefaultTranslationEngine","defaultLang","currentResources","defaultResources","lang","resources","APP_LANGUAGE_KEY","TRANSLATIONS_PREFIX","AVAILABLE_LANGS_KEY","languageStorage","languages","TranslationContext","createContext","LANGUAGE_CODE_KEYS","readLanguageCode","TranslationProvider","mode","broadcastEventName","sessionChangeEventName","apiAdapter","staticLanguages","staticResources","defaultLanguage","autoSetAxiosHeader","axiosInstance","currentLanguage","setCurrentLanguage","setLanguages","isReady","setIsReady","setError","resourceVersion","setResourceVersion","engine","instance","inFlightRef","revalidatedRef","idiomaVigenteRef","updateAxiosHeader","applyResources","revalidateResources","inFlight","request","fresh","loadLanguageResources","cached","hasSomethingToRender","err","loadAvailableLanguages","availableLangs","freshLangs","setLanguage","langInput","fromBroadcast","refreshTranslations","targets","failed","vigente","handleLanguageChange","newLang","handleSessionChange","useTranslationInternal","useContext","cachedLangs","currentLang","useTranslation","translate","resolve","createTranslationHook","dictionaries","baseT","resolveEnMotor","enMotorActivo","encontrado","enMotorConFallback","enDiccionario","diccionario","fuentes","vars","sufijo","fuente","replacement","MATCH_MODAL_TRANSLATIONS_ES","MATCH_MODAL_TRANSLATIONS_EN","MATCH_MODAL_TRANSLATIONS","useMatchModalTranslation","MatchModal","matches","fieldName","onView","onContinue","viewLabel","continueLabel","nombreCampo","coincidencias","tituloModal","textoVer","textoContinuar","match","Tab","disabledClasses","contentBaseClasses","contentStateClasses","textClasses","badgeClasses","indicatorClasses","contentFinalClasses","Tabs","activeId","defaultActiveId","internalActiveId","setInternalActiveId","currentActiveId","handleTabClick","itemWidthClass","useLanguage","FlagIcon","code","LanguageSelector","ctxLanguages","isLanguageChanging","safeLanguages","getLangId","l","getLangName","selectedLanguage","dropdownItems","langId","setLanguageHeader","syncAxiosLanguage","HeroShoppingCartIcon","HeroBellIcon","HeroMagnifyingGlassIcon","HeroChevronDownIcon","HeroExclamationTriangleIcon","HeroArrowLeftStartOnRectangleIcon","HeroSquares2X2Icon","Navbar","logo","darkLogo","productName","environmentBadge","userDropdown","notifications","hideActionButtons","showNavigationButton","navigationButtonProps","leadingAction","siesaLogo","showBusinessLogo","showSiesaLogoLeading","showSiesaLogoTrailing","isAppShell","microfrontends","onMicrofrontendClick","activeMicrofrontendName","onNavigationClick","onSearchClick","onCartClick","onNotificationsClick","languageSelector","selectedMicrofrontend","setSelectedMicrofrontend","actionButtonClasses","isMobile","isDesktop","isTablet","isResponsive","AppLauncher","mfe","NavigationButton","defaultButtonProps","BusinessLogo","logoContent","SiesaLogoLeading","logoFull","logoMobile","SiesaLogoTrailing","responsive","dividerContent","ProductName","baseName","EnvironmentBadge","SearchButton","CartButton","NotificationsButton","userMenuItems","selectorItem","logoutIndex","UserDropdown","renderFullDropdown","renderBusinessLogo","NavigationBar","activeItemId","renderItem","itemContainerClasses","destinationsClasses","ConventionIcon","lightColor","darkColor","POSConvention","UsersIcon","POSLocationButton","locationName","capacity","StatusIcon","backgroundClasses","capacityText","POSNumberButton","border","textSizeClasses","POSProductButton","image","POSProductCard","price","buttonText","onAddClick","onCardClick","stateClasses","cardClasses","handleCardClick","handleButtonClick","POSProductSidebarItems","categoryLabel","categoryColor","productRef","descriptionItems","quantity","minQuantity","maxQuantity","onQuantityChange","onDelete","deleteIcon","categoryColorClasses","handleQuantityChange","newQuantity","handleDelete","POSTable","tableNumber","chairs","showChairs","Chair","rotation","handleClick","useAuditHistory","fetchFn","entityId","setPageState","selectedEntryId","setSelectedEntryId","isLoading","useQuery","setPage","newPage","selectedEntry","SkeletonThemeContext","defaultEnableAnimation","styleOptionsToCssProperties","baseColor","highlightColor","borderRadius","circle","duration","enableAnimation","customHighlightBackground","Skeleton","Wrapper","customClassName","containerClassName","containerTestId","styleProp","originalPropsStyleOptions","_a","_b","_c","contextStyleOptions","propsStyleOptions","styleOptions","countCeil","thisStyle","fractionalPart","fractionalWidth","skeletonSpan","millisecondsInWeek","millisecondsInDay","constructFromSymbol","constructFrom","date","toDate","defaultOptions","getDefaultOptions","startOfWeek","weekStartsOn","_date","day","diff","startOfISOWeek","getISOWeekYear","year","fourthOfJanuaryOfNextYear","startOfNextYear","fourthOfJanuaryOfThisYear","startOfThisYear","getTimezoneOffsetInMilliseconds","utcDate","normalizeDates","dates","normalize","startOfDay","differenceInCalendarDays","laterDate","earlierDate","laterDate_","earlierDate_","laterStartOfDay","earlierStartOfDay","laterTimestamp","earlierTimestamp","startOfISOWeekYear","fourthOfJanuary","isDate","isValid","startOfYear","date_","formatDistanceLocale","formatDistance","token","tokenValue","buildFormatLongFn","dateFormats","timeFormats","dateTimeFormats","formatLong","formatRelativeLocale","formatRelative","_baseDate","_options","buildLocalizeFn","valuesArray","defaultWidth","eraValues","quarterValues","monthValues","dayValues","dayPeriodValues","formattingDayPeriodValues","ordinalNumber","dirtyNumber","number","rem100","localize","quarter","buildMatchFn","matchPattern","matchResult","matchedString","parsePatterns","findIndex","pattern","findKey","object","predicate","buildMatchPatternFn","parseResult","matchOrdinalNumberPattern","parseOrdinalNumberPattern","matchEraPatterns","parseEraPatterns","matchQuarterPatterns","parseQuarterPatterns","matchMonthPatterns","parseMonthPatterns","matchDayPatterns","parseDayPatterns","matchDayPeriodPatterns","parseDayPeriodPatterns","enUS","getDayOfYear","getISOWeek","getWeekYear","firstWeekContainsDate","firstWeekOfNextYear","firstWeekOfThisYear","startOfWeekYear","firstWeek","getWeek","addLeadingZeros","targetLength","sign","output","lightFormatters","signedYear","month","dayPeriodEnumValue","numberOfDigits","milliseconds","fractionalSeconds","dayPeriodEnum","formatters","era","signedWeekYear","weekYear","twoDigitYear","isoWeekYear","week","isoWeek","dayOfYear","dayOfWeek","localDayOfWeek","isoDayOfWeek","hours","_localize","timezoneOffset","formatTimezoneWithOptionalMinutes","formatTimezone","formatTimezoneShort","timestamp","delimiter","absOffset","minutes","dateLongFormatter","timeLongFormatter","dateTimeLongFormatter","datePattern","timePattern","dateTimeFormat","longFormatters","dayOfYearTokenRE","weekYearTokenRE","throwTokens","isProtectedDayOfYearToken","isProtectedWeekYearToken","warnOrThrowProtectedError","format","_message","subject","formattingTokensRegExp","longFormattingTokensRegExp","escapedStringRegExp","doubleQuoteRegExp","unescapedLatinCharacterRegExp","formatStr","locale","defaultLocale","originalDate","substring","firstCharacter","longFormatter","cleanEscapedString","formatterOptions","formatter","matched","formatRelativeLocalePlural","es","formatAuditTimestamp","isoTimestamp","formatAuditTimestampExact","AuditTimestamp","classes","MAX_FIELDS_PREVIEW","ACTION_CONFIG","groupByDate","groups","today","yesterday","dateLabel","SkeletonCard","TimelineCard","onSelect","fieldsLabel","previewFields","extraCount","getTimelinePageNumbers","TimelinePagination","p","AuditTimeline","totalCount","listRef","en","prev","formatAuditValue","isEmptyAuditValue","Placeholder","AuditEntryDetail","detail","oldEmpty","newEmpty","oldFormatted","newFormatted","AuditHistoryPanel","mobileShowDetail","setMobileShowDetail","handleSelect","createStoreImpl","createState","listeners","setState","partial","replace","nextState","previousState","api","createStore","DEFAULT_SEARCH_PARAMS","createListSlice","initialPageSize","set","params","filters","values","total","hasSearched","getAllFields","definition","s","DATA_TYPE_TO_INPUT","ALWAYS_SORTABLE","MAX_QUICK_FILTERS","COL_SPAN_MAP","computeColSpanClass","field","inputType","inferInputType","rawColSize","colSizeNum","validateFieldDefinitions","fields","deriveListColumns","listFields","deriveFormInputs","tab","deriveFilterControls","getDefaultFilterOperator","deriveQuickFilters","deriveSortableFields","seen","dataType","computeInitialValues","createFormSlice","defaultCreateValues","initialValues","record","errors","isDirty","isSaving","isLoadingRecord","recordLoadFailed","createFilterSlice","createUISlice","action","createOverrideSlice","overrides","buildStateCreator","createMasterViewStore","creator","MasterViewContext","MasterViewProvider","storeRef","useMasterViewStore","store","useStore","positionClasses","animationClasses","containerColorClasses","Toast","Icon","autoClose","isVisible","onClose","closeLabel","shouldRender","setShouldRender","isAnimating","setIsAnimating","animTimer","positionClass","animationClass","containerColorClass","addToastRef","ToastProvider","toasts","setToasts","newToast","toast","finalMessage","TOAST_EVENT","fireInternalToast","InternalToastContainer","handler","useToast","externalToast","showInternalToasts","dispatch","GLOBAL_SENTINEL","CompanySelector","companies","activeCompanyId","onCompanyChange","toastProp","showGlobalOption","assignedCompanyIds","tt","dropdownOpen","setDropdownOpen","showWarning","isGlobalActive","chipClass","chipDisabledClass","Building2","activeCompany","activeLabel","ActiveIcon","company","isAssigned","CompanyEnableModal","recordLabel","pendingChanges","setPendingChanges","assignedSet","filteredCompanies","bodyHeight","isEffectivelyAssigned","companyId","originallyAssigned","handleEnableAll","handleConfirm","changes","pendingCount","btnAssign","btnUnassign","effective","ConfigTableContent","configService","renderConfigBody","renderToolbarActions","renderActionsMenuItems","defaultCompany","companyBehavior","activeCompanyContext","setActiveCompanyContext","isShowGlobalValuesEnabled","toggleShowGlobalValues","setRows","globalData","setGlobalData","setIsSaving","setIsLoading","linkedCompanyIds","setLinkedCompanyIds","pendingCompany","setPendingCompany","isLinking","setIsLinking","linkModalOpen","setLinkModalOpen","actionsDropdownOpen","setActionsDropdownOpen","isLinkModalSaving","setIsLinkModalSaving","isCompanyMode","showsGlobalOption","initial","ids","newRows","globalRows","handleCompanyChange","handleConfirmLink","updatedIds","handleSave","changedRows","handleRestoreRow","rowId","globalRow","handleRestoreAll","handleLinkModalConfirm","toLink","toUnlink","showMostrarDatosGlobales","showUsarDatosGlobales","showVincularCompanias","hasBuiltinActionsItems","hasActionsItems","ctx","Menu","ChevronDown","RotateCcw","Globe","Link2","OPERATION_TO_PERMISSION","isActionAllowed","permissions","operation","masterType","permissionKey","getDisabledToastMessage","SaveIcon","BUTTON_TEXT_CLASS","FormActionBar","onSave","onEdit","onHamburgerCreate","onHamburgerChangeStatus","onHamburgerEnableCompany","onHamburgerAudit","onHamburgerUseGlobalData","onHamburgerToggleShowGlobal","showGlobalValues","definitionType","recordIsActive","compact","saveDisabled","companyDisabled","editHidden","editGrayed","editGrayedReason","displayTitle","isViewing","isEditing","isCreating","showCompany","isCompanyContext","menuOpen","setMenuOpen","toggleMenu","close","motion","RotateCcwIcon","getFieldTabKey","formTab","TabBar","activeTabKey","onTabChange","navigationType","formMode","detailTabConfigs","contentTabs","isModal","showDetailTabs","visibleContentTabs","errorCountByTab","tabKey","basicDataTab","additionalTabs","detailTabs","dt","isBasicData","SidebarPanel","onBackdropClick","ModalPanel","maxHeight","PagePanel","interpolateTemplate","template","statusText","getFriendlyErrorMessage","ApiError","isExpressiveFilter","filter","buildExpressiveFilter","simpleFilter","normalizeFilters","mergeFilters","DEBOUNCE_MS","useDebouncedSearch","delay","debouncedValue","setDebouncedValue","useKeyboardNavigation","records","onEscape","onClear","onEnterWithoutHighlight","highlightedIndex","setHighlightedIndex","FALLBACK_STRINGS","useTranslationSafe","i18nT","i18n","useClickOutside","excludeRefs","excludeRef","memo","getDeps","opts","isInitial","memoizedFunction","depTime","newDeps","dep","resultTime","depEndTime","resultEndTime","resultFpsPercentage","pad","str","num","notUndefined","msg","approxEqual","debounce","targetWindow","ms","getRect","defaultKeyExtractor","defaultRangeExtractor","range","arr","observeElementRect","cb","observer","run","box","addEventListenerOptions","supportsScrollend","observeElementOffset","fallback","createHandler","isScrolling","horizontal","isRtl","endHandler","registerScrollendEvent","measureElement","elementScroll","adjustments","behavior","toOffset","Virtualizer","_ro","get","opts2","sync","scrollElement","measurements","furthestMeasurementsFound","furthestMeasurements","m","measurement","previousFurthestMeasurement","paddingStart","scrollMargin","getItemKey","lanes","itemSizeCache","laneLastIndex","cachedLane","lane","prevIndex","prevInLane","furthestMeasurement","measuredSize","outerSize","scrollOffset","calculateRange","endIndex","rangeExtractor","overscan","attributeName","indexStr","prevNode","itemSize","delta","indexes","virtualItems","findNearestBinarySearch","maxOffset","initialAlign","attempts","maxAttempts","tryScroll","currentAlign","offsetInfo","verify","currentOffset","afterInfo","scheduleRetry","endByLane","val","low","high","getCurrentValue","middle","currentValue","lastIndex","getOffset","endPerLane","pos","startPerLane","useIsomorphicLayoutEffect","useVirtualizerBase","useFlushSync","rerender","resolvedOptions","instance2","flushSync","useVirtualizer","DEFAULT_OPTION_HEIGHT_PX","DEFAULT_OVERSCAN","useVirtualList","parentRef","estimateSize","virtualizer","SearchInput","listboxId","activeDescendantId","searchOperator","onSearchOperatorChange","startsWithLabel","containsLabel","exactMatchStatus","handleClear","operadores","Loader2","AlignStartVertical","AlignHorizontalSpaceAround","Search","X","LiveRegion","CreatePopup","showHeader","previousOverflow","bodyRef","stickyHeight","setStickyHeight","measure","isSidebar","DEFAULT_PAGE_SIZE","SCROLL_THRESHOLD_PX","DEFAULT_MIN_CHARS","MAX_VISIBLE_CHIPS","LookupFieldInner","entity","displayFields","fetcher","clearable","clearSelectionLabel","removeLabel","onError","searchFields","minChars","displayValue","displayTemplate","renderSelected","getFilters","dependencies","orderBy","bindFields","onFocusProp","onBlurProp","onReady","onInvalidValue","noResultsText","searchPlaceholder","showRequiredIndicator","validateOnBlur","onValidationChange","errorText","onCreateNew","createVariant","createTitle","createButtonLabel","createIcon","showCreateButtonProp","createWidth","createHeight","createShowHeader","isMultiple","maxSelected","onMaxSelectedReached","displayFieldsKey","bindFieldsKey","searchFieldsKey","filtersKey","orderByKey","effectiveOrderBy","isCreateOpen","setIsCreateOpen","apiError","setApiError","setRecords","selectedRecords","setSelectedRecords","selectedRecord","setCurrentPage","hasMorePages","setHasMorePages","isLoadingMore","setIsLoadingMore","abortControllerRef","previousRecordRef","previousDependenciesRef","optionsRef","searchInputRef","triggerRef","debouncedSearchQuery","setSearchOperator","announcement","setAnnouncement","setExactMatchStatus","isResolvingExactMatchRef","hasCalledOnReadyRef","selectedRecordRef","selectedRecordsRef","componentRef","isFocusWithinRef","onInvalidValueRef","displayRecords","selectedIds","totalSize","isInvalidValue","setIsInvalidValue","validationError","setValidationError","cachedRecords","setCachedRecords","cachedScrollPosition","setCachedScrollPosition","cachedCurrentPage","setCachedCurrentPage","cacheValid","setCacheValid","cachedSearchQueryRef","isRestoringCacheRef","currentPageRef","showError","showCreateButton","effectiveShowRequiredIndicator","onValidationChangeRef","getEffectiveFilters","fetchRecords","controller","effectiveFilters","allFields","response","imperativeRef","fetchError","fetchMoreRecords","actualCurrentPage","nextPage","fetchAndSetRecordById","recordId","fetchRecordsByIds","recordIds","byId","performValidation","handleScroll","container","scrollTop","scrollHeight","clientHeight","previousValueRef","fetchAndSetRecordByIdRef","valueSyncRequestIdRef","singleValue","valueChanged","currentRecord","currentRequestId","fetchRecordsByIdsRef","previousMultiValueKeyRef","idsKey","currentIds","resolved","dependenciesKey","previousFiltersRef","previousSearchOperatorRef","getSelectedDisplay","handleTriggerClick","handleCreateClick","getOptionDisplay","handleSelectRecord","prevRecords","alreadySelected","nextRecords","justSelectedRef","displayText","handleRecordCreated","handleExactMatchEnter","query","trimmed","handleKeyboardClear","isTabNavigatingRef","allTabbable","componentIndex","nextElement","handleEscapeClose","handleImperativeClear","useImperativeHandle","highlightedOption","wasClickedRef","handleTriggerMouseDown","handleTriggerKeyDown","handleTriggerFocus","handleComponentFocus","handleComponentBlur","relatedTarget","renderDropdownContent","useVirtualizedRendering","isOptionSelected","isOptionMaxDisabled","renderOptionContent","Check","virtualItem","setTriggerRef","createElement","Plus","LookupField","DATE_REGEX","buildZodSchema","buildFieldSchema","z","inferInputTypeFromDataType","buildNumberSchema","buildBooleanSchema","buildDateSchema","buildStringSchema","requiredMsg","inner","schema","defaultMessages","defaultT","VALIDATION_KEY_MAP","useMasterForm","service","validate","onCreateSuccess","onUpdateSuccess","onFormSave","isCustomSubmitting","setIsCustomSubmitting","activeRecord","setErrors","setActiveTabKey","closeForm","openConflictDialog","globalValues","revertedFields","showSuccess","queryClient","useQueryClient","createMutation","useMutation","payload","updateMutation","initialIsActive","currentVersion","payloadVersion","currentIsActive","rf","fieldErrors","validationT","mapped","runValidation","vals","issue","customErrors","version","MasterPatternViewCreateFormInner","entityName","onCreated","chrome","companyLocked","openCreate","submit","MasterPatternViewForm","MasterPatternViewCreateForm","useDefinition","client","QueryClient","QueryClientProvider","g","h","q","w","u","A","reactIs_production_min","hasSymbol","REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","REACT_FRAGMENT_TYPE","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_PROVIDER_TYPE","REACT_CONTEXT_TYPE","REACT_ASYNC_MODE_TYPE","REACT_CONCURRENT_MODE_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_BLOCK_TYPE","REACT_FUNDAMENTAL_TYPE","REACT_RESPONDER_TYPE","REACT_SCOPE_TYPE","isValidElementType","typeOf","$$typeof","$$typeofType","AsyncMode","ConcurrentMode","ContextConsumer","ContextProvider","Element","Lazy","Memo","Portal","Profiler","StrictMode","Suspense","hasWarnedAboutDeprecatedIsAsyncMode","isAsyncMode","isConcurrentMode","isContextConsumer","isContextProvider","isForwardRef","isFragment","isLazy","isMemo","isPortal","isProfiler","isStrictMode","isSuspense","reactIs_development","reactIsModule","require$$0","require$$1","getOwnPropertySymbols","hasOwnProperty","propIsEnumerable","toObject","shouldUseNative","test1","test2","order2","test3","letter","objectAssign","source","from","to","symbols","ReactPropTypesSecret","ReactPropTypesSecret_1","has","printWarning","loggedTypeFailures","checkPropTypes","typeSpecs","location","componentName","getStack","typeSpecName","ex","stack","checkPropTypes_1","ReactIs","assign","require$$2","require$$3","require$$4","emptyFunctionThatReturnsNull","factoryWithTypeCheckers","isValidElement","throwOnDirectAccess","ITERATOR_SYMBOL","FAUX_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","iteratorFn","ANONYMOUS","ReactPropTypes","createPrimitiveTypeChecker","createAnyTypeChecker","createArrayOfTypeChecker","createElementTypeChecker","createElementTypeTypeChecker","createInstanceTypeChecker","createNodeChecker","createObjectOfTypeChecker","createEnumTypeChecker","createUnionTypeChecker","createShapeTypeChecker","createStrictShapeTypeChecker","is","PropTypeError","createChainableTypeChecker","manualPropTypeCallCache","manualPropTypeWarningCount","checkType","isRequired","propFullName","secret","cacheKey","chainedCheckType","expectedType","propValue","propType","getPropType","preciseType","getPreciseType","typeChecker","expectedClass","expectedClassName","actualClassName","getClassName","expectedValues","valuesString","arrayOfTypeCheckers","checker","getPostfixForTypeWarning","expectedTypes","checkerResult","expectedTypesMessage","invalidValidatorError","shapeTypes","allKeys","iterator","isSymbol","emptyFunction","emptyFunctionWithReset","factoryWithThrowingShims","shim","getShim","propTypesModule","__assign","__rest","__awaiter","thisArg","_arguments","P","generator","adopt","reject","fulfilled","rejected","__spreadArray","pack","ar","COMMON_MIME_TYPES","toFileWithPath","file","withMimeType","webkitRelativePath","setObjProp","ext","FILES_TO_IGNORE","fromEvent","evt","isObject","isDataTransfer","getDataTransferFiles","isChangeEvt","getInputFiles","getFsHandleFiles","fromList","handles","files","toFilePromises","noIgnoredFiles","flatten","fromDataTransferItem","fromDirEntry","fromEntry","fromFileEntry","reader","readEntries","batch","fwp","acceptedFiles","acceptedFilesArray","fileName","mimeType","baseMimeType","validType","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","iter","_arrayLikeToArray","ownKeys","enumerableOnly","sym","_objectSpread","_defineProperty","obj","_slicedToArray","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","minLen","arr2","_i","_arr","_n","_d","_s","_e","accepts","_accepts","FILE_INVALID_TYPE","FILE_TOO_LARGE","FILE_TOO_SMALL","TOO_MANY_FILES","getInvalidTypeRejectionErr","accept","acceptArr","getTooLargeRejectionErr","maxSize","getTooSmallRejectionErr","minSize","TOO_MANY_FILES_REJECTION","isDataTransferItemWithEmptyType","fileAccepted","isAcceptable","fileMatchSize","isDefined","allFilesAccepted","multiple","maxFiles","_fileAccepted","_fileAccepted2","accepted","_fileMatchSize","_fileMatchSize2","sizeMatch","isPropagationStopped","isEvtWithFiles","onDocumentDragOver","isIe","userAgent","isEdge","isIeOrEdge","fns","canUseFileSystemAccessAPI","pickerOptionsFromAccept","acceptForPicker","_ref2","_ref3","ok","isMIMEType","isExt","agg","_ref4","_ref5","acceptPropAsAcceptAttr","_ref6","_ref7","isAbort","isSecurityError","_excluded","_excluded2","_excluded3","_excluded4","_objectWithoutProperties","excluded","_objectWithoutPropertiesLoose","sourceSymbolKeys","sourceKeys","Dropzone","_useDropzone","useDropzone","defaultProps","PropTypes","_defaultProps$props","getFilesFromEvent","onDragEnter","onDragLeave","onDragOver","onDrop","onDropAccepted","onDropRejected","onFileDialogCancel","onFileDialogOpen","useFsAccessApi","autoFocus","preventDropOnDocument","noClick","noKeyboard","noDrag","noDragEventsBubbling","acceptAttr","pickerTypes","onFileDialogOpenCb","onFileDialogCancelCb","rootRef","_useReducer","useReducer","reducer","_useReducer2","isFocused","isFileDialogActive","fsAccessApiWorksRef","onWindowFocus","dragTargetsRef","globalDragTargetsRef","onDocumentDrop","onDocumentDragEnter","onDocumentDragLeave","onDocumentDragEnd","onDocumentDropGlobal","onErrCb","onDragEnterCb","stopPropagation","fileCount","isDragAccept","isDragReject","onDragOverCb","hasFiles","onDragLeaveCb","targetIdx","setFiles","fileRejections","acceptError","sizeError","onDropCb","openFileDialog","onKeyDownCb","onFocusCb","onBlurCb","onClickCb","composeHandler","composeKeyboardHandler","composeDragHandler","getRootProps","_ref2$refKey","refKey","role","onKeyDown","onFocus","onInputElementClick","getInputProps","_ref3$refKey","inputProps","FilePreview","onRemove","dictionary","getFileIcon","FileUploader","uploadFunction","initialFiles","autoUpload","errorMessages","subLabel","onFilesChange","showValidationHints","getHintsText","extensions","mb","newFiles","fileWrapper","uploadFile","progress","url","uploadPendingFiles","removeFile","isDragActive","fileRejectionItems","hasPendingFiles","EMPTY_FILES","LOOKUP_DISPLAY_FIELD_SUFFIX","getLookupSelectedDisplay","cfg","FileField","handleFilesChange","compactClass","FieldRenderer","allValues","setFormValue","colSpanClass","rowSpanClass","strValue","selectOptions","errorEl","AlertTriangle","resolvedMode","inputEl","hasCustomLabels","trueLabel","falseLabel","rec","prevRec","asLookupRecord","fetched","SELECTION_TYPES","OverridableFieldWrapper","isOverridable","isCompanyOnly","globalValue","onRevert","fieldType","isSelection","revertBtn","hint","DEFAULT_HEADER_FIELDS","renderField","showOverrides","fieldContext","onFieldRevert","renderer","BasicDataTab","headerFields","noticeBanner","SectionIcon","basicFields","orderedFields","TabSection","sectionKey","ContentTab","tabConfig","tabFields","sectionMap","fieldsBySection","existing","sectionKeys","sectionFields","sectionConfig","MasterPatternViewFormInner","formWidth","formHeight","tabConfigs","onRequestRefresh","renderForm","onHamburgerEnableCompanyProp","onRetryLoad","recordTitleFields","canEdit","showScrollbar","setValues","openEdit","setIsDirty","openChangeStatusModal","setPendingAction","openCompanyEnableModal","setOverrides","setRevertedFields","isReadOnly","handleFieldChange","handleTabChange","canUpdate","editCheck","isEditHidden","isEditGrayed","editBlockReason","handleEdit","handleUseGlobalData","handleDetailTabFieldReverted","handleFieldRevert","_removed","remaining","allTabConfigs","visibleTabConfigs","enrichedValues","enrichedRecord","isVisibleRegular","isVisibleDetail","activeDetailTab","customFormContent","loadingOverlay","errorBanner","RefreshCw","tabContent","formTitle","valuePart","hasCode","hasName","actionBar","tabBar","useFieldEngine","resolveDisplay","_idSeq","newId","buildInitialFilterState","activeFilters","connectorEntry","advConditions","filterValues","inputClass","selectClass","labelClass","LOOKUP_COMPACT_CSS","FilterPanel","LOOKUP_OPS","getOpsForDataType","STRING_OPS","NUMBER_OPS","DATE_OPS","BOOLEAN_OPS","filterControls","initialFilterState","setFilterValues","advOpen","setAdvOpen","connector","setConnector","setAdvConditions","hasFilterableFields","getFieldValue","setFieldValue","setFieldProp","addCondition","first","defaultOp","removeCondition","updateCondition","patch","updated","fc","isNextLookup","handleAdvToggle","nextOpen","activeAdvCount","handleBuscar","basicFilters","fv","activeAdv","connectorFilter","advFilters","isAdvancedActive","handleLimpiar","boolStr","fieldDef","cond","isLookup","ops","isSelect","isBoolean","op","Eraser","ToolbarActions","defaultActions","onCreateClick","globalActions","showExport","showImport","onExport","onImport","canCreate","nodataImg","EmptyState","resolveActionConfig","PRIORITY_IDS","MAX_DIRECT","bounceTransition","RowActions","onOpenView","onOpenEdit","onChangeStatus","rowActions","canRead","canChangeStatus","showView","disabledView","showEdit","disabledEdit","showChangeStatus","disabledChangeStatus","handleView","handleChangeStatus","resolvedActions","Pencil","directActions","menuActions","priority","fill","actionBtnClass","actionBtnClassDanger","actionBtnClassSuccess","toneClass","RowActionsMenu","triggerIcon","triggerLabel","setOpen","btnRef","setPos","reposition","btn","menu","mw","mh","onDocClick","onKey","onScroll","CompanyStatusBadge","enabledLabel","notEnabledLabel","colFilterInputClass","SortIcon","sortBy","sortOrder","ChevronsUpDown","ChevronUp","ListTable","onCompanyStatusClick","modalOpen","isCompanyCtx","listColumns","storeColumnFilters","setStoreColumnFilters","setSearchParams","openColumnFilter","setOpenColumnFilter","columnFilters","setColumnFilters","filtersRef","debounceRef","changed","handleColumnFilter","isBooleanField","commit","filterValue","operator","fieldMap","dataColumns","col","isFilterable","isLookupField","renderFn","baseRender","overrideBadge","isFilterOpen","hasActiveFilter","nextDir","Filter","actionsColumn","_value","companyStatusColumn","emptyContent","formatValue","CardSkeleton","ListCard","renderCardContent","titleCol","subtitleCol","bodyColumns","footerColumns","visibleCols","anyHasPosition","titleValue","titleFd","isGlobal","titleNode","subtitleFd","subtitleValue","fd","PaginationBar","BatchBar","onClearSelection","onBatchChangeStatus","batchActions","loadingKey","setLoadingKey","recordWord","selectedWord","countLabel","handleBatchAction","emptyLabel","DirtyStateDialog","onDiscard","onSaveAndExit","ChangeStatusModal","companyName","isCurrentlyActive","baseDesc","ConflictDialog","onRefresh","closeConflictDialog","handleRefresh","NotEnabledModal","trigger","getActionText","trig","getConfirmLabel","useMasterList","autoLoad","defaultFiltersOpen","searchParams","quickFilterValues","setHasSearched","isInfinite","quickFiltersAsActive","allFilters","serviceFilters","viewFilter","baseParams","pageQuery","infiniteQuery","useInfiniteQuery","pageParam","lastPage","useChangeStatus","onStatusChangeSuccess","closeChangeStatusModal","clearPendingAction","mutation","newStatus","oldData","patchRow","useSortState","setSort","useMasterPatternViewTranslation","uiPrefix","fieldsPrefix","externalTranslations","internalTranslations","tProp","globalI18n","globalT","activeT","uiKey","fieldKey","fieldTranslated","internalSet","MasterPatternViewInner","renderBody","selectable","auditHistory","tabs","openRecordId","openRecordMode","onRecordOpen","onRecordClose","onRecordSaved","externalIsLoading","showViewToggle","showCompanySelector","customSave","externalIsDirty","CustomContent","MasterPatternViewContent","initialCreateValues","pendingAction","setInitialCreateValues","lateDefaults","openView","updateActiveRecord","setIsLoadingRecord","setRecordLoadFailed","clearSelection","isDirtyStateDialogOpen","openDirtyStateDialog","closeDirtyStateDialog","isChangeStatusModalOpen","isCompanyEnableModalOpen","closeCompanyEnableModal","isFilterPanelOpen","toggleFilterPanel","setActiveFilters","clearFilters","setGlobalValues","viewMode","setViewMode","mediaQuery","handleDeviceChange","SESSION_COMPANY_KEY","LOCAL_LAST_COMPANY_KEY","localStored","didRestoreCompanyRef","sessionStored","restoredId","initialCompany","showOnlyCompany","setShowOnlyCompany","notEnabledState","setNotEnabledState","pendingCompanySwitchId","setPendingCompanySwitchId","closeNotEnabled","companyEnableRecord","setCompanyEnableRecord","setAssignedCompanyIds","isCompanyEnableLoading","setIsCompanyEnableLoading","formCompanyIds","setFormCompanyIds","cancelled","auditModalState","setAuditModalState","openAuditModal","closeAuditModal","isPostCreateModalRef","paginationConfig","fetchNextPage","hasNextPage","isFetchingNextPage","scrollContainerRef","hasNextPageRef","isFetchingNextPageRef","fetchNextPageRef","savedScrollTopRef","handleCreateSuccess","handleUpdateSuccess","changedFields","original","draft","norm","raw","shadow","isEffectivelyDirty","handleStatusChangeSuccess","executeChangeStatus","isChanging","showLoading","handleOpenCreate","openEditRecord","globalRecord","companyRecord","fullRecord","openViewRecord","prevModeRef","wasAutoCreateModeRef","lastOpenedRecordIdRef","openFn","loaded","handleRetryLoad","handleOpenEdit","handleCloseForm","handleCancel","handleContinueEditing","handleDiscard","handleSaveAndExit","handleStatusConfirm","handleNotEnabledConfirm","targetCompanyId","gr","handleApplyFilters","withoutView","handleClearFilters","handleToggleShowOnlyCompany","pendingRecord","isAnyModalOpen","isCompanyCtxActive","showMostrarSoloCompania","handleCompanyEnableClick","prevRecordId","injectedRowActions","SearchIcon","FilterIcon","wasPostCreate","change","targetId","ctxCompanyId","handleCustomSave","onBeforeSave","onAfterSave","hasSaveButton","hasToolbar","displayCompanySelector","MasterPatternView","instanceClient","HeroCheckCircleIcon","HeroDocumentArrowDownIcon","HeroBuildingOffice2Icon","EnableCompanyIcon","RevertIcon","HeroArrowUturnLeftIcon","HeroLinkIcon","HeroGlobeAltIcon","HeroCheckIcon","HeroBars3Icon","HeroPencilIcon","HeroTrashIcon","HeroPlusIcon","CloseIcon","HeroXMarkIcon","BackIcon","HeroArrowLeftIcon","HeroFunnelIcon","GridIcon","ListIcon","HeroListBulletIcon","HeroCalendarIcon","HeroClockIcon","HeroEllipsisVerticalIcon","HeroNoSymbolIcon","ROW_ACTION_BTN","SortChevron","ColumnFilterHeader","sortState","filterable","isEnum","enumOptions","setText","controlClasses","RowActionsCell","isDelete","MasterCrudTable","showRowActions","enableMultiSelect","onSelectionChange","columnFilterableFields","onColumnFilterChange","showCompanyStatusColumn","isRecordCompanyEnabled","finalEmptyMessage","handleColumnSort","enumOptionsFor","accessorKey","useRawHeader","renderCellByType","visibleActions","DEFAULT_HEADERS","createFetcher","baseUrl","headers","selectedCompany","companyEnabledMap","ContextIcon","companyLabel","renderOption","optIsGlobal","OptIcon","globalCompanies","realCompanies","wideDropdown","RuleEngine","effects","fieldsById","rule","triggerField","triggerValue","targetField","actualValue","condition","ruleValue","strActual","strRule","targetFieldCode","resolveFetcher","init","DynamicEntitiesHttpError","isDynamicEntitiesHttpError","createDynamicEntitiesApi","http","valuesUrl","featureCode","entityCode","idEntityMultiple","DynamicEntitiesApi","DynamicEntitiesContext","DynamicEntitiesProvider","latestRef","stableFetcher","stableOnError","canDelete","stablePermissions","useDynamicEntitiesContext","useOptionalDynamicEntitiesContext","useDynamicEntitiesFetcher","useDynamicEntitiesPermissions","useDynamicEntitiesApi","useDynamicDefinition","setDefinition","setLoading","setTrigger","mounted","DynamicFieldType","asBoolean","normalized","DynamicFieldRenderer","commonProps","dateValue","timeValue","dateTimeValue","cbError","cbProps","swError","swProps","rdError","rdProps","geError","geProps","baseFilters","mappedRequestFilters","mappedCond","mappedRequest","res","withBooleanDefaults","seeded","DynamicEntities","onSaved","hideSubmitButton","hideTitle","onRenderableChange","saving","setSaving","valuesRef","ruleEffects","visibleFields","valuesToValidate","newErrors","save","overrideRecordId","currentValues","finalRecordId","handleSubmit","colSpan","spanClass","FeatureService","feature","hasFileManagement","featureId","featureEntity","dynamicEntityId","rules","renderMode","enabledSystemEntityId","useFeatureService","DynamicEntityGrid","masterRecordId","onCreate","defLoading","defError","flatRecords","DynamicEntityMultiRecord","setIdEntityMultiple","isFormVisible","setIsFormVisible","formKey","setFormKey","LayoutContent","onBack","primaryAction","toolbarEndContent","toolbarClasses","toolbarInnerClasses","contentAreaClasses","EntityContainer","DynamicFeatureOrchestrator","setFeature","activeTab","setActiveTab","setModalOpen","firstTab","fe","modals","inlines","endContent","DynamicEntitiesRegistrationContext","MasterCrudDynamicEntities","dynamicFeature","dynamicFeatureCode","registerDynamicRef","showOnlyPlansAndCriteria","registrationContext","activeDynamicTab","setActiveDynamicTab","filtered","inlineEntities","tabEntities","DEFAULT_ACCEPTED_EXTENSIONS","DEFAULT_MAX_FILE_SIZE_MB","DEFAULT_MAX_TOTAL_SIZE_MB","GalleryItem","resource","allowSelection","allowDeletion","onResourceCheck","onDeleteRequest","showFileName","isLoaded","setIsLoaded","hasError","setHasError","esImg","shouldShowName","FileUploaderGallery","isMaximized","acceptButtonText","showFileUploader","onAccept","onUpload","embedded","acceptedExtensions","maxFileSizeMB","maxTotalSizeMB","multipleFiles","resourceToDelete","setResourceToDelete","internalError","setInternalError","isDeleting","setIsDeleting","renderSkeletons","handleUploadFunction","onProgress","maxBytes","sum","confirmDelete","resourceId","panelClasses","uuid","FileGalleryRegistrationContext","MasterCrudFileManager","register","selectedResourcesRef","handleResourceCheck","selectedResources","saveFileManagement","GlobalLookupResolver","lookupConfig","setResolvedValue","valueField","requestFields","filterCondition","defaultInitialData","MasterCrudForm","initialData","onSubmit","saveButtonText","cancelButtonText","hideHeaderFooter","fullWidthButton","idField","activeByCompany","companyRequired","onSearchMatches","canOverrideMultiCompany","onShowGlobalValuesChange","onUseGlobalData","onLinkCompanies","hideDynamicTabs","propRegisterDynamicRef","showValidationErrorDialog","formTabs","featCodeFileManager","fileManagerConfig","effectiveHideDynamicTabs","hasFieldTabs","fieldTabs","byList","ft","cfgTab","defaultId","formId","finalSaveText","finalCancelText","formState","setFormState","errorAlert","setErrorAlert","devDynamicEntitiesWarning","setDevDynamicEntitiesWarning","lastSearchedValue","formElementRef","isSubmittingRef","initializedRecordIdRef","currentId","dynamicContext","setDynamicFeature","activeGlobalTab","setActiveGlobalTab","dynamicRefs","tabsRowRef","tabIndicatorRef","moveTabIndicator","instant","ind","dynamicEntitiesRegisteredRef","registerDynamicEntitiesPresence","registrationContextValue","hasStandardDynamicEntities","hasPlansAndCriteriaEntities","fileGallerySaveRef","fileGalleryRegisteredRef","devFileManagerWarning","setDevFileManagerWarning","registerFileGallerySave","saveCallback","fileGalleryRegistrationContextValue","fileManagerRecordId","overrideableFields","newValues","activeEntities","savePromises","entityRef","getValue","handleRevertSingleField","actionItems","filteredActions","actionName","headerDropdownItems","mcActions","resolveProp","validateField","theField","isRequiredMsg","isEnglish","finalPrefix","finalSuffix","numValue","validateForm","fieldSetter","currentData","errorFields","handleBlur","cleanValue","renderFieldError","renderFieldWrapper","companyUuid","isOverrideActive","globalValueText","hasOverride","renderDefaultField","isConfigDisabled","isRestrictedByCompany","isOverrideForbidden","fieldContent","newValue","inWrapper","valField","renderCustomField","inputRenderer","gridClasses","renderSkeleton","errCount","MasterCrudToolbar","onSearchChange","viewType","onViewChange","showAdvancedSearch","extraContent","hasSelection","isAdvancedSearchActive","onAdvancedSearchToggle","viewScope","onViewScopeChange","showViewScope","finalSearchPlaceholder","moreOpen","setMoreOpen","moreRef","currentActions","handleViewChange","view","handleCompanySelect","hasMoreMenu","actionIcon","MasterCRUDCard","titleField","footerField","contentFields","renderValue","linkAction","selectionCheckbox","defaultContent","customContent","OPERATORS","rowSeq","newRow","MasterCrudAdvancedSearch","filterableFields","whitelist","filterableCols","basic","setBasic","advancedOpen","setAdvancedOpen","setBasicValue","updateRow","removeRow","addRow","buildFilters","leaves","controlCls","condCtrlCls","LinkModal","isLinked","selectedUuids","setSelectedUuids","initialUuids","setInitialUuids","setSearch","targetCompanies","normalizedSearch","initialLinks","hasChanges","handleToggleLink","handleLinkAll","getDynamicTitle","titleValues","suffix","getDescription","isCurrentlyLinked","Info","noDataImage","MasterCrudDetailSection","masterId","isInsideModal","foreignKey","allowEdit","allowDelete","customActions","formColumns","createButtonText","onDetailCreateSuccess","onDetailUpdateSuccess","onDetailDeleteSuccess","setTotal","detailViewState","setDetailViewState","selectedDetail","setSelectedDetail","formLoading","setFormLoading","deleteConfirm","setDeleteConfirm","toastConfig","setToastConfig","formRef","showToast","loadData","handleCreate","formData","dataWithFk","created","handleDeleteClick","handleDeleteConfirm","actionsList","innerModalZ","sectionTitle","addLabel","toastType","toCamelCase","toPascalCase","normalizeResponseKeys","throwIfNotOk","convertAdvancedFilters","andGroups","toLeaf","orLeaves","MasterPatternCrudAdapter","companyData","custom","advancedFilters","converted","json","normalizedData","limit","knownMin","BulkDynamicEditService","signal","decoder","buffer","done","lines","eventType","dataLine","line","parsed","initialProgress","useBulkDynamicEdit","onComplete","phase","setPhase","setProgress","setResult","finalResult","cancel","MasterCrudBulkDynamicEditor","loadingFeature","setLoadingFeature","loadError","setLoadError","entitiesWithFields","setEntitiesWithFields","fieldValues","setFieldValues","modalPhase","setModalPhase","typedConfirmationValue","setTypedConfirmationValue","isTypedConfirmModalOpen","setIsTypedConfirmModalOpen","expectedConfirmationKeyword","isTypedConfirmationValid","handleBulkComplete","entities","fieldCode","buildPatches","defined","countFilledFields","handlePreview","patches","handleBackToEdit","handleOpenTypedConfirm","handleCancelTypedConfirm","handleConfirmTypedConfirm","exportErrors","csv","blob","progressPercent","lists","isReadonlyOrDisabled","listOptions","fCode","fVal","useMasterCrudTranslation","MasterCrud","serviceProp","masterPattern","softDelete","onDeleteSuccess","renderToolbar","defaultViewScope","useToolbar","enableGridInfiniteScroll","onBeforeCreate","onBeforeUpdate","onBeforeDelete","internalErrorHandling","batchActionsProp","emptyStateConfig","showDefaultEditAction","maximizeEditModal","maximizeCustomModal","fetchDetailOnEdit","navigationTypeProp","showAdvancedSearchConnectors","maxAdvancedFilters","initialFiltersVisible","headerBadges","renderHeaderExtra","onConfirmLinking","isCompanyLinked","showGlobalValuesProp","allowStatusReversion","statusField","deactivateTooltip","activateTooltip","onBulkUpdateComplete","fileAcceptedExtensions","fileMaxSizeMB","fileTotalMaxSizeMB","fileMultiple","detailConfig","getErrorMessage","errObj","responseData","fromData","serviceRef","getErrorMessageRef","canBulkUpdate","effectiveAllowStatusReversion","finalTitle","globalCompany","allCompanies","viewState","setViewState","setSelectedRecord","globalRecordId","setGlobalRecordId","setSelectedCompany","hideToast","linkConfirmState","setLinkConfirmState","setIsAdvancedSearchActive","setAdvancedFilters","hasMore","setHasMore","searchTerm","setSearchTerm","searchField","setSearchField","searchFieldRef","internalPageSize","setInternalPageSize","setSortColumn","setSortDirection","setViewType","setViewScope","dirtyModal","setDirtyModal","detailActionsOpen","setDetailActionsOpen","detailActionsRef","customModalState","setCustomModalState","linkModalState","setLinkModalState","showGlobalResetConfirm","setShowGlobalResetConfirm","showCreateConfirm","setShowCreateConfirm","setShowGlobalValues","matchModalState","setMatchModalState","previewModalState","setPreviewModalState","showBulkDynamicEditor","setShowBulkDynamicEditor","fileResources","setFileResources","fileResourcesLoading","setFileResourcesLoading","getCompanyPrimaryData","checkLinkStatus","currentRecordId","linked","recordInList","rid","effectiveColumnFilterableFields","detailCompanyEnabledMap","handleConfirmDynamicLink","currentLinks","newLinks","handleLinkRecords","companyUuids","svc","refreshed","actualLinks","handleSearchMatches","results","handleViewMatch","handleConfirmGlobalReset","searchFieldOptions","targetFields","firstField","sortFieldOptions","lastElementRef","prevPage","currentSearchField","columnAdvancedFilters","mergedAdvancedFilters","scopeFilter","hasFilters","loadedCount","handleColumnFilterChange","handleViewScopeChange","isCompanyScopeActive","handleSearch","handleSortChange","newSortColumn","handleSortDirectionChange","handleFilterChange","handlePageSizeChange","detailedRecord","handleFormCancel","handleBackGuarded","handleSelectionChange","newIds","idsToUnselect","idsToAdd","recordsToAdd","toggleAdvancedSearch","handleAdvancedSearch","isBranchContext","successMsg","prevData","newData","handleCustomAction","handleCloseCustomModal","getActionsDefinition","combinedBatchActions","explicitBatchActions","inferredBatchActions","handleBulkUpdateComplete","handleFormSubmit","dataToCreate","dataToUpdate","overriddenFields","effectiveFileManagerConfig","recId","defaultToolbar","recordActive","extraActions","showMasterData","showLinkCreate","menuItemCls","isDestructive","wasSuccess","EnvelopeIcon","LoginView","onForgotPassword","onSignUp","showBackground","email","setEmail","password","setPassword","showPassword","setShowPassword","emailError","setEmailError","handleEmailChange","togglePasswordVisibility","UserCircleIcon","SignUpView","onSignIn","onTermsClick","onPrivacyClick","setName","ParameterEditorSearchBar","ParameterEditorScrollableTabs","scrollRef","showLeftArrow","setShowLeftArrow","showRightArrow","setShowRightArrow","updateArrows","ChevronLeft","ChevronRight","stripDiacritics","getAllCategoryParameters","category","direct","fromSections","buildOriginalValues","dataSource","cat","validateParameter","numVal","minVal","maxVal","maxLen","filterParameters","parameters","getVisibleParameters","getCategoryChangeCount","editedValues","originalValues","edited","getTotalChangeCount","buildChangeList","entityDisplayLabels","pushChange","catName","catId","sectionName","sectionId","filterCategoryBySearch","filteredParams","filteredSections","buildSavePayload","getDisplayValue","isSensitive","entityDisplayLabel","getMinMaxFromValidations","validations","ParameterEditorDynamicField","parameter","originalValue","onValidationError","onEntityDisplayLabel","onResetToDefault","isModified","maxLength","isResetting","setIsResetting","showResetConfirm","setShowResetConfirm","lastEntitySelectionRef","entityFetcher","whereClause","handleResetToDefault","renderResetButton","entityValue","previousRecord","descField","prevId","prevLabel","ParameterGrid","validationErrors","visibleParams","ParameterEditorFieldList","visibleDirectParams","sortedSections","gridProps","ChangeRow","onUndoChange","oldDisplay","newDisplay","ParameterEditorConfirmPanel","confirmButtonText","grouped","categoryName","sectionChanges","ChevronBackIcon","ParameterEditor","onChangeExternal","onSaveSuccess","setEditedValues","activeTabId","setActiveTabId","showConfirmPanel","setShowConfirmPanel","setValidationErrors","incoming","hasRealChanges","filteredCategories","tabItems","activeCategory","activeDirectParameters","activeSections","totalChanges","changeList","parameterId","handleEntityDisplayLabel","handleValidationError","handleOpenConfirm","handleUndoChange","TreeCheckbox","DashIcon","TreeNodeInner","level","expanded","hasChildren","showBadge","childCount","onToggle","onExpand","tabIndex","paddingLeft","handleChevronClick","handleCheckboxClick","rowClasses","chevronIconClasses","TreeNode","cloneNode","cloneMap","nodeMap","buildNodeMap","nodes","walk","treeNodes","parentId","depth","childIds","cascadeDown","dfs","childId","propagateUp","startNode","currentParentId","parent","cid","allChecked","noneChecked","flattenTree","rootIds","rootId","getVisibleNodes","expandedIds","diffNodes","originalChecked","collectBranchIds","branches","initExpandedIds","nodeStateToTreeNode","treeNode","useTree","initialNodes","setNodeMap","nodeMapRef","snapshot","initialMap","setExpandedIds","readOnlyRef","beforeCheckRef","toggle","prevMap","nextChecked","allowed","afterCascade","afterPropagate","affectedNodes","sourceNode","expand","collapse","expandAll","collapseAll","getAll","getChecked","getDisabled","getModified","failures","focusedId","setFocusedId","visibleNodes","TreeInner","inputNodes","beforeCheck","defaultExpanded","expandedIdsProp","showDividers","nodeRefs","handleExpandToggle","firstChildIndex","setNodeRef","treeItem","handleNodeFocus","rootNodeIndex","isRoot","TreeNodeWithRef","onNodeFocus","treeNodeProps","refCallback","handleFocus","Tree","LayoutBase","siesaLogoPath","siesaLogoWidth","siesaLogoHeight","navigationItems","contentClassName","hideSidebar","navbarProps","navigationRailProps","translateMenuItems","translatedNavigationItems","navState","setNavState","handleNavStateChange","HomeIcon","CloudIcon","SquaresPlusIcon","ListView","navbarProductName","tableTitle","quickFilters","showNavigationRail","navigationRailState","onNavigationRailStateChange","onNavItemClick","viewOptions","selectedViewOption","onViewOptionChange","showViewDropdown","setShowViewDropdown","defaultNavigationItems","defaultQuickFilters","defaultActionButtons","tableColumns","ProductsView","changeTableLabel","menusTitle","menus","selectedMenuId","onMenuSelect","onChangeTable","categoryTitle","categories","selectedCategoryId","onCategorySelect","productsTitle","products","onAddProduct","orderItems","onOrderItemQuantityChange","onOrderItemDelete","subtotal","taxes","confirmLabel","onConfirmOrder","userAvatar","userName","userRole","businessLogo","product","qty","RecoverPasswordView","onBackToLogin","successMessage","ArrowRightEndOnRectangleIcon","ArrowsRightLeftIcon","RectangleGroupIcon","TableLayoutView","locations","activeLocationId","tables","tablesTitle","showPeopleCountPanel","selectedTable","onLocationSelect","onTableSelect","onCreateTables","onMergeTables","onSplitTables","onPeopleCountSelect","onAssignTable","onTransferTable","onSetCutlery","onClosePeoplePanel","onTableSwitchChange","tableLayout","userInfo","renderNavbar","renderLocationsSidebar","renderTablesArea","table","renderPeopleCountSidebar","ThemeContext","ThemeProvider","defaultTheme","setThemeState","toggleTheme","setTheme","newTheme","useTheme","useFileUploaderGallery","create","galleryProps","updatedResources","FileUploaderGalleryGlobal","closeGallery","updateResources","FeatureList","onSelectFeature","onCreatePlansAndCriteria","features","setFeatures","debouncedSearch","setDebouncedSearch","togglingId","setTogglingId","loadFeatures","handleToggleFileManagement","useCombinedRefs","canUseDOM","isWindow","elementString","_target$ownerDocument","_target$ownerDocument2","isDocument","Document","isSVGElement","getOwnerDocument","useEvent","handlerRef","useInterval","intervalRef","clear","useLatestValue","valueRef","useLazyMemo","useNodeRef","onChangeHandler","useUniqueId","createAdjustmentFn","accumulator","adjustment","valueAdjustment","add","subtract","hasViewportRelativeCoordinates","isKeyboardEvent","KeyboardEvent","isTouchEvent","TouchEvent","getEventCoordinates","CSS","scaleX","scaleY","easing","SELECTOR","findFirstFocusableNode","hiddenStyles","HiddenText","ariaLiveType","visuallyHidden","useAnnouncement","DndMonitorContext","useDndMonitor","registerListener","useDndMonitorProvider","_listener$type","defaultScreenReaderInstructions","defaultAnnouncements","over","Accessibility","announcements","hiddenTextDescribedById","screenReaderInstructions","announce","liveRegionId","setMounted","markup","Action","useSensor","sensor","useSensors","sensors","defaultCoordinates","distanceBetween","p1","p2","sortCollisionsAsc","sortCollisionsDesc","cornersOfRectangle","getFirstCollision","collisions","firstCollision","centerOfRectangle","closestCenter","collisionRect","droppableRects","droppableContainers","centerRect","droppableContainer","distBetween","closestCorners","corners","rectCorners","distances","corner","effectiveDistance","getIntersectionRatio","right","bottom","targetArea","entryArea","intersectionArea","intersectionRatio","rectIntersection","adjustScale","rect1","rect2","getRectDelta","createRectAdjustmentFn","getAdjustedRect","parseTransform","transformArray","inverseTransform","transformOrigin","parsedTransform","translateX","translateY","getClientRect","getTransformAgnosticClientRect","getWindowClientRect","isScrollable","overflowRegex","getScrollableAncestors","scrollParents","findScrollableAncestors","getFirstScrollableAncestor","firstScrollableAncestor","getScrollableElement","getScrollXCoordinate","getScrollYCoordinate","getScrollCoordinates","Direction","isDocumentScrollingElement","getScrollPosition","scrollingContainer","minScroll","dimensions","maxScroll","isTop","isLeft","isBottom","isRight","defaultThreshold","getScrollDirectionAndSpeed","scrollContainer","scrollContainerRect","acceleration","thresholdPercentage","speed","getScrollElementRect","innerWidth","innerHeight","getScrollOffsets","scrollableAncestors","getScrollXOffset","getScrollYOffset","scrollIntoViewIfNeeded","properties","Rect","scrollOffsets","getScrollOffset","currentOffsets","scrollOffsetsDeltla","Listeners","_this$target","eventName","_this$target2","getEventListenerTarget","EventTarget","hasExceededDistance","dx","dy","EventName","preventDefault","KeyboardCode","defaultKeyboardCodes","defaultKeyboardCoordinateGetter","currentCoordinates","KeyboardSensor","activeNode","onStart","keyboardCodes","coordinateGetter","scrollBehavior","newCoordinates","coordinatesDelta","scrollDelta","scrollElementRect","clampedCoordinates","canScrollX","canScrollY","newScrollCoordinates","canScrollToNewCoordinates","coordinates","onEnd","onActivation","activator","isDistanceConstraint","constraint","isDelayConstraint","AbstractPointerSensor","listenerTarget","_getEventCoordinates","activationConstraint","bypassActivationConstraint","onPending","initialCoordinates","_getEventCoordinates2","activated","onAbort","_this$document$getSel","PointerSensor","events$1","MouseButton","MouseSensor","events$2","TouchSensor","touches","AutoScrollActivator","TraversalOrder","useAutoScroller","canScroll","draggingRect","interval","order","pointerCoordinates","scrollableAncestorRects","scrollIntent","useScrollIntent","setAutoScrollInterval","clearAutoScrollInterval","scrollSpeed","scrollDirection","autoScroll","scrollLeft","sortedScrollableAncestors","defaultScrollIntent","previousDelta","previousIntent","useCachedNode","draggableNodes","draggableNode","cachedNode","useCombineActivators","getSyntheticHandler","Sensor","sensorActivators","MeasuringStrategy","MeasuringFrequency","useDroppableMeasuring","containers","dragging","queue","setQueue","frequency","containersRef","disabledRef","measureDroppableContainers","previousValue","useInitialValue","computeFn","useInitialRect","useMutationObserver","handleMutations","mutationObserver","MutationObserver","useResizeObserver","handleResize","ResizeObserver","defaultMeasure","useRect","fallbackRect","setRect","measureRect","currentRect","newRect","useRectDelta","initialRect","defaultValue$1","useScrollableAncestors","previousNode","useScrollOffsets","scrollCoordinates","setScrollCoordinates","prevElements","scrollingElement","previousElements","scrollableElement","useScrollOffsetsDelta","initialScrollOffsets","hasScrollOffsets","useSensorSetup","teardownFns","teardown","useSyntheticListeners","useWindowRect","defaultValue$2","useRects","firstElement","windowRect","setRects","measureRects","getMeasurableNode","firstChild","useDragOverlayMeasuring","handleNodeChange","nodeRef","defaultSensors","defaultData","defaultMeasuringConfiguration","DroppableContainersMap","_super$get","_this$get$node$curren","_this$get","defaultPublicContext","defaultInternalContext","InternalContext","PublicContext","getInitialState","RestoreFocus","activatorEvent","previousActivatorEvent","previousActiveId","activatorNode","focusableNode","applyModifiers","useMeasuringConfiguration","useLayoutShiftScrollCompensation","initialized","rectDelta","ActiveDraggableContext","Status","DndContext","_sensorContext$curren","_dragOverlay$nodeRef$","_dragOverlay$rect","_over$rect","accessibility","collisionDetection","measuring","dispatchMonitorEvent","registerMonitorListener","setStatus","isInitialized","activeRects","_node$data","activeRef","activeSensor","setActiveSensor","setActivatorEvent","latestProps","draggableDescribedById","enabledDroppableContainers","measuringConfiguration","measuringScheduled","activationCoordinates","autoScrollOptions","getAutoScrollerOptions","initialActiveNodeRect","activeNodeRect","containerNodeRect","sensorContext","overNode","dragOverlay","draggingNode","draggingNodeRect","usesDragOverlay","nodeRectDelta","modifiedTranslate","scrollAdjustment","activeNodeScrollDelta","scrollAdjustedTranslate","overId","setOver","appliedTranslate","activeSensorRef","instantiateSensor","sensorInstance","onDragAbort","onDragPending","onDragStart","unstable_batchedUpdates","cancelDrop","bindActivatorToSensorInstantiator","nativeEvent","activeDraggableNode","activationContext","activators","onDragMove","overContainer","publicContext","internalContext","activeSensorDisablesAutoscroll","autoScrollGloballyDisabled","NullContext","defaultRole","ID_PREFIX","useDraggable","attributes","ariaDescribedById","roleDescription","isDragging","setActivatorNodeRef","memoizedAttributes","useDndContext","ID_PREFIX$1","defaultResizeObserverConfig","useDroppable","resizeObserverConfig","resizeObserverConnected","callbackId","resizeObserverDisabled","updateMeasurementsFor","resizeObserverTimeout","previousElement","arrayMove","newArray","getSortedRects","isValidIndex","itemsEqual","normalizeDisabled","defaultScale","horizontalListSortingStrategy","_rects$activeIndex","fallbackActiveRect","activeIndex","overIndex","itemGap","getItemGap","newIndexRect","previousRect","nextRect","rectSortingStrategy","newRects","oldRect","defaultScale$1","verticalListSortingStrategy","overIndexRect","getItemGap$1","clientRects","SortableContext","userDefinedItems","disabledProp","containerId","useDragOverlay","previousItemsRef","itemsHaveChanged","disableTransforms","contextValue","defaultNewIndexGetter","defaultAnimateLayoutChanges","isSorting","wasDragging","newIndex","previousItems","previousContainerId","transition","defaultTransition","transitionProperty","disabledTransition","defaultAttributes","useDerivedTransform","derivedTransform","setDerivedtransform","previousIndex","useSortable","animateLayoutChanges","userDefinedAttributes","localDisabled","customData","getNewIndex","localStrategy","globalDisabled","sortedRects","globalStrategy","normalizeLocalDisabled","itemsAfterCurrentSortable","isOver","setDroppableNodeRef","setDraggableNodeRef","displaceItem","shouldDisplaceDragSource","dragSourceDisplacement","finalTransform","shouldAnimateLayoutChanges","getTransition","_localDisabled$dragga","_localDisabled$droppa","hasSortableData","directions","sortableKeyboardCoordinates","filteredContainers","closestId","activeDroppable","newDroppable","newNode","hasDifferentScrollAncestors","hasSameContainer","isSameContainer","isAfterActive","isAfter","rectCoordinates","GripIcon","SortableItem","isReadonly","FieldDesigner","onAdd","isPlansAndCriteria","handleDragEnd","oldIndex","reorderedFields","sortedFields","FIELD_TYPE_LABELS","FieldEditor","genericLists","isNew","handleLabelChange","parsedVal","EntityEditor","featureEntityId","initialRenderMode","setEntity","setFields","setRules","editingField","setEditingField","setRenderMode","alertConfig","setAlertConfig","loadEntity","handleSaveEntity","isSystem","saveAction","newField","SortableFeatureEntity","FeatureEditor","setView","selectedFeatureEntity","setSelectedFeatureEntity","isAddModalOpen","setIsAddModalOpen","newEntityCode","setNewEntityCode","newEntityDesc","setNewEntityDesc","newEntityRenderMode","setNewEntityRenderMode","isOrderDirty","setIsOrderDirty","systemEntities","setSystemEntities","systemEntitiesLoading","setSystemEntitiesLoading","isSystemPanelOpen","setIsSystemPanelOpen","enableModalEntity","setEnableModalEntity","enableRenderMode","setEnableRenderMode","isEnabling","setIsEnabling","disableModalEntity","setDisableModalEntity","isDisabling","setIsDisabling","loadFeature","loadSystemEntities","handleConfirmAddEntity","handleSaveOrder","updatedEntities","handleDeleteEntity","handleOpenEnableModal","handleConfirmEnable","handleConfirmDisable","sortedEntities","enabledSystemCount","customToolbarActions","feToEdit","enabledAtFormatted","enabledByShort","CatalogManager","setLists","editingList","setEditingList","loadLists","method","newItems","DynamicEntitiesAdmin","selectedFeatureId","setSelectedFeatureId","selectedPlansAndCriteriaEntityId","setSelectedPlansAndCriteriaEntityId","selectedPlansAndCriteriaFeatureEntityId","setSelectedPlansAndCriteriaFeatureEntityId","selectedPlansAndCriteriaRenderMode","setSelectedPlansAndCriteriaRenderMode","handleCreatePlansAndCriteria","existingEntity","newEntity","GenericEntityModal","initialItems","setCode","setDescription","setItems","isEdit","handleAddItem","handleUpdateItem","handleRemoveItem","GenericEntities","onSelectEntity","onCreateEntity","onSaveEntity","onLoadItems","modalState","setModalState","isLoadingItems","setIsLoadingItems","handleSelectForEdit","loadedItems","handleCloseModal","handleSaveModal","entityData","itemsData","defaultTranslations","currentName","newName","defaultName","newDefaultName","mergeTranslations","defaults","deepMerge","override","baseVal","ContactServiceContext","TranslationsContext","useContactServiceAdapter","adapter","useTranslations","ContactServiceProvider","translations","merged","DEFAULT_VALUE","buildEnumOptions","useContactStore","contacts","contactData","contact","updatedContacts","updatedContact","newPendingEdits","newPendingDeletes","firstRemaining","currentDefault","hasPendingAdds","hasPendingEdits","hasPendingDeletes","pendingAddIds","useMediaQuery","setMatches","TAG_COLORS","getColorForIndex","STATE_SHADOW_STYLE","getContactState","pendingAdds","pendingEdits","pendingDeletes","formatPhoneForGrid","phone","categoryLabelMap","formatSocialForGrid","sn","socialNetworkLabelMap","SKELETON_ROWS","ContactGridSkeleton","layout","ContactGridEmptyState","ContactRowActions","contactId","isPendingDelete","onRestore","Eye","Trash2","ResponsiveContactCard","useForOptions","phoneCategoryOptions","socialNetworkTypes","stateStyle","isDeleted","showClassification","snt","useForValue","colorIndex","EmailPills","emails","ClassificationBadges","useFor","idxA","idxB","PhoneCell","phones","SocialCell","socialNetworks","ContactGrid","onAddContact","onEditContact","onViewContact","onDeleteContact","onRestoreContact","isTabletOrAbove","paginatedContacts","contactIndex","groupBg","createContactPhoneSchema","createContactSocialNetworkSchema","createContactSchema","emailItemSchema","useForSchema","_defaultSchema","useEscapeKeydown","onEscapeKeyDownProp","ownerDocument","onEscapeKeyDown","DISMISSABLE_LAYER_NAME","CONTEXT_UPDATE","POINTER_DOWN_OUTSIDE","FOCUS_OUTSIDE","originalBodyPointerEvents","DismissableLayerContext","DismissableLayer","disableOutsidePointerEvents","onPointerDownOutside","onFocusOutside","onInteractOutside","onDismiss","layerProps","force","layers","highestLayerWithOutsidePointerEventsDisabled","highestLayerWithOutsidePointerEventsDisabledIndex","isBodyPointerEventsDisabled","isPointerEventsEnabled","pointerDownOutside","usePointerDownOutside","isPointerDownOnBranch","branch","focusOutside","useFocusOutside","dispatchUpdate","handleUpdate","BRANCH_NAME","DismissableLayerBranch","handlePointerDownOutside","isPointerInsideReactTreeRef","handleClickRef","handlePointerDown","handleAndDispatchPointerDownOutsideEvent2","handleAndDispatchCustomEvent","eventDetail","timerId","handleFocusOutside","isFocusInsideReactTreeRef","discrete","AUTOFOCUS_ON_MOUNT","AUTOFOCUS_ON_UNMOUNT","FOCUS_SCOPE_NAME","FocusScope","trapped","onMountAutoFocusProp","onUnmountAutoFocusProp","scopeProps","setContainer","onMountAutoFocus","onUnmountAutoFocus","lastFocusedElementRef","focusScope","handleFocusIn2","focus","handleFocusOut2","handleMutations2","mutations","focusScopesStack","previouslyFocusedElement","mountEvent","removeLinks","getTabbableCandidates","unmountEvent","isTabKey","focusedElement","container2","last","getTabbableEdges","select","findVisible","walker","isHiddenInput","isHidden","upTo","isSelectableInput","createFocusScopesStack","activeFocusScope","arrayRemove","updatedArray","PORTAL_NAME","containerProp","portalProps","useFocusGuards","edgeGuards","createFocusGuard","zeroRightClassName","fullWidthClassName","noScrollbarsClassName","removedBarSizeVariable","assignRef","initialValue","useMergeRefs","oldValue","prevRefs_1","nextRefs_1","current_1","ItoI","innerCreateMedium","assigned","medium","cbs","pendingQueue","executeQueue","cycle","createSidecarMedium","SideCar","sideCar","Target","exportSidecar","exported","effectCar","nothing","RemoveScroll","callbacks","setCallbacks","forwardProps","removeScrollBar","shards","noRelative","noIsolation","inert","allowPinchZoom","Container","gapMode","containerRef","containerProps","getNonce","makeStyleTag","tag","nonce","injectStyles","insertStyleTag","head","stylesheetSingleton","counter","stylesheet","styleHookSingleton","sheet","isDynamic","styleSingleton","useStyle","Sheet","dynamic","zeroGap","parse","cs","getGapWidth","documentWidth","windowWidth","Style","lockAttribute","getStyles","allowRelative","important","gap","getCurrentUseCounter","useLockAttribute","newCounter","RemoveScrollBar","noImportant","passiveSupported","nonPassive","alwaysContainsScroll","elementCanBeScrolled","elementCouldBeVScrolled","elementCouldBeHScrolled","locationCouldBeScrolled","elementCouldBeScrolled","getScrollVariables","getVScrollVariables","getHScrollVariables","scrollWidth","clientWidth","getDirectionFactor","endTarget","sourceDelta","noOverscroll","directionFactor","targetInLock","shouldCancelScroll","isDeltaPositive","availableScroll","availableScrollTop","scroll_1","parent_1","getTouchXY","getDeltaXY","extractRef","deltaCompare","generateStyle","idCounter","lockStack","RemoveScrollSideCar","shouldPreventQueue","touchStartRef","activeAxis","lastProps","allow_1","shouldCancelEvent","touch","touchStart","deltaX","deltaY","currentAxis","moveDirection","anchorNode","isTouchingSelection","canBeScrolledInMainDirection","cancelingAxis","shouldPrevent","_event","sourceEvent","shardNodes","shouldStop","shouldCancel","should","getOutermostShadowParent","scrollTouchStart","scrollWheel","scrollTouchMove","inst","shadowParent","ReactRemoveScroll","getDefaultParent","originalTarget","sampleTarget","counterMap","uncontrolledNodes","markerMap","lockCount","unwrapHost","correctTargets","correctedTarget","applyAttributeToOthers","markerName","controlAttribute","markerCounter","hiddenNodes","elementsToKeep","elementsToStop","keep","deep","attr","alreadyHidden","counterValue","markerValue","hideOthers","activeParentNode","DIALOG_NAME","createDialogContext","createDialogScope","DialogProvider","useDialogContext","__scopeDialog","openProp","modal","contentRef","prevOpen","TRIGGER_NAME","DialogTrigger","triggerProps","composedTriggerRef","PortalProvider","usePortalContext","DialogPortal","PortalPrimitive","OVERLAY_NAME","DialogOverlay","portalContext","overlayProps","DialogOverlayImpl","CONTENT_NAME","DialogContent","contentProps","DialogContentModal","DialogContentNonModal","DialogContentImpl","originalEvent","ctrlLeftClick","hasInteractedOutsideRef","hasPointerDownOutsideRef","trapFocus","onOpenAutoFocus","onCloseAutoFocus","TitleWarning","DescriptionWarning","TITLE_NAME","DialogTitle","titleProps","DESCRIPTION_NAME","DialogDescription","descriptionProps","CLOSE_NAME","DialogClose","closeProps","TITLE_WARNING_NAME","WarningProvider","useWarningContext","titleWarningContext","MESSAGE","DESCRIPTION_WARNING_NAME","descriptionId","describedById","Trigger","Overlay","Content","Title","Description","Close","createSlottable","Slottable2","Fragment2","ROOT_NAME","createAlertDialogContext","useDialogScope","__scopeAlertDialog","alertDialogProps","dialogScope","DialogPrimitive.Root","AlertDialogTrigger","DialogPrimitive.Trigger","AlertDialogPortal","DialogPrimitive.Portal","AlertDialogOverlay","DialogPrimitive.Overlay","AlertDialogContentProvider","useAlertDialogContentContext","Slottable","AlertDialogContent","cancelRef","DialogPrimitive.WarningProvider","DialogPrimitive.Content","AlertDialogTitle","DialogPrimitive.Title","AlertDialogDescription","DialogPrimitive.Description","ACTION_NAME","AlertDialogAction","actionProps","DialogPrimitive.Close","CANCEL_NAME","AlertDialogCancel","cancelProps","Portal2","Overlay2","Content2","Cancel","Title2","Description2","NAME","Arrow","arrowProps","POPPER_NAME","createPopperContext","createPopperScope","PopperProvider","usePopperContext","Popper","__scopePopper","anchor","setAnchor","ANCHOR_NAME","PopperAnchor","virtualRef","anchorProps","anchorRef","previousAnchor","PopperContentProvider","useContentContext","PopperContent","sideOffset","alignOffset","arrowPadding","avoidCollisions","collisionBoundary","collisionPaddingProp","sticky","hideWhenDetached","updatePositionStrategy","onPlaced","setContent","setArrow","arrowSize","arrowWidth","arrowHeight","desiredPlacement","collisionPadding","hasExplicitBoundaries","isNotNull","isPositioned","anchorWidth","anchorHeight","contentStyle","floatingUIarrow","placedSide","placedAlign","getSideAndAlignFromPlacement","handlePlaced","arrowX","arrowY","cannotCenterArrow","contentZIndex","setContentZIndex","ARROW_NAME","OPPOSITE_SIDE","PopperArrow","contentContext","baseSide","ArrowPrimitive.Root","isArrowHidden","noArrowAlign","arrowXCenter","arrowYCenter","Anchor","POPOVER_NAME","createPopoverContext","usePopperScope","PopoverProvider","usePopoverContext","Popover","__scopePopover","popperScope","hasCustomAnchor","setHasCustomAnchor","PopperPrimitive.Root","PopoverAnchor","onCustomAnchorAdd","onCustomAnchorRemove","PopperPrimitive.Anchor","PopoverTrigger","PopoverPortal","PopoverContent","PopoverContentModal","PopoverContentNonModal","isRightClickOutsideRef","PopoverContentImpl","isRightClick","PopperPrimitive.Content","PopoverClose","PopoverArrow","PopperPrimitive.Arrow","DialogHeader","EMAIL_REGEX","PillEmailInput","ariaInvalid","ariaDescribedBy","inputValue","setInputValue","addEmail","removeEmail","UseForDropdown","itemClickedRef","selectedLabels","optionValue","handleOpenChange","AlertDialogPrimitive.Root","AlertDialogPrimitive.Portal","AlertDialogPrimitive.Overlay","AlertDialogPrimitive.Content","AlertDialogHeader","AlertDialogFooter","AlertDialogPrimitive.Title","AlertDialogPrimitive.Description","AlertDialogPrimitive.Action","AlertDialogPrimitive.Cancel","DefaultConfirmationDialog","currentDefaultName","AREA_MAX","NUMBER_MAX","EXTENSION_MAX","UnifiedPhoneInput","areaRef","numberRef","extensionRef","handleAreaChange","handleNumberChange","handleExtensionChange","segment","atStart","atEnd","DEFAULT_SOCIAL_NETWORK","TAB_BASIC_DATA","TAB_LOCATION","TAB_PHONE","TAB_SOCIAL","getTabForField","ContactModal","isFirstContact","currentDefaultContactName","isOnlyDefault","currentDefaultOnlyHasDefault","isViewMode","requireClassification","modalFormSchema","getCategoryLabel","categoryValue","hasCities","hasNeighborhoods","hasAnyGeoConfig","transferDialogOpen","setTransferDialogOpen","pendingUseFor","setPendingUseFor","preventRemovalError","setPreventRemovalError","watch","setFocus","useForm","standardSchemaResolver","phoneFields","prependPhone","removePhone","useFieldArray","socialNetworkFields","prependSocialNetwork","removeSocialNetwork","nameValue","handleCityChange","handleNeighborhoodChange","formErrors","firstErrorField","targetTab","handleAddPhone","handleUseForChange","currentUseFor","wasAdded","wasRemoved","handleTransferConfirm","handleTransferCancel","handleAddSocialNetwork","phoneTableColumns","_row","phoneCountryId","phoneData","phoneVal","socialTableColumns","snTypeId","Save","isTabActive","newEmails","DeleteDefaultConfirmationDialog","isDefaultDelete","defaultContactName","cancelLabel","ContactManager","useForOptionsProp","onContactsChange","consumerExtendedUseFor","consumerExtendedPhoneCat","fetchedValues","setFetchedValues","resolvedPhoneCategoryOptions","normalizedUseForOptions","setSocialNetworkTypes","snConfig","loadContacts","addContact","editContact","deleteContact","restoreContact","deleteDialogOpen","setDeleteDialogOpen","pendingDeleteId","setPendingDeleteId","modalStateRef","handleAdd","found","currentDefaultContact","currentMode","currentContact","ensuredUseFor","oldDefault","newUseFor","handleDeleteCancel","deleteDialogContact","deleteDialogNewDefault","englishTranslations","stringify","settings","nameRe","nameReJsx","emptyOptions","re","whitespace","thing","empty","Schema","normal","space","merge","definitions","attribute","powers","boolean","increment","booleanish","overloadedBoolean","spaceSeparated","commaSeparated","commaOrSpaceSeparated","checks","types","DefinedInfo","mask","mark","check","normals","info","aria","caseSensitiveTransform","caseInsensitiveTransform","svg","xlink","xmlns","xml","hastToReact","cap","dash","valid","find","Type","camelcase","dashes","kebab","$0","htmlBase","svgBase","COMMENT_REGEX","NEWLINE_REGEX","WHITESPACE_REGEX","PROPERTY_REGEX","COLON_REGEX","VALUE_REGEX","SEMICOLON_REGEX","TRIM_REGEX","NEWLINE","FORWARD_SLASH","ASTERISK","EMPTY_STRING","TYPE_COMMENT","TYPE_DECLARATION","lineno","updatePosition","Position","comments","comment","declaration","ret","trim","declarations","decls","decl","cjs","__importDefault","this","StyleToObject","inline_style_parser_1","styleObject","hasIterator","utilities","CUSTOM_PROPERTY_REGEX","HYPHEN_REGEX","NO_HYPHEN_REGEX","VENDOR_PREFIX_REGEX","MS_VENDOR_PREFIX_REGEX","skipCamelCase","capitalize","character","trimHyphen","camelCase","style_to_object_1","utilities_1","StyleToJS","pointEnd","point","pointStart","stringifyPosition","VFileMessage","causeOrReason","optionsOrParentOrPlace","origin","legacyCause","own","emptyMap","tableCellElement","docs","toJsxRuntime","filePath","developmentCreate","productionCreate","one","mdxExpression","mdxJsxElement","mdxEsm","parentSchema","findComponentFromName","createElementProps","createChildren","addNode","addChildren","expression","assert","crashEstree","createJsxElementProps","jsxDEV","isStaticChildren","alignValue","createProperty","objectExpression","countsByName","commas","spaces","parseStyle","transformStylesToCssCasing","styleToJs","cause","allowExpression","identifiers","isIdentifierName","place","domCasing","cssCasing","transformStyleToCssCasing","toDash","urlAttributes","toString","includeImageAlt","includeHtml","all","decodeNamedCharacterReference","characterReference","splice","remove","chunkStart","push","combineExtensions","syntaxExtension","extension","hook","constructs","before","decodeNumericCharacterReference","normalizeIdentifier","asciiAlpha","regexCheck","asciiAlphanumeric","asciiAtext","asciiControl","asciiDigit","asciiHexDigit","asciiPunctuation","markdownLineEnding","markdownLineEndingOrSpace","markdownSpace","unicodePunctuation","unicodeWhitespace","regex","normalizeUri","factorySpace","initializeContent","contentStart","afterContentStartConstruct","paragraphInitial","lineStart","document","initializeDocument","containerConstruct","tokenizeContainer","self","continued","childFlow","childToken","lineStartOffset","documentContinue","checkNewContainers","closeFlow","indexBeforeExits","indexBeforeFlow","exitContainers","documentContinued","flowStart","thereIsANewContainer","thereIsNoNewContainer","containerContinue","flowContinue","writeToChild","endOfFile","stream","nok","classifyCharacter","resolveAll","called","attention","resolveAllAttention","tokenizeAttention","openingSequence","closingSequence","use","nextEvents","movePoint","attentionMarkers","marker","inside","after","autolink","tokenizeAutolink","schemeOrEmailAtext","emailAtext","schemeInsideOrEmailAtext","urlInside","emailAtSignOrDot","emailLabel","emailValue","blankLine","tokenizeBlankLine","blockQuote","tokenizeBlockQuoteContinuation","exit","tokenizeBlockQuoteStart","contStart","contBefore","characterEscape","tokenizeCharacterEscape","tokenizeCharacterReference","test","numeric","nonLazyContinuation","tokenizeNonLazyContinuation","codeFenced","tokenizeCodeFenced","closeStart","tokenizeCloseStart","initialPrefix","sizeOpen","beforeSequenceOpen","tail","sequenceOpen","infoBefore","atNonLazyBreak","metaBefore","meta","contentBefore","beforeContentChunk","contentChunk","startBefore","beforeSequenceClose","sequenceClose","sequenceCloseAfter","codeIndented","tokenizeCodeIndented","furtherStart","tokenizeFurtherStart","afterPrefix","atBreak","codeText","resolveCodeText","tokenizeCodeText","tailExitIndex","headEnterIndex","enter","between","SpliceBuffer","stop","deleteCount","removed","chunkedPush","subtokenize","eventsArray","jumps","lineIndex","otherIndex","otherEvent","subevents","more","subcontent","eventIndex","startPosition","startPositions","tokenizer","childEvents","gaps","adjust","breaks","slice","resolveContent","tokenizeContent","continuationConstruct","tokenizeContinuation","chunkInside","contentEnd","contentContinue","startLookahead","prefixed","factoryDestination","literalType","literalMarkerType","rawType","stringType","balance","enclosedBefore","enclosed","enclosedEscape","rawEscape","factoryLabel","markerType","labelInside","labelEscape","factoryTitle","begin","escape","factoryWhitespace","tokenizeDefinition","titleBefore","tokenizeTitleBefore","identifier","labelAfter","markerAfter","destinationBefore","destinationAfter","afterWhitespace","beforeMarker","titleAfter","titleAfterOptionalWhitespace","hardBreakEscape","tokenizeHardBreakEscape","headingAtx","resolveHeadingAtx","tokenizeHeadingAtx","sequenceFurther","htmlBlockNames","htmlRawNames","htmlFlow","resolveToHtmlFlow","tokenizeHtmlFlow","blankLineBefore","tokenizeBlankLineBefore","nonLazyContinuationStart","tokenizeNonLazyContinuationStart","closingTag","markerB","declarationOpen","tagCloseStart","continuationDeclarationInside","tagName","commentOpenInside","cdataOpenInside","continuation","slash","basicSelfClosing","completeClosingTagAfter","completeAttributeNameBefore","completeEnd","completeAttributeName","completeAttributeNameAfter","completeAttributeValueBefore","completeAttributeValueQuoted","completeAttributeValueUnquoted","completeAttributeValueQuotedAfter","completeAfter","continuationCommentInside","continuationRawTagOpen","continuationClose","continuationCdataInside","continuationAfter","continuationStart","continuationStartNonLazy","continuationBefore","continuationRawEndTag","htmlText","tokenizeHtmlText","returnState","instruction","tagOpen","commentEnd","commentClose","lineEndingBefore","cdata","cdataClose","cdataEnd","instructionClose","tagClose","tagCloseBetween","tagOpenBetween","tagOpenAttributeName","tagOpenAttributeNameAfter","tagOpenAttributeValueBefore","tagOpenAttributeValueQuoted","tagOpenAttributeValueUnquoted","tagOpenAttributeValueQuotedAfter","lineEndingAfter","lineEndingAfterPrefix","labelEnd","resolveAllLabelEnd","resolveToLabelEnd","tokenizeLabelEnd","resourceConstruct","tokenizeResource","referenceFullConstruct","tokenizeReferenceFull","referenceCollapsedConstruct","tokenizeReferenceCollapsed","newEvents","media","labelStart","labelEndNok","labelEndOk","referenceNotFull","resourceStart","resourceBefore","resourceOpen","resourceEnd","resourceDestinationAfter","resourceDestinationMissing","resourceBetween","resourceTitleAfter","referenceFull","referenceFullAfter","referenceFullMissing","referenceCollapsedStart","referenceCollapsedOpen","labelStartImage","tokenizeLabelStartImage","labelStartLink","tokenizeLabelStartLink","lineEnding","tokenizeLineEnding","thematicBreak","tokenizeThematicBreak","sequence","tokenizeListContinuation","tokenizeListEnd","tokenizeListStart","listItemPrefixWhitespaceConstruct","tokenizeListItemPrefixWhitespace","indentConstruct","tokenizeIndent","initialSize","kind","atMarker","onBlank","endOfPrefix","otherPrefix","notBlank","notInCurrentItem","setextUnderline","resolveToSetextUnderline","tokenizeSetextUnderline","paragraph","flow","initializeFlow","atBlankEnding","afterConstruct","resolver","createResolver","initializeFactory","resolveAllLineSuffixes","initializeText","notText","extraResolver","resolveAllText","chunks","bufferIndex","chunk","contentInitial","flowInitial","insideSpan","resolveText","disable","createTokenizer","parser","initialize","columnStart","resolveAllConstructs","constructFactory","onsuccessfulconstruct","onsuccessfulcheck","consume","defineSkip","now","sliceSerialize","sliceStream","write","main","addResult","expandTabs","serializeChunks","sliceChunks","_bufferIndex","_index","accountForPotentialSkip","chunkIndex","go","construct","onreturn","bogusState","listOfConstructs","constructIndex","currentConstruct","handleListOfConstructs","handleMapOfConstructs","handleConstruct","startPoint","startPrevious","startCurrentConstruct","startEventsIndex","startStack","restore","startBufferIndex","endBufferIndex","atTab","defaultConstructs","postprocess","preprocess","atCarriageReturn","preprocessor","encoding","endPosition","characterEscapeOrReference","decodeString","decode","$1","$2","hex","fromMarkdown","compiler","opener","link","onenterdata","codeFlow","emphasis","hardBreak","listItem","onenterlistitemvalue","onenterlistordered","onenterreference","strong","closer","onexitatxheadingsequence","onexitautolinkemail","onexitautolinkprotocol","onexitdata","onexitcharacterreferencemarker","onexitcharacterreferencevalue","onexitcharacterreference","onexitcodefenced","onexitcodefencedfence","onexitcodefencedfenceinfo","onexitcodefencedfencemeta","onexitcodeindented","onexitcodetext","onexitdefinitiondestinationstring","onexitdefinitionlabelstring","onexitdefinitiontitlestring","onexithardbreak","onexithtmlflow","onexithtmltext","onexitimage","onexitlabel","onexitlabeltext","onexitlineending","onexitlink","onexitreferencestring","onexitresourcedestinationstring","onexitresourcetitlestring","onexitresource","onexitsetextheading","onexitsetextheadinglinesequence","onexitsetextheadingtext","configure","compile","resume","listStack","prepareList","defaultOnError","containerBalance","listSpread","firstBlankLineIndex","tailIndex","tailEvent","and","errorHandler","onExitError","siblings","referenceType","fragment","combined","remarkParse","blockquote","language","strikethrough","footnoteReference","clobberPrefix","safeId","reuseCounter","sup","revert","subtype","contents","imageReference","inlineCode","linkReference","loose","listLoose","listItemLoose","spread","firstRow","tableContent","tableRow","cellIndex","cells","cell","tableCell","trimLines","trimLine","handlers","ignore","VOID","PRIMITIVE","ARRAY","OBJECT","DATE","REGEXP","MAP","SET","ERROR","BIGINT","env","deserializer","as","out","unpair","flags","deserialize","serialized","EMPTY","asString","shouldSkip","TYPE","serializer","strict","pair","serialize","lossy","structuredClone$1","any","defaultFootnoteBackContent","rereferenceIndex","defaultFootnoteBackLabel","referenceIndex","footer","footnoteBackContent","footnoteBackLabel","footnoteLabel","footnoteLabelTagName","footnoteLabelProperties","listItems","backReferences","counts","tailTail","structuredClone","convert","castFactory","anyFactory","propertiesFactory","typeFactory","tests","checkAsRecord","nodeAsRecord","testFunction","looksLikeANode","CONTINUE","EXIT","SKIP","visitParents","visitor","reverse","factory","parents","visit","subresult","grandparents","toResult","nodeAsParent","testOrVisitor","visitorOrReverse","maybeReverse","overload","definitionById","footnoteById","footnoteCounts","defaultHandlers","applyData","wrap","handle","shallow","defaultUnknownHandler","trimMarkdownSpaceStart","hName","hChildren","hProperties","toHast","foot","remarkRehype","destination","hastTree","bail","hasOwn","toStr","defineProperty","gOPD","isArray","isPlainObject","hasOwnConstructor","hasIsPrototypeOf","setProperty","getProperty","extend","copy","copyIsArray","clone","prototype","trough","pipeline","middlewareIndex","middelware","wrapped","fnExpectsCallback","exception","then","minpath","basename","dirname","extname","join","assertPath","seenNonSlash","firstNonSlashEnd","extnameIndex","unmatchedSlash","startPart","startDot","preDotState","segments","joined","absolute","normalizeString","allowAboveRoot","lastSegmentLength","lastSlash","dots","lastSlashIndex","minproc","cwd","isUrl","fileUrlOrPath","urlToPath","getPathFromURLPosix","pathname","third","VFile","isUint8Array","assertNonEmpty","assertPart","stem","CallableInstance","proto","Processor","attacher","assertUnfrozen","transformer","realFile","vfile","assertParser","assertCompiler","executor","parseTree","realDone","compileTree","compileResult","looksLikeAValue","complete","assertDone","assertNode","transformers","outputTree","resultingTree","attachers","namespace","addPlugin","addList","addPreset","plugin","plugins","entryIndex","primary","currentPrimary","isPlainObj","unified","frozen","asyncName","looksLikeAVFile","changelog","emptyPlugins","emptyRemarkRehypeOptions","safeProtocol","deprecations","Markdown","processor","createProcessor","createFile","post","rehypePlugins","remarkPlugins","remarkRehypeOptions","allowedElements","allowElement","components","disallowedElements","skipHtml","unwrapDisallowed","urlTransform","defaultUrlTransform","deprecation","colon","questionMark","numberSign","ccount","escapeStringRegexp","findAndReplace","ignored","pairs","toPairs","pairIndex","grandparent","matchObject","tupleOrList","tuple","toExpression","toFunction","inConstruct","notInConstruct","gfmAutolinkLiteralFromMarkdown","transformGfmAutolinkLiterals","enterLiteralAutolink","enterLiteralAutolinkValue","exitLiteralAutolink","exitLiteralAutolinkEmail","exitLiteralAutolinkHttp","exitLiteralAutolinkWww","gfmAutolinkLiteralToMarkdown","findUrl","findEmail","protocol","domain","isCorrectDomain","splitUrl","atext","trailExec","trail","closingParenIndex","openingParens","closingParens","footnoteReferencePeek","enterFootnoteCallString","enterFootnoteCall","enterFootnoteDefinitionLabelString","enterFootnoteDefinition","exitFootnoteCallString","exitFootnoteCall","exitFootnoteDefinitionLabelString","exitFootnoteDefinition","tracker","subexit","gfmFootnoteFromMarkdown","gfmFootnoteToMarkdown","firstLineBlank","footnoteDefinition","mapAll","mapExceptFirst","blank","constructsWithoutStrikethrough","peekDelete","gfmStrikethroughFromMarkdown","enterStrikethrough","exitStrikethrough","gfmStrikethroughToMarkdown","defaultStringLength","markdownTable","stringLength","alignments","cellMatrix","sizeMatrix","longestCellByColumn","mostCellsPerRow","sizes","columnIndex","toAlignment","patternInScope","listInScope","none","_1","longestStreak","expected","formatCodeAsIndented","checkFence","checkQuote","quote","checkEmphasis","encodeCharacterReference","encodeInfo","outside","outsideKind","insideKind","emphasisPeek","betweenHead","betweenTail","formatHeadingAsSetext","literalWithBreak","rank","htmlPeek","imagePeek","imageReferencePeek","inlineCodePeek","formatLinkAsAutolink","linkPeek","linkReferencePeek","checkBullet","checkBulletOther","bullet","bulletOther","checkBulletOrdered","checkRule","bulletCurrent","useDifferentMarker","firstListItem","checkListItemIndent","listItemIndent","phrasing","checkStrong","strongPeek","checkRuleRepetition","repetition","gfmTableFromMarkdown","enterTable","enterCell","enterRow","exitCodeText","exitTable","gfmTableToMarkdown","alignDelimiters","around","inlineCodeWithTable","handleTable","handleTableCell","handleTableRow","serializeData","handleTableAsData","handleTableRowAsData","matrix","gfmTaskListItemFromMarkdown","exitCheck","exitParagraphWithTaskListItem","gfmTaskListItemToMarkdown","listItemWithTaskListItem","firstParaghraph","sibling","checkable","checkbox","gfmFromMarkdown","gfmToMarkdown","wwwPrefix","tokenizeWwwPrefix","tokenizeDomain","tokenizePath","tokenizeTrail","emailDomainDotTrail","tokenizeEmailDomainDotTrail","wwwAutolink","tokenizeWwwAutolink","previousWww","protocolAutolink","tokenizeProtocolAutolink","previousProtocol","emailAutolink","tokenizeEmailAutolink","previousEmail","gfmAutolinkLiteral","dot","gfmAtext","previousUnbalanced","emailDomain","emailDomainAfter","emailDomainDot","wwwStart","wwwAfter","protocolStart","protocolPrefixInside","protocolSlashesInside","afterProtocol","protocolAfter","wwwPrefixInside","wwwPrefixAfter","underscoreInLastSegment","underscoreInLastLastSegment","domainInside","domainAfter","domainAtPunctuation","sizeClose","pathInside","pathAtPunctuation","trailCharacterReferenceStart","trailBracketAfter","trailCharacterReferenceInside","indent","gfmFootnote","tokenizeDefinitionStart","tokenizeDefinitionContinuation","gfmFootnoteDefinitionEnd","tokenizeGfmFootnoteCall","tokenizePotentialGfmFootnoteCall","resolveToPotentialGfmFootnoteCall","call","callStart","callData","callEscape","labelAtMarker","whitespaceAfter","gfmStrikethrough","single","tokenizeStrikethrough","resolveAllStrikethrough","EditMap","addImplementation","vecs","editMap","at","gfmTableAlign","inDelimiterRow","alignIndex","gfmTable","tokenizeTable","resolveTable","sizeB","bodyRowStart","headRowBefore","headRowStart","headRowBreak","headDelimiterStart","headRowData","headRowEscape","headDelimiterBefore","headDelimiterValueBefore","headDelimiterCellBefore","headDelimiterNok","headDelimiterLeftAlignmentAfter","headDelimiterCellAfter","headDelimiterFiller","headDelimiterRightAlignmentAfter","bodyRowBreak","bodyRowData","bodyRowEscape","inFirstCellAwaitingPipe","rowKind","lastCell","afterHeadAwaitingFirstBodyRow","lastTableEnd","currentTable","currentBody","currentCell","flushTableEnd","flushCell","rowEnd","previousCell","groupName","valueName","getPoint","relatedStart","relatedEnd","valueToken","tableBody","exits","related","tasklistCheck","tokenizeTasklistCheck","gfmTaskListItem","spaceThenNonSpace","gfm","remarkGfm","micromarkExtensions","fromMarkdownExtensions","toMarkdownExtensions","ChatMessage","isUser","formattedTime","User","Bot","ReactMarkdown","href","DEFAULT_INPUT_LABELS","ChatInput","onSend","labelsProp","textareaRef","handleSend","handleInput","Send","QuickActions","ChatWindow","suggestedActions","onSendMessage","onMinimize","messagesEndRef","previousActiveElement","handleActionClick","showWelcome","Minus","DEFAULT_CHAT_LABELS","ChatWidget","AnimatePresence","MessageCircle","SIZE_CLASSES","Loading","inheritColor","MASTER_DOCUMENT_TRANSLATIONS_ES","MASTER_DOCUMENT_TRANSLATIONS_EN","MASTER_DOCUMENT_TRANSLATIONS","useMasterDocumentTranslation","FieldSpinnerIcon","FieldLoadingIndicator","MoreOptionsMenu","busy","StateBadge","bg","HeroDocumentIcon","PrintIcon","HistoryIcon","DuplicateIcon","PurchasesIcon","SalesIcon","InventoryIcon","DeactivateRecordIcon","CircleMinus","ActivateRecordIcon","CircleCheck","ACTIVAR_FG","TONO_ANULAR","accionDeEstadoAlCanon","clasesDeTonoBoton","tone","ActionBar","breadcrumbLabel","documentTitle","onBreadcrumbClick","documentId","documentNumber","stateBadge","docTypeBadge","transitions","onTransition","CLAVES_DIRECTAS","directas","guardar","anular","imprimir","overflowActions","tr","moreMenuActions","iconOf","overflowTransitions","overflowPlain","showOverflowBtn","algoEnVuelo","numero","canon","rotulo","HIDE_ON_BREAKPOINT_CLASS","hideClasses","breakpoints","bp","ContextStrip","currencyPanel","SourceType","memoizeOnce","lastArgs","lastValue","charIsNumber","char","isNil","isNanValue","isNotValidValue","escapeRegExp","getThousandsGroupRegex","thousandsGroupStyle","applyThousandSeparator","thousandSeparator","thousandsGroupRegex","usePersistentCallback","persistentCbRef","splitDecimal","numStr","allowNegative","hasNegation","addNegation","beforeDecimal","afterDecimal","fixLeadingZero","isNegative","limitToScale","fixedDecimalScale","filler","repeat","toNumericString","_num","coefficient","exponent","decimalIndex","coffiecientLn","roundToPrecision","shouldHaveDecimalSeparator","floatValue","floatValueStr","roundedDecimalParts","intPart","roundedStr","decimalPart","negation","decimalSeparator","setCaretPosition","caretPos","findChangeRange","prevValue","j","prevLength","newLength","findChangedRangeFromCaretPositions","lastCaretPositions","currentCaretPosition","geInputCaretPosition","addInputMode","getDefaultChangeMeta","defaultIsCharacterSame","formattedValue","currentValueIndex","formattedValueIndex","getCaretPosition","newFormattedValue","lastFormattedValue","curValue","curCaretPos","isValidInputCharacter","isCharacterSame","firstAllowedPosition","prefixFormat","curValLn","formattedValueLn","addedIndexMap","indexMap","jLn","isCharSame","getCaretPosInBoundary","valLn","caretUnknownFormatBoundary","boundaryAry","ln","useInternalValues","valueIsNumericString","removeFormatting","getValues","numAsString","_onValueChange","sourceInfo","_valueIsNumericString","defaultRemoveFormatting","defaultFormat","NumberFormatBase","displayType","customInput","renderText","getInputRef","isAllowed","onMouseUp","getCaretBoundary","otherProps","ref_0","onFormattedValueChange","caretPositionBeforeChange","lastUpdatedValue","ref$1","focusedElm","timeout","_format","getValueObject","setPatchedCaretPosition","correctCaretPosition","getNewCaretPosition","caretBoundary","updatedCaretPos","updateValueAndCaretPosition","lastNumAsString","formatInputValue","changeRange","changeMeta","_numAsString","_formattedValue","input$1","setCaretPositionInfoBeforeChange","endOffset","selectionStart","selectionEnd","_onChange","_onKeyDown","expectedCaretPosition","isArrowKey","newCaretPosition","_onMouseUp","correctCaretPositionIfRequired","caretPosition","_onFocus","currentTarget","_onBlur","inputMode","CustomInput","decimalScale","getSeparators","hasDecimalSeparator","allowedDecimalSeparators","handleNegation","negationRegex","doubleNegationRegex","removeNegation","getNumberRegex","global","isNumericString","isBeforeDecimalSeparator","separator","stripNegation","hasDoubleNegation","charsToRemove","toMetadata","fromStart","fromEnd","updatedSuffixPart","suffixStartIndex","firstIndex","ref$2","validateAndUpdateProps","useNumericFormat","allowLeadingZeros","restProps","_removeFormatting","roundIncomingValueToPrecision","ref$1_0","_thousandSeparator","inputChar","curChar","newChar","typedRange","getDecimalSeparatorIndex","NumericFormat","numericFormatProps","controlHeight","readonlyBase","LookupResolveCacheContext","LookupResolveCacheProvider","cacheRef","labelFieldsOf","computeLabel","useResolvedLookupRecord","ctxCache","localCacheRef","setRecord","promise","LookupReadonlyValue","isMono","REGION_POR_IDIOMA","MONEDA_POR_DEFECTO","resolveLocale","parseDate","soloFecha","createCurrencyFormatter","currency","delCldr","decimales","fmt","createFormatters","currencyFmt","amountFmt","rateFmt","numberFmt","dateFmt","dateTimeFmt","useMasterDocumentFormatters","isEmptyValue","asNumber","incumple","customValidators","vacio","cota","evaluateFieldValidations","reglas","warning","evaluateFields","evaluateBlockingFields","regla","inputBase","inputError","REQUIRED_HIGHLIGHT_CONTROLS","labelBase","ReadonlyField","TextInput","boundOf","CurrencyInput","prefijo","separadores","partes","NumberInput","acotado","DateInput","SelectInput","SearcherControl","onRecordSelect","getLookupFilters","lookupDependencies","labelFields","fetchFields","TextareaInput","ToggleInput","CheckboxInput","editable","locked","lockTooltip","lockTooltipKey","formatCurrency","formatAmount","touched","setTouched","lockTooltipText","clientError","shownError","hasWarning","errorId","isRequiredEmpty","showErrorBorder","renderControl","minNum","maxNum","_exhaustive","renderReadonly","formato","esNumero","isFieldLocked","docState","hasLines","lock","stateMatch","linesMatch","CanonTabsBar","activeKey","idPrefix","testId","buttonRefs","indicator","setIndicator","medirIndicador","ro","nextKey","isFilterValueEmpty","buildDependentLookupProps","parentValues","parentMissing","staticFilters","backendField","buildDependentsByParent","lookupConfigs","onlyKeys","depKey","parentKey","ChevronIcon","FieldsGrid","onFieldChange","modeForm","gridColumns","paddingX","gridClass","isEditable","isSearcher","lookupCfg","depProps","AccordionSection","TabsRenderer","activeFields","tabsMeta","errorMap","seIntentoGuardar","enSoloLectura","obligatorios","HeaderRenderer","mode_form","dependentsByParent","dependents","allFieldKeys","formLevelErrors","LineContextMenu","handleKey","STATUS_CONFIG","LineFulfillmentBadge","UTILIDADES_DE_TAMANO","ajustarTamanoIcono","icono","sinTamano","FILAS_POR_DEFECTO","ALTO_MINIMO_TABLA","ANCHO_MINIMO_ACCIONES","ANCHO_COLUMNA_UTILITARIA","CHECKBOX_CLS","shouldHideColumn","hideOn","formatCellValue","formatCurrencyCompact","formatNumber","isMobileBreakpoint","isTerminalStatus","LineCard","onMenu","lineEditable","selectionMode","selectionError","isBusy","cardColumns","LinesSection","columnConfigs","alerts","canAddLine","onAddLine","onEditLine","onViewLine","onDeleteLine","lineDeletable","onDuplicateLine","activeLineId","busyLineId","currentBreakpoint","selectedLineIds","onLineSelect","lineStatuses","lineSelectionErrors","onOpenLineCloseModal","lineActions","getLineActions","contextMenu","setContextMenu","visibleColumns","construirAccionesDeLinea","lineaId","lineStatus","lineDesc","MAX_DIRECTAS_LINEA","repartir","todas","anchoColumnaAcciones","enMenu","cols","nonTerminalLines","nonTerminalSelected","allSelected","someSelected","_v","anchoDeclarado","noSeEstira","lineId","pagina","setPagina","tamanoPagina","setTamanoPagina","totalPaginas","paginaSegura","lineasDeLaPagina","mostrarBarra","paginacion","contextMenuItems","handleMenuForCard","alert","EmptyLines","FactBoxWidget","FactBoxContent","grid","FactBox","_open","_onClose","FactBoxInline","abierto","setAbierto","ContentLayout","factBox","compareValue","actual","exp","evaluateCondition","formValues","extractDependencyFields","TEXTO_COMUN_ES","TEXTO_COMUN_EN","SERIAL_PANEL_TRANSLATIONS_ES","SERIAL_PANEL_TRANSLATIONS_EN","SERIAL_PANEL_TRANSLATIONS","useSerialPanelTranslation","counterClasses","SerialCapturePanel","serials","externalError","validating","duplicate","setDuplicate","refocus","inlineError","interpolatePath","formatDate","applyDisplayTemplate","ConfirmDialog","confirmDisabled","RowContextMenu","onContextMenuOpen","CardGrid","subtitle","badgeRaw","DocumentModalList","contextParams","maximized","setMaximized","setTotalCount","buttonLoading","setButtonLoading","menuRow","setMenuRow","setMenuPosition","confirm","setConfirm","contextVars","extraVars","handleToolbarButton","executeToolbarButton","handleContextMenuOpen","handleContextMenuClose","handleMenuItemSelect","recordIdField","executeMenuAction","displayMode","STATUS_BADGE","DEFAULT_CONFIRM_MESSAGE_KEY","SerialSelectPanel","queryProp","onQueryChange","pageProp","confirmOnStatuses","confirmMessageKey","serverMode","queryLocal","setQueryLocal","pageLocal","setPageLocal","overAttempted","setOverAttempted","pendingRow","setPendingRow","setQuery","pageItems","goToPage","clamped","commitSelection","rowToConfirm","rowNeedingConfirm","confirmPending","isEmpty","isSel","SerialPanel","DEFAULT_TRIGGER_FIELD","DEFAULT_QUANTITY_FIELD","DEFAULT_SERIAL_IDS_FIELD","DEFAULT_ITEM_FIELD","DEFAULT_STORAGE_FIELD","DEFAULT_LOT_FIELD","SELECT_PAGE_SIZE","FETCH_DEBOUNCE_MS","toBool","toStringArray","useSerialPanel","serialSupport","validateSerial","fetchAvailableSerials","quantityField","serialIdsField","itemField","storageField","lotField","useWatch","quantityValue","itemValue","storageValue","lotValue","serialIdsValue","serialIds","serialIdsRef","itemExtensionId","storageId","lotId","captureCodes","setCaptureCodes","captureError","setCaptureError","selectRows","setSelectRows","selectTotal","setSelectTotal","selectLoading","setSelectLoading","setValidating","selectQuery","setSelectQuery","selectPage","setSelectPage","selectGenRef","commitSerialIds","capped","prevOpenRef","prevItemRef","justOpened","unsupported","loggedUnsupportedRef","gen","handleCaptureChange","nextCodes","currentCodes","nextSet","removedIdx","nextIds","added","handleSelectQueryChange","isComplete","panelProps","ComputedRulesRunner","allWatchFields","watchedValues","formSnapshot","FormValuesWatcher","LineBlockingWatcher","calcular","firmaPrevia","errores","firma","ServerRulesRunner","onEvaluate","setLoadingFields","allTriggerFields","watched","generations","isInit","LineFormModal","onConfirmAndAddAnother","computedRules","serverRules","onEvaluateServerRule","externalErrors","widgetSlot","dynamicEntitiesSlot","onFormValuesChange","headerValues","serialReadOnly","resolvedConfirmLabel","resolvedCancelLabel","modalRef","erroresCliente","setErroresCliente","huboIntentoFallido","loadingFields","conditionDeps","defaultValues","watchedConditionValues","conditionSnapshot","snap","lineFieldKeys","lineParentKeys","watchedParents","lineParentSnapshot","resolveCascadeValue","lineDependentsByParent","handleLineFieldChange","visibleSections","configuredSectionKeys","commonFields","activeTabFields","initialSnap","firstVisible","serialT","serial","serialBlocksSave","computedTargets","isFieldEditable","camposQueBloquean","calcularBloqueo","bloqueaGuardado","claves","primera","sec","handleConfirmAndAddAnother","emptyValues","fieldKeys","isComputed","FieldRendererControlled","faltan","dependentProps","handleRecordSelect","sourceField","bound","ConflictModal","modifiedBy","modifiedAgo","onReload","onKeepEditing","dismissable","SkeletonBlock","SkeletonDocument","SkeletonList","BASE","inlineActionButton","inlineActionButtonDanger","inlineActionButtonNeutral","AsyncSearchInput","searchDocuments","alreadySelectedIds","setResults","visibleResults","CrossingSourceSelector","selectedDocuments","showInput","setShowInput","StaleDataBanner","fetchedAt","staleThresholdSeconds","isRefreshing","isStale","setIsStale","ageSeconds","CrossingClassMenu","HEADER_CLASS","CELL_CLASS","PendingLinesPanel","quantities","onTrySelectTerminalLine","terminal","buildDisplayList","walkAncestors","connectorPath","walkDescendants","rootDepth","SmallDocIcon","ExclamationIcon","DocLinkIcon","LoadingSkeleton","ErrorState","onRetry","ConnectorBlock","drawVertical","drawElbow","TreeNodeRow","displayNode","onNodeClick","pct","shouldContinue","DocumentTraceabilityTree","dn","LineCloseModal","lineDescription","closeReason","setCloseReason","isCloseMode","CrossingGenerateModal","classLabel","hasFields","LineTabsBar","LineTabsRegion","renderLines","helpers","showBar","TRACEABILITY_TAB_KEY","groupFieldsBySection","MasterDocument","contextItems","headerLayout","headerErrors","onHeaderFieldChange","linesTitle","lineColumns","lineFields","lineComputedRules","lineServerRules","lineWidgetSlot","lineDynamicEntitiesSlot","onLineFormValuesChange","lineModalSections","lineAlerts","onLineSave","lineTabs","activeLineTabKey","onLineTabChange","factBoxSections","conflict","forbidden","crossing","lineModal","setLineModal","lineErrors","setLineErrors","resolvedLinesTitle","handleEditLine","lineData","handleViewLine","handleAddLine","handleLineModalConfirm","handleLineModalConfirmAndAddAnother","handleLineModalClose","lineTabHelpers","renderLinesContent","declared","internalTabKey","setInternalTabKey","firstContentTabKey","contentTabKey","activeDetailTabKey","handleDetailTabChange","DocumentDynamicEntities","grain","defaultTitleKey","showEntityNames","grainRef","renderable","setRenderable","renderableCallbacks","reportRenderable","registerCallbacks","nothingToShow","DEFAULT_SUFFIX","normalizeGrain","resolveFeatureCode","documentClass","useDocumentDynamicEntities","headerConfig","lineConfig","headerCode","lineCode","wantedKey","alive","codes","headerRefs","lineRefs","makeGrain","grainConfig","header","CurrencyPanel","rate","rateLabel","formatRate","formattedRate","baseClass","CurrencySelectorModal","currentCode","currencies","validateQuantity","uom","tpl","readCompatKey","useCreateFromSource","operationCenterId","lockedThirdPartyId","userPermissions","onAppended","onFreeCapture","pendingField","canMultiSelect","perm","canFreeCapture","canSeeFinancial","hasOriginStep","hasConfirmStep","setStep","originChoice","setOriginChoiceState","setCandidates","candidatesLoading","setCandidatesLoading","candidatesError","setCandidatesError","selectedSourceIds","setSelectedSourceIds","pendingLines","setPendingLines","linesLoading","setLinesLoading","linesError","setLinesError","setSelectedLineIds","setQuantities","setDefaults","setHeaderValues","setSelectOptions","submitting","setSubmitting","submitError","setSubmitError","incompatibleReasons","cand","diffs","setOriginChoice","choice","toggleSource","sourceId","toggleLine","setQuantity","setDefault","setHeaderValue","loadLines","canAdvance","buildSources","byDoc","sources","back","OVERLAY_CLASS","PANEL_CLASS","HEADER_CELL","CELL","LABEL_CLASS","INPUT_CLASS","readCell","CreateFromSourceModal","fmtNum","fmtCur","renderColumnCell","showFormBlock","eff","resolveHeaders","apiService","errorField","createFormatCurrency","createFormatDate","createFormatNumber","createDefaultAdapter","docClass","docPath","classPath","req","lid","_docState","serverVersion","actionKey","documentState","_dc","_dcs","_co","cleanFilters","lastModified","onlyActive","currencyCode","DEFAULT_ICON_REGISTRY","PRINT_VIEWER_CSS","DEFAULT_NOT_CONFIGURED_MESSAGE","FOCUSABLE_SELECTOR","MasterDocumentPrintModal","backendConfigured","notConfiguredMessage","Viewer","renderViewer","viewerProps","setIsMaximized","dialogRef","focusables","viewerContent","PrintApiContext","useMasterDocumentPrint","MasterDocumentPrintProvider","printing","documentLabel","isPrintAvailable","openPrint","reportId","apiBaseUrl","defaultTitle","MasterDocumentAuditModal","AuditApiContext","useMasterDocumentAudit","MasterDocumentAuditProvider","auditLabel","isAuditAvailable","openAudit","AdapterContext","TemplateContext","IconContext","FactBoxWidgetContext","LineTabRendererContext","PermissionsContext","useMasterDocumentAdapter","useMasterDocumentTemplate","useIconRegistry","useFactBoxWidgets","useLineTabRenderers","useUserPermissions","MasterDocumentProvider","icons","factBoxWidgets","lineTabRenderers","mergedIcons","widgets","tabRenderers","RefreshContext","INERT_REFRESH","useMasterDocumentRefresh","useMasterDocumentReload","MasterDocumentRefreshProvider","isFieldRef","isLiteral","toNumber","resolveNode","customEvaluator","evaluateExpression","expr","den","decimals","factor","passes","evaluateNode","OPTIMISTIC_LOCK_CODE","ROW_VERSION_CONFLICT_CODE","CONCURRENCY_CODES","pick","isConflictError","codeStr","CLAVE_POR_STATUS","leerStatus","candidatos","esTextoParaUsuario","leerTextoBackend","bolsas","bolsa","texto","plano","esFalloDeRed","mensaje","classifyError","generico","technical","backend","clave","CONFLICT_KEY","FORBIDDEN_KEY","DEFAULT_LINE_VERSION_KEY","DEFAULT_HEADER_VERSION_KEY","mergeLineVersion","versionKey","mergeHeaderVersion","withHeaderVersion","headerVersionKey","partitionReservedErrors","conflictErr","forbiddenErr","applyLineTotals","discount","createInitialState","useMasterDocumentReducer","viewOnly","onNavigateToList","persistenceHooks","persistenceHooksRef","lineVersionKey","raiseConflict","handleMutationError","linesRef","totals","handleHeaderFieldChange","computed","handleSaveHeader","docId","headerPayload","autoSaveLineTotals","updatedLines","docIdOverride","updatedHeaderValues","handleLineSave","partitionLineResult","newLine","handleDeleteLine","deleteResult","rowVersion","headerRowVersion","backendHeaderValues","newVersion","handleDuplicateLine","_id","_ln","baseData","handleTransition","validation","handleAction","newDocId","localLines","lineResult","handleApprove","handleReject","useFactBoxData","adapterSections","LINE_LEVEL_ERROR_CODES","isLineLevelCrossingError","errorCode","FALLBACK_KEY","FALLBACK_MESSAGE","extractCrossingError","fromBackend","resolveCrossingError","extracted","createCrossingFetch","generic","buildHttpError","mapNode","mapPendingLine","fallbackSourceId","useCrossingInternal","crossingFetch","onDocumentGenerated","selectedSourceDocuments","setSelectedSourceDocuments","setLineStatuses","setLineSelectionErrors","quantitiesToCross","setQuantitiesToCross","pendingLinesFetchedAt","setPendingLinesFetchedAt","pendingLinesLoading","setPendingLinesLoading","crossingClassOptions","setCrossingClassOptions","crossingClassMenuOpen","setCrossingClassMenuOpen","lineCloseModal","setLineCloseModal","generateModal","setGenerateModal","generateError","setGenerateError","pageErrors","setPageErrors","traceabilityTree","setTraceabilityTree","traceabilityLoading","setTraceabilityLoading","traceabilityError","setTraceabilityError","fetchPendingLines","childClassId","perDoc","fetchTraceabilityTree","addSourceDocument","removeSourceDocument","searchSourceDocuments","toggleLineSelection","trySelectTerminalLine","setQuantityToCross","openCrossClassMenu","closeCrossClassMenu","generateChildInternal","sourceDocId","selectedLines","generateChild","openLineCloseModal","closeLineCloseModal","openGenerateModal","cancelGenerateModal","confirmGenerate","clearGenerateError","addPageError","dismissPageError","confirmLineClose","handleSetActiveTab","canGenerate","useCrossing","FactBoxTotals","grandTotal","kpis","breakdown","hasSections","kpi","statusConfig","FactBoxCfde","onRetransmit","onDownloadPdf","statusLabel","periodModeTranslationKeys","Row","mono","accent","FactBoxPaymentTerms","bold","FactBoxFinancial","hasReceivable","hasPayable","hasAdvance","hasCash","hasLocal","ACTION_KEY_TRANSLATION_KEYS","resolveProcessLabel","translationKey","displayUser","changedBy","changedByName","relativeTime","isoString","mins","hrs","days","months","formatTimestamp","FactBoxStatusHistory","processLabel","userLabel","resolveData","resolveField","computeAggregations","aggregations","renderTotals","resolvedData","fmtValue","negated","formatted","renderCfde","renderPaymentTerms","renderFinancial","renderKeyValue","renderProgressBar","buildFactBoxSections","sectionTemplates","badgeValue","badgeConfig","historyEntries","widget","isLineFieldVisibleInState","LineActionFormModal","submitLabel","setField","nextErrors","fieldError","commonId","evaluateLineActionGate","statusValue","disabledByState","disabledByDocState","buildLineActionPath","ACTION_FAILED_KEY","actionFailed","runLineAction","operacionDeLineaPermitida","booleano","estados","resolveActionDisabledState","applyPermissions","LineWidgetPanel","generationRef","timerRef","watchSnapshot","SmartMasterDocument","adapterOverride","onNavigateToDocument","contextAdapter","iconRegistry","print","audit","dynamicEntitiesRef","persistDynamicHeader","persistedDocumentId","persistDynamicLine","persistedLineId","dynamicEntities","resolvedDocClass","dynamicStates","setDynamicStates","availableActionKeys","setAvailableActionKeys","resolveIcon","runningAction","setRunningAction","runTransition","runAction","refreshToken","setRefreshToken","bumpRefresh","refetchDocument","refreshApi","setBusyLineId","runLineSave","pendingDeleteLineId","setPendingDeleteLineId","runDeleteLine","confirmDeleteLine","runDuplicateLine","activeLineAction","setActiveLineAction","lineActionLineId","setLineActionLineId","lineActionBusy","setLineActionBusy","lineActionError","setLineActionError","handleLineAction","outcome","registry","gate","registryEntry","legacyMeta","activeTransitionKeys","disabledReason","setActiveModalListConfig","setModalListLineId","setModalListOpen","setCreateFromSourceOpen","isModalList","isCreateFromSource","actionsWithPrint","actionsWithAudit","COMPANY_FIELD","exchangeRate","setExchangeRate","modalListOpen","activeModalListConfig","modalListLineId","createFromSourceOpen","currencyModalOpen","setCurrencyModalOpen","availableCurrencies","setAvailableCurrencies","currenciesLoading","setCurrenciesLoading","handleOpenCurrencyModal","handleCurrencySelect","factBoxAdapter","conflictProp","forbiddenProp","resolvedStateBadge","fieldRules","setFieldRules","dynamicOptions","setDynamicOptions","coId","fieldsWithSource","loads","withRules","editableOn","resolvedHeaderSections","resolvedLineColumns","visible","renderKey","flexQuery","allowedActions","externalFilters","addLineLockedWhen","configs","searcherCfg","handleEvaluateServerRule","ruleId","lineFormValues","setLineFormValues","visibleWidgets","navigateToDocument","targetDocumentId","crossingProps","ca","DEFAULT_ROW_ACTION_ICONS","elNavegadorSeEncarga","MARGEN_VIEWPORT","SEPARACION_TRIGGER","ALTO_MINIMO_MENU_FILA","acciones","espacioDebajo","espacioEncima","haciaArriba","altoMaximo","prioritarias","relleno","contenido","clases","estilo","ADV_CONTROL_CLS","ALTO_MINIMO_UTIL","CompanyDropdown","menuPos","setMenuPos","updatePos","onMouseDown","abreGrupoReal","LookupColumnFilter","searcher","parentField","columnFilterField","ColumnHeaderFilter","DocumentList","createNewLabel","pills","onPillClick","searchValues","onClearSearch","searchOpen","onToggleSearch","onViewRow","onEditRow","getRowHref","onDeleteRow","getRowActions","busyRowIds","onPrintRow","isPrintRowAvailable","printLabel","bulkMode","selectedRowIds","onRowSelect","getRowId","bulkConvertOptions","onBulkConvert","emptyState","quickSearchEnabled","quickSearchPlaceholder","quickSearchValue","onQuickSearchChange","pendingConfirm","setPendingConfirm","handleRowAction","hasRowMenu","buildRowActions","lista","porEstado","DefaultIcon","todasSeleccionadas","algunaSeleccionada","alternarTodas","marcar","yaEsta","conEmbudo","hayFiltroActivo","cajaBusqueda","pill","WIZARD_LOOKUP_LABEL_FIELD","plegar","empiezaPorAlgunaPalabra","palabra","coincideBusqueda","registro","campo","igual","valorRegistro","valorFiltro","pasaFiltros","grupo","condicion","aRegistro","crearFetcherDeOpciones","registros","_entity","desde","useWizardOptionFetcher","OptionCard","WizardOptionLookup","StepSkeleton","DocumentCreationWizard","onSelectCompany","documentClasses","selectedDocumentClass","onSelectDocumentClass","operationCenters","selectedCO","onSelectCO","documentTypes","selectedType","onSelectType","loadingStep","errorStep","hasClassStep","coStepIndex","typeStepIndex","canConfirm","StepError","dc","SpinnerIcon","BulkConversionProgress","job","onViewResults","processed","failedCount","partialCount","isTerminal","conErrores","conParciales","detalleCompletado","BulkResultsSummary","onRetryFailed","successCount","failedIds","normalizeResultStatus","blocked","mapResult","normalizeJobStatus","isTerminalJobStatus","useBulkConversion","setJob","showResults","setShowResults","lastClassId","setLastClassId","lastHeaderValues","setLastHeaderValues","stopPolling","pollJob","jobId","startJob","documentIds","newJob","cancelJob","closeProgress","openResults","closeResults","retryFailed","buildColumns","templateCols","searchers","buildColumnFilter","buildPills","buildSearchFields","PARAM_DOCUMENTO","PARAM_MODO","leerVistaDeLaUrl","MasterDocumentPage","onCreateDocument","onDocumentCreated","listConfig","wizardConfig","documentClassIdsKey","documentClassIds","singleClassId","createFromSourceEnabled","deLaUrl","destino","alNavegar","activePill","setActivePill","setSearchValues","setSearchOpen","listLoading","setListLoading","listError","setListError","availableCompanies","setAvailableCompanies","selectedListCompany","setSelectedListCompany","setPageSize","quickSearchCfg","quickSearch","setQuickSearch","quickSearchApplied","setQuickSearchApplied","setCompanies","setOperationCenters","setDocumentTypes","setSelectedType","companiesLoading","setCompaniesLoading","cosLoading","setCosLoading","typesLoading","setTypesLoading","confirmLoading","setConfirmLoading","setBusyRowIds","markRowBusy","wizardCacheRef","latestCOKeyRef","latestTypesKeyRef","wizardCompanyId","setWizardCompanyId","wizardCOId","setWizardCOId","wizardDocClass","setWizardDocClass","effectiveDocClass","setSelectedRowIds","setBulkConvertOptions","bulkJob","showBulkResults","startBulkJob","cancelBulkJob","closeBulkProgress","openBulkResults","closeBulkResults","retryBulkFailed","fetchedCompanies","fetchList","pageNum","pillKey","companyFilter","pillConfig","fetchWizardStep","setter","mapper","latestKeyRef","idle","initialCompanyId","initialClass","initialCOId","initialDocClass","companyStep","coStep","typeStep","handleWizardCompanyChange","handleWizardClassChange","handleWizardCOChange","handleWizardConfirm","typeId","handleListCompanyChange","handleViewRow","handleEditRow","resolverHrefDeFila","rowStateField","getRowState","availableByState","setAvailableByState","distinctRowStates","states","st","repRow","repId","concurrencyTokenField","getRowVersion","buildRowState","runRowAction","buildRowPrintContext","pendingDeleteRow","setPendingDeleteRow","handleDeleteRow","confirmDeleteRow","handleBackToList","adapterWithNav","origAction","docViewOnly","toFlexRowActions","disabledActions","StepCircle","baseCircle","ConnectorLine","ApprovalBanner","steps","onApprove","approveLabel","onReject","rejectLabel","MasterDocumentFormModal","GlobalDiscountControl","isPercentage","computedAmount","computedPct","SignBadge","isEcd","AvailableRow","lineCountText","CrossDocumentPanel","available","onToggleSelect","onCross","formatCurrencyProp","formatCurrencyDefault","emptyAvailable","subtotalLabel","crossButton","isInvoiced","CrossedRow","onUncross","uncrossLabel","SourceDocumentsFactBox","documents","emptyCrossed","DEFAULT_ROUTES","buildRoute","normalizeSign","deriveType","upper","mapAvailable","crossingSign","lineCountRaw","mapCrossed","toArray","useCrossDocumentsInternal","canCross","onCrossingChanged","setAvailable","crossed","setCrossed","setSelectedIds","setBusy","routes","fetchAll","availRes","crossedRes","toggleSelect","crossedSubtotal","cross","uncross","sourceDocumentId","clearError","useCrossDocuments","ADVANCES_TRANSLATIONS_ES","ADVANCES_TRANSLATIONS_EN","ADVANCES_TRANSLATIONS","useAdvancesTranslation","STATUS_COLOR","STATUS_LABEL_KEY","AdvanceStatusBadge","tooltip","availableAdvancesQueryKey","advanceApplicationsQueryKey","useAvailableAdvances","availableAdvancesEndpoint","httpRequest","STATUS_BY_CODE","normalizeAdvanceStatus","normalizeAdvanceApplication","useDocumentAdvanceApplications","applicationsEndpoint","optimisticCounter","useApplyAdvance","applyAdvanceEndpoint","appsKey","availKey","optimistic","_error","_input","useRemoveAdvance","removeAdvanceEndpoint","applicationId","app","_applicationId","ApplyAdvanceModal","documentCurrencyId","searchEntity","formatAmountProp","defaultFormatAmount","applyMutation","amount","setAmount","setForbidden","numericAmount","isApplying","AdvanceApplicationsPanel","formatDateTime","iso","tooltipDate","applicationsQuery","availableQuery","removeMutation","applications","availableCount","handleRemove","canRemove","INSTALLMENTS_TRANSLATIONS_ES","INSTALLMENTS_TRANSLATIONS_EN","INSTALLMENTS_TRANSLATIONS","useInstallmentsTranslation","InstallmentManualBadge","autoAmountLabel","RegenerateInstallmentsModal","isProcessing","installmentsQueryKey","normalizeSnapshot","normalizeInstallment","sortInstallments","installments","useInstallments","installmentsEndpoint","useModifyInstallment","modifyInstallmentEndpoint","installmentId","useRegenerateInstallments","regenerateEndpoint","regenerated","DASH","InstallmentsPanel","canAlter","initialInstallments","formatDateProp","defaultFormatDate","editableNow","editingId","setEditingId","editValue","setEditValue","pendingId","setPendingId","installmentsQuery","modifyMutation","regenerateMutation","cancelEdit","startEdit","reportError","commitEdit","handleRegenerate","WITHHOLDINGS_TRANSLATIONS_ES","WITHHOLDINGS_TRANSLATIONS_EN","WITHHOLDINGS_TRANSLATIONS","useWithholdingsTranslation","ORIGIN_CONFIG","WithholdingOriginBadge","labelKey","WithholdingTotalCell","hasOriginal","WithholdingsActionBar","canWrite","canRecalculate","hasCatalogs","selectedRow","onRecalculate","canDeleteSelected","WithholdingFormDialog","isSubmitting","submitDisabled","withholdingsQueryKey","withholdingClassesQueryKey","withholdingKeysQueryKey","withholdingOperationCentersQueryKey","getWithholdingOrigin","coerceAction","normalizeWithholding","sortWithholdings","withholdings","useWithholdings","withholdingsEndpoint","useAddManualWithholding","withholdingsBaseEndpoint","useModifyWithholding","withholdingId","useDeleteWithholding","deletedId","useRecalculateWithholdings","STALE_TIME","useWithholdingClasses","catalogs","useWithholdingKeys","useWithholdingOperationCenters","WithholdingsAddModal","setClassId","keyId","setKeyId","setOperationCenterId","setBase","classesQuery","keysQuery","ocQuery","catalogsFailed","classOptions","keyOptions","ocOptions","ocRequired","baseNum","totalNum","baseValid","totalValid","formValid","WithholdingsEditModal","setAction","actionOptions","WithholdingsConfirmModal","WithholdingsPanel","initialWithholdings","setSelectedId","addOpen","setAddOpen","editOpen","setEditOpen","withholdingsQuery","addMutation","deleteMutation","recalcMutation","showActionBar","handleRecalculate","FINANCIAL_INSTRUMENT_TRANSLATIONS_ES","FINANCIAL_INSTRUMENT_TRANSLATIONS_EN","FINANCIAL_INSTRUMENT_TRANSLATIONS","useFinancialInstrumentTranslation","InstrumentTypeField","canChangeDefaultType","selectedTypeName","readonlyName","FinancialInstrumentForm","instrument","instrumentTypes","defaultInstrumentTypeId","defaultInstrumentTypeName","isCreate","setForm","amountNum","amountAltNum","typeValid","numberValid","issueValid","dueValid","beneficiaryValid","amountValid","dueAfterIssue","amountAltValid","FinancialInstrumentConfirmModal","financialInstrumentQueryKey","instrumentTypesQueryKey","normalizeFinancialInstrument","useFinancialInstrument","financialInstrumentEndpoint","useCreateFinancialInstrument","financialInstrumentBaseEndpoint","useUpdateFinancialInstrument","financialInstrumentId","useDeleteFinancialInstrument","useInstrumentTypes","FinancialInstrumentPanel","canCapture","initialInstrument","confirmOpen","setConfirmOpen","instrumentQuery","typesQuery","isoDate","FinancialInstrumentFactBox","requiresInstrument","typeName","TRADUCCIONES","useDashboardTranslation","DASHBOARD_TRANSLATIONS","GLOBAL_UUID","SEARCH_THRESHOLD","DashboardCompanySelector","selectedCompanyId","optionDisabledReasons","searchable","searchRef","chipLabel","needle","globals","reales","chipClasses","getCatalogWidgets","createWidget","newWidget","updateWidget","widgetId","deleteWidget","getAllowedInternalRoutes","getUserLayout","userId","saveUserLayout","e$1","O","j$2","E","R","N","P$1","B","M","S","C","T","G","H","I","J","K","Q","V","W","Z","PureAbility","it","et","F","nt","rt","ot","ct","ut","ht","lt","Ability","isAbilityClass","AbilityBuilder","createDashboardAbility","userRoles","can","build","canUserViewWidget","widgetRoles","resolveWidgetPermissions","esSembrado","useWidgetEngine","isAdmin","catalog","setCatalog","initialLayout","setInitialLayout","initError","setInitError","isEditMode","setIsEditMode","period","setPeriod","isMounted","catalogData","layoutData","newPeriod","readFromStorage","useOptimisticLayout","saveLayout","debounceMs","storageKey","setLayout","saved","prevInitialRef","layoutToSaveRef","isFirstRender","newLayout","useDashboardLayout","currentLayout","calcGridColWidth","positionParams","margin","containerPadding","containerWidth","calcGridItemWHPx","gridUnits","colOrRowSize","marginPx","calcGridItemPosition","dragPosition","resizePosition","rowHeight","colWidth","actualMarginRight","actualMarginBottom","calcXY","maxRows","calcXYRaw","calcWHRaw","lowerBound","upperBound","collides","l1","l2","layoutItem","getAllCollisions","sortLayoutItems","compactType","sortLayoutItemsByColRow","sortLayoutItemsByRowCol","bottomY","getLayoutItem","getStatics","cloneLayoutItem","cloneLayout","modifyLayout","withLayoutItem","itemKey","correctBounds","bounds","collidesWith","moveElement","isUserAction","preventCollision","allowOverlap","oldX","oldY","hasCollisions","resultLayout","collision","moveElementAwayFromCollision","itemToMove","compactH","compactV","fakeItem","collisionNorth","collisionWest","newX","newY","gridBounds","maxW","maxH","minMaxSize","defaultConstraints","applyPositionConstraints","constraints","applySizeConstraints","setTransform","setTopLeft","perc","constrainWidth","currentWidth","newWidth","constrainHeight","currentHeight","newHeight","constrainLeft","constrainTop","resizeNorth","currentSize","newSize","_containerWidth","resizeEast","resizeWest","resizeSouth","resizeNorthEast","resizeNorthWest","resizeSouthEast","resizeSouthWest","resizeHandlerMap","resizeItemInDirection","transformStrategy","defaultPositionStrategy","defaultGridConfig","defaultDragConfig","defaultResizeConfig","defaultDropConfig","resolveCompactionCollision","moveToCoord","hasStatics","sizeProp","layoutHasStatics","otherItem","compactItemVertical","compareWith","fullLayout","maxY","compactItemHorizontal","verticalCompactor","_cols","sortedItem","originalIndex","horizontalCompactor","noCompactor","verticalOverlapCompactor","horizontalOverlapCompactor","noOverlapCompactor","getCompactor","baseCompactor","sortBreakpoints","getBreakpointFromWidth","matching","breakpointName","breakpointWidth","getColsFromBreakpoint","breakpoint","colCount","findOrGenerateResponsiveLayout","layouts","lastBreakpoint","compactTypeOrCompactor","existingLayout","breakpointsSorted","breakpointsAbove","layoutForBreakpoint","clonedLayout","corrected","getIndentationValue","breakpointMap","breakpointValue","createDefaultIsNestedEqual","comparator","_indexOrKeyA","_indexOrKeyB","_parentA","_parentB","createIsCircular","areItemsEqual","isEqual","cachedA","cachedB","isPromiseLike","sameValueZeroEqual","ARGUMENTS_TAG","BOOLEAN_TAG","DATE_TAG","REG_EXP_TAG","MAP_TAG","NUMBER_TAG","OBJECT_TAG","SET_TAG","STRING_TAG","createComparator","areArraysEqual","areDatesEqual","areMapsEqual","areObjectsEqual","areRegExpsEqual","areSetsEqual","createIsNestedEqual","aArray","bArray","aTag","areArraysEqualCircular","isValueEqual","matchedIndices","indexA","aValue","aKey","hasMatch","matchIndexB","bValue","bKey","areMapsEqualCircular","OWNER","keysA","reactElementA","reactElementB","areObjectsEqualCircular","matchIndex","areSetsEqualCircular","DEFAULT_CONFIG","DEFAULT_CIRCULAR_CONFIG","isDeepEqual","clsxModule","shims","dontSetMe","findInArray","int","isNum","getPrefix_1","browserPrefixToKey","browserPrefixToStyle","getPrefix","prefixes","kebabToTitleCase","shouldCapitalize","domFns","addClassName","addEvent","addUserSelectStyles","createCSSTransform","createSVGTransform","getTouch","getTouchIdentifier","getTranslation","matchesSelector","matchesSelectorAndParentsTo","offsetXYFromParent","outerHeight","outerWidth","removeClassName","removeEvent","scheduleRemoveUserSelectStyles","_shims","_getPrefix","_interopRequireWildcard","matchesSelectorFunc","baseNode","inputOptions","offsetParentRect","controlPos","positionOffset","translation","unitSuffix","defaultX","defaultY","styleEl","removeUserSelectStyles","positionFns","canDragX","canDragY","createCoreData","createDraggableData","getBoundPosition","getControlPosition","snapToGrid","_domFns","draggable","cloneBounds","findDOMNode","boundNode","boundNodeEl","nodeStyle","boundNodeStyle","pendingX","pendingY","touchIdentifier","draggableCore","touchObj","coreData","log_1","log","DraggableCore_1","_propTypes","_interopRequireDefault","_reactDom","_positionFns","require$$5","_log","require$$6","_toPropertyKey","_toPrimitive","eventsFor","dragEventFor","DraggableCore$1","thisNode","coreEvent","DraggableCore","exports","_DraggableCore","_clsx","require$$7","require$$8","_extends","Draggable","prevPropsPosition","uiData","newState","newStateX","newStateY","defaultPosition","defaultClassName","defaultClassNameDragging","defaultClassNameDragged","draggableCoreProps","svgTransform","validPosition","transformOpts","cjsModule","utils","_react","propTypes","Resizable_1","_reactDraggable","_utils","Resizable$1","minConstraints","maxConstraints","lockAspectRatio","deltaW","deltaH","oldW","oldH","slackW","slackH","handlerName","axisV","axisH","handleRect","deltaLeftSinceLast","deltaTopSinceLast","dimensionsChanged","handleAxis","isDOMElement","_this$props","draggableOpts","handleSize","onResize","onResizeStop","onResizeStart","resizeHandles","transformScale","Resizable","ResizableBox_1","_Resizable","_propTypes2","ResizableBox$1","ResizableBox","reactResizableModule","GridItem","isDraggable","isResizable","isBounded","isStatic","useCSSTransforms","usePercentages","positionStrategy","dragThreshold","droppingPosition","minW","minH","resizeHandle","onDragStartProp","onDragProp","onDragStopProp","onResizeStartProp","onResizeProp","onResizeStopProp","setDragging","resizing","setResizing","elementRef","dragPositionRef","resizePositionRef","prevDroppingPositionRef","layoutRef","onDragStartRef","onDragRef","dragPendingRef","initialDragClientRef","thresholdExceededRef","constraintContext","getConstraintContext","effectiveLayoutItem","createStyle","pos2","styleObj","parentRect","cLeft","pLeft","cTop","pTop","newPosition","mouseEvent","rawPos","onDrag","rawPos2","startX","startY","bottomBoundary","colWidth2","rightBoundary","onDragStop","wasPending","onResizeHandler","resizeHandle2","updatedSize","rawSize","newW","newH","handleResizeStart","typedData","handleResizeStop","prevDroppingPosition","shouldDrag","fakeData","childClassName","childStyle","newChild","resizableHandle","layoutClassName","isFirefox","childrenEqual","aArr","bArr","aChild","bChild","synchronizeLayoutWithChildren","compactor","childKeys","existingItem","dataGrid","GridLayout","gridConfigProp","dragConfigProp","resizeConfigProp","dropConfigProp","compactorProp","propsLayout","droppingItemProp","autoSize","innerRef","onLayoutChange","onDropProp","onDropDragOverProp","gridConfig","dragConfig","resizeConfig","dropConfig","draggableHandle","draggableCancel","isDroppable","defaultDropItem","dropConfigOnDragOver","droppingItem","effectiveContainerPadding","activeDrag","setActiveDrag","droppingDOMNode","setDroppingDOMNode","setDroppingPosition","oldDragItemRef","oldResizeItemRef","oldLayoutRef","dragEnterCounterRef","prevLayoutRef","prevPropsLayoutRef","prevChildrenRef","prevCompactTypeRef","layoutChanged","childrenChanged","compactTypeChanged","publicLayout","containerHeight","nbRow","containerPaddingY","_x","_y","oldDragItem","finalLayout","oldLayout","_w","_h","oldResizeItem","shouldMoveItem","removeDroppingPlaceholder","handleDragOver","rawResult","dragOffsetX","dragOffsetY","onDragOverResult","finalDroppingItem","gridRect","actualColWidth","itemPixelWidth","itemPixelHeight","itemCenterOffsetX","itemCenterOffsetY","rawGridX","rawGridY","clampedGridX","clampedGridY","newDroppingPosition","calculatedPosition","baseLayout","handleDragLeave","handleDragEnter","handleDrop","processGridItem","isDroppingItem","resizable","resizeHandlesOptions","bounded","resizeHandleElement","renderPlaceholder","mergedClassName","mergedStyle","DEFAULT_BREAKPOINTS","DEFAULT_COLS","noop2","synchronizeLayoutWithChildren2","ResponsiveGridLayout","propBreakpoint","colsConfig","propsLayouts","propMargin","propContainerPadding","onBreakpointChange","onWidthChange","initialBreakpoint","initialCols","setBreakpoint","setCols","setLayouts","prevWidthRef","prevBreakpointRef","prevBreakpointsRef","prevColsRef","prevLayoutsRef","layoutsRef","derivedLayout","effectiveLayout","newLayouts","widthChanged","breakpointPropChanged","breakpointsChanged","colsChanged","newBreakpoint","newCols","currentMargin2","currentPadding","handleLayoutChange","currentMargin","currentContainerPadding","withResponsiveWidth","WrappedComponent","measureBeforeMount","setWidth","LEGACY_ROW_HEIGHT","ROW_HEIGHT","LAYOUT_VERSION","migratePreference","preference","migrateLayout","ResponsiveGrid","ResponsiveGridLayoutOriginal","DashboardGrid","globalFilters","onRemoveWidget","renderWidget","migrated","gridLayouts","validLayouts","pref","updatedPreferences","gridItem","WIDGET_TYPE_CONFIG","Hash","BarChart3","LayoutList","TrendingUp","PieChart","Table2","Image","Puzzle","WIDGET_TYPE_MAP","getTypeIcon","tipo","getTypeLabel","DashboardContext","useDashboardContext","INDICATORS_CATALOG","INDICATOR_PAISES","INDICATOR_CATEGORIAS","buildIndicatorUrl","apiKey","INITIAL_FORM_DATA","HIGH_VOLUME_THRESHOLD","Step1DataSource","testSuccess","isTesting","testError","onUpdateForm","onTestConnection","onIndicatorSelect","filtroPais","setFiltroPais","filtroCateg","setFiltroCateg","busqueda","setBusqueda","newHeaderKey","setNewHeaderKey","newHeaderValue","setNewHeaderValue","headerCount","hasParams","showAdvanced","setShowAdvanced","bodyJsonText","setBodyJsonText","bodyJsonError","setBodyJsonError","selectedIndicator","catalogMode","handleModeChange","handleIndicatorClick","handleApiKeyChange","filteredCatalog","addHeader","handleBodyJsonChange","Key","CheckCircle","BookOpen","ExternalLink","Settings2","Activity","FileJson","classifyFields","sample","textFields","numericFields","dateFields","fullKey","AGGREGATIONS","CHART_AGGREGATIONS","optionalBadge","Step2FieldMapping","presentationType","jsonPreview","mappingConfig","onMappingConfigChange","isCatalogMode","campoValorPrefill","campoFechaPrefill","indicatorName","renderKpiMapping","SummaryBadge","renderBarMapping","renderLineMapping","renderDonutMapping","renderTableMapping","oldIdx","newIdx","reordered","addColumn","removeColumn","SortableColumnItem","renderMapping","GripVertical","SELECTABLE_TYPES","TIPOS","Step3PresentationType","selectedTipo","normalizeCategories","categorias","verticalDeLaCategoria","categoria","encontrada","DEFAULT_WIDGET_CATEGORIES","Step4Appearance","indicatorUnidad","indicatorBandera","availableCategories","delHost","DEFAULT_AVAILABLE_ROLES","nombreDe","Step5Permissions","esPrivado","onUpdatePrivacy","vertical","reparto","onUpdateReparto","personas","onUpdatePersonas","searchPeople","puedeRepartirAlCrear","consulta","setConsulta","resultados","setResultados","buscando","setBuscando","ultimaBusqueda","buscarRef","buscar","turno","ofrecePersonas","agregar","Lock","Users","CATALOG_STEPS","Database","Palette","ShieldCheck","MANUAL_STEPS","Layout","buildFieldMapping","fm","isMappingValid","WidgetBuilder","onSuccess","editWidget","canPublishWidgets","showExternalEndpoints","onNeedsAccessDialog","accessAdapter","setIsTesting","setTestSuccess","setTestError","setJsonPreview","setMappingConfig","setFormData","setReparto","setPersonas","avisoReparto","setAvisoReparto","creadoAMedias","setCreadoAMedias","baseSteps","puedeExponer","categoriasDelHost","buscarPersonas","maxStep","currentStepId","setTotalRecords","allowedRoutes","setAllowedRoutes","setSelectedIndicator","updateForm","resolverIsInternal","detectIsInternal","currentHost","handleTestConnection","detected","repartoAPersonas","repartirAlCrear","fallidos","persona","limpiarAsistente","fieldMapping","configSchema","catalogFieldMappingObj","rawField","rawDateField","hasNestedPath","canonicalField","widgetGenerado","finalWidget","aviso","validationHint","isPrivate","ArrowLeft","ArrowRight","WidgetAccessDialog","onChanged","caps","puedeCompartir","puedeEditarPolitica","puedePublicar","niveles","sujetosDeclarados","sujetos","filas","setFilas","cargando","setCargando","setAviso","cargarFilas","tipoSujeto","setTipoSujeto","sujetoId","setSujetoId","sujetoLabel","setSujetoLabel","nivel","setNivel","vencimiento","setVencimiento","fecha","setFecha","agregados","setAgregados","revocados","setRevocados","politicaOriginal","vencimientoElegido","dias","permisosOfrecibles","permisosFiltrados","pm","adapterRef","turnoBusqueda","encolarAcceso","quitarAcceso","fila","politica","setPolitica","guardando","setGuardando","vivo","filasEfectivas","politicaCambio","cambios","guardarCambios","avisos","cerrarConEsc","visibilidadCerrada","etiquetaNivel","fechaCorta","etiquetaVisibilidad","porDefecto","pistaVisibilidad","notaSiempreVe","restringido","hoyLoVe","WidgetManagerPanel","canWriteWidgets","showWidgetBuilder","onRequestAdd","onRequestModify","onWidgetCreated","onWidgetUpdated","onDeleteWidget","puertaDelConstructor","accessWidget","setAccessWidget","puedeEscribir","categoryFilter","setCategoryFilter","isBuilderOpen","setIsBuilderOpen","pendingDeleteWidget","setPendingDeleteWidget","cats","inLayoutIds","matchSearch","matchCategory","aIn","bIn","inLayout","TypeIcon","typeLabel","TYPE_FAMILIES","getCompatibleTypes","valuesCount","family","extractChartContract","detectValueFields","groupByField","hasMeta","hasActual","hasValue","firstNumeric","resolveChartFields","userOverride","widgetFieldMapping","contract","resolveLabel","widgetAliases","userAliases","CHART_COLORS","FIELD_MAPPING_COLORS","CATEGORICAL_PALETTE","OTHERS_COLOR","OTHERS_KEY","MAX_CATEGORIES","hashString","colorsForCategories","asignados","resultado","colorForSeries","buildFallbackSchema","getLabel","getCategoryFields","getNumericFields","FieldMappingPanel","currentCategory","chartType","effectiveSchema","activeValues","isDonut","maxValues","stringFields","availableToAdd","valuesLabel","handleCategoryChange","handleAddValue","handleRemoveValue","handleReset","AlertCircle","isUsed","DEFAULT_CATEGORIES","REFRESH_OPTIONS","WidgetCustomizationPanel","existingFieldMapping","activeValuesCount","compatibleTypes","showTypeSelector","currentType","showFieldMapping","handleFieldMappingChange","newOverride","clean","CustomizationWithSchema","MAX_COLS","buildOccupiedMap","isPositionFree","findFirstAvailablePosition","WidgetErrorBoundary","Component","errorInfo","Bar","BAR_HEIGHTS","TABLE_WIDTHS","WidgetSkeleton","reducedMotion","pulse","SHAPE_BY_TYPE","skeletonShapeFor","useReducedMotion","reduced","setReduced","DASHBOARD_LOCALE","DEFAULT_LOCALE","DEFAULT_CURRENCY","resolveCurrency","nf","ABBREVIATE_FROM","compactNf","splitCompact","abbreviate","integer","abs","formatCompact","symbol","formatExact","formatPercent","hasTime","NUMERIC_STYLE","fetchWidgetDataProxy","widgetDataQueryKey","userParams","getNestedValue","applyFieldMapping","mapping","apiField","mapObject","widgetField","fetchWidgetEnvelope","endpointMeta","asConfig","FORMATS","readFormat","DIRECTIONS","readDirection","readColumns","validas","readPositiveNumber","readString","readObject","WidgetWrapper","queryKey","isRefetching","useIsFetching","dataUpdatedAt","setDataUpdatedAt","dataLength","setDataLength","forceRender","readState","ts","rowCount","unsubscribe","tick","criticalVolume","isHighVolume","freshness","chromeButtonClass","isAccessOpen","setIsAccessOpen","accessButton","refreshButton","widgetContent","ShapedSkeleton","highVolumeBadge","Maximize2","Minimize2","typeRegistry","LazyWidget","customWidgetRegistry","overrideType","effectiveType","DashboardProvider","DEFAULT_ROTATE_SECONDS","usePresentationMode","onRotate","rotatableCount","setIsActive","isRotating","setRotating","UNCATEGORIZED","DashboardPage","showPeriodSelector","categoryOrder","companyDisabledReasons","categoryTerms","esAdminDelCatalogo","layoutManager","isManagerOpen","setIsManagerOpen","customizingWidget","setCustomizingWidget","pendingRemoveId","setPendingRemoveId","layoutByCategory","sortedCategories","prioritized","categoriesRef","handleRotate","boardLayout","placed","presentation","catalogCategories","handleCategoryLayoutChange","newCategoryLayout","otherCategoriesLayout","handleRemoveWidget","instanceId","confirmRemove","LayoutTemplate","Layers","Columns","LayoutGrid","Monitor","editMode","categoryLayout","newDef","updatedDef","deleteWidgetAPI","cleaned","restored","wasAdd","formCacheKeys","cacheId","createFormCacheApi","safeParse","rawJson","emptyFilter","emptyType","sortCaches","caches","useFormCacheSelectorSchema","NAME_CONFLICT_KEY","useFormCacheSelector","onSelected","httpClient","setActiveId","isMutating","setIsMutating","saveDialogOpen","setSaveDialogOpen","saveNameError","setSaveNameError","renameDialogOpen","setRenameDialogOpen","renameError","setRenameError","deletingCacheName","setDeletingCacheName","setCaches","activeToast","setActiveToast","filterRef","emptyFilterRef","hasRestoredRef","lastInUseItem","emptyAsRecord","handleSelectNoFilter","handleSelectCache","handleUpsert","handleUpdateLastInUse","openDeleteDialog","handleRename","clearSaveNameError","clearRenameError","PopoverPrimitive.Root","PopoverPrimitive.Trigger","PopoverPrimitive.Portal","PopoverPrimitive.Content","U","Y","L","D","be","le","ce","Re","ae","ue","de","ee","me","pe","ge","ke","ne","te","we","De","oe","ie","se","Te","he","ve","Ee","ye","Se","Ce","xe","w.Root","w.Portal","w.Overlay","w.Content","Ie","Pe","Me","Command","CommandPrimitive","CommandList","CommandEmpty","CommandGroup","CommandItem","CommandSeparator","CommandInput","NO_FILTER_VALUE","CacheSelector","onSelectCache","onSelectNoFilter","noFilterLabel","activeName","handleSelectCacheClick","handleSelectNoFilterClick","DialogFooter","SaveDialog","serverError","onServerErrorClear","localError","setLocalError","runSubmit","firstIssue","RenameDialog","DeleteDialog","cacheName","FormCacheSelector","handleSaveClick","activeCache","openRenameDialog","HeroBuildingOffice","PanelCompany"],"mappings":"kpBAAA,SAASA,GAAE,EAAE,CAAC,IAAI,EAAEC,EAAEC,EAAE,GAAG,GAAa,OAAO,GAAjB,UAA8B,OAAO,GAAjB,SAAmBA,GAAG,UAAoB,OAAO,GAAjB,SAAmB,GAAG,MAAM,QAAQ,CAAC,EAAE,CAAC,IAAIC,EAAE,EAAE,OAAO,IAAI,EAAE,EAAE,E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AA,CAAA,CAED,EACF,EACA5pI,EAAAA,KAAC,MAAA,CAAI,UAAU,WACb,SAAA,CAAAF,EAAAA,IAAC,OAAI,UAAU,0EACb,eAAC2pB,GAAA,CAAe,UAAU,gEAAgE,CAAA,CAC5F,EACA3pB,EAAAA,IAAC,QAAA,CACC,GAAG,iBACH,KAAMqqI,EAAe,OAAS,WAC9B,YAAY,WACZ,MAAOF,EACP,SAAWh8G,GAA2Ci8G,EAAYj8G,EAAE,OAAO,KAAK,EAChF,SAAU89B,EACV,SAAQ,GACR,aAAa,mBACb,UAAW,CACT,SACA,OACA,QACA,SACA,YACA,YACA,gBACA,0BACA,SACA,wBACA,kCACA,aACA,oCACA,8CACA,uBACA,iCACA,uBACA,2BACA,uCACA,eACA,yBACA,qCACA,iBACA,cAAA,EACA,KAAK,GAAG,CAAA,CAAA,EAEZjsD,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,QAAS0qI,EACT,UAAU,0QACV,aAAYL,EAAe,qBAAuB,qBAElD,SAAArqI,EAAAA,IAACopB,GAAA,CAAQ,UAAU,SAAA,CAAU,CAAA,CAAA,CAC/B,CAAA,CACF,CAAA,EACF,EAGAppB,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,SAAUisD,GAAa,CAACg+E,GAAS,CAACE,EAClC,UAAW,CACT,WACA,SACA,SACA,SACA,OACA,eACA,iBACA,QACA,YACA,UACA,YACA,+BACA,sBACA,eACA,0BACA,SACA,mBACA,wBACA,aACA,sBACA,uBACA,0BACA,kBACA,iBACA,eACA,uBACA,eACA,yBACA,4BACA,sBACA,mCACA,sBACA,6BAAA,EACA,KAAK,GAAG,EAET,WAAY,sBAAwB,gBAAA,CAAA,CACvC,EACF,EAGAnqI,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,QAAS+pI,EACT,UAAW,CACT,SACA,SACA,SACA,OACA,eACA,iBACA,QACA,YACA,UACA,YACA,iBACA,sBACA,uBACA,6BACA,aACA,iBACA,eACA,uBACA,eACA,yBACA,4BAC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,CAAe,UAAU,gEAAgE,CAAA,CAC5F,EACA3pB,EAAAA,IAAC,QAAA,CACC,GAAG,iBACH,KAAMqqI,EAAe,OAAS,WAC9B,YAAY,WACZ,MAAOF,EACP,SAAWh8G,GAA2Ci8G,EAAYj8G,EAAE,OAAO,KAAK,EAChF,SAAU89B,EACV,SAAQ,GACR,aAAa,eACb,UAAW,CACT,SACA,OACA,QACA,SACA,YACA,YACA,gBACA,0BACA,SACA,wBACA,kCACA,aACA,oCACA,8CACA,uBACA,iCACA,uBACA,2BACA,uCACA,eACA,yBACA,qCACA,iBACA,cAAA,EACA,KAAK,GAAG,CAAA,CAAA,EAEZjsD,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,QAAS0qI,EACT,UAAU,0QACV,aAAYL,EAAe,qBAAuB,qBAElD,SAAArqI,EAAAA,IAACopB,GAAA,CAAQ,UAAU,SAAA,CAAU,CAAA,CAAA,CAC/B,CAAA,CACF,CAAA,EACF,EAGAppB,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,SAAUisD,GAAa,CAACz1C,GAAQ,CAACyzH,GAAS,CAACE,EAC3C,UAAW,CACT,WACA,SACA,SACA,SACA,OACA,eACA,iBACA,QACA,YACA,UACA,YACA,+BACA,sBACA,eACA,0BACA,SACA,mBACA,wBACA,aACA,sBACA,uBACA,0BACA,kBACA,iBACA,eACA,uBACA,eACA,yBACA,4BACA,sBACA,mCACA,sBACA,6BAAA,EACA,KAAK,GAAG,EAET,WAAY,iBAAmB,aAAA,CAAA,CAClC,EACF,EAGAnqI,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,QAAS6qI,EACT,UAAW,CACT,SACA,SACA,SACA,OACA,eACA,iBACA,QACA,YACA,UACA,YACA,iBACA,sBACA,uBACA,6BACA,aACA,iBACA,eACA,uBACA,eACA,yBACA,4BACA,sBACA,kCAAA,EACA,KAAK,GAAG,EACX,SAAA,qBAAA,CAAA,EAKD7qI,EAAAA,IAAC,MAAA,CAAI,UAAU,qBACb,SAAA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,UAAU,uGACZ,SAAA0P,EAAM,eAAeqtD,EAAM,IAAI,EAC9BrtD,EAAM,aAAaqtD,EAAM,KAAoD,CAC3E,UAAW,+CAAA,CACZ,EAEDA,EAAM,KAEV,EACA78D,EAAAA,KAAC,MAAA,CAAI,UAAU,uCACb,SAAA,CAAAF,EAAAA,IAAC,OAAA,CAAK,UAAU,gFACb,SAAA+8D,EAAM,MACT,EACA/8D,EAAAA,IAAC,OAAA,CAAK,UAAU,sFACb,WAAM,KAAA,CACT,CAAA,CAAA,CACF,CAAA,CAAA,CAAA,CACF,CAAA,EA3BmBsF,CA4BrB,CACD,CAAA,CAAA,CAAA","x_google_ignoreList":[0,1,3,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,106,107,108,109,110,111,112,113,114,115,116,117,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,204,235,236,237,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,364,365,366,367,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,638,777,778,779,780,781,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,845,846]}