/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/vanillajs-excelike-table@2.3.3/dist/excelike-table.browser.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
!function(e,t){if("function"==typeof define&&define.amd)define([],t);else if("object"==typeof module&&module.exports)module.exports=t();else{const n=t();e.ExceLikeTable=n.ExceLikeTable,e.ColumnHelpers=n.ColumnHelpers,e.TABLE_CONFIG=n.TABLE_CONFIG}}("undefined"!=typeof self?self:this,(function(){"use strict";const e={createElement(e,t="",n={}){const a=document.createElement(e);return t&&(a.textContent=t),Object.entries(n).forEach((([e,t])=>{"class"===e?a.className=t:"data"===e?Object.entries(t).forEach((([e,t])=>{a.dataset[e]=t})):a.setAttribute(e,t)})),a},createElementWithHTML(e,t="",n={}){const a=this.createElement(e,"",n),r=document.createElement("template");return r.innerHTML=t,a.appendChild(r.content),a},setContent(e,t,n=!1){e&&(n?e.innerHTML=t:e.textContent=t)},createTableCell(e,t={}){const n=this.createElement("td","",{class:t.className||"",style:t.style||""});return t.isHTML?this.setContent(n,e,!0):n.textContent=e,t.width&&(n.style.width=`${t.width}px`),t.dataAttributes&&Object.entries(t.dataAttributes).forEach((([e,t])=>{n.dataset[e]=t})),n},createButton(e,t={}){const n=this.createElement("button",e,{class:t.className||"btn",type:t.type||"button"});return t.onClick&&n.addEventListener("click",t.onClick),t.dataAttributes&&Object.entries(t.dataAttributes).forEach((([e,t])=>{n.dataset[e]=t})),n},clearElement(e){if(!e)return;e.querySelectorAll("*").forEach((e=>{const t=e.cloneNode(!0);e.parentNode.replaceChild(t,e)})),e.innerHTML=""},appendChildren(e,t){if(!e||!Array.isArray(t))return;const n=document.createDocumentFragment();t.forEach((e=>{e instanceof HTMLElement&&n.appendChild(e)})),e.appendChild(n)}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.DOMUtils=e);const t={debounce(e,t){let n;return function(...a){clearTimeout(n),n=setTimeout((()=>{clearTimeout(n),e(...a)}),t)}},throttle(e,t){let n;return function(...a){n||(e.apply(this,a),n=!0,setTimeout((()=>n=!1),t))}},rafDebounce(e){let t;return function(...n){t&&cancelAnimationFrame(t),t=requestAnimationFrame((()=>{e.apply(this,n)}))}},memoize(e,t,n=100){const a=new Map;return function(...r){const i=t?t(...r):JSON.stringify(r);if(a.has(i)){const e=a.get(i);return a.delete(i),a.set(i,e),e}const s=e.apply(this,r);if(a.size>=n){const e=a.keys().next().value;a.delete(e)}return a.set(i,s),s}},createCache(e=3e5){const t=new Map,n=new Map;return{set(a,r){n.has(a)&&clearTimeout(n.get(a)),t.set(a,r);const i=setTimeout((()=>{t.delete(a),n.delete(a)}),e);n.set(a,i)},get:e=>t.get(e),has:e=>t.has(e),delete:e=>(n.has(e)&&(clearTimeout(n.get(e)),n.delete(e)),t.delete(e)),clear(){n.forEach((e=>clearTimeout(e))),n.clear(),t.clear()},size:()=>t.size}},batchDOMUpdates(e){requestAnimationFrame((()=>{e.forEach((e=>e()))}))},createVirtualScroller(e){const{itemHeight:t,containerHeight:n,totalItems:a,renderItem:r,buffer:i=5}=e,s=Math.ceil(n/t);return{totalHeight:a*t,getVisibleRange(e){const n=Math.max(0,Math.floor(e/t)-i);return{start:n,end:Math.min(a,n+s+2*i)}},renderVisibleItems(e,n){const{start:a,end:i}=this.getVisibleRange(e),s=document.createDocumentFragment();for(let e=a;e<i;e++){const n=r(e);n.style.position="absolute",n.style.top=e*t+"px",s.appendChild(n)}n.innerHTML="",n.appendChild(s)}}},createLazyLoader:(e,t={})=>new IntersectionObserver(((t,n)=>{t.forEach((t=>{t.isIntersecting&&(e(t.target),n.unobserve(t.target))}))}),{root:null,rootMargin:"50px",threshold:.01,...t})};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.PerformanceUtils=t);const n={create(e){const{container:n,renderItem:a,getItemData:r,onScroll:i}=e;let s=void 0!==e.itemHeight?e.itemHeight:50,o=void 0!==e.buffer?e.buffer:5;const l=void 0!==e.estimatedItemHeight?e.estimatedItemHeight:s;let c=e.totalItems||0,d=0,u=0,h=0,p=0,m=!1,f=null;const g=document.createElement("div");g.className="virtual-scroll-container",g.style.cssText="\n      height: 100%;\n      overflow: auto;\n      position: relative;\n    ";const y=document.createElement("div");y.className="virtual-scroll-spacer",y.style.cssText=`\n      height: ${c*l}px;\n      pointer-events: none;\n    `;const b=document.createElement("div");b.className="virtual-scroll-viewport",b.style.cssText="\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      pointer-events: none;\n    ";const v=document.createElement("div");v.className="virtual-scroll-content",v.style.cssText="\n      position: relative;\n      pointer-events: auto;\n    ",b.appendChild(v),g.appendChild(y),g.appendChild(b),n&&n.appendChild(g);let S=null;const w=()=>{S&&cancelAnimationFrame(S),S=requestAnimationFrame((()=>{x(),i&&i({scrollTop:d,visibleStartIndex:h,visibleEndIndex:p,isScrolling:m})}))},x=()=>{const{start:e,end:t}=(()=>{u=g.clientHeight;const e=Math.ceil(u/s);return h=Math.max(0,Math.floor(d/s)-o),p=Math.min(c,h+e+2*o),{start:h,end:p,visibleCount:e}})();v.innerHTML="";const n=document.createDocumentFragment();for(let i=e;i<t;i++){const e=r?r(i):{index:i},t=a(e,i);t&&(t.style.cssText+=`\n            position: absolute;\n            top: ${i*s}px;\n            left: 0;\n            right: 0;\n            height: ${s}px;\n            box-sizing: border-box;\n          `,n.appendChild(t))}v.appendChild(n),b.style.transform=`translateY(${h*s}px)`};t?.debounce&&t.debounce((()=>{m=!1}),150);g.addEventListener("scroll",(e=>{d=e.target.scrollTop,m=!0,w(),f&&clearTimeout(f),f=setTimeout((()=>{m=!1}),150)}),{passive:!0});let C=null;window.ResizeObserver?(C=new ResizeObserver((()=>{w()})),C.observe(g)):window.addEventListener("resize",w);const k={updateTotalItems(e){c=e,y.style.height=c*l+"px",w()},setItemHeight(e){s=e,y.style.height=c*s+"px",w()},refresh(){w()},scrollToIndex(e,t="smooth"){const n=Math.max(0,e*s-u/2);g.scrollTo({top:n,behavior:t})},scrollToTop(){g.scrollTo({top:0,behavior:"smooth"})},scrollToBottom(){const e=c*s-u;g.scrollTo({top:e,behavior:"smooth"})},getVisibleRange:()=>({start:h,end:p,total:c}),getScrollTop:()=>d,getContainerHeight:()=>u,isItemVisible:e=>e>=h&&e<p,setBuffer(e){o=e,w()},getItemOffset:e=>e*s,findItemAtPosition:e=>Math.floor(e/s),getStats:()=>({totalItems:c,visibleItems:p-h,containerHeight:u,scrollTop:d,itemHeight:s,buffer:o}),setItemHeights(e){if(!Array.isArray(e))return;let t=0;const n=[0];e.forEach(((e,a)=>{t+=e,n.push(t)})),y.style.height=`${t}px`,this._dynamicHeights={heights:e,offsets:n,totalHeight:t},w()},destroy(){S&&cancelAnimationFrame(S),f&&clearTimeout(f),C?C.disconnect():window.removeEventListener("resize",w),g.parentNode&&g.parentNode.removeChild(g)},getElements:()=>({scrollContainer:g,viewport:b,content:v,spacer:y})};return w(),k},createTableVirtualizer(e){const{tableContainer:t,data:n=[],columns:a=[],rowHeight:r=50,headerHeight:i=40,renderRow:s,onRowClick:o,onRowDoubleClick:l,renderCellHTML:c=!1}=e,d=this.create({container:t,itemHeight:r,totalItems:n.length,renderItem:(e,t)=>{const n=s?s(e,t,a):this.createDefaultRow(e,t,a);return o&&n.addEventListener("click",(n=>o(e,t,n))),l&&n.addEventListener("dblclick",(n=>l(e,t,n))),n},getItemData:e=>n[e],onScroll:e=>{t.dispatchEvent(new CustomEvent("virtualScroll",{detail:e}))}}),u=document.createElement("div");u.className="virtual-table-header",u.style.cssText=`\n      position: sticky;\n      top: 0;\n      z-index: 10;\n      background: #fafafa;\n      border-bottom: 1px solid #d9d9d9;\n      height: ${i}px;\n    `;const h=this.createHeaderRow(a,i);u.appendChild(h);const p=d.getElements();return p.scrollContainer.parentNode&&p.scrollContainer.parentNode.insertBefore(u,p.scrollContainer),{...d,updateData(e){d.updateTotalItems(e.length)},updateColumns(e){a.splice(0,a.length,...e),u.innerHTML="",u.appendChild(this.createHeaderRow(a,i)),d.refresh()},getHeader:()=>u}},createDefaultRow(e,t,n){const a=document.createElement("div");return a.className="virtual-table-row",a.style.cssText=`\n      display: flex;\n      align-items: center;\n      border-bottom: 1px solid #f0f0f0;\n      background: ${t%2==0?"#ffffff":"#fafafa"};\n    `,n.forEach((t=>{const n=document.createElement("div");n.className="virtual-table-cell",n.style.cssText=`\n        flex: 0 0 ${t.width||150}px;\n        padding: 8px 12px;\n        border-right: 1px solid #f0f0f0;\n        overflow: hidden;\n        text-overflow: ellipsis;\n        white-space: nowrap;\n      `;const r=e[t.dataIndex];if(t.render){const a=t.render(r,e,t);"string"==typeof a?n.innerHTML=a:a instanceof HTMLElement&&n.appendChild(a)}else renderCellHTML&&"string"==typeof r?n.innerHTML=r:n.textContent=r??"";a.appendChild(n)})),a},createHeaderRow(e,t){const n=document.createElement("div");return n.className="virtual-table-header-row",n.style.cssText="\n      display: flex;\n      align-items: center;\n      height: 100%;\n      font-weight: 600;\n    ",e.forEach((e=>{const t=document.createElement("div");t.className="virtual-table-header-cell",t.style.cssText=`\n        flex: 0 0 ${e.width||150}px;\n        padding: 8px 12px;\n        border-right: 1px solid #d9d9d9;\n        overflow: hidden;\n        text-overflow: ellipsis;\n        white-space: nowrap;\n      `,t.textContent=e.title,n.appendChild(t)})),n}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.VirtualScroll=n);const a={init(e,t={}){const{announceChanges:n=!0,keyboardNavigation:a=!0,screenReader:r=!0,highContrast:i=!1,focusManagement:s=!0}=t;this.table=e,this.options=t,this.currentFocus={row:-1,column:-1},this.announcer=null,r&&this.setupScreenReader(),a&&this.setupKeyboardNavigation(),s&&this.setupFocusManagement(),n&&this.setupAnnouncements(),i&&this.setupHighContrast(),this.setupARIAAttributes()},setupScreenReader(){this.announcer=document.createElement("div"),this.announcer.setAttribute("aria-live","polite"),this.announcer.setAttribute("aria-atomic","true"),this.announcer.className="sr-only",this.announcer.style.cssText="\n      position: absolute !important;\n      width: 1px !important;\n      height: 1px !important;\n      padding: 0 !important;\n      margin: -1px !important;\n      overflow: hidden !important;\n      clip: rect(0, 0, 0, 0) !important;\n      white-space: nowrap !important;\n      border: 0 !important;\n    ",document.body.appendChild(this.announcer),this.assertiveAnnouncer=document.createElement("div"),this.assertiveAnnouncer.setAttribute("aria-live","assertive"),this.assertiveAnnouncer.setAttribute("aria-atomic","true"),this.assertiveAnnouncer.className="sr-only",this.assertiveAnnouncer.style.cssText=this.announcer.style.cssText,document.body.appendChild(this.assertiveAnnouncer)},setupARIAAttributes(){const e=this.table.container.querySelector(".table"),t=this.table.container.querySelector(".excelike-table-wrapper");t&&(t.setAttribute("role","region"),t.setAttribute("aria-label",this.t("table.label","Data table")),t.setAttribute("tabindex","0")),e&&(e.setAttribute("role","table"),e.setAttribute("aria-rowcount",this.table.state.filteredData.length+1),e.setAttribute("aria-colcount",this.table.options.columns.length)),this.updateHeaderARIA(),this.updateRowsARIA(),this.updatePaginationARIA()},updateHeaderARIA(){const e=this.table.container.querySelector(".table-header tr");if(e){e.setAttribute("role","row"),e.setAttribute("aria-rowindex","1");e.querySelectorAll("th").forEach(((e,t)=>{e.setAttribute("role","columnheader"),e.setAttribute("aria-colindex",t+1),e.setAttribute("tabindex","0");const n=this.table.options.columns[t];if(n&&n.sortable){const t=this.getSortState(n.key);e.setAttribute("aria-sort",t),e.setAttribute("aria-label",this.t("column.sortable",`${n.title}, sortable column, currently ${t}`))}else e.setAttribute("aria-label",n.title);if(n&&n.filterable){if(this.table.state.filters[n.dataIndex]){const t=e.getAttribute("aria-label")||"";e.setAttribute("aria-label",t+", "+this.t("column.filtered","filtered"))}}}))}},updateRowsARIA(){this.table.container.querySelectorAll(".table-body tr").forEach(((e,t)=>{e.setAttribute("role","row"),e.setAttribute("aria-rowindex",t+2),e.setAttribute("tabindex","-1");e.querySelectorAll("td").forEach(((e,t)=>{e.setAttribute("role","gridcell"),e.setAttribute("aria-colindex",t+1),e.setAttribute("tabindex","-1")}))}))},updatePaginationARIA(){const e=this.table.container.querySelector(".table-pagination");if(e){e.setAttribute("role","navigation"),e.setAttribute("aria-label",this.t("pagination.label","Table pagination"));e.querySelectorAll(".pagination-page").forEach((e=>{const t=e.dataset.page,n=e.classList.contains("active");e.setAttribute("aria-label",n?this.t("pagination.currentPage",`Page ${t}, current page`):this.t("pagination.goToPage",`Go to page ${t}`))}));const t=e.querySelector(".pagination-prev"),n=e.querySelector(".pagination-next");t&&t.setAttribute("aria-label",this.t("pagination.previous","Previous page")),n&&n.setAttribute("aria-label",this.t("pagination.next","Next page"))}},setupKeyboardNavigation(){const e=this.table.container.querySelector(".excelike-table-wrapper");e&&(e.addEventListener("keydown",(e=>{this.handleKeyDown(e)})),e.addEventListener("focusin",(e=>{this.handleFocusIn(e)})),e.addEventListener("focusout",(e=>{this.handleFocusOut(e)})))},handleKeyDown(e){const{key:t,ctrlKey:n,shiftKey:a,altKey:r}=e,i=document.activeElement;if(this.table.container.contains(i))switch(t){case"ArrowUp":e.preventDefault(),this.navigateVertical(-1,i);break;case"ArrowDown":e.preventDefault(),this.navigateVertical(1,i);break;case"ArrowLeft":e.preventDefault(),this.navigateHorizontal(-1,i);break;case"ArrowRight":e.preventDefault(),this.navigateHorizontal(1,i);break;case"Home":e.preventDefault(),n?this.navigateToFirst():this.navigateToRowStart();break;case"End":e.preventDefault(),n?this.navigateToLast():this.navigateToRowEnd();break;case"PageUp":e.preventDefault(),this.navigatePage(-1);break;case"PageDown":e.preventDefault(),this.navigatePage(1);break;case"Enter":case" ":e.preventDefault(),this.activateElement(i);break;case"Escape":e.preventDefault(),this.closeActiveElements();break;case"Tab":this.handleTabNavigation(e)}},navigateVertical(e,t){const n=this.getElementPosition(t);if(!n)return;let a=n.row+e;if("header"===n.type&&e>0){a=0;const e=this.getCellAt(a,n.column);e&&(e.focus(),this.announceNavigation(a,n.column))}else if("cell"===n.type){if(e<0&&a<0){const e=this.getHeaderCellAt(n.column);return void(e&&(e.focus(),this.announceNavigation("header",n.column)))}if(a>this.table.state.filteredData.length-1)return;const t=this.getCellAt(a,n.column);t&&(t.focus(),this.announceNavigation(a,n.column))}},navigateHorizontal(e,t){const n=this.getElementPosition(t);if(!n)return;const a=n.column+e,r=this.table.options.columns.length-1;if(a<0||a>r)return;let i;i="header"===n.type?this.getHeaderCellAt(a):this.getCellAt(n.row,a),i&&(i.focus(),this.announceNavigation(n.row,a))},getElementPosition(e){if("TH"===e.tagName){const t=e.parentElement;return{type:"header",row:"header",column:Array.from(t.children).indexOf(e)}}if("TD"===e.tagName){const t=e.parentElement,n=Array.from(this.table.container.querySelectorAll(".table-body tr")),a=Array.from(t.children);return{type:"cell",row:n.indexOf(t),column:a.indexOf(e)}}return null},getCellAt(e,t){const n=this.table.container.querySelectorAll(".table-body tr");if(e<0||e>=n.length)return null;const a=n[e].querySelectorAll("td");return t<0||t>=a.length?null:a[t]},getHeaderCellAt(e){const t=this.table.container.querySelectorAll(".table-header th");return e<0||e>=t.length?null:t[e]},setupFocusManagement(){const e=document.createElement("style");e.textContent="\n      .excelike-table-wrapper:focus {\n        outline: 2px solid #1890ff;\n        outline-offset: -2px;\n      }\n      \n      .excelike-table th:focus,\n      .excelike-table td:focus {\n        outline: 2px solid #1890ff;\n        outline-offset: -2px;\n        background-color: #e6f7ff;\n        position: relative;\n        z-index: 1;\n      }\n      \n      .excelike-table .focus-trap {\n        position: relative;\n      }\n      \n      @media (prefers-reduced-motion: reduce) {\n        .excelike-table * {\n          transition: none !important;\n          animation: none !important;\n        }\n      }\n      \n      @media (prefers-high-contrast: high) {\n        .excelike-table {\n          border: 2px solid;\n        }\n        \n        .excelike-table th,\n        .excelike-table td {\n          border: 1px solid;\n        }\n      }\n    ",document.head.appendChild(e)},setupAnnouncements(){this.table.on&&(this.table.on("sort",(e=>{this.announce(this.t("sort.announced",`Table sorted by ${e.column} ${e.direction}`))})),this.table.on("filter",(e=>{this.announce(this.t("filter.announced",`Table filtered, ${this.table.state.filteredData.length} rows visible`))})),this.table.on("pageChange",(e=>{this.announce(this.t("pagination.announced",`Page ${e.page} of ${Math.ceil(this.table.state.filteredData.length/e.pageSize)}`))})))},setupHighContrast(){const e=this.table.container.querySelector(".excelike-table-wrapper");e&&e.classList.add("high-contrast-mode")},announce(e,t=!1){const n=t?this.assertiveAnnouncer:this.announcer;n&&(n.textContent=e,setTimeout((()=>{n.textContent=""}),1e3))},announceNavigation(e,t){const n=this.table.options.columns[t]?.title||`Column ${t+1}`;let a;if("header"===e)a=this.t("nav.header",`${n} column header`);else{const r=this.table.state.filteredData[e],i=r?r[this.table.options.columns[t].dataIndex]:"";a=this.t("nav.cell",`Row ${e+1}, ${n}, ${i}`)}this.announce(a,!0)},getSortState(e){const t=this.table.state.sortState;return t.column===e?"asc"===t.direction?"ascending":"descending":"none"},t:(e,t)=>t,navigateToFirst(){const e=this.getHeaderCellAt(0);e&&e.focus()},navigateToLast(){const e=this.table.state.filteredData.length-1,t=this.table.options.columns.length-1,n=this.getCellAt(e,t);n&&n.focus()},navigateToRowStart(){const e=document.activeElement,t=this.getElementPosition(e);if(t){let e;e="header"===t.type?this.getHeaderCellAt(0):this.getCellAt(t.row,0),e&&e.focus()}},navigateToRowEnd(){const e=document.activeElement,t=this.getElementPosition(e);if(t){const e=this.table.options.columns.length-1;let n;n="header"===t.type?this.getHeaderCellAt(e):this.getCellAt(t.row,e),n&&n.focus()}},navigatePage(e){const t=this.table.state.currentPage,n=this.table.state.pageSize,a=Math.ceil(this.table.state.filteredData.length/n);let r=t+e;r=Math.max(1,Math.min(r,a)),r!==t&&this.table.setPage&&this.table.setPage(r)},activateElement(e){("TH"===e.tagName&&null!==e.getAttribute("aria-sort")||"BUTTON"===e.tagName||"TD"===e.tagName)&&e.click()},closeActiveElements(){this.table.container.querySelectorAll('[aria-expanded="true"]').forEach((e=>{e.setAttribute("aria-expanded","false")})),this.table.closeFilter&&this.table.closeFilter()},handleTabNavigation(e){},handleFocusIn(e){const t=e.target;if("TH"===t.tagName||"TD"===t.tagName){const e=this.getElementPosition(t);e&&(this.currentFocus=e)}},handleFocusOut(e){},update(){this.updateHeaderARIA(),this.updateRowsARIA(),this.updatePaginationARIA()},destroy(){this.announcer&&this.announcer.parentNode&&this.announcer.parentNode.removeChild(this.announcer),this.assertiveAnnouncer&&this.assertiveAnnouncer.parentNode&&this.assertiveAnnouncer.parentNode.removeChild(this.assertiveAnnouncer)}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.AccessibilityModule=a);const r={init(e={}){return this.currentLocale=e.locale||"en",this.fallbackLocale=e.fallbackLocale||"en",this.messages=new Map,this.dateFormats=new Map,this.numberFormats=new Map,this.pluralRules=new Map,this.loadDefaultMessages(),e.messages&&this.addMessages(this.currentLocale,e.messages),this.setupFormatters(),this},loadDefaultMessages(){this.addMessages("en",{"table.label":"Data table","table.loading":"Loading...","table.empty":"No data","table.error":"Error loading data","column.sortable":"{title}, sortable column, currently {sort}","column.filtered":"filtered","column.settings":"Column Settings","column.show":"Show","column.hide":"Hide","column.pin_left":"Pin to left","column.pin_right":"Pin to right","column.unpin":"Unpin","column.resize":"Resize column","sort.ascending":"ascending","sort.descending":"descending","sort.none":"not sorted","sort.announced":"Table sorted by {column} {direction}","filter.label":"Filter","filter.placeholder":"Search...","filter.apply":"Apply","filter.clear":"Clear","filter.all":"(Select All)","filter.announced":"Table filtered, {count} rows visible","filter.min":"Min","filter.max":"Max","filter.from":"From","filter.to":"To","filter.clearColumn":"Clear this column filter","filter.cancel":"Cancel","filter.ok":"OK","filter.filterByRange":"Filter by Range","filter.selectValues":"Select Values","filter.empty":"(Blank)","filter.includeBlank":"Include Blank","filter.rangeDescription":"{min} to {max}","filter.startDate":"Start Date","filter.endDate":"End Date","filter.expandLabel":"Expand:","filter.year":"Year","filter.month":"Month","filter.day":"Day","filter.dayUnit":"day","filter.monthNames":["January","February","March","April","May","June","July","August","September","October","November","December"],"pagination.label":"Table pagination","pagination.previous":"Previous page","pagination.next":"Next page","pagination.first":"First page","pagination.last":"Last page","pagination.page":"Page {page}","pagination.currentPage":"Page {page}, current page","pagination.goToPage":"Go to page {page}","pagination.announced":"Page {page} of {total}","pagination.itemsPerPage":"items per page","pagination.total":"{start}-{end} of {total} items","action.edit":"Edit","action.delete":"Delete","action.view":"View","action.copy":"Copy","menu.clearFilters":"Clear All Filters","menu.columnSettings":"Column Settings","menu.conditionalFormat":"Conditional Formatting","menu.fontSize":"Font Size","menu.cellPadding":"Cell Padding","menu.language":"Language","menu.clearStorage":"Clear LocalStorage","fontSize.smallest":"Smallest","fontSize.small":"Small","fontSize.medium":"Medium","fontSize.large":"Large","fontSize.largest":"Largest","cellPadding.wide":"Wide","cellPadding.standard":"Standard","cellPadding.narrow":"Narrow","settings.fontSize":"Font Size","settings.cellPadding":"Cell Padding","settings.theme":"Theme","settings.save":"Save Settings","settings.reset":"Reset Settings","settings.export":"Export Settings","settings.import":"Import Settings","settings.columnSettings":"Column Settings","settings.clearStorageTitle":"Clear LocalStorage Confirmation","settings.clearStorageMessage":"This will delete all ExceLikeTable LocalStorage data and reset settings to default. Continue?","settings.clearStorageCancel":"Cancel","settings.clearStorageConfirm":"Delete","settings.clearScopeThis":"Clear this table only","settings.clearScopeAll":"Clear all tables","settings.cleared":"Settings cleared. Page will reload automatically.","settings.clearError":"Error occurred while clearing settings","settings.pluginNotLoaded":"Conditional formatting plugin is not loaded.\nPlease load the plugin file.","settings.clearThisTable":"Clear This Table Settings","settings.clearAllTables":"Clear All Tables Settings","settings.clearThisTableMessage":"⚠️ Warning: This will delete all settings for this table\n\nThe following settings will be lost:\n• Column widths and pinning\n• Filter and sort states\n• Conditional formatting rules\n• Font size and cell padding\n• Language preference\n\nThis action cannot be undone. Continue?","settings.clearAllTablesMessage":"⚠️ WARNING: This will delete settings for ALL tables\n\nThe following settings will be lost from ALL tables:\n• Column widths and pinning\n• Filter and sort states\n• Conditional formatting rules\n• Font size and cell padding\n• Language preferences\n\nThis action cannot be undone and affects all tables in this application. Continue?","settings.clearSuccess":"Settings cleared successfully","settings.clearCancelled":"Operation cancelled","export.csv":"Export to CSV","export.excel":"Export to Excel","export.json":"Export to JSON","export.filename":"Filename","export.includeHeaders":"Include headers","export.selectedOnly":"Selected rows only","nav.header":"{column} column header","nav.cell":"Row {row}, {column}, {value}","error.network":"Network error","error.parsing":"Data parsing error","error.permission":"Permission denied","a11y.sortableColumn":"Sortable column","a11y.filterableColumn":"Filterable column","a11y.rowSelected":"Row selected","a11y.menuExpanded":"Menu expanded","a11y.menuCollapsed":"Menu collapsed","time.now":"now","time.secondsAgo":"{count} seconds ago","time.minutesAgo":"{count} minutes ago","time.hoursAgo":"{count} hours ago","time.daysAgo":"{count} days ago","cf.title":"Conditional Formatting Rules","cf.newRule":"New Rule","cf.editRule":"Edit Rule","cf.createRule":"Create New Rule","cf.rulesCount":"Rules: {count}","cf.close":"Close","cf.applyAll":"Apply All","cf.cancel":"Cancel","cf.save":"Save","cf.update":"Update","cf.create":"Create","cf.ruleName":"Rule Name","cf.ruleNamePlaceholder":"Enter rule name","cf.column":"Column","cf.selectColumn":"Select column...","cf.operator":"Operator","cf.value":"Value","cf.valuePlaceholder":"Enter comparison value","cf.dataType":"Data Type","cf.applyTo":"Apply To","cf.op.equals":"Equals (=)","cf.op.notEquals":"Not equals (≠)","cf.op.greater":"Greater than (>)","cf.op.greaterEqual":"Greater than or equal (≥)","cf.op.less":"Less than (<)","cf.op.lessEqual":"Less than or equal (≤)","cf.op.contains":"Contains","cf.op.notContains":"Does not contain","cf.dataType.text":"Text","cf.dataType.number":"Number","cf.dataType.date":"Date","cf.applyTo.cell":"Cell only","cf.applyTo.row":"Entire row","cf.format":"Format","cf.backgroundColor":"Background Color","cf.textColor":"Text Color","cf.textStyle":"Text Style","cf.bold":"Bold","cf.italic":"Italic","cf.underline":"Underline","cf.preview":"Preview","cf.previewSample":"Sample Cell","cf.noRules":"No conditional formatting rules yet.","cf.clickNewRule":'Click "New Rule" to get started.',"cf.ruleCreated":"Rule created successfully","cf.ruleUpdated":"Rule updated successfully","cf.ruleDeleted":"Rule deleted successfully","cf.rulesApplied":"Conditional formatting applied","cf.priorityUpdated":"Priority updated","cf.confirmDelete":'Are you sure you want to delete the rule "{name}"?',"cf.errorSave":"Error saving rule","cf.priority":"Priority: {priority}","cf.sample":"Sample"}),this.addMessages("ja",{"table.label":"データテーブル","table.loading":"読み込み中...","table.empty":"データがありません","table.error":"データの読み込みエラー","column.sortable":"{title}、ソート可能な列、現在{sort}","column.filtered":"フィルター済み","column.settings":"列設定","column.show":"表示","column.hide":"非表示","column.pin_left":"左に固定","column.pin_right":"右に固定","column.unpin":"固定解除","column.resize":"列幅変更","sort.ascending":"昇順","sort.descending":"降順","sort.none":"ソートなし","sort.announced":"テーブルを{column}で{direction}ソートしました","filter.label":"フィルター","filter.placeholder":"検索...","filter.apply":"適用","filter.clear":"クリア","filter.all":"(すべて選択)","filter.announced":"テーブルをフィルターしました、{count}行が表示されています","filter.min":"最小","filter.max":"最大","filter.from":"開始","filter.to":"終了","filter.clearColumn":"この列のフィルタをクリア","filter.cancel":"キャンセル","filter.ok":"OK","filter.filterByRange":"範囲で絞り込む","filter.selectValues":"値を選択","filter.empty":"(空白)","filter.includeBlank":"空白を含む","filter.rangeDescription":"{min} 以上 {max} 以下の値を表示","filter.startDate":"開始日","filter.endDate":"終了日","filter.expandLabel":"展開表示:","filter.year":"年","filter.month":"月","filter.day":"日","filter.dayUnit":"日","filter.monthNames":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"pagination.label":"テーブルページネーション","pagination.previous":"前のページ","pagination.next":"次のページ","pagination.first":"最初のページ","pagination.last":"最後のページ","pagination.page":"ページ{page}","pagination.currentPage":"ページ{page}、現在のページ","pagination.goToPage":"ページ{page}に移動","pagination.announced":"{total}ページ中{page}ページ","pagination.itemsPerPage":"件/ページ","pagination.total":"{total}件中{start}-{end}件","menu.clearFilters":"フィルタ全解除","menu.columnSettings":"表示列設定","menu.conditionalFormat":"条件付き書式","menu.fontSize":"文字サイズ","menu.cellPadding":"セル内パディング","menu.language":"言語","menu.clearStorage":"LocalStorageクリア","fontSize.smallest":"最小","fontSize.small":"小","fontSize.medium":"中","fontSize.large":"大","fontSize.largest":"最大","cellPadding.wide":"広め","cellPadding.standard":"標準","cellPadding.narrow":"狭め","action.edit":"編集","action.delete":"削除","action.view":"表示","action.copy":"コピー","settings.fontSize":"文字サイズ","settings.cellPadding":"セル間隔","settings.theme":"テーマ","settings.save":"設定を保存","settings.reset":"設定をリセット","settings.export":"設定をエクスポート","settings.import":"設定をインポート","settings.columnSettings":"列設定","settings.clearStorageTitle":"LocalStorage クリア確認","settings.clearStorageMessage":"ExceLikeTable関連のLocalStorage情報を削除し、設定をデフォルトに戻します。よろしいですか？","settings.clearStorageCancel":"キャンセル","settings.clearStorageConfirm":"削除する","settings.clearScopeThis":"このテーブルのみクリア","settings.clearScopeAll":"全てのテーブルをクリア","settings.cleared":"設定をクリアしました。ページが自動で再読み込みされます。","settings.clearError":"設定クリア中にエラーが発生しました","settings.pluginNotLoaded":"条件付き書式プラグインが読み込まれていません。\nプラグインファイルを読み込んでください。","settings.clearThisTable":"このテーブルの設定をクリア","settings.clearAllTables":"全テーブルの設定をクリア","settings.clearThisTableMessage":"⚠️ 警告: このテーブルの全設定を削除します\n\n以下の設定が失われます：\n• 列幅とピン留め\n• フィルタ・ソート状態\n• 条件付き書式ルール\n• 文字サイズとセルパディング\n• 言語設定\n\nこの操作は取り消せません。続行しますか？","settings.clearAllTablesMessage":"⚠️ 警告: 全テーブルの設定を削除します\n\n以下の設定が全テーブルから失われます：\n• 列幅とピン留め\n• フィルタ・ソート状態\n• 条件付き書式ルール\n• 文字サイズとセルパディング\n• 言語設定\n\nこの操作は取り消せず、このアプリケーション内の全テーブルに影響します。続行しますか？","settings.clearSuccess":"設定をクリアしました","settings.clearCancelled":"操作をキャンセルしました","export.csv":"CSVにエクスポート","export.excel":"Excelにエクスポート","export.json":"JSONにエクスポート","export.filename":"ファイル名","export.includeHeaders":"ヘッダーを含む","export.selectedOnly":"選択された行のみ","nav.header":"{column}列ヘッダー","nav.cell":"行{row}、{column}、{value}","error.network":"ネットワークエラー","error.parsing":"データ解析エラー","error.permission":"権限がありません","time.now":"たった今","time.secondsAgo":"{count}秒前","time.minutesAgo":"{count}分前","time.hoursAgo":"{count}時間前","time.daysAgo":"{count}日前","cf.title":"条件付き書式ルール","cf.newRule":"新規ルール","cf.editRule":"ルール編集","cf.createRule":"新規ルール作成","cf.rulesCount":"ルール数: {count}","cf.close":"閉じる","cf.applyAll":"すべて適用","cf.cancel":"キャンセル","cf.save":"保存","cf.update":"更新","cf.create":"作成","cf.ruleName":"ルール名","cf.ruleNamePlaceholder":"ルール名を入力","cf.column":"列","cf.selectColumn":"列を選択...","cf.operator":"演算子","cf.value":"値","cf.valuePlaceholder":"比較値を入力","cf.dataType":"データ型","cf.applyTo":"適用先","cf.op.equals":"等しい (=)","cf.op.notEquals":"等しくない (≠)","cf.op.greater":"より大きい (>)","cf.op.greaterEqual":"以上 (≥)","cf.op.less":"より小さい (<)","cf.op.lessEqual":"以下 (≤)","cf.op.contains":"含む","cf.op.notContains":"含まない","cf.dataType.text":"テキスト","cf.dataType.number":"数値","cf.dataType.date":"日付","cf.applyTo.cell":"セルのみ","cf.applyTo.row":"行全体","cf.format":"書式","cf.backgroundColor":"背景色","cf.textColor":"文字色","cf.textStyle":"文字スタイル","cf.bold":"太字","cf.italic":"斜体","cf.underline":"下線","cf.preview":"プレビュー","cf.previewSample":"サンプルセル","cf.noRules":"まだ条件付き書式ルールがありません。","cf.clickNewRule":"「新規ルール」をクリックして開始してください。","cf.ruleCreated":"ルールを作成しました","cf.ruleUpdated":"ルールを更新しました","cf.ruleDeleted":"ルールを削除しました","cf.rulesApplied":"条件付き書式を適用しました","cf.priorityUpdated":"優先度を更新しました","cf.confirmDelete":"ルール「{name}」を削除してよろしいですか？","cf.errorSave":"ルールの保存中にエラーが発生しました","cf.priority":"優先度: {priority}","cf.sample":"サンプル"})},addMessages(e,t){this.messages.has(e)||this.messages.set(e,new Map);const n=this.messages.get(e);Object.entries(t).forEach((([e,t])=>{n.set(e,t)}))},setLocale(e){return!!this.messages.has(e)&&(this.currentLocale=e,this.setupFormatters(),!0)},getLocale(){return this.currentLocale},t(e,t={},n=null){const a=n||this.currentLocale;let r=this.getMessage(e,a);return r||a===this.fallbackLocale||(r=this.getMessage(e,this.fallbackLocale)),r?this.interpolate(r,t):(console.warn(`Missing translation for key: ${e}`),e)},getMessage(e,t){const n=this.messages.get(t);return n?n.get(e):null},interpolate:(e,t)=>e.replace(/\{(\w+)\}/g,((e,n)=>t.hasOwnProperty(n)?t[n]:e)),plural(e,t,n={}){const a=`${e}.${this.getPluralKey(t,this.currentLocale)}`;return this.t(a,{count:t,...n})},getPluralKey:(e,t)=>"ja"===t||"ko"===t||"zh"===t?"other":1===e?"one":"other",setupFormatters(){this.dateFormatter=new Intl.DateTimeFormat(this.currentLocale,{year:"numeric",month:"2-digit",day:"2-digit"}),this.dateTimeFormatter=new Intl.DateTimeFormat(this.currentLocale,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),this.numberFormatter=new Intl.NumberFormat(this.currentLocale),this.currencyFormatter=new Intl.NumberFormat(this.currentLocale,{style:"currency",currency:this.getCurrencyForLocale(this.currentLocale)}),this.percentFormatter=new Intl.NumberFormat(this.currentLocale,{style:"percent",minimumFractionDigits:0,maximumFractionDigits:2})},getCurrencyForLocale(e){const t={en:"USD","en-US":"USD","en-GB":"GBP",ja:"JPY","ja-JP":"JPY",zh:"CNY","zh-CN":"CNY",ko:"KRW","ko-KR":"KRW"};return t[e]||t[e.split("-")[0]]||"USD"},formatDate(e,t={}){const n=new Date(e);if(isNaN(n.getTime()))return"";if(t.relative)return this.formatRelativeTime(n);return(t.includeTime?this.dateTimeFormatter:this.dateFormatter).format(n)},formatRelativeTime(e){const t=(new Date).getTime()-e.getTime(),n=Math.floor(t/1e3),a=Math.floor(n/60),r=Math.floor(a/60),i=Math.floor(r/24);return n<60?this.t("time.now"):a<60?this.t("time.minutesAgo",{count:a}):r<24?this.t("time.hoursAgo",{count:r}):this.t("time.daysAgo",{count:i})},formatNumber(e,t={}){if("number"!=typeof e||isNaN(e))return"";if("currency"===t.style){return new Intl.NumberFormat(this.currentLocale,{style:"currency",currency:t.currency||this.getCurrencyForLocale(this.currentLocale)}).format(e)}return"percent"===t.style?this.percentFormatter.format(e):this.numberFormatter.format(e)},isRTL(e=null){const t=e||this.currentLocale;return["ar","he","fa","ur"].some((e=>t.startsWith(e)))},getAvailableLocales(){return Array.from(this.messages.keys())},async loadLocale(e,t){try{const n=await fetch(t),a=await n.json();return this.addMessages(e,a),!0}catch(t){return console.error(`Failed to load locale ${e}:`,t),!1}},exportLocale(e=null){const t=e||this.currentLocale,n=this.messages.get(t);if(!n)return{};const a={};return n.forEach(((e,t)=>{a[t]=e})),a}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.I18nModule=r);const i={init(e={}){return this.themes=new Map,this.currentTheme=e.defaultTheme||"default",this.customProperties=new Map,this.loadBuiltInThemes(),e.themes&&Object.entries(e.themes).forEach((([e,t])=>{this.addTheme(e,t)})),this.applyTheme(this.currentTheme),this.watchSystemTheme(),this},loadBuiltInThemes(){this.addTheme("default",{name:"Default",colors:{primary:"#1890ff",primaryHover:"#40a9ff",primaryActive:"#096dd9",primaryDisabled:"#b3d9ff",background:"#ffffff",backgroundSecondary:"#fafafa",backgroundHover:"#f5f5f5",backgroundSelected:"#e6f7ff",backgroundDisabled:"#f5f5f5",text:"#000000d9",textSecondary:"#00000073",textDisabled:"#00000040",textInverse:"#ffffff",border:"#d9d9d9",borderLight:"#f0f0f0",borderHover:"#40a9ff",success:"#52c41a",warning:"#faad14",error:"#ff4d4f",info:"#1890ff",shadow:"rgba(0, 0, 0, 0.15)",overlay:"rgba(0, 0, 0, 0.45)"},typography:{fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif",fontSize:{smallest:"10px",small:"12px",medium:"14px",large:"16px",largest:"18px"},fontWeight:{normal:"400",medium:"500",bold:"600"},lineHeight:{small:"1.2",medium:"1.5",large:"1.8"}},spacing:{xs:"4px",sm:"8px",md:"12px",lg:"16px",xl:"24px",xxl:"32px"},borderRadius:{small:"2px",medium:"4px",large:"6px"},shadows:{small:"0 2px 4px rgba(0, 0, 0, 0.1)",medium:"0 4px 8px rgba(0, 0, 0, 0.12)",large:"0 8px 24px rgba(0, 0, 0, 0.15)"},transitions:{fast:"0.15s",medium:"0.3s",slow:"0.45s"}}),this.addTheme("dark",{name:"Dark",colors:{primary:"#1890ff",primaryHover:"#40a9ff",primaryActive:"#096dd9",primaryDisabled:"#0050b3",background:"#141414",backgroundSecondary:"#1f1f1f",backgroundHover:"#262626",backgroundSelected:"#111b26",backgroundDisabled:"#262626",text:"#ffffffd9",textSecondary:"#ffffff73",textDisabled:"#ffffff40",textInverse:"#000000",border:"#434343",borderLight:"#303030",borderHover:"#40a9ff",success:"#52c41a",warning:"#faad14",error:"#ff4d4f",info:"#1890ff",shadow:"rgba(0, 0, 0, 0.45)",overlay:"rgba(0, 0, 0, 0.65)"},extends:"default"}),this.addTheme("compact",{name:"Compact",spacing:{xs:"2px",sm:"4px",md:"6px",lg:"8px",xl:"12px",xxl:"16px"},typography:{fontSize:{smallest:"10px",small:"11px",medium:"12px",large:"14px",largest:"16px"}},extends:"default"}),this.addTheme("high-contrast",{name:"High Contrast",colors:{primary:"#0000ff",primaryHover:"#0000cc",primaryActive:"#000099",background:"#ffffff",backgroundSecondary:"#f0f0f0",backgroundHover:"#e0e0e0",backgroundSelected:"#ffffcc",text:"#000000",textSecondary:"#000000",textDisabled:"#666666",textInverse:"#ffffff",border:"#000000",borderLight:"#666666",borderHover:"#0000ff",success:"#008000",warning:"#ff8000",error:"#ff0000",info:"#0000ff"},extends:"default"}),this.addTheme("material",{name:"Material",colors:{primary:"#2196f3",primaryHover:"#42a5f5",primaryActive:"#1976d2",background:"#ffffff",backgroundSecondary:"#fafafa",backgroundHover:"#f5f5f5",backgroundSelected:"#e3f2fd",border:"#e0e0e0",borderLight:"#f0f0f0"},borderRadius:{small:"4px",medium:"8px",large:"12px"},shadows:{small:"0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)",medium:"0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)",large:"0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23)"},extends:"default"}),this.addTheme("bootstrap",{name:"Bootstrap",colors:{primary:"#0d6efd",primaryHover:"#0b5ed7",primaryActive:"#0a58ca",success:"#198754",warning:"#ffc107",error:"#dc3545",info:"#0dcaf0"},typography:{fontFamily:"'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"},extends:"default"})},addTheme(e,t){if(t.extends){const e=this.themes.get(t.extends);e&&(t=this.mergeThemes(e,t))}this.themes.set(e,t)},mergeThemes(e,t){const n=JSON.parse(JSON.stringify(e)),a=(e,t)=>{Object.keys(t).forEach((n=>{"extends"!==n&&(t[n]&&"object"==typeof t[n]&&!Array.isArray(t[n])?(e[n]||(e[n]={}),a(e[n],t[n])):e[n]=t[n])}))};return a(n,t),n},applyTheme(e){let t;"string"==typeof e?(t=this.themes.get(e),t||(console.warn(`Theme "${e}" not found, using default`),t=this.themes.get("default")),this.currentTheme=e):(t=e,this.currentTheme=t.name||"custom"),t&&(this.applyCSSProperties(t),this.applyThemeClass(this.currentTheme),document.dispatchEvent(new CustomEvent("themeChanged",{detail:{theme:this.currentTheme,themeData:t}})))},applyCSSProperties(e){const t=document.documentElement;this.customProperties.forEach(((e,n)=>{t.style.removeProperty(n)})),this.customProperties.clear(),this.applyThemeSection(t,"color",e.colors),this.applyThemeSection(t,"font",e.typography),this.applyThemeSection(t,"spacing",e.spacing),this.applyThemeSection(t,"border-radius",e.borderRadius),this.applyThemeSection(t,"shadow",e.shadows),this.applyThemeSection(t,"transition",e.transitions)},applyThemeSection(e,t,n){if(!n)return;const a=(n,r="")=>{Object.entries(n).forEach((([n,i])=>{if("object"==typeof i&&null!==i)a(i,`${r}${n}-`);else{const a=`--table-${t}-${r}${n}`;e.style.setProperty(a,i),this.customProperties.set(a,i)}}))};a(n)},applyThemeClass(e){document.body.classList.remove(...Array.from(document.body.classList).filter((e=>e.startsWith("table-theme-")))),document.body.classList.add(`table-theme-${e}`)},getCurrentTheme(){return this.currentTheme},getTheme(e){return this.themes.get(e)||null},getAvailableThemes(){return Array.from(this.themes.keys())},getThemeList(){return Array.from(this.themes.entries()).map((([e,t])=>({key:e,name:t.name||e,description:t.description,category:t.category||"custom"})))},watchSystemTheme(){if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)"),t=window.matchMedia("(prefers-contrast: high)"),n=()=>{if("auto"===this.currentTheme){let n="default";t.matches?n="high-contrast":e.matches&&(n="dark"),this.applyTheme(n)}};e.addListener(n),t.addListener(n)}},createThemePicker(e){const t=document.createElement("div");t.className="theme-picker",t.innerHTML=`\n      <label for="theme-select">Theme:</label>\n      <select id="theme-select" class="theme-select">\n        ${this.getThemeList().map((e=>`<option value="${e.key}" ${e.key===this.currentTheme?"selected":""}>\n            ${e.name}\n          </option>`)).join("")}\n      </select>\n    `;return t.querySelector("#theme-select").addEventListener("change",(e=>{this.applyTheme(e.target.value)})),e&&e.appendChild(t),t},exportTheme(e){const t=this.themes.get(e);return t?JSON.parse(JSON.stringify(t)):null},importTheme(e,t){this.addTheme(e,t)},generateCSS(e){const t=this.themes.get(e);if(!t)return"";let n=":root {\n";const a=(e,t)=>{Object.entries(e).forEach((([e,r])=>{"object"==typeof r&&null!==r?a(r,`${t}-${e}`):n+=`  --table${t}-${e}: ${r};\n`}))};return t.colors&&a(t.colors,"-color"),t.typography&&a(t.typography,"-font"),t.spacing&&a(t.spacing,"-spacing"),t.borderRadius&&a(t.borderRadius,"-border-radius"),t.shadows&&a(t.shadows,"-shadow"),t.transitions&&a(t.transitions,"-transition"),n+="}\n",n},reset(){this.applyTheme("default")},destroy(){this.customProperties.forEach(((e,t)=>{document.documentElement.style.removeProperty(t)})),document.body.classList.remove(...Array.from(document.body.classList).filter((e=>e.startsWith("table-theme-")))),this.customProperties.clear(),this.themes.clear()}};class s{constructor(e){this.tableId=e,this.storageKey=`excelike-table-theme-${e}`,this.presets={classic:{name:"Classic",description:"Original clean design",headerBg:"#fafafa",cellBg:"#ffffff",hoverBg:"#f5f5f5",borderColor:"#d9d9d9",borderWidth:1,borderHorizontal:!0,borderVertical:!0,headerTextColor:"rgba(0, 0, 0, 0.85)",cellTextColor:"rgba(0, 0, 0, 0.85)"},modern:{name:"Modern",description:"Sleek minimal design",headerBg:"#ffffff",cellBg:"#ffffff",hoverBg:"#f0f7ff",borderColor:"#e8e8e8",borderWidth:1,borderHorizontal:!0,borderVertical:!1,headerTextColor:"rgba(0, 0, 0, 0.88)",cellTextColor:"rgba(0, 0, 0, 0.75)"},professional:{name:"Professional",description:"Bold and structured",headerBg:"#2c3e50",cellBg:"#ffffff",hoverBg:"#ecf0f1",borderColor:"#bdc3c7",borderWidth:1,borderHorizontal:!0,borderVertical:!0,headerTextColor:"#ffffff",cellTextColor:"rgba(0, 0, 0, 0.85)"},ocean:{name:"Ocean",description:"Cool blue tones",headerBg:"#1890ff",cellBg:"#ffffff",hoverBg:"#e6f7ff",borderColor:"#91d5ff",borderWidth:1,borderHorizontal:!0,borderVertical:!0,headerTextColor:"#ffffff",cellTextColor:"rgba(0, 0, 0, 0.85)"},dark:{name:"Dark",description:"Easy on the eyes",headerBg:"#1f1f1f",cellBg:"#2d2d2d",hoverBg:"#3a3a3a",borderColor:"#404040",borderWidth:1,borderHorizontal:!0,borderVertical:!0,headerTextColor:"#e0e0e0",cellTextColor:"#d0d0d0"},subtle:{name:"Subtle",description:"Soft and minimal",headerBg:"#e0f7fa",cellBg:"#ffffff",hoverBg:"#f1f3f5",borderColor:"#dee2e6",borderWidth:1,borderHorizontal:!0,borderVertical:!1,headerTextColor:"rgba(0, 0, 0, 0.75)",cellTextColor:"rgba(0, 0, 0, 0.70)"},vibrant:{name:"Vibrant",description:"Energetic and colorful",headerBg:"#ff6600",cellBg:"#fffef0",hoverBg:"#fff9e6",borderColor:"#ffd699",borderWidth:2,borderHorizontal:!0,borderVertical:!0,headerTextColor:"#ffffff",cellTextColor:"rgba(0, 0, 0, 0.85)"},nature:{name:"Nature",description:"Fresh green tones",headerBg:"#52c41a",cellBg:"#ffffff",hoverBg:"#f6ffed",borderColor:"#b7eb8f",borderWidth:1,borderHorizontal:!0,borderVertical:!0,headerTextColor:"#ffffff",cellTextColor:"rgba(0, 0, 0, 0.85)"}},this.currentTheme=this.loadTheme()||{preset:"classic",custom:null}}getActiveTheme(){return this.currentTheme.custom?this.currentTheme.custom:this.presets[this.currentTheme.preset]||this.presets.classic}applyPreset(e){return this.presets[e]?(this.currentTheme={preset:e,custom:null},this.saveTheme(),!0):(console.error(`Theme preset "${e}" not found`),!1)}applyCustomTheme(e){const t={...this.presets.classic,...e};return this.currentTheme={preset:"custom",custom:t},this.saveTheme(),t}getCSSVariables(){const e=this.getActiveTheme();return{"--theme-header-bg":e.headerBg,"--theme-cell-bg":e.cellBg,"--theme-hover-bg":e.hoverBg,"--theme-border-color":e.borderColor,"--theme-border-width":`${e.borderWidth}px`,"--theme-border-horizontal":e.borderHorizontal?`${e.borderWidth}px solid ${e.borderColor}`:"none","--theme-border-vertical":e.borderVertical?`${e.borderWidth}px solid ${e.borderColor}`:"none","--theme-header-text-color":e.headerTextColor,"--theme-cell-text-color":e.cellTextColor}}saveTheme(){try{return localStorage.setItem(this.storageKey,JSON.stringify(this.currentTheme)),!0}catch(e){return console.error("Failed to save theme to LocalStorage:",e),!1}}loadTheme(){try{const e=localStorage.getItem(this.storageKey);if(e)return JSON.parse(e)}catch(e){console.error("Failed to load theme from LocalStorage:",e)}return null}reset(){this.currentTheme={preset:"classic",custom:null},this.saveTheme()}getPresets(){return Object.keys(this.presets).map((e=>({id:e,...this.presets[e]})))}isCustomTheme(){return"custom"===this.currentTheme.preset}getCurrentPresetName(){return this.currentTheme.preset}}"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.ThemeSystem=i,window.ThemeManager=s);const o={init(e){return this.table=e,this},async exportData(e={}){const{format:t="csv",filename:n=null,includeHeaders:a=!0,selectedRowsOnly:r=!1,visibleColumnsOnly:i=!0,customHeaders:s=null,dateFormat:o="YYYY-MM-DD",encoding:l="utf-8"}=e,c=this.getExportData(r),d=this.getExportColumns(i);if(!c||0===c.length)throw new Error("No data to export");const u=n||this.generateFilename(t);switch(t.toLowerCase()){case"csv":return this.exportToCSV(c,d,{filename:u,includeHeaders:a,customHeaders:s,encoding:l});case"xlsx":case"excel":return this.exportToExcel(c,d,{filename:u,includeHeaders:a,customHeaders:s});case"json":return this.exportToJSON(c,d,{filename:u,includeHeaders:a,customHeaders:s});case"xml":return this.exportToXML(c,d,{filename:u,includeHeaders:a,customHeaders:s});case"html":return this.exportToHTML(c,d,{filename:u,includeHeaders:a,customHeaders:s});default:throw new Error(`Unsupported export format: ${t}`)}},getExportData(e=!1){return e&&this.table.getSelectedRows?this.table.getSelectedRows():this.table.getFilteredData?this.table.getFilteredData():this.table.state.filteredData},getExportColumns(e=!0){const t=this.table.options.columns;return e?t.filter((e=>this.table.state.visibleColumns?!1!==this.table.state.visibleColumns[e.key]:!1!==e.visible)):t},generateFilename(e){const t=(new Date).toISOString().slice(0,19).replace(/[:T]/g,"-");return`${this.table.options.tableId||"table"}-export-${t}.${e}`},async exportToCSV(e,t,n={}){const{filename:a="export.csv",includeHeaders:r=!0,customHeaders:i=null,delimiter:s=",",lineBreak:o="\r\n",encoding:l="utf-8",quote:c='"'}=n;let d="";if(r){const e=t.map((e=>{const t=i&&i[e.key]?i[e.key]:e.title;return this.escapeCSVField(t,s,c)}));d+=e.join(s)+o}return e.forEach((e=>{const n=t.map((t=>{let n=e[t.dataIndex];if(t.render&&"function"==typeof t.render){const a=t.render(n,e,t);"string"==typeof a&&(n=a.replace(/<[^>]*>/g,""))}return n=this.formatValueForCSV(n),this.escapeCSVField(n,s,c)}));d+=n.join(s)+o})),this.downloadFile(d,a,"text/csv",l)},async exportToExcel(e,t,n={}){const{filename:a="export.xlsx",includeHeaders:r=!0,customHeaders:i=null,sheetName:s="Sheet1"}=n;if("undefined"==typeof XLSX)return console.warn("SheetJS (XLSX) library not found, falling back to CSV export"),this.exportToCSV(e,t,{filename:a.replace(".xlsx",".csv"),includeHeaders:r,customHeaders:i});const o=[];if(r){const e=t.map((e=>i&&i[e.key]?i[e.key]:e.title));o.push(e)}e.forEach((e=>{const n=t.map((t=>{let n=e[t.dataIndex];if(t.render&&"function"==typeof t.render){const a=t.render(n,e,t);"string"==typeof a&&(n=a.replace(/<[^>]*>/g,""))}return this.formatValueForExcel(n)}));o.push(n)}));const l=XLSX.utils.book_new(),c=XLSX.utils.aoa_to_sheet(o),d=t.map((e=>({wch:Math.max(e.title.length,15)})));c["!cols"]=d,XLSX.utils.book_append_sheet(l,c,s);const u=XLSX.write(l,{bookType:"xlsx",type:"binary"}),h=new Blob([this.s2ab(u)],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});return this.downloadBlob(h,a)},async exportToJSON(e,t,n={}){const{filename:a="export.json",includeHeaders:r=!1,customHeaders:i=null,pretty:s=!0}=n,o=e.map((e=>{const n={};return t.forEach((t=>{const a=i&&i[t.key]?i[t.key]:t.dataIndex;let r=e[t.dataIndex];if(t.render&&"function"==typeof t.render){const i=t.render(r,e,t);if("string"==typeof i){const e=i.replace(/<[^>]*>/g,"");n[`${a}_display`]=e}}n[a]=r})),n})),l=s?JSON.stringify(o,null,2):JSON.stringify(o);return this.downloadFile(l,a,"application/json")},async exportToXML(e,t,n={}){const{filename:a="export.xml",rootElement:r="table",rowElement:i="row",includeHeaders:s=!1}=n;let o='<?xml version="1.0" encoding="UTF-8"?>\n';return o+=`<${r}>\n`,o+="  <metadata>\n",o+=`    <exportDate>${(new Date).toISOString()}</exportDate>\n`,o+=`    <rowCount>${e.length}</rowCount>\n`,o+=`    <columnCount>${t.length}</columnCount>\n`,o+="  </metadata>\n",s&&(o+="  <columns>\n",t.forEach((e=>{o+="    <column>\n",o+=`      <key>${this.escapeXML(e.key)}</key>\n`,o+=`      <title>${this.escapeXML(e.title)}</title>\n`,o+=`      <dataIndex>${this.escapeXML(e.dataIndex)}</dataIndex>\n`,o+="    </column>\n"})),o+="  </columns>\n"),o+="  <data>\n",e.forEach(((e,n)=>{o+=`    <${i} id="${n}">\n`,t.forEach((t=>{let n=e[t.dataIndex];if(t.render&&"function"==typeof t.render){const a=t.render(n,e,t);"string"==typeof a&&(n=a.replace(/<[^>]*>/g,""))}const a=this.escapeXML(this.formatValueForXML(n));o+=`      <${t.dataIndex}>${a}</${t.dataIndex}>\n`})),o+=`    </${i}>\n`})),o+="  </data>\n",o+=`</${r}>`,this.downloadFile(o,a,"application/xml")},async exportToHTML(e,t,n={}){const{filename:a="export.html",includeHeaders:r=!0,title:i="Exported Table Data",includeStyles:s=!0}=n;let o="<!DOCTYPE html>\n<html>\n<head>\n";return o+=`  <title>${this.escapeHTML(i)}</title>\n`,o+='  <meta charset="UTF-8">\n',s&&(o+="  <style>\n    body { font-family: Arial, sans-serif; margin: 20px; }\n    table { border-collapse: collapse; width: 100%; }\n    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }\n    th { background-color: #f2f2f2; font-weight: bold; }\n    tr:nth-child(even) { background-color: #f9f9f9; }\n    .export-info { margin-bottom: 20px; color: #666; }\n  </style>\n"),o+="</head>\n<body>\n",o+=`  <h1>${this.escapeHTML(i)}</h1>\n`,o+=`  <div class="export-info">\n    Exported on: ${(new Date).toLocaleString()}<br>\n    Total rows: ${e.length}<br>\n    Total columns: ${t.length}\n  </div>\n`,o+="  <table>\n",r&&(o+="    <thead>\n      <tr>\n",t.forEach((e=>{o+=`        <th>${this.escapeHTML(e.title)}</th>\n`})),o+="      </tr>\n    </thead>\n"),o+="    <tbody>\n",e.forEach((e=>{o+="      <tr>\n",t.forEach((t=>{let n=e[t.dataIndex];t.render&&"function"==typeof t.render&&(n=t.render(n,e,t)),o+=`        <td>${this.escapeHTML(this.formatValueForHTML(n))}</td>\n`})),o+="      </tr>\n"})),o+="    </tbody>\n",o+="  </table>\n</body>\n</html>",this.downloadFile(o,a,"text/html")},formatValueForCSV:e=>null==e?"":e instanceof Date?e.toISOString().split("T")[0]:String(e),formatValueForExcel:e=>null==e?"":e instanceof Date||"number"==typeof e?e:String(e),formatValueForXML:e=>null==e?"":e instanceof Date?e.toISOString():String(e),formatValueForHTML:e=>null==e?"":"string"==typeof e&&e.startsWith("<")?e:e instanceof Date?e.toLocaleString():String(e),escapeCSVField(e,t,n){if(!e)return"";const a=String(e),r=SecurityUtils.escapeCSVFormula(a);return r.includes(t)||r.includes(n)||r.includes("\n")||r.includes("\r")?n+r.replace(new RegExp(n,"g"),n+n)+n:r},escapeXML:e=>e?String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"):"",escapeHTML:e=>e?String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"):"",s2ab(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=255&e.charCodeAt(t);return t},downloadFile(e,t,n,a="utf-8"){return new Promise((r=>{const i=new Blob([e],{type:`${n};charset=${a}`});this.downloadBlob(i,t),r({success:!0,filename:t,size:i.size})}))},downloadBlob(e,t){const n=URL.createObjectURL(e),a=document.createElement("a");a.href=n,a.download=t,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout((()=>URL.revokeObjectURL(n)),100)},getExportFormats:()=>({csv:{name:"CSV",description:"Comma-separated values file",extension:"csv",mimeType:"text/csv"},xlsx:{name:"Excel",description:"Microsoft Excel spreadsheet",extension:"xlsx",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",requiresLibrary:"XLSX"},json:{name:"JSON",description:"JavaScript Object Notation file",extension:"json",mimeType:"application/json"},xml:{name:"XML",description:"eXtensible Markup Language file",extension:"xml",mimeType:"application/xml"},html:{name:"HTML",description:"HyperText Markup Language file",extension:"html",mimeType:"text/html"}})};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.ExportModule=o);const l={init(e){return this.table=e,this.plugins=new Map,this.hooks=new Map,this.middlewares=new Map,this.eventListeners=new Map,this.initializeHooks(),this},registerPlugin(e,t){return!this.plugins.has(e)&&(this.validatePlugin(t)?(this.plugins.set(e,{...t,name:e,enabled:!0,initialized:!1}),this.table&&this.initializePlugin(e),!0):(console.error(`Invalid plugin structure for "${e}"`),!1))},unregisterPlugin(e){return this.plugins.get(e)?(this.cleanupPlugin(e),this.plugins.delete(e),!0):(console.warn(`Plugin "${e}" not found`),!1)},enablePlugin(e){const t=this.plugins.get(e);return t?(t.enabled=!0,t.initialized||this.initializePlugin(e),!0):(console.warn(`Plugin "${e}" not found`),!1)},disablePlugin(e){const t=this.plugins.get(e);return t?(t.enabled=!1,this.cleanupPlugin(e),!0):(console.warn(`Plugin "${e}" not found`),!1)},initializePlugin(e){const t=this.plugins.get(e);if(t&&t.enabled&&!t.initialized)try{t.init&&"function"==typeof t.init&&t.init(this.table,this.getPluginAPI()),t.hooks&&Object.entries(t.hooks).forEach((([t,n])=>{this.registerHook(t,n,e)})),t.events&&Object.entries(t.events).forEach((([t,n])=>{this.registerEventListener(t,n,e)})),t.middlewares&&Object.entries(t.middlewares).forEach((([t,n])=>{this.registerMiddleware(t,n,e)})),t.initialized=!0,this.emitHook("plugin:loaded",{plugin:e})}catch(n){console.error(`Failed to initialize plugin "${e}":`,n),t.enabled=!1}},cleanupPlugin(e){const t=this.plugins.get(e);if(t&&t.initialized)try{t.destroy&&"function"==typeof t.destroy&&t.destroy(),this.unregisterPluginHooks(e),this.unregisterPluginEventListeners(e),this.unregisterPluginMiddlewares(e),t.initialized=!1,this.emitHook("plugin:unloaded",{plugin:e})}catch(t){console.error(`Failed to cleanup plugin "${e}":`,t)}},validatePlugin(e){if(!e||"object"!=typeof e)return!1;const t=["version"];for(const n of t)if(!(n in e))return console.error(`Plugin missing required property: ${n}`),!1;return e.init&&"function"!=typeof e.init?(console.error("Plugin init must be a function"),!1):e.destroy&&"function"!=typeof e.destroy?(console.error("Plugin destroy must be a function"),!1):!e.hooks||"object"==typeof e.hooks||(console.error("Plugin hooks must be an object"),!1)},getPluginAPI(){return{table:this.table,registerHook:(e,t,n)=>this.registerHook(e,t,n),unregisterHook:(e,t)=>this.unregisterHook(e,t),emitHook:(e,t)=>this.emitHook(e,t),addEventListener:(e,t,n)=>this.registerEventListener(e,t,n),removeEventListener:(e,t)=>this.unregisterEventListener(e,t),registerMiddleware:(e,t,n)=>this.registerMiddleware(e,t,n),unregisterMiddleware:(e,t)=>this.unregisterMiddleware(e,t),createElement:(e,t,n)=>this.createElement(e,t,n),addCSS:(e,t)=>this.addCSS(e,t),removeCSS:e=>this.removeCSS(e),getPlugin:e=>this.getPlugin(e),getPlugins:()=>this.getPlugins(),setStorage:(e,t,n)=>this.setPluginStorage(e,t,n),getStorage:(e,t)=>this.getPluginStorage(e,t),removeStorage:(e,t)=>this.removePluginStorage(e,t)}},initializeHooks(){["table:beforeInit","table:afterInit","table:beforeDestroy","table:afterDestroy","data:beforeLoad","data:afterLoad","data:beforeFilter","data:afterFilter","data:beforeSort","data:afterSort","render:beforeRender","render:afterRender","cell:beforeEdit","cell:afterEdit","row:beforeSelect","row:afterSelect","plugin:loaded","plugin:unloaded"].forEach((e=>{this.hooks.set(e,[])}))},registerHook(e,t,n){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push({handler:t,plugin:n,priority:t.priority||0}),this.hooks.get(e).sort(((e,t)=>t.priority-e.priority))},unregisterHook(e,t){if(!this.hooks.has(e))return;const n=this.hooks.get(e).filter((e=>e.plugin!==t));this.hooks.set(e,n)},unregisterPluginHooks(e){this.hooks.forEach(((t,n)=>{this.unregisterHook(n,e)}))},emitHook(e,t){if(!this.hooks.has(e))return t;const n=this.hooks.get(e);let a=t;for(const{handler:t,plugin:r}of n){const n=this.plugins.get(r);if(n&&n.enabled)try{const e=t(a,this.table);void 0!==e&&(a=e)}catch(t){console.error(`Hook "${e}" failed for plugin "${r}":`,t)}}return a},registerEventListener(e,t,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);const a={handler:t,plugin:n};this.eventListeners.get(e).push(a),this.table.container&&this.table.container.addEventListener(e,t)},unregisterEventListener(e,t){if(!this.eventListeners.has(e))return;const n=this.eventListeners.get(e).filter((n=>n.plugin!==t||(this.table.container&&this.table.container.removeEventListener(e,n.handler),!1)));this.eventListeners.set(e,n)},unregisterPluginEventListeners(e){this.eventListeners.forEach(((t,n)=>{this.unregisterEventListener(n,e)}))},registerMiddleware(e,t,n){this.middlewares.has(e)||this.middlewares.set(e,[]),this.middlewares.get(e).push({handler:t,plugin:n,priority:t.priority||0}),this.middlewares.get(e).sort(((e,t)=>t.priority-e.priority))},unregisterMiddleware(e,t){if(!this.middlewares.has(e))return;const n=this.middlewares.get(e).filter((e=>e.plugin!==t));this.middlewares.set(e,n)},unregisterPluginMiddlewares(e){this.middlewares.forEach(((t,n)=>{this.unregisterMiddleware(n,e)}))},applyMiddleware(e,t,n){if(!this.middlewares.has(e))return n?n(t):t;const a=this.middlewares.get(e);let r=0;const i=t=>{if(r>=a.length)return n?n(t):t;const{handler:s,plugin:o}=a[r++],l=this.plugins.get(o);if(!l||!l.enabled)return i(t);try{return s(t,(()=>i(t)))}catch(n){return console.error(`Middleware "${e}" failed for plugin "${o}":`,n),i(t)}};return i(t)},createElement(e,t={},n=[]){const a=document.createElement(e);return Object.entries(t).forEach((([e,t])=>{"style"===e&&"object"==typeof t?Object.assign(a.style,t):e.startsWith("data-")?a.dataset[e.replace("data-","")]=t:a.setAttribute(e,t)})),n.forEach((e=>{"string"==typeof e?a.appendChild(document.createTextNode(e)):e instanceof Node&&a.appendChild(e)})),a},addCSS(e,t){const n=document.getElementById(t);if(n)return void(n.textContent=e);const a=document.createElement("style");a.id=t,a.textContent=e,document.head.appendChild(a)},removeCSS(e){const t=document.getElementById(e);t&&t.remove()},setPluginStorage(e,t,n){const a=`table-plugin-${n}-${e}`;try{localStorage.setItem(a,JSON.stringify(t))}catch(e){console.warn("Failed to save plugin storage:",e)}},getPluginStorage(e,t){const n=`table-plugin-${t}-${e}`;try{const e=localStorage.getItem(n);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to load plugin storage:",e),null}},removePluginStorage(e,t){const n=`table-plugin-${t}-${e}`;try{localStorage.removeItem(n)}catch(e){console.warn("Failed to remove plugin storage:",e)}},getPlugin(e){return this.plugins.get(e)||null},getPlugins(){return Array.from(this.plugins.values())},getEnabledPlugins(){return Array.from(this.plugins.values()).filter((e=>e.enabled))},getPluginList(){return Array.from(this.plugins.entries()).map((([e,t])=>({name:e,version:t.version,description:t.description,author:t.author,enabled:t.enabled,initialized:t.initialized})))},async loadPluginFromURL(e,t){try{if(!this.validatePluginURL(e))return console.error(`Invalid or unsafe plugin URL: "${e}"`),!1;const n=await fetch(e),a=await n.text(),r=this.createPluginFromCode(a,t);return!!r&&this.registerPlugin(t,r)}catch(t){return console.error(`Failed to load plugin from URL "${e}":`,t),!1}},validatePluginURL(e){try{const t=new URL(e),n=[/^(10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.)/,/^(127\.|169\.254\.)/,/^(localhost|0\.0\.0\.0)/i,/^(::1|fe80::|fc00::|fd00::)/i,/^(metadata\.google\.internal)/i],a=t.hostname;for(const e of n)if(e.test(a))return!1;if(!["http:","https:"].includes(t.protocol))return!1;const r=t.port;return r&&!["80","443",""].includes(r)&&(["8080","8443","3000"].includes(r)||console.warn(`Plugin URL uses non-standard port: ${r}`)),!0}catch(e){return!1}},createPluginFromCode(e,t){try{const t={console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function(...Object.keys(t),`${e}\nreturn typeof plugin !== 'undefined' ? plugin : null;`);return n(...Object.values(t))}catch(e){return console.error(`Failed to create plugin "${t}" from code:`,e),null}},createPluginManager(e){const t=this.createElement("div",{class:"plugin-manager",style:{padding:"20px",border:"1px solid #ddd",borderRadius:"4px",background:"#fafafa"}}),n=this.createElement("h3",{},["Plugin Manager"]);t.appendChild(n);const a=this.createElement("div",{class:"plugin-list"});return this.getPluginList().forEach((t=>{const n=this.createElement("div",{class:"plugin-item",style:{padding:"10px",margin:"5px 0",border:"1px solid #ddd",borderRadius:"3px",background:"#fff",display:"flex",justifyContent:"space-between",alignItems:"center"}}),r=this.createElement("div",{},[this.createElement("strong",{},[t.name]),this.createElement("span",{style:{color:"#666",marginLeft:"10px"}},[`v${t.version} - ${t.description||"No description"}`])]),i=this.createElement("div",{}),s=this.createElement("button",{style:{padding:"4px 8px",border:"1px solid #ddd",borderRadius:"3px",background:t.enabled?"#52c41a":"#f5222d",color:"white",cursor:"pointer"}},[t.enabled?"Disable":"Enable"]);s.addEventListener("click",(()=>{t.enabled?this.disablePlugin(t.name):this.enablePlugin(t.name),e.innerHTML="",this.createPluginManager(e)})),i.appendChild(s),n.appendChild(r),n.appendChild(i),a.appendChild(n)})),t.appendChild(a),e&&e.appendChild(t),t},destroy(){this.plugins.forEach(((e,t)=>{this.cleanupPlugin(t)})),this.plugins.clear(),this.hooks.clear(),this.middlewares.clear(),this.eventListeners.clear()}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.PluginSystem=l);const c={init(e){return this.table=e,this.workers=new Map,this.taskQueue=[],this.maxWorkers=navigator.hardwareConcurrency||4,this.workerPool=[],this.taskCounter=0,this.initializeWorkerPool(),this},initializeWorkerPool(){if(window.Worker)for(let e=0;e<this.maxWorkers;e++)this.createWorker();else console.warn("WebWorkers not supported in this browser")},createWorker(){const e={id:`worker-${Date.now()}-${Math.random()}`,worker:null,busy:!1,currentTask:null,createdAt:Date.now()};try{const t=new Blob([this.getWorkerCode()],{type:"application/javascript"}),n=URL.createObjectURL(t);e.worker=new Worker(n),e.worker.onmessage=t=>this.handleWorkerMessage(e,t),e.worker.onerror=t=>this.handleWorkerError(e,t),this.workerPool.push(e),setTimeout((()=>URL.revokeObjectURL(n)),1e3)}catch(e){console.error("Failed to create worker:",e)}return e},getWorkerCode:()=>"\n      // WebWorker code for table operations\n      self.onmessage = function(e) {\n        const { taskId, operation, data, options } = e.data;\n        \n        try {\n          let result;\n          \n          switch (operation) {\n            case 'filter':\n              result = performFilter(data, options);\n              break;\n            case 'sort':\n              result = performSort(data, options);\n              break;\n            case 'search':\n              result = performSearch(data, options);\n              break;\n            case 'aggregate':\n              result = performAggregate(data, options);\n              break;\n            case 'transform':\n              result = performTransform(data, options);\n              break;\n            case 'validate':\n              result = performValidation(data, options);\n              break;\n            case 'export':\n              result = performExport(data, options);\n              break;\n            case 'calculate':\n              result = performCalculation(data, options);\n              break;\n            default:\n              throw new Error('Unknown operation: ' + operation);\n          }\n          \n          self.postMessage({\n            taskId,\n            success: true,\n            result,\n            processingTime: Date.now() - e.data.startTime\n          });\n          \n        } catch (error) {\n          self.postMessage({\n            taskId,\n            success: false,\n            error: error.message,\n            processingTime: Date.now() - e.data.startTime\n          });\n        }\n      };\n      \n      // Filter operation\n      function performFilter(data, options) {\n        const { filters, logic } = options;\n        \n        return data.filter(row => {\n          if (logic === 'AND') {\n            return filters.every(filter => evaluateFilter(row, filter));\n          } else {\n            return filters.some(filter => evaluateFilter(row, filter));\n          }\n        });\n      }\n      \n      // Evaluate single filter\n      function evaluateFilter(row, filter) {\n        const value = row[filter.column];\n        const filterValue = filter.value;\n        \n        switch (filter.operator) {\n          case 'equals':\n            return value == filterValue;\n          case 'not_equals':\n            return value != filterValue;\n          case 'contains':\n            return String(value).toLowerCase().includes(String(filterValue).toLowerCase());\n          case 'not_contains':\n            return !String(value).toLowerCase().includes(String(filterValue).toLowerCase());\n          case 'starts_with':\n            return String(value).toLowerCase().startsWith(String(filterValue).toLowerCase());\n          case 'ends_with':\n            return String(value).toLowerCase().endsWith(String(filterValue).toLowerCase());\n          case 'greater_than':\n            return parseFloat(value) > parseFloat(filterValue);\n          case 'less_than':\n            return parseFloat(value) < parseFloat(filterValue);\n          case 'greater_equal':\n            return parseFloat(value) >= parseFloat(filterValue);\n          case 'less_equal':\n            return parseFloat(value) <= parseFloat(filterValue);\n          case 'between':\n            const val = parseFloat(value);\n            return val >= parseFloat(filter.min) && val <= parseFloat(filter.max);\n          case 'is_null':\n            return value == null || value === '';\n          case 'is_not_null':\n            return value != null && value !== '';\n          case 'regex':\n            try {\n              const regex = new RegExp(filterValue, filter.flags || 'i');\n              return regex.test(String(value));\n            } catch {\n              return false;\n            }\n          default:\n            return true;\n        }\n      }\n      \n      // Sort operation\n      function performSort(data, options) {\n        const { sorts } = options;\n        \n        return [...data].sort((a, b) => {\n          for (const sort of sorts) {\n            const aVal = a[sort.column];\n            const bVal = b[sort.column];\n            let comparison = 0;\n            \n            if (aVal === null || aVal === undefined) comparison = 1;\n            else if (bVal === null || bVal === undefined) comparison = -1;\n            else if (typeof aVal === 'number' && typeof bVal === 'number') {\n              comparison = aVal - bVal;\n            } else {\n              comparison = String(aVal).localeCompare(String(bVal));\n            }\n            \n            if (comparison !== 0) {\n              return sort.direction === 'desc' ? -comparison : comparison;\n            }\n          }\n          return 0;\n        });\n      }\n      \n      // Search operation\n      function performSearch(data, options) {\n        const { query, columns, fuzzy } = options;\n        const searchQuery = query.toLowerCase();\n        \n        return data.filter(row => {\n          return columns.some(column => {\n            const value = String(row[column] || '').toLowerCase();\n            \n            if (fuzzy) {\n              return fuzzyMatch(value, searchQuery);\n            } else {\n              return value.includes(searchQuery);\n            }\n          });\n        });\n      }\n      \n      // Fuzzy matching\n      function fuzzyMatch(text, pattern) {\n        const patternLength = pattern.length;\n        const textLength = text.length;\n        \n        if (patternLength === 0) return true;\n        if (textLength === 0) return false;\n        \n        let patternIndex = 0;\n        let textIndex = 0;\n        \n        while (patternIndex < patternLength && textIndex < textLength) {\n          if (pattern[patternIndex] === text[textIndex]) {\n            patternIndex++;\n          }\n          textIndex++;\n        }\n        \n        return patternIndex === patternLength;\n      }\n      \n      // Aggregate operation\n      function performAggregate(data, options) {\n        const { groupBy, aggregations } = options;\n        const groups = {};\n        \n        // Group data\n        data.forEach(row => {\n          const key = groupBy ? row[groupBy] : 'all';\n          if (!groups[key]) {\n            groups[key] = [];\n          }\n          groups[key].push(row);\n        });\n        \n        // Perform aggregations\n        const results = {};\n        Object.entries(groups).forEach(([key, rows]) => {\n          results[key] = {};\n          \n          aggregations.forEach(agg => {\n            const values = rows.map(row => parseFloat(row[agg.column])).filter(v => !isNaN(v));\n            \n            switch (agg.type) {\n              case 'count':\n                results[key][agg.column + '_count'] = rows.length;\n                break;\n              case 'sum':\n                results[key][agg.column + '_sum'] = values.reduce((a, b) => a + b, 0);\n                break;\n              case 'avg':\n                results[key][agg.column + '_avg'] = values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0;\n                break;\n              case 'min':\n                results[key][agg.column + '_min'] = values.length ? Math.min(...values) : null;\n                break;\n              case 'max':\n                results[key][agg.column + '_max'] = values.length ? Math.max(...values) : null;\n                break;\n            }\n          });\n        });\n        \n        return results;\n      }\n      \n      // Transform operation\n      function performTransform(data, options) {\n        const { transformations } = options;\n        \n        return data.map(row => {\n          const transformedRow = { ...row };\n          \n          transformations.forEach(transform => {\n            switch (transform.type) {\n              case 'calculate':\n                try {\n                  const func = new Function('row', 'return ' + transform.expression);\n                  transformedRow[transform.target] = func(row);\n                } catch (error) {\n                  transformedRow[transform.target] = null;\n                }\n                break;\n              case 'format':\n                transformedRow[transform.target] = formatValue(row[transform.source], transform.format);\n                break;\n              case 'convert':\n                transformedRow[transform.target] = convertValue(row[transform.source], transform.from, transform.to);\n                break;\n            }\n          });\n          \n          return transformedRow;\n        });\n      }\n      \n      // Format value\n      function formatValue(value, format) {\n        switch (format.type) {\n          case 'currency':\n            return new Intl.NumberFormat('en-US', { style: 'currency', currency: format.currency || 'USD' }).format(value);\n          case 'percentage':\n            return new Intl.NumberFormat('en-US', { style: 'percent', minimumFractionDigits: format.decimals || 2 }).format(value / 100);\n          case 'date':\n            return new Date(value).toLocaleDateString(format.locale || 'en-US');\n          default:\n            return value;\n        }\n      }\n      \n      // Convert value\n      function convertValue(value, from, to) {\n        if (from === 'string' && to === 'number') {\n          return parseFloat(value) || 0;\n        } else if (from === 'number' && to === 'string') {\n          return String(value);\n        } else if (from === 'date' && to === 'timestamp') {\n          return new Date(value).getTime();\n        } else if (from === 'timestamp' && to === 'date') {\n          return new Date(parseInt(value)).toISOString().split('T')[0];\n        }\n        return value;\n      }\n      \n      // Validation operation\n      function performValidation(data, options) {\n        const { rules } = options;\n        const errors = [];\n        \n        data.forEach((row, index) => {\n          rules.forEach(rule => {\n            const value = row[rule.column];\n            const isValid = validateValue(value, rule);\n            \n            if (!isValid) {\n              errors.push({\n                row: index,\n                column: rule.column,\n                value,\n                rule: rule.type,\n                message: rule.message || 'Validation failed'\n              });\n            }\n          });\n        });\n        \n        return { errors, isValid: errors.length === 0 };\n      }\n      \n      // Validate single value\n      function validateValue(value, rule) {\n        switch (rule.type) {\n          case 'required':\n            return value != null && value !== '';\n          case 'min_length':\n            return String(value).length >= rule.length;\n          case 'max_length':\n            return String(value).length <= rule.length;\n          case 'pattern':\n            return new RegExp(rule.pattern).test(String(value));\n          case 'range':\n            const num = parseFloat(value);\n            return num >= rule.min && num <= rule.max;\n          case 'unique':\n            // This would need to be handled with the full dataset\n            return true;\n          default:\n            return true;\n        }\n      }\n      \n      // Export operation\n      function performExport(data, options) {\n        const { format, columns, includeHeaders } = options;\n        \n        switch (format) {\n          case 'csv':\n            return generateCSV(data, columns, includeHeaders);\n          case 'json':\n            return generateJSON(data, columns);\n          case 'tsv':\n            return generateTSV(data, columns, includeHeaders);\n          default:\n            return data;\n        }\n      }\n      \n      // Generate CSV\n      function generateCSV(data, columns, includeHeaders) {\n        let csv = '';\n        \n        if (includeHeaders) {\n          csv += columns.map(col => col.title || col.key).join(',') + '\\n';\n        }\n        \n        data.forEach(row => {\n          const values = columns.map(col => {\n            let value = row[col.dataIndex || col.key] || '';\n            // Escape quotes and commas\n            if (String(value).includes(',') || String(value).includes('\"')) {\n              value = '\"' + String(value).replace(/\"/g, '\"\"') + '\"';\n            }\n            return value;\n          });\n          csv += values.join(',') + '\\n';\n        });\n        \n        return csv;\n      }\n      \n      // Generate JSON\n      function generateJSON(data, columns) {\n        const exportData = data.map(row => {\n          const exportRow = {};\n          columns.forEach(col => {\n            exportRow[col.title || col.key] = row[col.dataIndex || col.key];\n          });\n          return exportRow;\n        });\n        \n        return JSON.stringify(exportData, null, 2);\n      }\n      \n      // Generate TSV\n      function generateTSV(data, columns, includeHeaders) {\n        let tsv = '';\n        \n        if (includeHeaders) {\n          tsv += columns.map(col => col.title || col.key).join('\\t') + '\\n';\n        }\n        \n        data.forEach(row => {\n          const values = columns.map(col => {\n            return row[col.dataIndex || col.key] || '';\n          });\n          tsv += values.join('\\t') + '\\n';\n        });\n        \n        return tsv;\n      }\n      \n      // Calculation operation\n      function performCalculation(data, options) {\n        const { expressions } = options;\n        const results = {};\n        \n        expressions.forEach(expr => {\n          try {\n            const values = data.map(row => parseFloat(row[expr.column])).filter(v => !isNaN(v));\n            \n            switch (expr.operation) {\n              case 'sum':\n                results[expr.name] = values.reduce((a, b) => a + b, 0);\n                break;\n              case 'average':\n                results[expr.name] = values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0;\n                break;\n              case 'min':\n                results[expr.name] = values.length ? Math.min(...values) : null;\n                break;\n              case 'max':\n                results[expr.name] = values.length ? Math.max(...values) : null;\n                break;\n              case 'count':\n                results[expr.name] = data.length;\n                break;\n              case 'median':\n                const sorted = values.sort((a, b) => a - b);\n                const mid = Math.floor(sorted.length / 2);\n                results[expr.name] = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n                break;\n            }\n          } catch (error) {\n            results[expr.name] = null;\n          }\n        });\n        \n        return results;\n      }\n    ",executeTask(e,t,n={}){return new Promise(((a,r)=>{const i=`task-${++this.taskCounter}-${Date.now()}`,s=Date.now(),o={id:i,operation:e,data:t,options:n,startTime:s,resolve:a,reject:r};this.taskQueue.push(o),this.processTaskQueue()}))},processTaskQueue(){if(0===this.taskQueue.length)return;const e=this.workerPool.find((e=>!e.busy&&e.worker));if(!e)return;const t=this.taskQueue.shift();e.busy=!0,e.currentTask=t,e.worker.postMessage({taskId:t.id,operation:t.operation,data:t.data,options:t.options,startTime:t.startTime});const n=setTimeout((()=>{this.handleTaskTimeout(e,t)}),t.options.timeout||3e4);t.timeout=n,this.workers.set(t.id,{worker:e,task:t,timeout:n})},handleWorkerMessage(e,t){const{taskId:n,success:a,result:r,error:i,processingTime:s}=t.data,o=this.workers.get(n);if(!o)return;const{task:l,timeout:c}=o;clearTimeout(c),e.busy=!1,e.currentTask=null,this.workers.delete(n),a?l.resolve({result:r,processingTime:s,taskId:n}):l.reject(new Error(i)),setTimeout((()=>this.processTaskQueue()),0)},handleWorkerError(e,t){if(console.error("Worker error:",t),e.currentTask){const n=e.currentTask;n.reject(new Error("Worker error: "+t.message)),this.workers.delete(n.id)}this.recreateWorker(e)},handleTaskTimeout(e,t){console.warn("Task timeout:",t.id),t.reject(new Error("Task timeout")),this.workers.delete(t.id),this.recreateWorker(e)},recreateWorker(e){e.worker&&e.worker.terminate();const t=this.workerPool.indexOf(e);-1!==t&&this.workerPool.splice(t,1),this.createWorker()},getPoolStatus(){return{totalWorkers:this.workerPool.length,busyWorkers:this.workerPool.filter((e=>e.busy)).length,availableWorkers:this.workerPool.filter((e=>!e.busy)).length,queuedTasks:this.taskQueue.length,activeTasks:this.workers.size}},async filterData(e,t){return(await this.executeTask("filter",e,t)).result},async sortData(e,t){return(await this.executeTask("sort",e,t)).result},async searchData(e,t){return(await this.executeTask("search",e,t)).result},async aggregateData(e,t){return(await this.executeTask("aggregate",e,t)).result},async transformData(e,t){return(await this.executeTask("transform",e,t)).result},async validateData(e,t){return(await this.executeTask("validate",e,t)).result},async exportData(e,t){return(await this.executeTask("export",e,t)).result},async calculateStats(e,t){return(await this.executeTask("calculate",e,t)).result},async batchProcess(e){const t=e.map((e=>this.executeTask(e.operation,e.data,e.options)));return Promise.all(t)},async executeWithProgress(e,t,n={}){const a=n.chunkSize||Math.ceil(t.length/10),r=[];for(let e=0;e<t.length;e+=a)r.push(t.slice(e,e+a));const i=[],s=n.onProgress||(()=>{});for(let t=0;t<r.length;t++){const a=await this.executeTask(e,r[t],n);i.push(a.result),s({completed:t+1,total:r.length,percentage:Math.round((t+1)/r.length*100)})}return this.combineResults(e,i)},combineResults(e,t){switch(e){case"filter":case"sort":case"search":case"transform":return t.flat();case"aggregate":case"calculate":return t.reduce(((e,t)=>({...e,...t})),{});case"validate":const e=t.flatMap((e=>e.errors||[]));return{errors:e,isValid:0===e.length};case"export":return t.join("\\n");default:return t}},destroy(){this.taskQueue.forEach((e=>{e.reject(new Error("WebWorker system destroyed"))})),this.taskQueue=[],this.workers.forEach((({task:e,timeout:t})=>{clearTimeout(t),e.reject(new Error("WebWorker system destroyed"))})),this.workers.clear(),this.workerPool.forEach((e=>{e.worker&&e.worker.terminate()})),this.workerPool=[]}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.WebWorkerSupport=c);const d={name:"Row Selection",version:"1.0.0",description:"Enhanced row selection with checkboxes and bulk operations",author:"ExceLike Table Team",selectedRows:new Set,selectAllState:!1,selectionMode:"multiple",init(e,t){this.table=e,this.api=t,this.loadConfig(),this.addStyles(),this.api.registerHook("render:beforeRender",this.beforeRender.bind(this)),this.api.registerHook("render:afterRender",this.afterRender.bind(this)),this.api.addEventListener("click",this.handleRowClick.bind(this)),this.createSelectionToolbar()},loadConfig(){const e=this.api.getStorage("config","row-selection");this.config={showCheckboxes:!0,allowSelectAll:!0,highlightSelected:!0,selectionMode:"multiple",showSelectionToolbar:!0,...e}},addStyles(){this.api.addCSS("\n      /* Selection checkbox styles */\n      .table-selection-checkbox {\n        width: 16px;\n        height: 16px;\n        cursor: pointer;\n        margin: 2px;\n      }\n      \n      .table-selection-header {\n        width: 40px;\n        text-align: center;\n        padding: 8px 4px;\n        user-select: none;\n      }\n      \n      .table-selection-cell {\n        width: 40px;\n        text-align: center;\n        padding: 8px 4px;\n        cursor: pointer;\n      }\n      \n      /* Selected row styles */\n      .table-row-selected {\n        background-color: var(--table-color-background-selected, #e6f7ff) !important;\n        border-color: var(--table-color-primary, #1890ff) !important;\n      }\n      \n      .table-row-selected td {\n        background-color: var(--table-color-background-selected, #e6f7ff);\n      }\n      \n      /* Selection toolbar */\n      .table-selection-toolbar {\n        padding: 8px 16px;\n        background: var(--table-color-background-secondary, #fafafa);\n        border: 1px solid var(--table-color-border, #d9d9d9);\n        border-bottom: none;\n        display: none;\n        align-items: center;\n        gap: 12px;\n        font-size: 14px;\n        color: var(--table-color-text-secondary, #666);\n      }\n      \n      .table-selection-toolbar.visible {\n        display: flex;\n      }\n      \n      .table-selection-count {\n        font-weight: 500;\n        color: var(--table-color-primary, #1890ff);\n      }\n      \n      .table-selection-actions {\n        display: flex;\n        gap: 8px;\n      }\n      \n      .table-selection-action {\n        padding: 4px 8px;\n        border: 1px solid var(--table-color-border, #d9d9d9);\n        border-radius: 4px;\n        background: white;\n        cursor: pointer;\n        font-size: 12px;\n        transition: all 0.2s;\n      }\n      \n      .table-selection-action:hover {\n        border-color: var(--table-color-primary, #1890ff);\n        color: var(--table-color-primary, #1890ff);\n      }\n      \n      /* Select all checkbox states */\n      .table-select-all-checkbox.indeterminate {\n        opacity: 0.6;\n      }\n      \n      /* Row hover effects */\n      .table-row:hover .table-selection-cell {\n        background-color: var(--table-color-background-hover, #f5f5f5);\n      }\n    ","row-selection-plugin")},beforeRender(){this.config.showCheckboxes&&"none"!==this.config.selectionMode&&this.addSelectionColumn()},afterRender(){this.updateRowSelectionState(),this.updateSelectAllState(),this.updateSelectionToolbar()},addSelectionColumn(){const e=this.table.options.columns;if(e.some((e=>"_selection"===e.key)))return;const t={key:"_selection",title:this.config.allowSelectAll?this.createSelectAllCheckbox():"",dataIndex:"_selection",width:40,fixed:"left",render:(e,t,n,a)=>this.createRowCheckbox(t,a),className:"table-selection-header"};e.unshift(t)},createSelectAllCheckbox(){const e=this.api.createElement("input",{type:"checkbox",class:"table-selection-checkbox table-select-all-checkbox",title:"Select All"});return e.addEventListener("change",this.handleSelectAll.bind(this)),e.outerHTML},createRowCheckbox(e,t){const n=this.isRowSelected(e),a=this.api.createElement("input",{type:"checkbox",class:"table-selection-checkbox table-row-checkbox","data-row-index":t,checked:n,title:n?"Deselect Row":"Select Row"});return a.addEventListener("change",(n=>this.handleRowSelect(n,e,t))),a.outerHTML},handleRowClick(e){const t=e.target.closest(".table-row");if(!t)return;const n=parseInt(t.dataset.rowIndex),a=this.table.getRowData(n);a&&(e.target.matches(".table-selection-checkbox, button, a, input, select")||("single"===this.config.selectionMode?this.selectSingleRow(a):"multiple"===this.config.selectionMode&&(e.ctrlKey||e.metaKey?this.toggleRowSelection(a):e.shiftKey&&void 0!==this.lastSelectedIndex?this.selectRangeRows(this.lastSelectedIndex,n):this.selectSingleRow(a)),this.lastSelectedIndex=n))},handleSelectAll(e){e.target.checked?this.selectAllRows():this.deselectAllRows()},handleRowSelect(e,t,n){e.stopPropagation();e.target.checked?this.selectRow(t):this.deselectRow(t)},selectSingleRow(e){this.selectedRows.clear(),this.selectRow(e)},selectRow(e){const t=this.getRowId(e);this.selectedRows.add(t),this.emitSelectionChange(),this.updateUI()},deselectRow(e){const t=this.getRowId(e);this.selectedRows.delete(t),this.emitSelectionChange(),this.updateUI()},toggleRowSelection(e){this.isRowSelected(e)?this.deselectRow(e):this.selectRow(e)},selectAllRows(){this.table.getFilteredData().forEach((e=>{this.selectedRows.add(this.getRowId(e))})),this.selectAllState=!0,this.emitSelectionChange(),this.updateUI()},deselectAllRows(){this.selectedRows.clear(),this.selectAllState=!1,this.emitSelectionChange(),this.updateUI()},selectRangeRows(e,t){const n=this.table.getFilteredData(),a=Math.min(e,t),r=Math.max(e,t);for(let e=a;e<=r;e++)n[e]&&this.selectedRows.add(this.getRowId(n[e]));this.emitSelectionChange(),this.updateUI()},isRowSelected(e){return this.selectedRows.has(this.getRowId(e))},getRowId:e=>void 0!==e.id?String(e.id):JSON.stringify(e),getSelectedRows(){return this.table.getFilteredData().filter((e=>this.isRowSelected(e)))},getSelectedRowCount(){return this.selectedRows.size},updateRowSelectionState(){const e=this.table.container.querySelectorAll(".table-row"),t=this.table.getFilteredData();e.forEach(((e,n)=>{const a=t[n];a&&this.isRowSelected(a)?e.classList.add("table-row-selected"):e.classList.remove("table-row-selected");const r=e.querySelector(".table-row-checkbox");r&&(r.checked=a&&this.isRowSelected(a))}))},updateSelectAllState(){const e=this.table.container.querySelector(".table-select-all-checkbox");if(!e)return;const t=this.table.getFilteredData()?.length||0,n=this.getSelectedRowCount();0===n?(e.checked=!1,e.indeterminate=!1,e.classList.remove("indeterminate")):n===t?(e.checked=!0,e.indeterminate=!1,e.classList.remove("indeterminate")):(e.checked=!1,e.indeterminate=!0,e.classList.add("indeterminate"))},createSelectionToolbar(){if(!this.config.showSelectionToolbar)return;const e=this.api.createElement("div",{class:"table-selection-toolbar",id:"selection-toolbar"}),t=this.api.createElement("span",{class:"table-selection-count"}),n=this.api.createElement("div",{class:"table-selection-actions"}),a=this.api.createElement("button",{class:"table-selection-action",title:"Delete selected rows"},["Delete"]),r=this.api.createElement("button",{class:"table-selection-action",title:"Export selected rows"},["Export"]),i=this.api.createElement("button",{class:"table-selection-action",title:"Clear selection"},["Clear"]);a.addEventListener("click",(()=>this.handleDeleteSelected())),r.addEventListener("click",(()=>this.handleExportSelected())),i.addEventListener("click",(()=>this.deselectAllRows())),n.appendChild(a),n.appendChild(r),n.appendChild(i),e.appendChild(t),e.appendChild(n),this.table.container.parentNode.insertBefore(e,this.table.container),this.toolbar=e},updateSelectionToolbar(){if(!this.toolbar)return;const e=this.getSelectedRowCount(),t=this.toolbar.querySelector(".table-selection-count");e>0?(t.textContent=`${e} row${1===e?"":"s"} selected`,this.toolbar.classList.add("visible")):this.toolbar.classList.remove("visible")},updateUI(){this.updateRowSelectionState(),this.updateSelectAllState(),this.updateSelectionToolbar()},handleDeleteSelected(){const e=this.getSelectedRows();if(0===e.length)return;if(!confirm(`Delete ${e.length} selected row${1===e.length?"":"s"}?`))return;this.api.emitHook("rows:beforeDelete",{rows:e});const t=this.table.getData().filter((e=>!this.isRowSelected(e)));this.table.setData(t),this.deselectAllRows(),this.api.emitHook("rows:afterDelete",{deletedRows:e,newData:t})},handleExportSelected(){const e=this.getSelectedRows();0!==e.length&&(this.table.exportModule?this.table.exportModule.exportData({format:"csv",selectedRowsOnly:!0,filename:`selected-rows-${Date.now()}.csv`}):this.exportSelectedRowsAsCSV(e))},exportSelectedRowsAsCSV(e){const t=this.table.options.columns.filter((e=>"_selection"!==e.key)),n=[t.map((e=>e.title)).join(","),...e.map((e=>t.map((t=>e[t.dataIndex]||"")).join(",")))].join("\n"),a=new Blob([n],{type:"text/csv"}),r=URL.createObjectURL(a),i=document.createElement("a");i.href=r,i.download=`selected-rows-${Date.now()}.csv`,i.click(),URL.revokeObjectURL(r)},emitSelectionChange(){this.api.emitHook("selection:changed",{selectedRows:this.getSelectedRows(),selectedRowCount:this.getSelectedRowCount()}),this.saveSelection()},saveSelection(){const e=Array.from(this.selectedRows);this.api.setStorage("selectedRows",e,"row-selection")},loadSelection(){const e=this.api.getStorage("selectedRows","row-selection");e&&Array.isArray(e)&&(this.selectedRows=new Set(e),this.updateUI())},destroy(){const e=this.table.options.columns,t=e.findIndex((e=>"_selection"===e.key));-1!==t&&e.splice(t,1),this.toolbar&&this.toolbar.remove(),this.api.removeCSS("row-selection-plugin"),this.selectedRows.clear()}};"undefined"!=typeof module&&module.exports,"undefined"!=typeof window&&(window.RowSelectionPlugin=d),window.CF_CONSTANTS=window.CF_CONSTANTS||{},window.CF_CONSTANTS.TIMING={INITIAL_APPLY_DELAY:100,REAPPLY_DELAY:200,MUTATION_DEBOUNCE:100,PRIORITY_CHANGE_DELAY:300,TOAST_FADEIN_DELAY:100,TOAST_DISPLAY_DURATION:3e3,TOAST_FADEOUT_DURATION:300},window.CF_CONSTANTS.COLORS={DEFAULT_TEXT_COLOR:"#000000",DEFAULT_BACKGROUND_COLOR:"#ffffff",PRIMARY_ACCENT:"#1890ff",BORDER_LIGHT:"#e0e0e0",BACKGROUND_LIGHT:"#fafafa",TEXT_PRIMARY:"#222",TEXT_SECONDARY:"#333",TEXT_DISABLED:"#999"},window.CF_CONSTANTS.OPERATORS={EQUALS:"equals",NOT_EQUALS:"not-equals",GREATER:"greater",GREATER_EQUAL:"greater-equal",LESS:"less",LESS_EQUAL:"less-equal",CONTAINS:"contains",NOT_CONTAINS:"not-contains"},window.CF_CONSTANTS.OPERATOR_SYMBOLS={[window.CF_CONSTANTS.OPERATORS.EQUALS]:"=",[window.CF_CONSTANTS.OPERATORS.NOT_EQUALS]:"≠",[window.CF_CONSTANTS.OPERATORS.GREATER]:">",[window.CF_CONSTANTS.OPERATORS.GREATER_EQUAL]:"≥",[window.CF_CONSTANTS.OPERATORS.LESS]:"<",[window.CF_CONSTANTS.OPERATORS.LESS_EQUAL]:"≤",[window.CF_CONSTANTS.OPERATORS.CONTAINS]:"contains",[window.CF_CONSTANTS.OPERATORS.NOT_CONTAINS]:"!contains"},window.CF_CONSTANTS.DATA_TYPES={TEXT:"text",NUMBER:"number",DATE:"date"},window.CF_CONSTANTS.APPLY_TO={CELL:"cell",ROW:"row"},window.CF_CONSTANTS.UI={COLOR_INPUT_WIDTH:"60px",COLOR_INPUT_HEIGHT:"40px",MODAL_Z_INDEX:1e4,TOAST_Z_INDEX:10001,CHECKBOX_SIZE:"16px",ICON_SIZE:"14px",MAX_RULES_DISPLAY:100},window.CF_CONSTANTS.VALIDATION={MAX_RULE_NAME_LENGTH:100,MAX_VALUE_LENGTH:1e3,MAX_RULES_COUNT:100,COLOR_REGEX:/^#[0-9A-F]{6}$/i},window.CF_CONSTANTS.MESSAGES={RULE_CREATED:"ルールを作成しました",RULE_UPDATED:"ルールを更新しました",RULE_DELETED:"ルールを削除しました",RULES_APPLIED:"ルールを適用しました",PRIORITY_UPDATED:"優先度を更新し、ルールを再適用しました",ERROR_SAVE:"ルールの保存に失敗しました",ERROR_LOAD:"ルールの読み込みに失敗しました",ERROR_APPLY:"ルールの適用に失敗しました",CONFIRM_DELETE:'ルール"{0}"を削除してもよろしいですか？'},window.CF_CONSTANTS.CSS_CLASSES={FORMATTED:"cf-formatted",ROW_FORMATTED:"cf-row-formatted",MODAL_OVERLAY:"modal-overlay",MODAL:"modal",MODAL_LARGE:"modal-large",TOAST:"cf-toast",TOAST_SUCCESS:"cf-toast-success",TOAST_ERROR:"cf-toast-error",TOAST_SHOW:"cf-toast-show"},window.CF_CONSTANTS.DEFAULT_OPTIONS={enabled:!0,autoApply:!0,maxRules:window.CF_CONSTANTS.VALIDATION.MAX_RULES_COUNT,performance:{debounceDelay:window.CF_CONSTANTS.TIMING.MUTATION_DEBOUNCE,cacheTimeout:5e3},ui:{showToasts:!0,toastPosition:"top-right",modalAnimations:!0}},window.CF_CONSTANTS.ALL=window.CF_CONSTANTS,window.CF_CONSTANTS.ERROR_TYPES={VALIDATION:"VALIDATION_ERROR",RUNTIME:"RUNTIME_ERROR",INITIALIZATION:"INITIALIZATION_ERROR",SAVE:"SAVE_ERROR",LOAD:"LOAD_ERROR"},window.CF_UTILS=window.CF_UTILS||{},function(){const{DEFAULT_STYLES:e,LOG_LEVEL:t,COLOR_UTILS:n,ERROR_TYPES:a,VALIDATION:r,MESSAGES:i}=window.CF_CONSTANTS||{};class s extends Error{constructor(e){super(e),this.name="ValidationError"}}class o{constructor(e,t){this.row=e,this.col=t}equals(e){return e&&this.row===e.row&&this.col===e.col}toString(){return`${this.row},${this.col}`}static fromString(e){const[t,n]=e.split(",").map(Number);return new o(t,n)}}window.CF_UTILS.ErrorHandler=class{constructor(e={}){this.options={logToConsole:!1!==e.logToConsole,throwErrors:e.throwErrors||!1,onError:e.onError||null}}handle(e,t,n={}){const a={operation:e,message:t.message,type:this.categorizeError(t),context:n,timestamp:(new Date).toISOString()};if(this.options.logToConsole,this.options.onError&&this.options.onError(a),this.options.throwErrors)throw t;return{success:!1,error:a}}categorizeError(e){return"ValidationError"===e.name?a.VALIDATION:"ReferenceError"===e.name||"TypeError"===e.name?a.RUNTIME:e.message.includes("保存")||e.message.includes("save")?a.SAVE:e.message.includes("読み込み")||e.message.includes("load")?a.LOAD:a.RUNTIME}success(e=null){return{success:!0,data:e}}},window.CF_UTILS.ValidationError=s,window.CF_UTILS.ValidationUtils=class{static validateRuleName(e){if(!e||"string"!=typeof e)throw new s("ルール名は必須です");if(e.length>r.MAX_RULE_NAME_LENGTH)throw new s(`ルール名は${r.MAX_RULE_NAME_LENGTH}文字以内で入力してください`);return!0}static validateColor(e){if(e&&!r.COLOR_REGEX.test(e))throw new s("有効なカラーコード（#RRGGBB）を入力してください");return!0}static validateOperator(e,t){if(!t.includes(e))throw new s(`無効な演算子です: ${e}`);return!0}static validateValueLength(e){if(e&&e.length>r.MAX_VALUE_LENGTH)throw new s(`値は${r.MAX_VALUE_LENGTH}文字以内で入力してください`);return!0}},window.CF_UTILS.DOMUtils=class{static createCellCache(){return{cache:new Map,timestamp:null,timeout:5e3,get(e,t=!1){const n=Date.now();return(t||!this.timestamp||n-this.timestamp>this.timeout)&&this.refresh(e),this.cache.get(e)||[]},refresh(e){const t=Array.from(e.querySelectorAll(".table-cell, td"));this.cache.set(e,t),this.timestamp=Date.now()},clear(){this.cache.clear(),this.timestamp=null}}}static safeRemove(e){e&&e.parentNode&&e.parentNode.removeChild(e)}static getCellPosition(e){const t=e.closest("tr"),n=e.closest("table, .table-container");if(!t||!n)return null;return{rowIndex:Array.from(n.querySelectorAll("tr")).indexOf(t),cellIndex:Array.from(t.children).indexOf(e)}}static applyStyles(e,t){e&&t&&Object.entries(t).forEach((([t,n])=>{null!=n&&""!==n&&(e.style[t]=n)}))}static removeStyles(e,t){e&&t&&t.forEach((t=>{e.style[t]=""}))}static hasClass(e,t){return e&&e.classList.contains(t)}static addClass(e,t){e&&t&&e.classList.add(t)}static removeClass(e,t){e&&t&&e.classList.remove(t)}},window.CF_UTILS.StringUtils=class{static escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}static formatMessage(e,...t){return e.replace(/\{(\d+)\}/g,((e,n)=>void 0!==t[n]?t[n]:e))}static normalizeColor(e){return e?e.toLowerCase().replace(/\s/g,""):""}},window.CF_UTILS.PerformanceUtils=class{static debounce(e,t){let n;return function(...a){clearTimeout(n),n=setTimeout((()=>{clearTimeout(n),e(...a)}),t)}}static throttle(e,t){let n;return function(...a){n||(e.apply(this,a),n=!0,setTimeout((()=>n=!1),t))}}static binarySearch(e,t){let n=0,a=e.length-1;for(;n<=a;){const r=Math.floor((n+a)/2),i=t(e[r]);if(0===i)return r;i<0?n=r+1:a=r-1}return-1}},window.CF_UTILS.InitializationHelper=class{static checkDependencies(e){const t=[];for(const[n,a]of Object.entries(e))null==a&&t.push(n);if(t.length>0)throw new Error(`Required dependencies are missing: ${t.join(", ")}`)}static mergeOptions(e,t){return this.deepMerge(t,e||{})}static deepMerge(e,t){const n={...e};for(const a in t)t[a]&&"object"==typeof t[a]&&!Array.isArray(t[a])?n[a]=this.deepMerge(e[a]||{},t[a]):n[a]=t[a];return n}},window.CF_UTILS.CellPosition=o,window.CF_UTILS.RuleEvaluator=class{constructor(){this.cache=new Map}evaluate(e,t){const n=`${e}_${JSON.stringify(t)}`;if(this.cache.has(n))return this.cache.get(n);let a=!1;const r=Number(e),{type:i,value:s,min:o,max:l}=t;switch(i){case"greater":a=r>Number(s);break;case"less":a=r<Number(s);break;case"equal":a=e==s;break;case"notEqual":a=e!=s;break;case"between":a=r>=Number(o)&&r<=Number(l);break;case"contains":a=String(e).includes(s);break;case"startsWith":a=String(e).startsWith(s);break;case"endsWith":a=String(e).endsWith(s);break;case"empty":a=""===e||null==e;break;case"notEmpty":a=""!==e&&null!=e;break;default:a=!1}return this.cache.set(n,a),a}clearCache(){this.cache.clear()}},window.CF_UTILS.PriorityManager=class{static sortByPriority(e){return[...e].sort(((e,t)=>t.priority-e.priority))}static getHighestPriorityRule(e,t){const n=e.filter(((e,n)=>t[n]));return 0===n.length?null:n.reduce(((e,t)=>t.priority>e.priority?t:e))}},window.CF_UTILS.Validator=class{static validateRule(e){const t=[];return e.id||t.push("Rule ID is required"),e.name&&""!==e.name.trim()||t.push("Rule name is required"),e.condition&&e.condition.type||t.push("Rule condition is required"),e.style&&0!==Object.keys(e.style).length||t.push("Rule style is required"),void 0!==e.priority&&(e.priority<0||e.priority>999)&&t.push("Priority must be between 0 and 999"),{isValid:0===t.length,errors:t}}static validateCellRange(e){if(!e)return!1;const{startRow:t,startCol:n,endRow:a,endCol:r}=e;return t>=0&&n>=0&&a>=t&&r>=n}},window.CF_UTILS.PerformanceMonitor=class{constructor(e=!1){this.enabled=e,this.measurements=new Map}start(e){this.enabled&&this.measurements.set(e,performance.now())}end(e){if(!this.enabled)return;const t=this.measurements.get(e);if(t){const n=performance.now()-t;return this.measurements.delete(e),n}return 0}clear(){this.measurements.clear()}}}(),function(){window.CF_PERFORMANCE=window.CF_PERFORMANCE||{};window.CF_PERFORMANCE.BatchDOMOperations=class{constructor(){this.operations=[],this.rafId=null}addOperation(e,t,n){this.operations.push({element:e,operation:t,value:n}),this.scheduleUpdate()}addMultipleAttributes(e,t){this.operations.push({element:e,operation:"multipleAttributes",value:t}),this.scheduleUpdate()}scheduleUpdate(){this.rafId||(this.rafId=requestAnimationFrame((()=>{this.executeOperations(),this.rafId=null})))}executeOperations(){document.createDocumentFragment();this.operations.forEach((({element:e,operation:t,value:n})=>{switch(t){case"addClass":e.classList.add(n);break;case"removeClass":e.classList.remove(n);break;case"setAttribute":e.setAttribute(n.name,n.value);break;case"multipleAttributes":Object.entries(n).forEach((([t,n])=>{e.setAttribute(t,n)}));break;case"style":Object.assign(e.style,n)}})),this.operations.length=0}flush(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.executeOperations()}},window.CF_PERFORMANCE.OptimizedCellCache=class{constructor(e=1e3){this.cache=new Map,this.accessOrder=[],this.maxSize=e}get(e,t=!1){const n=this.getContainerKey(e);return!t&&this.cache.has(n)||this.refreshCells(e,n),this.updateAccess(n),this.cache.get(n)}refreshCells(e,t){const n=this.extractCellsWithPosition(e);this.cache.set(t,{cells:n,timestamp:Date.now(),columnCount:this.getColumnCount(e)}),this.evictIfNecessary()}extractCellsWithPosition(e){const t=[];return e.querySelectorAll("tbody tr, .table-row").forEach(((e,n)=>{e.querySelectorAll("td, .table-cell").forEach(((e,a)=>{t.push({element:e,rowIndex:n,colIndex:a,value:this.extractCellValue(e),column:this.getColumnKey(e,a)})}))})),t}extractCellValue(e){const t=e.getAttribute("data-value");return null!==t?t:e.innerText.trim()}getContainerKey(e){return e.id||e.className||"default"}getColumnCount(e){const t=e.querySelector("thead tr, .table-header-row");return t?t.children.length:0}getColumnKey(e,t){const n=e.getAttribute("data-column");if(n)return n;const a=e.getAttribute("data-column-key");if(a)return a;const r=e.getAttribute("data-key");if(r)return r;const i=e.closest("table");if(i){const e=i.querySelector("thead tr");if(e){const n=e.querySelectorAll("th");if(n[t]){const e=n[t].getAttribute("data-key")||n[t].getAttribute("data-column");if(e)return e}}}return`col_${t}`}updateAccess(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}evictIfNecessary(){for(;this.cache.size>this.maxSize;){const e=this.accessOrder.shift();this.cache.delete(e)}}clear(){this.cache.clear(),this.accessOrder.length=0}},window.CF_PERFORMANCE.RuleEvaluationCache=class{constructor(e=500){this.cache=new Map,this.maxSize=e}get(e,t,n){const a=`${e}:${n}:${t}`;return this.cache.get(a)}set(e,t,n,a){const r=`${e}:${n}:${t}`;if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(r,a)}clearForRule(e){for(const t of this.cache.keys())t.startsWith(`${e}:`)&&this.cache.delete(t)}clear(){this.cache.clear()}}}();class u{constructor(e={}){this.id=e.id||this._generateId(),this.name=e.name||"",this.enabled=!1!==e.enabled,this.priority=e.priority||0,this.created=e.created||Date.now(),this.modified=Date.now(),this.condition={column:e.condition?.column||"",operator:e.condition?.operator||"equals",value:e.condition?.value||"",dataType:e.condition?.dataType||"text"},window.__CF_DEBUG__&&console.log("[CF Rule Constructor]",{inputConfig:e.condition,resultCondition:this.condition}),this.applyTo=e.applyTo||"cell",this.format={backgroundColor:e.format?.backgroundColor||"",color:e.format?.color||"",fontWeight:e.format?.fontWeight||!1,fontStyle:e.format?.fontStyle||!1,textDecoration:e.format?.textDecoration||!1}}_generateId(){return"cf_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}validate(){const e=[];return this.name.trim()||e.push("ルール名は必須です"),this.condition.column.trim()||e.push("対象列は必須です"),this.condition.value.trim()||e.push("比較値は必須です"),["equals","not-equals","greater","greater-equal","less","less-equal","contains","not-contains"].includes(this.condition.operator)||e.push("無効な演算子です"),["number","text","date"].includes(this.condition.dataType)||e.push("無効なデータ型です"),["cell","row"].includes(this.applyTo)||e.push("無効な適用範囲です"),{isValid:0===e.length,errors:e}}toJSON(){const e={id:this.id,name:this.name,enabled:this.enabled,priority:this.priority,created:this.created,modified:this.modified,condition:{...this.condition},format:{...this.format},applyTo:this.applyTo};return window.__CF_DEBUG__&&console.log("[CF Rule toJSON]",{thisCondition:this.condition,resultCondition:e.condition}),e}static fromJSON(e){return new u(e)}clone(){return u.fromJSON(this.toJSON())}update(e){void 0!==e.name&&(this.name=e.name),void 0!==e.enabled&&(this.enabled=e.enabled),void 0!==e.applyTo&&(this.applyTo=e.applyTo),e.condition&&(this.condition={...this.condition,...e.condition}),e.format&&(this.format={...this.format,...e.format}),this.modified=Date.now()}}"undefined"!=typeof window&&(window.ConditionalFormattingRule=u);class h{evaluate(e,t){if(!t.enabled)return!1;try{const{operator:n,value:a,dataType:r}=t.condition,i=this._convertValue(e,r),s=this._convertValue(a,r);return window.__CF_DEBUG__&&console.log("[CF Evaluator]",{cellValue:e,dataType:r,convertedCellValue:i,ruleValue:a,convertedRuleValue:s,operator:n}),this._performComparison(i,s,n)}catch(e){return!1}}_convertValue(e,t){if(null==e)return"";switch(t){case"number":let t=String(e).replace(/[$,¥€£\s]/g,"");const n=parseFloat(t);return isNaN(n)?0:n;case"text":default:return String(e);case"date":if(e instanceof Date)return e;const a=new Date(e);return isNaN(a.getTime())?new Date(0):a}}_performComparison(e,t,n){switch(n){case"equals":return this._compareEquals(e,t);case"not-equals":return this._compareNotEquals(e,t);case"greater":return this._compareGreater(e,t);case"greater-equal":return this._compareGreaterEqual(e,t);case"less":return this._compareLess(e,t);case"less-equal":return this._compareLessEqual(e,t);case"contains":return this._compareContains(e,t);case"not-contains":return this._compareNotContains(e,t);default:throw new Error(`未対応の演算子: ${n}`)}}_compareEquals(e,t){return e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():e===t}_compareNotEquals(e,t){return e instanceof Date&&t instanceof Date?e.getTime()!==t.getTime():e!==t}_compareGreater(e,t){return"number"==typeof e&&"number"==typeof t?e>t:e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():String(e)>String(t)}_compareGreaterEqual(e,t){return"number"==typeof e&&"number"==typeof t?e>=t:e instanceof Date&&t instanceof Date?e.getTime()>=t.getTime():String(e)>=String(t)}_compareLess(e,t){return"number"==typeof e&&"number"==typeof t?e<t:e instanceof Date&&t instanceof Date?e.getTime()<t.getTime():String(e)<String(t)}_compareLessEqual(e,t){return"number"==typeof e&&"number"==typeof t?e<=t:e instanceof Date&&t instanceof Date?e.getTime()<=t.getTime():String(e)<=String(t)}_compareContains(e,t){const n=String(e).toLowerCase(),a=String(t).toLowerCase();return n.includes(a)}_compareNotContains(e,t){const n=String(e).toLowerCase(),a=String(t).toLowerCase();return!n.includes(a)}}"undefined"!=typeof window&&(window.ConditionalFormattingEvaluator=h);class p{constructor(){this.cssClassName="cf-formatted",this.attributeName="data-cf-rule-id"}applyToCell(e,t){if(e&&t)try{"row"===t.applyTo?this.applyRowLevelBasicFormat(e,t):this.applyCellFormat(e,t)}catch(e){}}applyCellFormat(e,t){this._applyFormat(e,t.format),e.classList.add(this.cssClassName),e.setAttribute(this.attributeName,t.id),e.setAttribute("data-cf-apply-to","cell")}_applyFormat(e,t){const n=e.style;t.backgroundColor&&n.setProperty("background-color",t.backgroundColor,"important");const a=t.color||"#000000";n.setProperty("color",a,"important"),t.fontWeight&&n.setProperty("font-weight","bold","important"),t.fontStyle&&n.setProperty("font-style","italic","important"),t.textDecoration&&n.setProperty("text-decoration","underline","important")}clearCell(e){if(e)try{e.classList.remove(this.cssClassName),e.classList.remove("cf-row-formatted"),e.removeAttribute(this.attributeName),e.removeAttribute("data-cf-apply-to"),this._clearFormat(e)}catch(e){}}_clearFormat(e){const t=e.style;t.removeProperty("background-color"),t.removeProperty("color"),t.removeProperty("font-weight"),t.removeProperty("font-style"),t.removeProperty("text-decoration")}clearAll(e){if(e)try{e.querySelectorAll(`.${this.cssClassName}`).forEach((e=>this.clearCell(e)));e.querySelectorAll(".cf-row-formatted").forEach((e=>this.clearCell(e)))}catch(e){}}clearByRule(e,t){if(e&&t)try{const n=`.${this.cssClassName}[${this.attributeName}="${t}"]`;e.querySelectorAll(n).forEach((e=>this.clearCell(e)))}catch(e){}}applyRowLevelBasicFormat(e,t){const n=e.closest("tr")||e.closest(".table-row")||e.parentElement;if(!n)return;const a=n.querySelectorAll("td")||n.querySelectorAll(".table-cell")||n.children;0!==a.length&&Array.from(a).forEach((e=>{this._hasSpecialFormatElements(e)?this._applyBasicFormatOnly(e,t.format):this._applyFormat(e,t.format),e.classList.add(this.cssClassName),e.classList.add("cf-row-formatted"),e.setAttribute(this.attributeName,t.id),e.setAttribute("data-cf-apply-to","row")}))}_hasSpecialFormatElements(e){return[".cf-icon-set",".cf-color-bar",".cf-color-scale",".cf-data-bar","[data-cf-special-format]"].some((t=>null!==e.querySelector(t)))}_applyBasicFormatOnly(e,t){const n=e.style;t.backgroundColor&&n.setProperty("background-color",t.backgroundColor);const a=t.color||"#000000";n.setProperty("color",a,"important"),t.fontWeight&&n.setProperty("font-weight","bold","important"),t.fontStyle&&n.setProperty("font-style","italic","important"),t.textDecoration&&n.setProperty("text-decoration","underline","important")}isFormatted(e){return e&&e.classList.contains(this.cssClassName)}getAppliedRuleId(e){return e?e.getAttribute(this.attributeName):null}previewFormat(e,t){if(e)try{this._clearFormat(e),this._applyFormat(e,t)}catch(e){}}}"undefined"!=typeof window&&(window.ConditionalFormattingApplier=p),function(){const e=window.CF_CONSTANTS||{},{ERROR_TYPES:t,VALIDATION:n,MESSAGES:a,DEFAULT_OPTIONS:r}=e,i=window.CF_UTILS||{},{ErrorHandler:s,ValidationError:o,ValidationUtils:l,InitializationHelper:c,StringUtils:d}=i;class h{constructor(e={}){this.options=c.mergeOptions(e,r),this.errorHandler=new s({logToConsole:!0,throwErrors:!1,onError:this.options.onError}),this.storageKey=e.storageKey||"excelike_cf_rules",this.rules=[],this.nextPriority=1}addRule(e){try{c.checkDependencies({rule:e});const t=e.validate();if(!t.isValid)throw new o(`ルール検証エラー: ${t.errors.join(", ")}`);if(this.rules.length>=this.options.maxRules)throw new o(`ルール数が上限（${this.options.maxRules}）に達しています`);if(this.rules.some((t=>t.id===e.id)))throw new o(`ルールID ${e.id} は既に存在します`);return 0===e.priority&&(e.priority=this.rules.length+1),this.rules.push(e),this.save(),this.errorHandler.success(e)}catch(t){return this.errorHandler.handle("addRule",t,{ruleId:e?.id})}}updateRule(e,t){try{const n=this.rules.findIndex((t=>t.id===e));if(-1===n)throw new o(`ルールID ${e} が見つかりません`);const a=this.rules[n],r=a.toJSON();try{a.update(t);const e=a.validate();if(!e.isValid)throw new o(`更新後のルール検証エラー: ${e.errors.join(", ")}`);return this.save(),this.errorHandler.success(a)}catch(e){throw a.update(r),e}}catch(n){return this.errorHandler.handle("updateRule",n,{ruleId:e,updates:t})}}removeRule(e){try{this.rules.length;const t=this.rules.find((t=>t.id===e));if(!t)throw new o(`ルールID ${e} が見つかりません`);return this.rules=this.rules.filter((t=>t.id!==e)),this.reindexPriorities(),this.errorHandler.success({removedRule:t,totalRules:this.rules.length})}catch(t){return this.errorHandler.handle("removeRule",t,{ruleId:e})}}getRule(e){return this.rules.find((t=>t.id===e))||null}getAllRules(e=!1){return[...e?this.rules.filter((e=>e.enabled)):this.rules].sort(((e,t)=>e.priority-t.priority))}moveRule(e,t){try{const n=this.getAllRules(),a=n.findIndex((t=>t.id===e));if(-1===a)throw new o(`ルールID ${e} が見つかりません`);const r=a+t;if(r<0||r>=n.length)return this.errorHandler.success({moved:!1,reason:"out_of_range"});const i=n[a],s=n[r],l=this.swapRulePriorities(i,s);return l.success?(this.save(),this.errorHandler.success({moved:!0,from:a,to:r,rules:[i.id,s.id]})):l}catch(n){return this.errorHandler.handle("moveRule",n,{ruleId:e,direction:t})}}swapRulePriorities(e,t){try{const n=e.priority;e.priority=t.priority,t.priority=n;const a=Date.now();return e.modified=a,t.modified=a,this.errorHandler.success()}catch(n){return this.errorHandler.handle("swapRulePriorities",n,{rule1Id:e?.id,rule2Id:t?.id})}}reindexPriorities(){[...this.rules].sort(((e,t)=>e.priority-t.priority)).forEach(((e,t)=>{e.priority=t+1,e.modified=Date.now()})),this.nextPriority=this.rules.length+1,this.save()}toggleRule(e){try{const t=this.getRule(e);if(!t)throw new o(`ルールID ${e} が見つかりません`);const n=t.enabled;return t.enabled=!t.enabled,t.modified=Date.now(),this.save(),this.errorHandler.success({ruleId:e,enabled:t.enabled,previousState:n})}catch(t){return this.errorHandler.handle("toggleRule",t,{ruleId:e})}}save(){try{if("undefined"==typeof localStorage)throw new Error("LocalStorage is not available");const e={version:"1.0",timestamp:Date.now(),nextPriority:this.nextPriority,rules:this.rules.map((e=>e.toJSON()))},t=JSON.stringify(e);if(t.length>5242880)throw new Error("保存データが大きすぎます");try{localStorage.setItem(this.storageKey+"_test","test"),localStorage.removeItem(this.storageKey+"_test")}catch(e){throw new Error("LocalStorage write failed: "+e.message)}return localStorage.setItem(this.storageKey,t),this.errorHandler.success({rulesCount:this.rules.length,dataSize:t.length})}catch(e){return"QuotaExceededError"===e.name&&(e.message="LocalStorage quota exceeded. Please clear some data."),this.errorHandler.handle("save",e)}}load(){try{if("undefined"==typeof localStorage)throw new Error("LocalStorage is not available");const e=localStorage.getItem(this.storageKey);if(!e)return this.errorHandler.success({isInitial:!0,rulesLoaded:0});if("string"!=typeof e||""===e.trim())throw new Error("Invalid localStorage data");const t=JSON.parse(e,((e,t)=>{if("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)return t}));if(!t||"object"!=typeof t||!Array.isArray(t.rules))throw new Error("Invalid data structure");return t.version,this.rules=t.rules.map((e=>u.fromJSON(e))),this.validateAndFixPriorities(),this.errorHandler.success({rulesLoaded:this.rules.length,version:t.version})}catch(e){this.rules=[],this.nextPriority=1;try{localStorage.removeItem(this.storageKey)}catch(e){}return this.errorHandler.handle("load",e)}}validateAndFixPriorities(){if(0===this.rules.length)return void(this.nextPriority=1);const e=this.rules.map((e=>e.priority)).sort(((e,t)=>e-t)),t=e.some(((t,n)=>n>0&&t===e[n-1])),n=e.some(((t,n)=>n>0&&t>e[n-1]+1));if(t||n)this.reindexPriorities();else{const t=Math.max(...e);this.nextPriority=t+1}}clear(){try{const e=this.rules.length;return this.rules=[],this.nextPriority=1,localStorage.removeItem(this.storageKey),this.errorHandler.success({clearedRules:e})}catch(e){return this.errorHandler.handle("clear",e)}}getStats(){const e=this.rules.filter((e=>e.enabled)).length,t=this.rules.length-e;return{total:this.rules.length,enabled:e,disabled:t,nextPriority:this.nextPriority,maxRules:this.options.maxRules,storageKey:this.storageKey}}updateOptions(e){this.options=c.mergeOptions(e,this.options),e.onError&&(this.errorHandler.options.onError=e.onError)}}"undefined"!=typeof window&&(window.ConditionalFormattingManager=h)}(),function(){const e=window.CF_CONSTANTS||{},{TIMING:t,COLORS:n,OPERATORS:a,OPERATOR_SYMBOLS:r,DATA_TYPES:i,APPLY_TO:s,UI:o,VALIDATION:l,MESSAGES:c,CSS_CLASSES:d,DEFAULT_OPTIONS:h}=e,p=window.CF_UTILS||{},{ErrorHandler:m,ValidationUtils:f,DOMUtils:g,StringUtils:y,PerformanceUtils:b,ValidationError:v}=p;class S{constructor(e,t){this.cf=e,this.i18n=t,this.currentEditingRule=null,this.isProcessingPriorityChange=!1,this.errorHandler=new m({logToConsole:!0,throwErrors:!1,onError:e=>this.showToast(this.i18n.t("cf.errorSave"),"error")})}showManagementScreen(){try{this.closeAllModals();const e=this.createModal("cf-management-modal").querySelector(".modal");return e.innerHTML=`\n        <div class="modal-header">\n          <h3>${this.i18n.t("cf.title")}</h3>\n          <button class="modal-close-btn" type="button">×</button>\n        </div>\n        <div class="modal-body">\n          <div class="cf-rules-toolbar">\n            <button class="cf-btn cf-btn-primary cf-new-rule-btn" type="button">+ ${this.i18n.t("cf.newRule")}</button>\n            <div class="cf-rules-stats">\n              <span class="cf-stats-text">${this.i18n.t("cf.rulesCount",{count:'<span id="cf-stats-total">0</span>'})}</span>\n            </div>\n          </div>\n          <div class="cf-rules-list" id="cf-rules-list" style="background-color: white;">\n            \x3c!-- ルール一覧がここに動的生成される --\x3e\n          </div>\n        </div>\n        <div class="modal-footer">\n          <button class="btn btn-secondary modal-close-btn" type="button">${this.i18n.t("cf.close")}</button>\n          <button class="btn btn-primary cf-apply-btn" type="button">${this.i18n.t("cf.applyAll")}</button>\n        </div>\n      `,this.attachManagementScreenEvents(e),this.updateRulesList(),e}catch(e){this.errorHandler.handle("showManagementScreen",e)}}attachManagementScreenEvents(e){try{e.querySelectorAll(".modal-close-btn").forEach((e=>{e.addEventListener("click",(()=>this.closeAllModals()))})),e.querySelector(".cf-new-rule-btn").addEventListener("click",(()=>{this.showRuleDialog()})),e.querySelector(".cf-apply-btn").addEventListener("click",(()=>{this.cf.applyRules(),this.showToast(this.i18n.t("cf.rulesApplied"))}));const t=e=>{"Escape"===e.key&&(this.closeAllModals(),document.removeEventListener("keydown",t))};document.addEventListener("keydown",t)}catch(e){this.errorHandler.handle("attachManagementScreenEvents",e)}}updateRulesList(){try{const e=document.getElementById("cf-rules-list"),t=document.getElementById("cf-stats-total");if(!e)return;const n=this.cf.manager.getAllRules();if(t.textContent=n.length,0===n.length)return void(e.innerHTML=`\n          <div class="cf-empty-state">\n            <p>${this.i18n.t("cf.noRules")}</p>\n            <p>${this.i18n.t("cf.clickNewRule")}</p>\n          </div>\n        `);e.innerHTML=n.map(((e,t)=>`\n        <div class="cf-rule-item" data-rule-id="${e.id}">\n          <div class="cf-rule-header">\n            <div class="cf-rule-info">\n              <div class="cf-rule-name">${y.escapeHtml(e.name)}</div>\n              <div class="cf-rule-description">\n                ${this.getRuleDescription(e)} (${this.i18n.t("cf.priority",{priority:e.priority})})\n              </div>\n            </div>\n            <div class="cf-rule-preview">\n              <div class="cf-preview-cell" style="${this.getPreviewStyle(e.format)}">${this.i18n.t("cf.sample")}</div>\n            </div>\n            <div class="cf-rule-actions">\n              <button class="cf-btn-icon cf-edit-btn" title="Edit" data-action="edit" data-rule-id="${e.id}">✏️</button>\n              <button class="cf-btn-icon cf-delete-btn" title="Delete" data-action="delete" data-rule-id="${e.id}">🗑️</button>\n              <button class="cf-btn-icon cf-up-btn" title="Higher Priority" data-action="up" data-rule-id="${e.id}" ${0===t?"disabled":""}>↑</button>\n              <button class="cf-btn-icon cf-down-btn" title="Lower Priority" data-action="down" data-rule-id="${e.id}" ${t===n.length-1?"disabled":""}>↓</button>\n            </div>\n          </div>\n        </div>\n      `)).join(""),this.attachRuleItemEvents(e)}catch(e){this.errorHandler.handle("updateRulesList",e)}}attachRuleItemEvents(e){e.addEventListener("click",(e=>{try{const t=e.target.closest("button[data-action]");if(!t)return;const n=t.dataset.action,a=t.dataset.ruleId;if(!n||!a)return;switch(n){case"edit":const e=this.cf.manager.getRule(a);e&&this.showRuleDialog(e);break;case"delete":this.confirmDeleteRule(a);break;case"up":this.changePriority(a,-1);break;case"down":this.changePriority(a,1)}}catch(e){this.errorHandler.handle("attachRuleItemEvents",e)}}))}showRuleDialog(e=null){try{const t=!!e;this.currentEditingRule=e;const n=this.createModal("cf-rule-dialog").querySelector(".modal"),a=this._getDialogDefaults(e);return n.innerHTML=this._generateDialogHTML(a,t),this.attachRuleDialogEvents(n),this.updatePreview(),n}catch(e){this.errorHandler.handle("showRuleDialog",e)}}_getDialogDefaults(e){return e?{name:e.name,column:e.condition.column,operator:e.condition.operator,value:e.condition.value,dataType:e.condition.dataType,applyTo:e.applyTo||s.CELL,backgroundColor:e.format.backgroundColor||"",color:e.format.color||n.DEFAULT_TEXT_COLOR,fontWeight:e.format.fontWeight||!1,fontStyle:e.format.fontStyle||!1,textDecoration:e.format.textDecoration||!1}:{name:"",column:"",operator:a.EQUALS,value:"",dataType:i.TEXT,applyTo:s.CELL,backgroundColor:"",color:n.DEFAULT_TEXT_COLOR,fontWeight:!1,fontStyle:!1,textDecoration:!1}}_generateDialogHTML(e,t){return`\n      <div class="modal-header">\n        <h3>${t?this.i18n.t("cf.editRule"):this.i18n.t("cf.createRule")}</h3>\n        <button class="modal-close-btn" type="button">×</button>\n      </div>\n      <div class="modal-body">\n        <form class="cf-rule-form" id="cf-rule-form">\n          ${this._generateBasicFields(e)}\n          ${this._generateFormatFields(e)}\n        </form>\n      </div>\n      <div class="modal-footer">\n        <button class="btn btn-secondary modal-close-btn" type="button">${this.i18n.t("cf.cancel")}</button>\n        <button class="btn btn-primary cf-save-btn" type="button">${t?this.i18n.t("cf.update"):this.i18n.t("cf.create")}</button>\n      </div>\n    `}_generateBasicFields(e){return`\n      <div class="cf-form-row">\n        <label class="cf-form-label">${this.i18n.t("cf.ruleName")}:</label>\n        <input type="text" class="cf-form-input" id="cf-rule-name" value="${y.escapeHtml(e.name)}" placeholder="${this.i18n.t("cf.ruleNamePlaceholder")}" required>\n      </div>\n      <div class="cf-form-row">\n        <label class="cf-form-label">${this.i18n.t("cf.column")}:</label>\n        <select class="cf-form-select" id="cf-rule-column" required>\n          <option value="">${this.i18n.t("cf.selectColumn")}</option>\n          ${this.getColumnOptions(e.column)}\n        </select>\n      </div>\n      <div class="cf-form-row">\n        <label class="cf-form-label">${this.i18n.t("cf.operator")}:</label>\n        <select class="cf-form-select" id="cf-rule-operator" required>\n          <option value="${a.EQUALS}" ${e.operator===a.EQUALS?"selected":""}>${this.i18n.t("cf.op.equals")}</option>\n          <option value="${a.NOT_EQUALS}" ${e.operator===a.NOT_EQUALS?"selected":""}>${this.i18n.t("cf.op.notEquals")}</option>\n          <option value="${a.GREATER}" ${e.operator===a.GREATER?"selected":""}>${this.i18n.t("cf.op.greater")}</option>\n          <option value="${a.GREATER_EQUAL}" ${e.operator===a.GREATER_EQUAL?"selected":""}>${this.i18n.t("cf.op.greaterEqual")}</option>\n          <option value="${a.LESS}" ${e.operator===a.LESS?"selected":""}>${this.i18n.t("cf.op.less")}</option>\n          <option value="${a.LESS_EQUAL}" ${e.operator===a.LESS_EQUAL?"selected":""}>${this.i18n.t("cf.op.lessEqual")}</option>\n          <option value="${a.CONTAINS}" ${e.operator===a.CONTAINS?"selected":""}>${this.i18n.t("cf.op.contains")}</option>\n          <option value="${a.NOT_CONTAINS}" ${e.operator===a.NOT_CONTAINS?"selected":""}>${this.i18n.t("cf.op.notContains")}</option>\n        </select>\n      </div>\n      <div class="cf-form-row">\n        <label class="cf-form-label">${this.i18n.t("cf.value")}:</label>\n        <input type="text" class="cf-form-input" id="cf-rule-value" value="${y.escapeHtml(e.value)}" placeholder="${this.i18n.t("cf.valuePlaceholder")}" required>\n      </div>\n      <div class="cf-form-row">\n        <label class="cf-form-label">${this.i18n.t("cf.dataType")}:</label>\n        <select class="cf-form-select" id="cf-rule-datatype" required>\n          <option value="${i.TEXT}" ${e.dataType===i.TEXT?"selected":""}>${this.i18n.t("cf.dataType.text")}</option>\n          <option value="${i.NUMBER}" ${e.dataType===i.NUMBER?"selected":""}>${this.i18n.t("cf.dataType.number")}</option>\n          <option value="${i.DATE}" ${e.dataType===i.DATE?"selected":""}>${this.i18n.t("cf.dataType.date")}</option>\n        </select>\n      </div>\n      <div class="cf-form-row">\n        <label class="cf-form-label">${this.i18n.t("cf.applyTo")}:</label>\n        <select class="cf-form-select" id="cf-rule-applyto" required>\n          <option value="${s.CELL}" ${e.applyTo===s.CELL?"selected":""}>${this.i18n.t("cf.applyTo.cell")}</option>\n          <option value="${s.ROW}" ${e.applyTo===s.ROW?"selected":""}>${this.i18n.t("cf.applyTo.row")}</option>\n        </select>\n      </div>\n    `}_generateFormatFields(e){return`\n      <div class="cf-form-section">\n        <h4>${this.i18n.t("cf.format")}</h4>\n        <div class="cf-form-row">\n          <label class="cf-form-label">${this.i18n.t("cf.backgroundColor")}:</label>\n          <div class="cf-color-input-group">\n            <input type="color" class="cf-color-input" id="cf-bg-color" value="${e.backgroundColor||n.DEFAULT_BACKGROUND_COLOR}">\n            <input type="text" class="cf-form-input cf-color-text" id="cf-bg-color-text" value="${e.backgroundColor||""}" placeholder="${n.DEFAULT_BACKGROUND_COLOR}" style="color: ${e.backgroundColor?n.TEXT_PRIMARY:n.TEXT_DISABLED}">\n          </div>\n        </div>\n        <div class="cf-form-row">\n          <label class="cf-form-label">${this.i18n.t("cf.textColor")}:</label>\n          <div class="cf-color-input-group">\n            <input type="color" class="cf-color-input" id="cf-text-color" value="${e.color||n.DEFAULT_TEXT_COLOR}">\n            <input type="text" class="cf-form-input cf-color-text" id="cf-text-color-text" value="${e.color||n.DEFAULT_TEXT_COLOR}" placeholder="${n.DEFAULT_TEXT_COLOR}" style="color: ${e.color?n.TEXT_PRIMARY:n.TEXT_DISABLED}">\n          </div>\n        </div>\n        <div class="cf-form-row">\n          <label class="cf-form-label">${this.i18n.t("cf.textStyle")}:</label>\n          <div class="cf-checkbox-group">\n            <label class="cf-checkbox-label">\n              <input type="checkbox" id="cf-font-weight" ${e.fontWeight?"checked":""}>\n              <span class="cf-checkbox-custom"></span>\n              ${this.i18n.t("cf.bold")}\n            </label>\n            <label class="cf-checkbox-label">\n              <input type="checkbox" id="cf-font-style" ${e.fontStyle?"checked":""}>\n              <span class="cf-checkbox-custom"></span>\n              ${this.i18n.t("cf.italic")}\n            </label>\n            <label class="cf-checkbox-label">\n              <input type="checkbox" id="cf-text-decoration" ${e.textDecoration?"checked":""}>\n              <span class="cf-checkbox-custom"></span>\n              ${this.i18n.t("cf.underline")}\n            </label>\n          </div>\n        </div>\n        <div class="cf-form-row">\n          <label class="cf-form-label">${this.i18n.t("cf.preview")}:</label>\n          <div class="cf-preview-container">\n            <div class="cf-preview-cell" id="cf-preview">${this.i18n.t("cf.previewSample")}</div>\n          </div>\n        </div>\n      </div>\n    `}attachRuleDialogEvents(e){try{e.querySelectorAll(".modal-close-btn").forEach((e=>{e.addEventListener("click",(()=>{const e=document.querySelector(".cf-rule-dialog");e&&e.remove()}))})),this.setupColorInputs(e);e.querySelectorAll("#cf-bg-color, #cf-bg-color-text, #cf-text-color, #cf-text-color-text, #cf-font-weight, #cf-font-style, #cf-text-decoration").forEach((e=>{e.addEventListener("input",(()=>this.updatePreview())),e.addEventListener("change",(()=>this.updatePreview()))})),e.querySelector(".cf-save-btn").addEventListener("click",(()=>{this.saveRule()})),e.querySelector("#cf-rule-form").addEventListener("submit",(e=>{e.preventDefault(),this.saveRule()}))}catch(e){this.errorHandler.handle("attachRuleDialogEvents",e)}}setupColorInputs(e){try{this.setupColorInput(e,"cf-bg-color","cf-bg-color-text",n.DEFAULT_BACKGROUND_COLOR,!0),this.setupColorInput(e,"cf-text-color","cf-text-color-text",n.DEFAULT_TEXT_COLOR,!1)}catch(e){this.errorHandler.handle("setupColorInputs",e)}}setupColorInput(e,t,a,r,i){const s=e.querySelector(`#${t}`),o=e.querySelector(`#${a}`);s&&o&&(s.addEventListener("input",(()=>{o.value=s.value,o.style.color=n.TEXT_PRIMARY,this.updatePreview()})),o.addEventListener("input",(()=>{const e=y.normalizeColor(o.value);f.validateColor(e)&&(e?(s.value=e,o.style.color=n.TEXT_PRIMARY):i&&(s.value=r,o.style.color=n.TEXT_DISABLED),this.updatePreview())})),o.addEventListener("blur",(()=>{""===o.value&&i&&(s.value=r,o.style.color=n.TEXT_DISABLED)})))}updatePreview(){try{const e=document.getElementById("cf-preview");if(!e)return;const t=this.getFormattingFromUI();e.style.cssText=this.getPreviewStyle(t)}catch(e){this.errorHandler.handle("updatePreview",e)}}getFormattingFromUI(){return{backgroundColor:document.getElementById("cf-bg-color-text")?.value||"",color:document.getElementById("cf-text-color-text")?.value||n.DEFAULT_TEXT_COLOR,fontWeight:document.getElementById("cf-font-weight")?.checked||!1,fontStyle:document.getElementById("cf-font-style")?.checked||!1,textDecoration:document.getElementById("cf-text-decoration")?.checked||!1}}saveRule(){try{const e=document.getElementById("cf-rule-form");if(!e.checkValidity())return void e.reportValidity();const t=this.getFormData();if(f.validateRuleName(t.name),f.validateColor(t.format.backgroundColor),f.validateColor(t.format.color),f.validateValueLength(t.condition.value),this.currentEditingRule)this.cf.manager.updateRule(this.currentEditingRule.id,t),this.showToast(this.i18n.t("cf.ruleUpdated"));else{const e=new u(t);this.cf.manager.addRule(e),this.showToast(this.i18n.t("cf.ruleCreated"))}this.cf.applyRules();const n=document.querySelector(".cf-rule-dialog");n&&n.remove(),this.updateRulesList()}catch(e){e instanceof v?this.showToast(e.message,"error"):(this.errorHandler.handle("saveRule",e),this.showToast(this.i18n.t("cf.errorSave"),"error"))}}getFormData(){const e=document.getElementById("cf-rule-datatype");window.__CF_DEBUG__&&console.log("[CF getFormData] Element check:",{dataTypeElement:e,dataTypeValue:e?.value,dataTypeExists:!!e});const t={name:document.getElementById("cf-rule-name").value.trim(),applyTo:document.getElementById("cf-rule-applyto").value,condition:{column:document.getElementById("cf-rule-column").value,operator:document.getElementById("cf-rule-operator").value,value:document.getElementById("cf-rule-value").value.trim(),dataType:e?.value||"text"},format:{backgroundColor:document.getElementById("cf-bg-color-text").value.trim(),color:document.getElementById("cf-text-color-text").value.trim()||n.DEFAULT_TEXT_COLOR,fontWeight:document.getElementById("cf-font-weight").checked,fontStyle:document.getElementById("cf-font-style").checked,textDecoration:document.getElementById("cf-text-decoration").checked}};return window.__CF_DEBUG__&&console.log("[CF getFormData] Result:",{dataType:t.condition.dataType,fullCondition:t.condition}),t}getColumnOptions(e=""){return this.cf.getTableColumns().map((t=>`\n      <option value="${t.key}" ${t.key===e?"selected":""}>\n        ${y.escapeHtml(t.title||t.key)}\n      </option>\n    `)).join("")}getRuleDescription(e){const t=r[e.condition.operator]||e.condition.operator,n=e.applyTo===s.ROW?` (${this.i18n.t("cf.applyTo.row").toLowerCase()})`:` (${this.i18n.t("cf.applyTo.cell").toLowerCase()})`;return`${e.condition.column} ${t} "${e.condition.value}"${n}`}getPreviewStyle(e){let t="padding: 4px 8px; border: 1px solid #ddd; display: inline-block; min-width: 60px; text-align: center;";e.backgroundColor&&(t+=`background-color: ${e.backgroundColor};`);return t+=`color: ${e.color||n.DEFAULT_TEXT_COLOR};`,e.fontWeight&&(t+="font-weight: bold;"),e.fontStyle&&(t+="font-style: italic;"),e.textDecoration&&(t+="text-decoration: underline;"),t}confirmDeleteRule(e){try{if(!this.cf.manager.getRule(e))return;this.cf.manager.removeRule(e),this.updateRulesList(),this.cf.applyRules(),this.showToast(this.i18n.t("cf.ruleDeleted"))}catch(e){this.errorHandler.handle("confirmDeleteRule",e)}}changePriority(e,n){try{if(this.isProcessingPriorityChange)return;this.isProcessingPriorityChange=!0;this.cf.manager.moveRule(e,n)&&(this.updateRulesList(),this.cf.applyRules(),this.showToast(this.i18n.t("cf.priorityUpdated")))}catch(e){this.errorHandler.handle("changePriority",e)}finally{setTimeout((()=>{this.isProcessingPriorityChange=!1}),t.PRIORITY_CHANGE_DELAY)}}createModal(e){const t=document.createElement("div");t.className=`${d.MODAL_OVERLAY} ${e}`;const n=document.createElement("div");return n.className=`${d.MODAL} ${d.MODAL_LARGE}`,t.appendChild(n),document.body.appendChild(t),t.addEventListener("click",(e=>{e.target===t&&(t.classList.contains("cf-rule-dialog")?t.remove():this.closeAllModals())})),t}closeAllModals(){document.querySelectorAll(`.${d.MODAL_OVERLAY}`).forEach((e=>e.remove())),this.currentEditingRule=null}showToast(e,n="success"){try{const a=document.createElement("div");a.className=`${d.TOAST} ${d[`TOAST_${n.toUpperCase()}`]}`,a.textContent=e,a.style.zIndex=o.TOAST_Z_INDEX,document.body.appendChild(a),setTimeout((()=>a.classList.add(d.TOAST_SHOW)),t.TOAST_FADEIN_DELAY),setTimeout((()=>{a.classList.remove(d.TOAST_SHOW),setTimeout((()=>{g.safeRemove(a)}),t.TOAST_FADEOUT_DURATION)}),t.TOAST_DISPLAY_DURATION)}catch(e){}}}"undefined"!=typeof window&&(window.ConditionalFormattingUI=S)}(),function(){const e=window.CF_CONSTANTS||{},t=window.CF_UTILS||{},{TIMING:n,DEFAULT_OPTIONS:a,CSS_CLASSES:r,MESSAGES:i,ERROR_TYPES:s}=e,{ErrorHandler:o,ValidationUtils:l,DOMUtils:c,PerformanceUtils:d,InitializationHelper:m}=t;class f{constructor(e,t={}){this.table=e,this.options=m.mergeOptions(t,a);const r=e.tableId||"default";this.options.storageKey=t.storageKey||`excelike_${r}_cf_rules`,this.options.autoLoad=!1!==t.autoLoad,this.options.autoApply=!1!==t.autoApply,this.errorHandler=new o({logToConsole:!0,throwErrors:this.options.throwErrors||!1,onError:this.options.onError}),this.batchDOM=new window.CF_PERFORMANCE.BatchDOMOperations,this.cellCache=new window.CF_PERFORMANCE.OptimizedCellCache(1e3),this.evaluationCache=new window.CF_PERFORMANCE.RuleEvaluationCache(500),this.manager=new ConditionalFormattingManager({storageKey:this.options.storageKey}),this.evaluator=new h,this.applier=new p,this.ui=new ConditionalFormattingUI(this,this.table.i18n),this.isInitialized=!1,this.debouncedApply=d.debounce((()=>this.applyRules()),n.MUTATION_DEBOUNCE),this.init()}init(){if(!this.isInitialized)try{this.validateDependencies(),this.options.autoLoad&&this.manager.load(),this.attachTableEvents(),this.isInitialized=!0,this.options.autoApply&&setTimeout((()=>{this.applyRules()}),n.INITIAL_APPLY_DELAY)}catch(e){if(this.errorHandler.handle("initialization",e,{table:!!this.table,options:this.options}),this.options.throwErrors)throw e}}validateDependencies(){const e={ConditionalFormattingRule:window.ConditionalFormattingRule,ConditionalFormattingManager:window.ConditionalFormattingManager,ConditionalFormattingEvaluator:window.ConditionalFormattingEvaluator,ConditionalFormattingApplier:window.ConditionalFormattingApplier,ConditionalFormattingUI:window.ConditionalFormattingUI,table:this.table};m.checkDependencies(e)}attachTableEvents(){if(this.table.container)try{this.options.autoApply&&"function"==typeof this.table.on&&this.table.on("dataChanged",(()=>{this.debouncedApply()})),this.observeTableChanges()}catch(e){this.errorHandler.handle("attachTableEvents",e,{hasContainer:!!this.table.container,hasOnMethod:"function"==typeof this.table.on})}}observeTableChanges(){if(this.table.container&&"undefined"!=typeof MutationObserver)try{this.observer=new MutationObserver((e=>{let t=!1;e.forEach((e=>{if("childList"===e.type&&e.addedNodes.length>0){Array.from(e.addedNodes).some((e=>e.nodeType===Node.ELEMENT_NODE&&(e.classList.contains("table-cell")||e.querySelector(".table-cell"))))&&(t=!0,this.cellCache.clear(),this.evaluationCache.clear())}})),t&&this.options.autoApply&&this.debouncedApply()})),this.observer.observe(this.table.container,{childList:!0,subtree:!0}),this.options.autoApply&&setTimeout((()=>{this.findTableCells().length>0&&this.applyRules()}),n.REAPPLY_DELAY)}catch(e){this.errorHandler.handle("observeTableChanges",e,{hasMutationObserver:"undefined"!=typeof MutationObserver})}}findTableCells(e=!1){if(!this.table.container)return[];const t=this.cellCache.get(this.table.container,e);return t?t.cells:[]}extractCellInfo(e){return this.extractCellInfoFromElement(e)}extractCellInfoFromElement(e){try{const t=e.dataset.column||e.dataset.key;if(!t)return null;return{element:e,column:t,value:this.extractCellValue(e)}}catch(t){return this.errorHandler.handle("extractCellInfo",t,{hasDataset:!!e.dataset,tagName:e.tagName}),null}}extractCellValue(e,t="text"){return"text"===t?e.textContent?.trim()||"":void 0!==e.dataset.value?e.dataset.value:e.textContent?.trim()||""}getTableCells(){try{const e=this.cellCache.get(this.table.container);return e?e.cells.map((e=>({element:e.element,column:e.column,value:e.value}))).filter((e=>e.column)):[]}catch(e){return this.errorHandler.handle("getTableCells",e,{containerExists:!!this.table.container}),[]}}applyRules(){try{this.clearAllFormatting();const e=this._getValidSortedRules();if(!e)return this.errorHandler.success({applied:0,message:"Invalid rules detected"});if(0===e.length)return this.errorHandler.success({applied:0,message:"No rules to apply"});const t=this.getTableCells();if(0===t.length)return this.errorHandler.success({applied:0,message:"No cells found"});const n=this._applyRulesToCells(e,t);return this.batchDOM.flush(),this.errorHandler.success({applied:n,rules:e.length,message:`Conditional formatting applied to ${n} cells using ${e.length} rules`})}catch(e){return this.errorHandler.handle("applyRules",e,{rulesCount:this.manager.getAllRules().length,containerExists:!!this.table.container})}}_getValidSortedRules(){const e=this.manager.getAllRules(!0);return e.filter((e=>e.condition.column.startsWith("column_"))).length>0?null:e.sort(((e,t)=>t.priority-e.priority))}_applyRulesToCells(e,t){let n=0;return e.forEach((e=>{t.forEach((t=>{let a=!1;if("cell"===e.applyTo&&t.column===e.condition.column){const n=this.extractCellValue(t.element,e.condition.dataType);this._evaluateRuleWithCache(n,e)&&(a=!0)}else if("row"===e.applyTo){const n=this._getRowCells(t.element).find((t=>t.column===e.condition.column));if(n){const t=this.extractCellValue(n.element,e.condition.dataType);this._evaluateRuleWithCache(t,e)&&(a=!0)}}a&&(this.applier.applyToCell(t.element,e),n++)}))})),n}_getCellKey(e){const t=e.closest("tr");return`${t?Array.from(t.parentNode.children).indexOf(t):0}-${Array.from(t.children).indexOf(e)}`}_getRowCells(e){const t=e.closest("tr");if(!t)return[];return Array.from(t.children).map((e=>this.extractCellInfoFromElement(e))).filter((e=>null!==e))}_evaluateRuleWithCache(e,t){const n=this.evaluationCache.get(t.id,e,t.condition.operator);if(void 0!==n)return n;const a=this.evaluator.evaluate(e,t);return this.evaluationCache.set(t.id,e,t.condition.operator,a),a}showManagementScreen(){try{return this.ui.showManagementScreen()}catch(e){return this.errorHandler.handle("showManagementScreen",e)}}clearAllRules(){try{return this.manager.clear(),this.clearAllFormatting(),this.errorHandler.success({message:i.RULES_APPLIED})}catch(e){return this.errorHandler.handle("clearAllRules",e)}}showCreateDialog(){try{return this.ui.showRuleDialog()}catch(e){return this.errorHandler.handle("showCreateDialog",e)}}showEditDialog(e){try{const t=this.manager.getRule(e);if(!t)throw new Error(`Rule not found: ${e}`);return this.ui.showRuleDialog(t)}catch(t){return this.errorHandler.handle("showEditDialog",t,{ruleId:e})}}clearAllFormatting(){try{this.table.container&&this.applier.clearAll(this.table.container)}catch(e){this.errorHandler.handle("clearAllFormatting",e)}}clearRuleFormatting(e){try{this.table.container&&this.applier.clearByRule(this.table.container,e)}catch(t){this.errorHandler.handle("clearRuleFormatting",t,{ruleId:e})}}getTableColumns(){try{if(!this.table.options||!this.table.options.columns)throw new Error("Table options or columns not found. Cannot get column information.");return this.table.options.columns}catch(e){return this.errorHandler.handle("getTableColumns",e),[]}}createRule(e){try{l.validateRuleName(e.name);const t=new u(e),n=this.manager.addRule(t);return n&&this.options.autoApply&&this.applyRules(),n?this.errorHandler.success(t):this.errorHandler.handle("createRule",new Error("Failed to add rule"),{config:e})}catch(t){return this.errorHandler.handle("createRule",t,{config:e})}}updateRule(e,t){try{t.name&&l.validateRuleName(t.name);const n=this.manager.updateRule(e,t);return n&&this.options.autoApply&&this.applyRules(),n?this.errorHandler.success({updated:!0}):this.errorHandler.handle("updateRule",new Error("Failed to update rule"),{ruleId:e,updates:t})}catch(n){return this.errorHandler.handle("updateRule",n,{ruleId:e,updates:t})}}deleteRule(e){try{this.clearRuleFormatting(e);const t=this.manager.removeRule(e);return t&&this.options.autoApply&&this.applyRules(),t?this.errorHandler.success({deleted:!0}):this.errorHandler.handle("deleteRule",new Error("Failed to delete rule"),{ruleId:e})}catch(t){return this.errorHandler.handle("deleteRule",t,{ruleId:e})}}getRules(e=!1){try{return this.errorHandler.success(this.manager.getAllRules(e))}catch(t){return this.errorHandler.handle("getRules",t,{enabledOnly:e})}}getRule(e){try{const t=this.manager.getRule(e);return t?this.errorHandler.success(t):this.errorHandler.handle("getRule",new Error("Rule not found"),{ruleId:e})}catch(t){return this.errorHandler.handle("getRule",t,{ruleId:e})}}getStats(){try{const e={rules:this.manager.getStats(),appliedCells:this.table.container?.querySelectorAll(`.${r.FORMATTED}`).length||0};return this.errorHandler.success(e)}catch(e){return this.errorHandler.handle("getStats",e)}}updateOptions(e){try{return this.options=m.mergeOptions(this.options,e),e.storageKey&&this.manager.storageKey!==e.storageKey&&(this.manager.storageKey=e.storageKey,this.options.autoLoad&&(this.manager.load(),this.options.autoApply&&this.applyRules())),this.errorHandler.success({updated:!0})}catch(t){return this.errorHandler.handle("updateOptions",t,{newOptions:e})}}destroy(){try{return this.observer&&(this.observer.disconnect(),this.observer=null),this.batchDOM&&this.batchDOM.flush(),this.cellCache&&this.cellCache.clear(),this.evaluationCache&&this.evaluationCache.clear(),this.clearAllFormatting(),this.ui&&this.ui.closeAllModals(),this.isInitialized=!1,this.errorHandler.success({destroyed:!0})}catch(e){return this.errorHandler.handle("destroy",e)}}}"undefined"!=typeof window&&(window.ConditionalFormatting=f)}();const m={FONT_SIZES:{smallest:"10px",small:"12px",medium:"14px",large:"18px",largest:"22px"},CELL_PADDING:{wide:{vertical:"12px",horizontal:"8px"},standard:{vertical:"8px",horizontal:"6px"},narrow:{vertical:"2px",horizontal:"2px"}},SIZES:{MIN_COLUMN_WIDTH:50,AUTO_RESIZE_MIN:80,AUTO_RESIZE_MAX:400,DOUBLE_CLICK_THRESHOLD:300,TOOLTIP_OFFSET:{x:15,y:40}},Z_INDEXES:{TOOLTIP:1e4,FILTER_DROPDOWN:9999,PINNED_HEADER:101,PINNED_CELL:100},TIMING:{TOOLTIP_FADE:200,DEBOUNCE_RESIZE:100}},f={text:(e,t,n={})=>({key:e,title:t,dataIndex:e,width:n.width||150,sortable:!1!==n.sortable,filterable:!1!==n.filterable,...n}),number:(e,t,n={})=>({key:e,title:t,dataIndex:e,width:n.width||120,sortable:!1!==n.sortable,filterable:!1!==n.filterable,render:n.render||(e=>"number"==typeof e?n.currency?`${n.currency}${e.toLocaleString()}`:e.toLocaleString():e),...n}),date:(e,t,n={})=>({key:e,title:t,dataIndex:e,type:"date",width:n.width||130,sortable:!1!==n.sortable,filterable:!1!==n.filterable,filterType:"date-hierarchy",render:n.render||(e=>e?new Date(e).toLocaleDateString():""),...n}),status:(e,t,n={},a={})=>({key:e,title:t,dataIndex:e,width:a.width||100,sortable:!1!==a.sortable,filterable:!1!==a.filterable,render:(e,t,a,r)=>{const i=n[e]||"#000";return r&&(r.style.color=i,r.style.fontWeight="500"),e},...a}),actions:(e,t,n={})=>({key:"actions",title:e||"Actions",dataIndex:"actions",width:n.width||120,sortable:!1,filterable:!1,render:(e,n)=>t.map((e=>`<button class="action-btn" data-action="${e.key}" data-id="${n.id||n.key}">${e.label}</button>`)).join(" "),...n})},g={getDecimalPlaces(e){let t=0;return e.forEach((e=>{if("number"==typeof e&&!Number.isInteger(e)){const n=e.toString().split(".")[1]?.length||0;t=Math.max(t,n)}})),t},formatNumberValue:(e,t)=>"number"!=typeof e?e:t>0?e.toFixed(t):Math.round(e).toString(),isNumericColumn:(e,t)=>t.slice(0,10).every((t=>{const n=t[e.dataIndex];return null==n||""===n||!isNaN(Number(n))})),isDateValue(e){if(!e)return!1;const t=new Date(e);return t instanceof Date&&!isNaN(t)&&e.toString().match(/^\d{4}-\d{2}-\d{2}/)},getCheckedFilterValues:(e,t=!0)=>Array.from(e.querySelectorAll(".filter-checkbox:checked")).map((e=>e.dataset.value)).filter((e=>!t||"__all__"!==e)),updateSelectAllState(e,t){const n=Array.from(t).filter((e=>e.checked)).length,a=t.length;0===n?(e.checked=!1,e.indeterminate=!1):n===a?(e.checked=!0,e.indeterminate=!1):(e.checked=!1,e.indeterminate=!0)},pxToCm:e=>(2.54*e/(96*window.devicePixelRatio)).toFixed(2),constrainToViewport(e,t,n,a=0,r=0){const i=e.getBoundingClientRect(),s=window.innerWidth-i.width-10,o=window.innerHeight-i.height-10;return{x:Math.max(10,Math.min(t+a,s)),y:Math.max(10,Math.min(n+r,o))}}};class y{constructor(){this.storage=localStorage}async save(e,t){try{return this.storage.setItem(e,JSON.stringify(t)),!0}catch(e){return console.warn("Failed to save table settings:",e),!1}}async load(e){try{const t=this.storage.getItem(e);return t?JSON.parse(t):null}catch(e){return console.warn("Failed to load table settings:",e),null}}async remove(e){try{return this.storage.removeItem(e),!0}catch(e){return console.warn("Failed to remove table settings:",e),!1}}isAvailable(){try{const e="__table_storage_test__";return this.storage.setItem(e,"test"),this.storage.removeItem(e),!0}catch{return!1}}}class b{constructor(e,t=null){this.tableId=e,this.storageAdapter=t||new y,this.storageKey=`excelike_table_${e}`}extractSettings(e){const t={};for(const[n,a]of Object.entries(e.state.columnWidths||{})){const e=Math.max(50,Math.min(2e3,a));t[n]=e}const n=this.validateFilterState(e.state);return{columnWidths:t,visibleColumns:{...e.state.visibleColumns},pinnedColumns:{...e.state.pinnedColumns},filters:n.filters,rangeFilters:n.rangeFilters,dateRangeFilters:n.dateRangeFilters,filterModes:n.filterModes,rangeIncludeBlanks:n.rangeIncludeBlanks,dateRangeIncludeBlanks:n.dateRangeIncludeBlanks,sortColumn:e.state.sortColumn,sortOrder:e.state.sortOrder,fontSize:e.state.fontSize,cellPadding:e.state.cellPadding,pageSize:e.state.pageSize,language:e.i18n.getLocale(),version:"1.0.0",timestamp:Date.now()}}validateFilterState(e){const t={filters:{},rangeFilters:{},dateRangeFilters:{},filterModes:{},rangeIncludeBlanks:{},dateRangeIncludeBlanks:{}};return new Set([...Object.keys(e.filters||{}),...Object.keys(e.rangeFilters||{}),...Object.keys(e.dateRangeFilters||{}),...Object.keys(e.filterModes||{})]).forEach((n=>{const a=e.filterModes?.[n];"range"===a?e.rangeFilters?.[n]?(t.rangeFilters[n]=e.rangeFilters[n],t.filterModes[n]="range",void 0!==e.rangeIncludeBlanks?.[n]&&(t.rangeIncludeBlanks[n]=e.rangeIncludeBlanks[n])):e.dateRangeFilters?.[n]&&(t.dateRangeFilters[n]=e.dateRangeFilters[n],t.filterModes[n]="range",void 0!==e.dateRangeIncludeBlanks?.[n]&&(t.dateRangeIncludeBlanks[n]=e.dateRangeIncludeBlanks[n])):"values"===a?e.filters?.[n]&&(t.filters[n]=e.filters[n],t.filterModes[n]="values"):e.rangeFilters?.[n]?(t.rangeFilters[n]=e.rangeFilters[n],t.filterModes[n]="range",void 0!==e.rangeIncludeBlanks?.[n]&&(t.rangeIncludeBlanks[n]=e.rangeIncludeBlanks[n])):e.dateRangeFilters?.[n]?(t.dateRangeFilters[n]=e.dateRangeFilters[n],t.filterModes[n]="range",void 0!==e.dateRangeIncludeBlanks?.[n]&&(t.dateRangeIncludeBlanks[n]=e.dateRangeIncludeBlanks[n])):e.filters?.[n]&&(t.filters[n]=e.filters[n],t.filterModes[n]="values")})),t}applySettings(e,t){if(!t||!this.isValidSettings(t))return!1;try{t.columnWidths&&Object.assign(e.state.columnWidths,t.columnWidths),t.visibleColumns&&Object.assign(e.state.visibleColumns,t.visibleColumns),t.pinnedColumns&&Object.assign(e.state.pinnedColumns,t.pinnedColumns);const n={filters:t.filters||{},rangeFilters:t.rangeFilters||{},dateRangeFilters:t.dateRangeFilters||{},filterModes:t.filterModes||{},rangeIncludeBlanks:t.rangeIncludeBlanks||{},dateRangeIncludeBlanks:t.dateRangeIncludeBlanks||{}},a=this.validateFilterState(n);return e.state.filters=a.filters,e.state.rangeFilters=a.rangeFilters,e.state.dateRangeFilters=a.dateRangeFilters,e.state.filterModes=a.filterModes,e.state.rangeIncludeBlanks=a.rangeIncludeBlanks,e.state.dateRangeIncludeBlanks=a.dateRangeIncludeBlanks,t.sortColumn&&(e.state.sortColumn=t.sortColumn),t.sortOrder&&(e.state.sortOrder=t.sortOrder),t.fontSize&&(e.state.fontSize=t.fontSize),t.cellPadding&&(e.state.cellPadding=t.cellPadding),t.pageSize&&(e.state.pageSize=t.pageSize),t.language&&e.i18n.setLocale(t.language),!0}catch(e){return console.warn("Failed to apply table settings:",e),!1}}isValidSettings(e){if(!e||"object"!=typeof e||!e.version||!e.timestamp)return!1;if(e.columnWidths)for(const[t,n]of Object.entries(e.columnWidths))if("number"!=typeof n||n<50||n>2e3)return console.warn(`Invalid column width for ${t}: ${n}. Must be between 50-2000px`),!1;return!0}async saveSettings(e){if(!this.storageAdapter.isAvailable())return!1;const t=this.extractSettings(e);return await this.storageAdapter.save(this.storageKey,t)}async loadSettings(e){if(!this.storageAdapter.isAvailable())return!1;const t=await this.storageAdapter.load(this.storageKey);return!!t&&(this.isValidSettings(t)?this.applySettings(e,t):(console.warn("TableSettingsManager: Invalid settings detected, clearing storage"),await this.storageAdapter.remove(this.storageKey),!1))}async clearSettings(){return await this.storageAdapter.remove(this.storageKey)}}const v={autoIdCounter:0,generateTableId(e,t){if(t.tableId)return t.tableId;if(e.id)return e.id;const n=this.getStableSelector(e),a=this.simpleHash(n);return"undefined"!=typeof process&&process.env&&"development"===process.env.NODE_ENV&&console.warn(`[ExceLikeTable] tableId not specified. Generated ID from selector: table_${a}\nRecommendation: Set tableId option or add id attribute to container element.`),`table_${a}`},getStableSelector(e){const t=[];let n=e;for(;n&&n!==document.body&&n!==document.documentElement;){let e=n.tagName.toLowerCase();if(n.className&&"string"==typeof n.className){const t=n.className.split(" ").filter((e=>e&&!e.startsWith("excelike-")));t.length>0&&(e+=`.${t.join(".")}`)}if(n.dataset){Object.keys(n.dataset).filter((e=>!e.startsWith("excelike"))).slice(0,2).forEach((t=>{e+=`[data-${t}]`}))}t.unshift(e),n=n.parentElement}return t.join(" > ")},simpleHash(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(36)},getStorageKey:(e,t)=>`excelike_${e}_${t}`};class S{constructor(e,t={}){if(!e)throw new Error("Container element is required");if(this.container="string"==typeof e?document.querySelector(e):e,!this.container)throw new Error("Container element not found");const n=v.generateTableId(this.container,t);this.options={data:t.data||[],columns:t.columns||[],rowKey:t.rowKey||"id",renderCellHTML:t.renderCellHTML||!1,pagination:!1!==t.pagination&&{pageSize:10,showSizeChanger:!0,showTotal:null,current:1,..."object"==typeof t.pagination?t.pagination:{}},bordered:!1!==t.bordered,size:t.size||"middle",loading:t.loading||!1,tableId:n,persistSettings:!1!==t.persistSettings,storageAdapter:t.storageAdapter||null,locale:t.locale,i18nMessages:t.i18nMessages},this.tableId=this.options.tableId,this.settingsManager=null,this.options.persistSettings&&(this.settingsManager=new b(this.tableId,this.options.storageAdapter)),this.i18n=Object.create(r),this.i18n.init({locale:t.locale||"en",messages:t.i18nMessages||{}}),this.themeManager=new s(this.tableId);const a=this._deepCopyData(this.options.data||[]);this.state={data:a,filteredData:[...a],filters:{},filterModes:{},sortState:{column:null,direction:null},currentPage:this.options.pagination&&this.options.pagination.current||1,pageSize:this.options.pagination&&this.options.pagination.pageSize||10,columnWidths:{},visibleColumns:{},pinnedColumns:{},openFilter:null,rangeFilters:{},dateRangeFilters:{},fontSize:"medium",cellPadding:"standard"},this.initializeColumns(),this.handleSort=this.handleSort.bind(this),this.handleFilter=this.handleFilter.bind(this),this.handlePageChange=this.handlePageChange.bind(this),this.handleColumnResize=this.handleColumnResize.bind(this),this.handleColumnToggle=this.handleColumnToggle.bind(this),this.handleColumnPin=this.handleColumnPin.bind(this),this.init()}initializeColumns(){this.options.columns.forEach((e=>{if(void 0===e.sortable&&(e.sortable=!0),void 0===e.filterable&&(e.filterable=!0),void 0===e.filterType&&this.options.data&&this.options.data.length>0){this.options.data.slice(0,10).map((t=>t[e.dataIndex])).some((e=>e&&g.isDateValue(e)))&&(e.filterType="date-hierarchy")}this.state.columnWidths[e.key]=e.width||150,this.state.visibleColumns[e.key]=!0!==e.hidden,this.state.pinnedColumns[e.key]=!0===e.pinned}))}getColumnWidth(e){return this.state.columnWidths[e.key]||e.width||150}getOrderedColumns(){const e=this.getVisibleColumns(),t=e.filter((e=>this.state.pinnedColumns[e.key])),n=e.filter((e=>!this.state.pinnedColumns[e.key]));return{all:[...t,...n],pinned:t,unpinned:n}}getColumnWidth(e){return this.state.columnWidths[e.key]||e.width||150}getLastPinnedColumnKey(){const e=this.getOrderedColumns();return e.pinned.length>0?e.pinned[e.pinned.length-1].key:null}calculateAllColumnPositions(){const e=this.getOrderedColumns(),t={};let n=0;return e.all.forEach((e=>{const a=this.getColumnWidth(e);t[e.key]={left:n,width:a,isPinned:this.state.pinnedColumns[e.key]||!1},n+=a})),t}applyColumnStyles(e,t,n){const a=n[t.key];if(a&&(e.style.width=`${a.width}px`,a.isPinned)){e.classList.add("pinned-column"),e.style.setProperty("--pinned-left",`${a.left}px`);const n=this.getLastPinnedColumnKey();t.key===n&&e.classList.add("last-pinned-column")}}calculateColumnPositions(e){const t={};let n=0;return e.forEach((e=>{t[e.key]=n;const a=this.getColumnWidth(e);n+=a})),t}updateColumnWidth(e,t){this.state.columnWidths[e]=t,this.applyColumnWidthToDOM(e,t),this.updateAllPinnedPositions(),this.saveStateDebounced&&this.saveStateDebounced()}applyColumnWidthToDOM(e,t){const n=this.container.querySelectorAll("th.table-header");let a=-1;if(n.forEach(((t,n)=>{const r=t.querySelector(".resize-handle");r&&r.dataset.column===e&&(a=n)})),-1===a)return;const r=n[a];r&&(r.style.width=`${t}px`,r.style.minWidth=`${t}px`,r.style.maxWidth=`${t}px`);this.container.querySelectorAll(`tbody td:nth-child(${a+1})`).forEach((e=>{e.style.width=`${t}px`,e.style.minWidth=`${t}px`,e.style.maxWidth=`${t}px`}))}updateAllPinnedPositions(){const e=this.container.querySelectorAll("th.table-header");if(0===e.length)return;let t=0;const n=[];e.forEach(((e,a)=>{n[a]=t,t+=e.offsetWidth})),this.applyPinnedPositions(n)}applyPinnedPositions(e){this.container.querySelectorAll("th.pinned-column").forEach((t=>{const n=Array.from(t.parentNode.children).indexOf(t);void 0!==e[n]&&t.style.setProperty("--pinned-left",`${e[n]}px`)}));this.container.querySelectorAll("tbody tr").forEach((t=>{t.querySelectorAll("td.pinned-column").forEach((t=>{const n=Array.from(t.parentNode.children).indexOf(t);void 0!==e[n]&&t.style.setProperty("--pinned-left",`${e[n]}px`)}))}))}initializePersistence(){const e=this.options.tableId||"default";this.storageKey=`excelike-table-${e}-state`,this.saveStateDebounced=this.debounce((()=>this.saveState()),300),window.addEventListener("beforeunload",(()=>this.saveState()))}saveState(){try{const e={version:"1.1.0",timestamp:Date.now(),columnState:{widths:this.state.columnWidths,pinned:Object.keys(this.state.pinnedColumns).filter((e=>this.state.pinnedColumns[e]))},filterState:{filters:this.state.filters,rangeFilters:this.state.rangeFilters,dateRangeFilters:this.state.dateRangeFilters,filterModes:this.state.filterModes},sortState:{column:this.state.sortState.column,direction:this.state.sortState.direction}};localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){if("QuotaExceededError"===e.name){this.cleanupOldStorageData();try{localStorage.setItem(this.storageKey,JSON.stringify(state))}catch(e){}}}}loadState(){try{const e=localStorage.getItem(this.storageKey);if(!e)return!1;if("string"!=typeof e||""===e.trim())throw new Error("Invalid localStorage data");const t=JSON.parse(e,((e,t)=>{if("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)return t}));if(!t||"object"!=typeof t)throw new Error("Invalid state structure");if("1.0.0"===t.version||"1.1.0"===t.version)return this.applyLoadedState(t),!0}catch(e){try{localStorage.removeItem(this.storageKey)}catch(e){}}return!1}applyLoadedState(e){if(e.columnState&&(e.columnState.widths&&Object.entries(e.columnState.widths).forEach((([e,t])=>{this.options.columns.find((t=>t.key===e))&&(this.state.columnWidths[e]=t,this.applyColumnWidthToDOM(e,t))})),void 0!==e.columnState.pinned&&(this.options.columns.forEach((e=>{this.state.pinnedColumns[e.key]=!1})),Array.isArray(e.columnState.pinned)&&e.columnState.pinned.forEach((e=>{this.options.columns.find((t=>t.key===e))&&(this.state.pinnedColumns[e]=!0)})))),"1.1.0"===e.version&&e.filterState&&(e.filterState.filters&&Object.entries(e.filterState.filters).forEach((([e,t])=>{this.options.columns.find((t=>t.key===e))&&(this.state.filters[e]=t)})),e.filterState.rangeFilters&&Object.entries(e.filterState.rangeFilters).forEach((([e,t])=>{this.options.columns.find((t=>t.key===e))&&(this.state.rangeFilters[e]=t)})),e.filterState.dateRangeFilters&&Object.entries(e.filterState.dateRangeFilters).forEach((([e,t])=>{this.options.columns.find((t=>t.key===e))&&(this.state.dateRangeFilters[e]=t)})),e.filterState.filterModes&&Object.entries(e.filterState.filterModes).forEach((([e,t])=>{this.options.columns.find((t=>t.key===e))&&(this.state.filterModes[e]=t)}))),"1.1.0"===e.version&&e.sortState){const{column:t,direction:n}=e.sortState;t&&n&&this.options.columns.find((e=>e.key===t))&&(this.state.sortState={column:t,direction:n})}}cleanupOldStorageData(){const e=Object.keys(localStorage).filter((e=>e.startsWith("excelike-table-"))).map((e=>{try{return{key:e,timestamp:JSON.parse(localStorage.getItem(e)).timestamp||0}}catch{return{key:e,timestamp:0}}})).sort(((e,t)=>e.timestamp-t.timestamp)),t=Math.floor(e.length/2);for(let n=0;n<t;n++)localStorage.removeItem(e[n].key)}debounce(e,t){let n;return function(...a){clearTimeout(n),n=setTimeout((()=>{clearTimeout(n),e(...a)}),t)}}checkFixedHeight(){const e=getComputedStyle(this.container);e.height&&"auto"!==e.height&&"0px"!==e.height&&setTimeout((()=>{const e=this.tableContainer.querySelector(".table-container");e&&e.classList.add("fixed-height")}),0)}initializePluginSystem(){try{void 0!==l?this.pluginSystem=l.init(this):console.warn("[ExceLikeTable] PluginSystem not available")}catch(e){console.error("[ExceLikeTable] Plugin system initialization failed:",e),this.pluginSystem=null}}async init(){try{e?e.clearElement(this.container):this.container.innerHTML="",this.container.className="excelike-table-wrapper",this.initializePluginSystem(),this.initializePersistence(),this.createStructure(),this.settingsManager&&await this.loadSettings(),this.loadState(),this.render(),this.attachEvents(),this.initializeConditionalFormatting()}catch(e){throw console.error("[ExceLikeTable] Initialization failed:",e),e}}createStructure(){if(this.tableContainer=document.createElement("div"),this.tableContainer.className="excelike-table",this.checkFixedHeight(),this.loadingOverlay=document.createElement("div"),this.loadingOverlay.className="table-loading",this.loadingOverlay.style.display=this.options.loading?"flex":"none",e){const t=e.createElement("div","Loading...");this.loadingOverlay.appendChild(t)}else this.loadingOverlay.innerHTML="<div>Loading...</div>";this.menuContainer=document.createElement("div"),this.menuContainer.className="table-menu-container",this.tableWrapper=document.createElement("div"),this.tableWrapper.className="table-container",this.table=document.createElement("table"),this.table.className=`table ${this.options.bordered?"bordered":""} ${this.options.size}`,this.thead=document.createElement("thead"),this.tbody=document.createElement("tbody"),this.table.appendChild(this.thead),this.table.appendChild(this.tbody),this.tableWrapper.appendChild(this.table),this.paginationContainer=document.createElement("div"),this.paginationContainer.className="enhanced-table-pagination",this.tableContainer.appendChild(this.loadingOverlay),this.tableContainer.appendChild(this.menuContainer),this.tableContainer.appendChild(this.tableWrapper),this.tableContainer.appendChild(this.paginationContainer),this.container.appendChild(this.tableContainer)}render(){this.pluginSystem&&this.pluginSystem.emitHook("render:beforeRender",{fullRender:!0}),this.applyFilters(),this.renderMenu(),this.renderHeader(),this.updateTableWidth(),this.renderBody(),this.renderPagination(),this.applyCurrentStyling(),this.applyTheme(this.themeManager.getCurrentPresetName(),!0),this.pluginSystem&&this.pluginSystem.emitHook("render:afterRender",{fullRender:!0})}renderMenu(){let e=[];if(e.push(`<div class="table-menu-item" data-action="clear-all-filters"><i class="bi bi-funnel-fill"></i> ${this.i18n.t("menu.clearFilters")}</div>`),e.push(`<div class="table-menu-item" data-action="column-settings"><i class="bi bi-layout-three-columns"></i> ${this.i18n.t("menu.columnSettings")}</div>`),e.push(`<div class="table-menu-item" data-action="conditional-formatting"><i class="bi bi-palette-fill"></i> ${this.i18n.t("menu.conditionalFormat")}</div>`),e.push(`\n      <div class="table-menu-item table-menu-item-submenu" data-action="font-size">\n        <i class="bi bi-fonts"></i> ${this.i18n.t("menu.fontSize")}\n        <span class="submenu-arrow">▶</span>\n        <div class="table-submenu-dropdown">\n          <div class="table-menu-item ${"smallest"===this.state.fontSize?"table-menu-item-current":""}" data-action="font-size" data-size="smallest">${this.i18n.t("fontSize.smallest")} ${"smallest"===this.state.fontSize?"✓":""}</div>\n          <div class="table-menu-item ${"small"===this.state.fontSize?"table-menu-item-current":""}" data-action="font-size" data-size="small">${this.i18n.t("fontSize.small")} ${"small"===this.state.fontSize?"✓":""}</div>\n          <div class="table-menu-item ${"medium"===this.state.fontSize?"table-menu-item-current":""}" data-action="font-size" data-size="medium">${this.i18n.t("fontSize.medium")} ${"medium"===this.state.fontSize?"✓":""}</div>\n          <div class="table-menu-item ${"large"===this.state.fontSize?"table-menu-item-current":""}" data-action="font-size" data-size="large">${this.i18n.t("fontSize.large")} ${"large"===this.state.fontSize?"✓":""}</div>\n          <div class="table-menu-item ${"largest"===this.state.fontSize?"table-menu-item-current":""}" data-action="font-size" data-size="largest">${this.i18n.t("fontSize.largest")} ${"largest"===this.state.fontSize?"✓":""}</div>\n        </div>\n      </div>\n    `),e.push(`\n      <div class="table-menu-item table-menu-item-submenu" data-action="cell-padding">\n        <i class="bi bi-border-all"></i> ${this.i18n.t("menu.cellPadding")}\n        <span class="submenu-arrow">▶</span>\n        <div class="table-submenu-dropdown">\n          <div class="table-menu-item ${"wide"===this.state.cellPadding?"table-menu-item-current":""}" data-action="cell-padding" data-padding="wide">${this.i18n.t("cellPadding.wide")} ${"wide"===this.state.cellPadding?"✓":""}</div>\n          <div class="table-menu-item ${"standard"===this.state.cellPadding?"table-menu-item-current":""}" data-action="cell-padding" data-padding="standard">${this.i18n.t("cellPadding.standard")} ${"standard"===this.state.cellPadding?"✓":""}</div>\n          <div class="table-menu-item ${"narrow"===this.state.cellPadding?"table-menu-item-current":""}" data-action="cell-padding" data-padding="narrow">${this.i18n.t("cellPadding.narrow")} ${"narrow"===this.state.cellPadding?"✓":""}</div>\n        </div>\n      </div>\n    `),this.i18n&&"function"==typeof this.i18n.getAvailableLocales){const t=this.i18n.getLocale(),n=this.i18n.getAvailableLocales(),a={en:"English",ja:"日本語",es:"Español",fr:"Français",de:"Deutsch"};e.push(`\n      <div class="table-menu-item table-menu-item-submenu" data-action="language">\n        <i class="bi bi-globe"></i> ${this.i18n.t("menu.language")}\n        <span class="submenu-arrow">▶</span>\n        <div class="table-submenu-dropdown">\n          ${n.map((e=>`\n            <div class="table-menu-item ${t===e?"table-menu-item-current":""}" data-action="language" data-locale="${e}">\n              ${a[e]||e} ${t===e?"✓":""}\n            </div>\n          `)).join("")}\n        </div>\n      </div>\n    `)}const t=this.themeManager.getCurrentPresetName(),n=this.themeManager.getPresets();e.push(`\n      <div class="table-menu-item table-menu-item-submenu" data-action="theme">\n        <i class="bi bi-palette"></i> テーマ\n        <span class="submenu-arrow">▶</span>\n        <div class="table-submenu-dropdown">\n          ${n.map((e=>`\n            <div class="table-menu-item ${t===e.id?"table-menu-item-current":""}" data-action="theme" data-theme="${e.id}">\n              ${e.name} ${t===e.id?"✓":""}\n            </div>\n          `)).join("")}\n        </div>\n      </div>\n    `),e.push(`<div class="table-menu-item" data-action="clear-localstorage"><i class="bi bi-trash3-fill"></i> ${this.i18n.t("menu.clearStorage")}</div>`),this.menuContainer.innerHTML=`\n      <div class="table-menu-wrapper">\n        <button class="table-menu-btn" data-menu-toggle>⚙️</button>\n        <div class="table-menu-dropdown" style="display: none;">\n          ${e.join("")}\n        </div>\n      </div>\n    `}renderHeader(){const e=document.createElement("tr"),t=this.getOrderedColumns(),n=this.calculateAllColumnPositions();t.all.forEach(((t,a)=>{const r=document.createElement("th");r.className="table-header",this.applyColumnStyles(r,t,n);const i=document.createElement("div");i.className="header-content";const s=document.createElement("span");s.className="header-title",s.textContent=t.title,this.addTooltipToCell(s,t.title);const o=document.createElement("div");if(o.className="header-controls",t.sortable){const e=this.createSortControls(t);o.appendChild(e)}if(t.filterable){const e=this.createFilterButton(t);o.appendChild(e)}i.appendChild(s),i.appendChild(o);{const e=document.createElement("div");e.className="resize-handle",e.dataset.column=t.key,i.appendChild(e)}r.appendChild(i),e.appendChild(r)})),this.thead.innerHTML="",this.thead.appendChild(e)}updateTableWidth(){const e=this.getOrderedColumns();let t=0;e.all.forEach((e=>{const n=this.getColumnWidth(e);t+=n})),this.table&&(this.table.style.width=`${t}px`)}createSortControls(e){const t=document.createElement("div");t.className="sort-controls";const n=document.createElement("div");n.className="sort-indicator",n.dataset.column=e.key;const a=document.createElement("span");a.className="sort-triangle up "+(this.state.sortState.column===e.key&&"asc"===this.state.sortState.direction?"active":"");const r=document.createElement("span");return r.className="sort-triangle down "+(this.state.sortState.column===e.key&&"desc"===this.state.sortState.direction?"active":""),n.appendChild(a),n.appendChild(r),t.appendChild(n),t}createFilterButton(e){const t=document.createElement("div");t.className="filter-dropdown-container";const n=document.createElement("button");return n.className="filter-btn "+(this.hasActiveFilter(e.key)?"active":""),n.dataset.column=e.key,n.innerHTML='<span class="filter-funnel"></span>',t.appendChild(n),t}renderBody(){this.tbody.innerHTML="";const e=this.getOrderedColumns(),t=this.calculateAllColumnPositions();this.getPaginatedData().forEach((n=>{const a=document.createElement("tr");e.all.forEach(((e,r)=>{const i=document.createElement("td");i.className="table-cell",i.dataset.column=e.key,this.applyColumnStyles(i,e,t);const s=n[e.dataIndex];i.dataset.value=s;const o=e.render?e.render(s,n):s;"string"==typeof o?e.render||this.options.renderCellHTML?i.innerHTML=o:i.textContent=o:i.innerHTML=o,this.addTooltipToCell(i,o),a.appendChild(i)})),this.tbody.appendChild(a)}))}renderPagination(){if(!1===this.options.pagination)return void(this.paginationContainer.innerHTML="");const e=this.state.filteredData.length,t=Math.ceil(e/this.state.pageSize),n=(this.state.currentPage-1)*this.state.pageSize+1,a=Math.min(this.state.currentPage*this.state.pageSize,e);let r="";if(this.options.pagination.showTotal){r+=`<div class="pagination-info">${this.options.pagination.showTotal(e,[n,a])}</div>`}else r+=`<div class="pagination-info">${this.i18n.t("pagination.total",{start:n,end:a,total:e})}</div>`;r+=`\n      <div class="pagination-controls">\n        <button ${this.state.currentPage<=1?"disabled":""} data-page="${this.state.currentPage-1}">${this.i18n.t("pagination.previous")}</button>\n        <span class="page-info">${this.i18n.t("pagination.page",{page:this.state.currentPage})} / ${t}</span>\n        <button ${this.state.currentPage>=t?"disabled":""} data-page="${this.state.currentPage+1}">${this.i18n.t("pagination.next")}</button>\n    `,this.options.pagination.showSizeChanger&&(r+=`\n        <div class="page-size-selector">\n          <select class="page-size-select">\n            <option value="5" ${5===this.state.pageSize?"selected":""}>5 ${this.i18n.t("pagination.itemsPerPage")}</option>\n            <option value="10" ${10===this.state.pageSize?"selected":""}>10 ${this.i18n.t("pagination.itemsPerPage")}</option>\n            <option value="20" ${20===this.state.pageSize?"selected":""}>20 ${this.i18n.t("pagination.itemsPerPage")}</option>\n            <option value="50" ${50===this.state.pageSize?"selected":""}>50 ${this.i18n.t("pagination.itemsPerPage")}</option>\n          </select>\n        </div>\n      `),r+="</div>",this.paginationContainer.innerHTML=r}getVisibleColumns(){return this.options.columns.filter((e=>this.state.visibleColumns[e.key]))}getPaginatedData(){const e=(this.state.currentPage-1)*this.state.pageSize,t=e+this.state.pageSize;return this.state.filteredData.slice(e,t)}hasActiveFilter(e){return this.state.filters[e]&&this.state.filters[e].length>0||this.state.rangeFilters[e]&&null!==this.state.rangeFilters[e]}updateFilterButtonState(e){const t=this.tableContainer.querySelector(`.filter-btn[data-column="${e}"]`);if(t){const e=this.options.data.length;this.state.filteredData.length<e?t.classList.add("active"):t.classList.remove("active")}}handleSort(e,t){this.state.sortState=null===t?{column:null,direction:null}:{column:e,direction:t},this.applySorting(),this.render(),this.autoSaveSettings(),this.saveStateDebounced&&this.saveStateDebounced()}handleFilter(e,t){this.state.filters[e]=t,this.state.currentPage=1,this.render(),this.autoSaveSettings(),this.saveStateDebounced&&this.saveStateDebounced()}handlePageChange(e){const t=this.state.currentPage;this.state.currentPage=e,this.renderBody(),this.renderPagination(),this.applyCurrentStyling(),this.pluginSystem&&this.pluginSystem.emitHook("pagination:afterChange",{oldPage:t,newPage:e,pageSize:this.state.pageSize||this.options.pagination?.pageSize||10})}handleColumnResize(e,t){this.updateColumnWidth(e,t)}handleColumnToggle(e,t){this.state.visibleColumns[e]=t,this.render(),this.autoSaveSettings()}handleColumnPin(e,t){this.state.pinnedColumns[e]=t,this.render(),this.autoSaveSettings(),this.saveStateDebounced&&this.saveStateDebounced()}applyFilters(e=!1){let t=[...this.state.data];Object.keys(this.state.filters).forEach((e=>{const n=this.state.filters[e];if(n&&n.length>0){const a=this.options.columns.find((t=>t.key===e));if(a){if("range"===(this.state.filterModes?.[e]||"values"))return;t="date-hierarchy"===a.filterType?t.filter((e=>{const t=e[a.dataIndex];if(!t)return n.some((e=>!e||"null"===e||"undefined"===e||""===e));const r=new Date(t),i=r.getFullYear().toString(),s=r.getMonth(),o=(this.i18n.getMessage("filter.monthNames",this.i18n.currentLocale)||["January","February","March","April","May","June","July","August","September","October","November","December"])[s];return n.some((e=>e===i||(e===`${i}-${o}`||e===t)))})):a.onFilter?t.filter((e=>n.some((t=>a.onFilter(t,e))))):this.isNumericColumn(a)?t.filter((e=>{const t=e[a.dataIndex],r=parseFloat(t);return isNaN(r)||null==t||""===t?n.some((e=>{const t=parseFloat(e);return isNaN(t)||null===e||"null"===e||"undefined"===e||""===e})):n.includes(r)})):t.filter((e=>{const t=e[a.dataIndex],r=null==t||""===t;return n.some((e=>{const n=null===e||"null"===e||void 0===e||"undefined"===e||""===e;return!(!r||!n)||r===n&&t===e}))}))}}})),Object.keys(this.state.rangeFilters).forEach((e=>{const n=this.state.rangeFilters[e];if(n){const a=this.options.columns.find((t=>t.key===e));if(a){if("range"===(this.state.filterModes?.[e]||"values")){const r=void 0===this.state.rangeIncludeBlanks?.[e]||this.state.rangeIncludeBlanks[e];t=t.filter((e=>{const t=e[a.dataIndex],i=parseFloat(t),s=null==t||""===t||isNaN(i);return!(!s||!r)||!(s&&!r)&&(i>=n.min&&i<=n.max)}))}}}})),Object.keys(this.state.dateRangeFilters||{}).forEach((e=>{const n=this.state.dateRangeFilters[e];if(n&&n.startDate&&n.endDate){const a=this.options.columns.find((t=>t.key===e));if(a){if("range"===(this.state.filterModes?.[e]||"values")){const r=new Date(n.startDate),i=new Date(n.endDate),s=void 0===this.state.dateRangeIncludeBlanks?.[e]||this.state.dateRangeIncludeBlanks[e];t=t.filter((e=>{const t=e[a.dataIndex],n=!t||null==t||""===t;if(n&&s)return!0;if(n&&!s)return!1;const o=new Date(t);return o>=r&&o<=i}))}}}})),this.state.filteredData=t,e||this.applySorting(),this.pluginSystem&&this.pluginSystem.emitHook("filter:afterApply",{filteredData:t,originalData:this.state.data,activeFilters:this.state.filters})}applySorting(){if(this.state.sortState.column&&this.state.sortState.direction){const e=this.options.columns.find((e=>e.key===this.state.sortState.column));e&&(this.state.filteredData.sort(((t,n)=>{if(e.sorter)return"asc"===this.state.sortState.direction?e.sorter(t,n):e.sorter(n,t);{const a=t[e.dataIndex],r=n[e.dataIndex];return a<r?"asc"===this.state.sortState.direction?-1:1:a>r?"asc"===this.state.sortState.direction?1:-1:0}})),this.pluginSystem&&this.pluginSystem.emitHook("sort:afterSort",{sortedData:this.state.filteredData,column:this.state.sortState.column,direction:this.state.sortState.direction}))}else null===this.state.sortState.column&&null===this.state.sortState.direction&&this.applyFilters(!0)}applyFiltersAndSort(){if(!this.state.data||!Array.isArray(this.state.data))return console.warn("applyFiltersAndSort: No valid data available"),void(this.state.filteredData=[]);this.applyFilters(),this.applySorting(),this.state.filteredData&&Array.isArray(this.state.filteredData)||(console.warn("applyFiltersAndSort: Filtered data is invalid, resetting to original data"),this.state.filteredData=[...this.state.data])}applyCurrentStyling(){this.applyFontSize(),this.applyCellPadding()}attachEvents(){this.tableContainer.addEventListener("click",(e=>{if(e.target.closest(".sort-indicator")){const t=e.target.closest(".sort-indicator").dataset.column,n=this.state.sortState.column===t?this.state.sortState.direction:null;let a;a=null===n?"asc":"asc"===n?"desc":null,this.handleSort(t,a)}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.closest(".filter-btn")){const t=e.target.closest(".filter-btn").dataset.column;this.toggleFilter(t,e.target.closest(".filter-btn"))}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches("[data-page]")){const t=parseInt(e.target.dataset.page);this.handlePageChange(t)}})),this.tableContainer.addEventListener("change",(e=>{if(e.target.matches(".page-size-select")){const t=this.state.pageSize||this.options.pagination?.pageSize||10;this.state.pageSize=parseInt(e.target.value),this.state.currentPage=1,this.renderBody(),this.renderPagination(),this.applyCurrentStyling(),this.autoSaveSettings(),this.pluginSystem&&this.pluginSystem.emitHook("pagination:afterChange",{oldPage:1,newPage:1,oldPageSize:t,pageSize:this.state.pageSize,type:"pageSize"})}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches("[data-menu-toggle]")){const t=e.target.nextElementSibling;t.style.display="none"===t.style.display?"block":"none"}})),this.documentClickHandler=e=>{if(!e.target.closest(".table-menu-wrapper")){this.tableContainer.querySelectorAll(".table-menu-dropdown").forEach((e=>{e.style.display="none"}))}},document.addEventListener("click",this.documentClickHandler),this.tableContainer.addEventListener("click",(e=>{e.target.closest(".table-menu-dropdown")&&e.stopPropagation()})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="column-settings"]')){this.showColumnSettings();e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="conditional-formatting"]')){this.showConditionalFormatting();e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="clear-all-filters"]')){this.clearAllFilters();e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="clear-localstorage"]')){this.showLocalStorageClearConfirmation();e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="font-size"][data-size]')){const t=e.target.dataset.size;this.setFontSize(t);e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="cell-padding"][data-padding]')){const t=e.target.dataset.padding;this.setCellPadding(t);e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="language"][data-locale]')){const t=e.target.dataset.locale;this.setLanguage(t);e.target.closest(".table-menu-dropdown").style.display="none"}})),this.tableContainer.addEventListener("click",(e=>{if(e.target.matches('[data-action="theme"][data-theme]')){const t=e.target.dataset.theme;this.applyTheme(t);e.target.closest(".table-menu-dropdown").style.display="none"}})),this.attachResizeEvents()}attachResizeEvents(){let e=!1,t=null,n=0,a=0,r=0,i=null,s=null;const o=(e,t,n)=>{const a=(s||(s=document.createElement("div"),s.className="resize-tooltip",s.style.display="none",document.body.appendChild(s)),s),r=g.pxToCm(n);a.textContent=`${n}px (${r}cm)`;const i=m.SIZES.TOOLTIP_OFFSET,o=g.constrainToViewport(a,e,t,i.x,-i.y);a.style.left=`${o.x}px`,a.style.top=`${o.y}px`,a.style.display="block",a.style.opacity="1"},l=()=>{s&&(s.style.opacity="0",setTimeout((()=>{s&&(s.style.display="none")}),m.TIMING.TOOLTIP_FADE))};this.tableContainer.addEventListener("mousedown",(s=>{if(s.target.matches(".resize-handle")){const c=Date.now(),d=s.target.dataset.column;if(c-r<m.SIZES.DOUBLE_CLICK_THRESHOLD&&i===d)return this.autoResizeColumn(d),l(),s.preventDefault(),r=0,void(i=null);r=c,i=d,e=!0,t=d,n=s.clientX;const u=s.target.closest("th");a=u?u.offsetWidth:this.state.columnWidths[t],document.body.style.cursor="col-resize",o(s.clientX,s.clientY,a),s.preventDefault()}})),document.addEventListener("mousemove",(r=>{if(e){const e=r.clientX-n,i=Math.max(m.SIZES.MIN_COLUMN_WIDTH,a+e);this.handleColumnResize(t,i),o(r.clientX,r.clientY,i)}})),document.addEventListener("mouseup",(()=>{e&&(e=!1,t=null,document.body.style.cursor="",l())}))}autoResizeColumn(e){const t=this.options.columns.find((t=>t.key===e));if(!t)return;const n=document.createElement("div");n.style.position="absolute",n.style.visibility="hidden",n.style.whiteSpace="nowrap",n.style.fontSize=getComputedStyle(this.tableContainer).fontSize,n.style.fontFamily=getComputedStyle(this.tableContainer).fontFamily,n.style.padding="8px 12px",document.body.appendChild(n);let a=0;n.textContent=t.title||t.key;const r=n.offsetWidth+40;a=Math.max(a,r);this.getCurrentPageData().forEach((e=>{let r=e[t.dataIndex]||"";t.render&&"function"==typeof t.render&&(r=t.render(r,e),"string"==typeof r&&(r=r.replace(/<[^>]*>/g,""))),n.textContent=String(r);const i=n.offsetWidth;a=Math.max(a,i)})),document.body.removeChild(n);const i=Math.max(m.SIZES.AUTO_RESIZE_MIN,Math.min(a,m.SIZES.AUTO_RESIZE_MAX));this.handleColumnResize(e,i)}getCurrentPageData(){const e=(this.state.currentPage-1)*this.state.pageSize,t=e+this.state.pageSize;return this.state.filteredData.slice(e,t)}async saveSettings(){return!!this.settingsManager&&await this.settingsManager.saveSettings(this)}async loadSettings(){if(!this.settingsManager)return!1;const e=await this.settingsManager.loadSettings(this);return e&&(this.applyFilters(),this.render()),e}async clearSettings(){return!!this.settingsManager&&await this.settingsManager.clearSettings()}async autoSaveSettings(){this.settingsManager&&this.options.persistSettings&&(clearTimeout(this._autoSaveTimeout),this._autoSaveTimeout=setTimeout((async()=>{await this.saveSettings()}),1e3))}toggleFilter(e,t){if(this.state.openFilter===e)return void this.closeFilter();this.closeFilter();const n=()=>{if(document.querySelector(".filter-dropdown-wrapper"))requestAnimationFrame(n);else{this.state.openFilter=e;const n=this.options.columns.find((t=>t.key===e));this.showFilterDropdown(n,t)}};requestAnimationFrame(n)}showFilterDropdown(e,t){const n=JSON.parse(JSON.stringify(this.state.filters)),a=JSON.parse(JSON.stringify(this.state.rangeFilters)),r=JSON.parse(JSON.stringify(this.state.dateRangeFilters)),i=JSON.parse(JSON.stringify(this.state.filterModes||{})),s=JSON.parse(JSON.stringify(this.state.rangeIncludeBlanks||{})),o=JSON.parse(JSON.stringify(this.state.dateRangeIncludeBlanks||{})),l=document.createElement("div");l.className="filter-dropdown-wrapper",l.style.position="fixed",l.style.zIndex="9999";const c=[...new Set(this.state.data.map((t=>{const n=t[e.dataIndex];return null==n||""===n?null:n})))];this.state.filterModes?.[e.key];this.state.filterModes||(this.state.filterModes={}),void 0===this.state.filterModes[e.key]&&("date-hierarchy"===e.filterType?this.state.filterModes[e.key]="values":this.isNumericColumn(e)?this.state.filterModes[e.key]="range":this.state.filterModes[e.key]="values");const d=this.state.filters[e.key]||[];let u="";u="date-hierarchy"===e.filterType?this.createDateHierarchyFilter(c,d,e):this.isNumericColumn(e)?this.createRangeFilter(e,c):this.createTextFilter(c,d,e);const h=window.innerWidth<=480,p=`\n      <div class="filter-dropdown-footer">\n        <button class="filter-btn-clear-column">\n          🔄 ${this.i18n.t("filter.clearColumn")}\n        </button>\n        <div class="filter-footer-actions">\n          <button class="filter-btn-cancel">${this.i18n.t("filter.cancel")}</button>\n          <button class="filter-btn-confirm">${this.i18n.t("filter.ok")}</button>\n        </div>\n      </div>\n    `;if(h){l.innerHTML=`\n        <div class="filter-dropdown filter-dropdown-mobile">\n          <div class="filter-dropdown-header">\n            <div class="filter-dropdown-title">${e.title}</div>\n          </div>\n          ${u}\n        </div>\n      `;const t=l.querySelector(".filter-mode-content"),n=l.querySelector(".filter-dropdown-content");t?t.insertAdjacentHTML("afterend",`<div class="filter-dropdown-mobile-footer-wrapper">${p}</div>`):n&&n.insertAdjacentHTML("afterend",`<div class="filter-dropdown-mobile-footer-wrapper">${p}</div>`)}else l.innerHTML=`\n        <div class="filter-dropdown">\n          <div class="filter-dropdown-header">\n            <div class="filter-dropdown-title">${e.title}</div>\n          </div>\n          ${u}\n          ${p}\n        </div>\n      `;document.body.appendChild(l);const m=t.closest(".table-header"),f=m?m.getBoundingClientRect():t.getBoundingClientRect(),g=window.innerWidth,y=window.innerHeight,b=document.querySelector(".enhanced-table-pagination"),v=b?b.getBoundingClientRect().top:y,S=h?10:5,w=f.bottom+S,x=20,C=Math.min(v-w-10,y-w-20);let k;if(h)k=.9*y;else{const e=110;k=Math.max(e,Math.min(C,500))}const E=l.querySelector(".filter-dropdown");if(E&&!E.classList.contains("filter-dropdown-mobile")?E.style.maxHeight=`${k}px`:E&&E.classList.contains("filter-dropdown-mobile")&&(E.style.height=`${k}px`,E.style.maxHeight=`${k}px`),E){E.offsetHeight;const e=E.querySelector(".filter-dropdown-content"),t=E.querySelector(".filter-mode-content");e&&e.offsetHeight,t&&t.offsetHeight}let T=E?E.getBoundingClientRect():l.getBoundingClientRect();const A=Math.min(T.height,k);T={...T,height:A};let R=f.left;const L=l.getBoundingClientRect().width;if(R+L>g-5&&(R=g-L-5),R<5&&(R=5),h){const e=(y-A)/2,t=(g-T.width)/2;if(l.style.left=`${Math.max(5,t)}px`,l.style.top=`${Math.max(x,e)}px`,l.style.zIndex="10001",!document.querySelector(".filter-dropdown-backdrop")){const e=document.createElement("div");e.className="filter-dropdown-backdrop",e.style.cssText="\n          position: fixed;\n          top: 0;\n          left: 0;\n          right: 0;\n          bottom: 0;\n          background: rgba(0, 0, 0, 0.3);\n          z-index: 10000;\n        ",e.addEventListener("click",(()=>this.closeFilter())),document.body.appendChild(e),l._backdrop=e}}else{let e=w;const t=v-10;if(e<x)e=x;else if(e+T.height>t){const n=f.top-T.height-S;n>=x?e=n:(e=Math.max(x,t-T.height),e<x&&(e=x))}l.style.left=`${R}px`,l.style.top=`${e}px`}if("date-hierarchy"===e.filterType&&this.state.dateRangeFilters?.[e.key]){const t=this.state.dateRangeFilters[e.key];setTimeout((()=>{const e=l.querySelector(".date-range-min"),n=l.querySelector(".date-range-max");e&&n&&(e.value=t.startDate||"",n.value=t.endDate||"")}),0)}this.attachFilterEvents(l,e,n,a,r,i,s,o);const F=e=>{l.contains(e.target)||(this.closeFilter(),document.removeEventListener("click",F))};setTimeout((()=>{document.addEventListener("click",F)}),0),l._clickOutsideHandler=F;const _=e=>{"Escape"===e.key&&(this.closeFilter(),document.removeEventListener("keydown",_))};document.addEventListener("keydown",_),l._escapeKeyHandler=_}createTextFilter(e,t,n){const a=0===t.length,r=[...e].sort(((e,t)=>{const n=null==e||""===e,a=null==t||""===t;return n&&!a?-1:!n&&a?1:n&&a?0:String(e).localeCompare(String(t))}));return`\n      <div class="filter-dropdown-search">\n        <input type="text" class="filter-search-input" placeholder="${this.i18n.t("filter.placeholder")}">\n        </div>\n      <div class="filter-dropdown-content">\n        <div class="filter-option select-all">\n          <label class="filter-option-label">\n            <input type="checkbox" class="filter-checkbox" data-value="__all__" ${a?"checked":""}>\n            <span class="filter-option-text">${this.i18n.t("filter.all")} <span class="filter-option-count">(${this.countTotalDataItems(n)})</span></span>\n          </label>\n        </div>\n        <div class="filter-options-list" data-test="filter-checkbox-list">\n          ${r.map((e=>`\n            <div class="filter-option">\n              <label class="filter-option-label">\n                <input type="checkbox" class="filter-checkbox" data-value="${e}" ${a||t.includes(e)?"checked":""}>\n                <span class="filter-option-text">${null==e||""===e?this.i18n.t("filter.empty"):e} <span class="filter-option-count">(${this.countDataItems(n,e)})</span></span>\n              </label>\n            </div>\n          `)).join("")}\n        </div>\n      </div>\n    `}countDataItems(e,t){return this.state.data&&e?"date-hierarchy"===e.filterType||this.isDateValue(t)?this.state.data.filter((n=>{const a=n[e.dataIndex];if(!a)return!1;const r=a.toString();if(4===t.length&&/^\d{4}$/.test(t))return r.startsWith(t);if(7===t.length&&/^\d{4}-\d{2}$/.test(t))return r.startsWith(t);if(t.includes("-"))return r===t;{const n=this.getCurrentYearContext(e,t);return!!n&&r.startsWith(n)}})).length:this.state.data.filter((n=>n[e.dataIndex]==t)).length:0}isDateValue(e){return"string"==typeof e&&/^\d{4}(-\d{2})?(-\d{2})?$/.test(e)}countTotalDataItems(e){if(!this.state.data||!e)return 0;let t=[...this.state.data];return Object.entries(this.state.filters).forEach((([n,a])=>{n!==e.key&&a&&a.length>0&&(t=t.filter((e=>a.includes(e[n]))))})),Object.entries(this.state.rangeFilters).forEach((([n,a])=>{if(n!==e.key&&a){const e=this.options.columns.find((e=>e.key===n));e&&(t=t.filter((t=>{const n=parseFloat(t[e.dataIndex]);return!isNaN(n)&&(!(""!==a.min&&n<parseFloat(a.min))&&!(""!==a.max&&n>parseFloat(a.max)))})))}})),Object.entries(this.state.dateRangeFilters).forEach((([n,a])=>{if(n!==e.key&&a&&(a.start||a.end)){const e=this.options.columns.find((e=>e.key===n));e&&(t=t.filter((t=>{const n=t[e.dataIndex];if(!n)return!1;const r=new Date(n);return!(a.start&&r<new Date(a.start))&&!(a.end&&r>new Date(a.end))})))}})),t.length}countDataItemsForMonth(e,t,n){return this.state.data&&e?this.state.data.filter((a=>{const r=a[e.dataIndex];if(!r)return!1;const i=new Date(r),s=i.getFullYear(),o=i.toLocaleString("default",{month:"long"});return s==t&&o===n})).length:0}getCurrentYearContext(e,t){const n=this.state.data.find((n=>{const a=n[e.dataIndex];if(!a)return!1;return new Date(a).toLocaleString("default",{month:"long"})===t}));if(n){const t=new Date(n[e.dataIndex]);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}return null}createRangeFilter(e,t){const n=t.filter((e=>null!=e&&""!==e&&!isNaN(e))).map(Number),a=n.length>0?Math.min(...n):0,r=n.length>0?Math.max(...n):0,i=g.getDecimalPlaces(t.filter((e=>!isNaN(e))).map(Number)),s=this.state.rangeFilters[e.key]||{min:a,max:r},o=this.state.filters[e.key]||[],l=this.state.filterModes?.[e.key]||"range",c=[...t].sort(((e,t)=>{const n=parseFloat(e),a=parseFloat(t),r=isNaN(n)||null==e||""===e,i=isNaN(a)||null==t||""===t;return r&&!i?-1:!r&&i?1:r&&i?0:n-a})),d=0===o.length,u=(0===o.length&&this.state.filters[e.key]&&0===this.state.filters[e.key].length&&this.hasActiveFilter(e.key),o.length>0&&o.length<c.length);let h="",p="";return d&&!this.hasActiveFilter(e.key)?p="checked":u&&(h="indeterminate"),`\n      <div class="filter-mode-tabs">\n        <button class="filter-mode-tab ${"range"===l?"active":""}" data-mode="range">${this.i18n.t("filter.filterByRange")}</button>\n        <button class="filter-mode-tab ${"values"===l?"active":""}" data-mode="values">${this.i18n.t("filter.selectValues")}</button>\n      </div>\n\n      <div class="filter-mode-content">\n        \x3c!-- 範囲モードコンテンツ --\x3e\n        <div class="filter-mode-panel ${"range"===l?"active":""}" data-panel="range">\n          <div class="filter-dropdown-range">\n            <div class="range-filter">\n              <div class="range-inputs">\n                <div class="range-input-group">\n                  <label class="range-label">${this.i18n.t("filter.min")}</label>\n                  <input type="number" class="range-input range-min" value="${g.formatNumberValue(s.min,i)}" min="${a}" max="${r}" data-min="${a}" data-max="${r}" data-decimal-places="${i}" data-test="filter-min-input" placeholder="${this.i18n.t("filter.min")}">\n                </div>\n                <div class="range-input-group">\n                  <label class="range-label">${this.i18n.t("filter.max")}</label>\n                  <input type="number" class="range-input range-max" value="${g.formatNumberValue(s.max,i)}" min="${a}" max="${r}" data-min="${a}" data-max="${r}" data-decimal-places="${i}" data-test="filter-max-input" placeholder="${this.i18n.t("filter.max")}">\n                </div>\n              </div>\n              <div class="number-range-slider-container">\n                <div class="number-range-slider" data-min="${a}" data-max="${r}" data-current-min="${s.min}" data-current-max="${s.max}" data-decimal-places="${i}">\n                  <div class="number-range-track"></div>\n                  <div class="number-range-thumb number-range-thumb-min" data-type="min"></div>\n                  <div class="number-range-thumb number-range-thumb-max" data-type="max"></div>\n                </div>\n              </div>\n              <div class="range-blank-option">\n                <label class="filter-option-label">\n                  <input type="checkbox" class="range-include-blank-checkbox" ${this.state.rangeIncludeBlanks&&void 0!==this.state.rangeIncludeBlanks[e.key]?this.state.rangeIncludeBlanks[e.key]?"checked":"":"checked"}>\n                  <span class="filter-option-text">${this.i18n.t("filter.includeBlank")}</span>\n                </label>\n              </div>\n              <div class="range-description">\n                ${this.i18n.t("filter.rangeDescription",{min:g.formatNumberValue(s.min,i),max:g.formatNumberValue(s.max,i)})}\n              </div>\n            </div>\n          </div>\n        </div>\n\n        \x3c!-- 値選択モードコンテンツ --\x3e\n        <div class="filter-mode-panel ${"values"===l?"active":""}" data-panel="values">\n          <div class="filter-dropdown-search">\n            <input type="text" class="filter-search-input" placeholder="${this.i18n.t("filter.placeholder")}">\n        </div>\n          <div class="filter-dropdown-content">\n            <div class="filter-option select-all">\n              <label class="filter-option-label">\n                <input type="checkbox" class="filter-checkbox" data-value="__all__" ${p} data-state="${h}">\n                <span class="filter-option-text">${this.i18n.t("filter.all")} <span class="filter-option-count">(${this.countTotalDataItems(e)})</span></span>\n              </label>\n            </div>\n            <div class="filter-options-list" data-test="filter-checkbox-list">\n              ${c.map((t=>{const n=null==t||""===t||"string"==typeof t&&"null"===t.toLowerCase();let a=!1;return a=0===o.length&&!this.hasActiveFilter(e.key)||(n?o.some((e=>null===e||"null"===e||""===e||void 0===e)):o.includes(Number(t))),`\n                <div class="filter-option">\n                  <label class="filter-option-label">\n                    <input type="checkbox" class="filter-checkbox" data-value="${null===t?"null":t}" ${a?"checked":""}>\n                    <span class="filter-option-text">${n?this.i18n.t("filter.empty"):t} <span class="filter-option-count">(${this.countDataItems(e,t)}</span></span>\n                  </label>\n                </div>\n              `})).join("")}\n            </div>\n          </div>\n        </div>\n      </div>\n    `}createDateHierarchyFilter(e,t,n){const a=e.filter((e=>!e||null==e||""===e)),r=e.filter((e=>e&&null!=e&&""!==e)),i=this.groupDatesByHierarchy(r),s=0===t.length,o=a.length>0,l=e.filter((e=>e&&!isNaN(new Date(e).getTime()))),c=l.length>0?new Date(Math.min(...l.map((e=>new Date(e).getTime())))).toISOString().split("T")[0]:"",d=l.length>0?new Date(Math.max(...l.map((e=>new Date(e).getTime())))).toISOString().split("T")[0]:"",u=this.state.dateRangeFilters?.[n?.key]||{startDate:c,endDate:d},h=void 0!==u.startDate&&null!==u.startDate?u.startDate:c,p=void 0!==u.endDate&&null!==u.endDate?u.endDate:d,m=this.state.filterModes[n.key]||"values";return`\n      <div class="filter-mode-tabs">\n        <button class="filter-mode-tab ${"range"===m?"active":""}" data-mode="range">${this.i18n.t("filter.filterByRange")}</button>\n        <button class="filter-mode-tab ${"values"===m?"active":""}" data-mode="values">${this.i18n.t("filter.selectValues")}</button>\n      </div>\n\n      <div class="filter-mode-content">\n        \x3c!-- 範囲モードコンテンツ --\x3e\n        <div class="filter-mode-panel ${"range"===m?"active":""}" data-panel="range">\n          <div class="filter-dropdown-range">\n            <div class="date-range-filter">\n              <div class="date-range-inputs">\n                <div class="date-range-input-group">\n                  <label class="date-range-label">${this.i18n.t("filter.startDate")}</label>\n                  <input type="date" class="date-range-input date-range-min" value="${h}" min="${c}" max="${d}">\n                </div>\n                <div class="date-range-input-group">\n                  <label class="date-range-label">${this.i18n.t("filter.endDate")}</label>\n                  <input type="date" class="date-range-input date-range-max" value="${p}" min="${c}" max="${d}">\n                </div>\n              </div>\n              <div class="date-range-slider-container">\n                <div class="date-range-slider" data-min="${c}" data-max="${d}">\n                  <div class="date-range-track"></div>\n                  <div class="date-range-thumb date-range-thumb-min" data-type="min"></div>\n                  <div class="date-range-thumb date-range-thumb-max" data-type="max"></div>\n                </div>\n              </div>\n              <div class="range-blank-option">\n                <label class="filter-option-label">\n                  <input type="checkbox" class="date-range-include-blank-checkbox" ${this.state.dateRangeIncludeBlanks&&void 0!==this.state.dateRangeIncludeBlanks[n.key]?this.state.dateRangeIncludeBlanks[n.key]?"checked":"":"checked"}>\n                  <span class="filter-option-text">${this.i18n.t("filter.includeBlank")}</span>\n                </label>\n              </div>\n            </div>\n          </div>\n        </div>\n\n        \x3c!-- 値選択モードコンテンツ --\x3e\n        <div class="filter-mode-panel ${"values"===m?"active":""}" data-panel="values">\n          <div class="filter-dropdown-search">\n        <input type="text" class="filter-search-input" placeholder="${this.i18n.t("filter.placeholder")}">\n        </div>\n      <div class="date-expand-controls">\n        <div class="expand-control-header">\n          <span class="expand-control-label">${this.i18n.t("filter.expandLabel")}</span>\n          <div class="expand-control-buttons">\n            <button class="expand-control-btn active" data-level="year">${this.i18n.t("filter.year")}</button>\n            <button class="expand-control-btn" data-level="month">${this.i18n.t("filter.month")}</button>\n            <button class="expand-control-btn" data-level="day">${this.i18n.t("filter.day")}</button>\n          </div>\n        </div>\n      </div>\n      <div class="filter-dropdown-content">\n        <div class="filter-option select-all">\n          <label class="filter-option-label">\n            <input type="checkbox" class="filter-checkbox" data-value="__all__" ${s?"checked":""}>\n            <span class="filter-option-text">${this.i18n.t("filter.all")} <span class="filter-option-count">(${this.countTotalDataItems(n)})</span></span>\n          </label>\n        </div>\n        <div class="date-filter-content" data-test="filter-checkbox-list">\n          ${o?`\n            <div class="filter-option">\n              <label class="filter-option-label">\n                <input type="checkbox" class="filter-checkbox" data-value="" ${s||t.some((e=>!e||"null"===e||"undefined"===e||""===e))?"checked":""}>\n                <span class="filter-option-text">${this.i18n.t("filter.empty")} <span class="filter-option-count">(${a.length})</span></span>\n              </label>\n            </div>\n          `:""}\n          ${Object.keys(i).map((e=>`\n            <div class="date-filter-group">\n              <div class="date-filter-group-header">\n                <button class="expand-btn">▼</button>\n                <label class="date-filter-label">\n                  <input type="checkbox" class="date-filter-checkbox" data-value="${e}" ${s||this.isYearSelected(e,i[e],t)?"checked":""}>\n                  <span class="date-filter-text">${e} <span class="filter-option-count">(${this.countDataItems(n,e)})</span></span>\n                </label>\n              </div>\n              <div class="date-filter-children">\n                ${Object.keys(i[e]).map((a=>`\n                  <div class="date-filter-item date-filter-month">\n                    <div class="date-filter-month-header">\n                      <button class="expand-btn expand-btn-month">▼</button>\n                      <label class="date-filter-label">\n                        <input type="checkbox" class="date-filter-checkbox" data-value="${e}-${a}" ${s||this.isMonthSelected(e,a,i[e][a],t)?"checked":""}>\n                        <span class="date-filter-text">${a} <span class="filter-option-count">(${this.countDataItemsForMonth(n,e,a)})</span></span>\n                      </label>\n                    </div>\n                    <div class="date-filter-days">\n                      ${i[e][a].map((e=>`\n                        <div class="date-filter-item date-filter-day">\n                          <label class="date-filter-label">\n                            <input type="checkbox" class="date-filter-checkbox" data-value="${e}" ${s||t.includes(e)?"checked":""}>\n                            <span class="date-filter-text">${new Date(e).getDate()} <span class="filter-option-count">(${this.countDataItems(n,e)})</span></span>\n                          </label>\n                        </div>\n                      `)).join("")}\n                    </div>\n                  </div>\n                `)).join("")}\n              </div>\n            </div>\n          `)).join("")}\n        </div>\n      </div>\n        </div>\n      </div>\n    `}attachFilterEvents(e,t,n,a,r,i,s,o){const l=e.querySelectorAll(".filter-mode-tab");l.length>0&&l.forEach((n=>{n.addEventListener("click",(()=>{const a=n.dataset.mode;l.forEach((e=>e.classList.remove("active"))),n.classList.add("active");if(e.querySelectorAll(".filter-mode-panel").forEach((e=>{e.dataset.panel===a?e.classList.add("active"):e.classList.remove("active")})),this.state.filterModes[t.key]=a,"range"===a&&"date-hierarchy"===t.filterType&&this.state.dateRangeFilters?.[t.key]){const n=e.querySelector(".date-range-min"),a=e.querySelector(".date-range-max");n&&a&&(n.value=this.state.dateRangeFilters[t.key].startDate||n.value,a.value=this.state.dateRangeFilters[t.key].endDate||a.value)}if("range"===a)if(delete this.state.filters[t.key],"date-hierarchy"===t.filterType){if(!this.state.dateRangeFilters[t.key]){const n=e.querySelector(".date-range-min"),a=e.querySelector(".date-range-max");n&&a&&(this.state.dateRangeFilters[t.key]={startDate:n.value,endDate:a.value})}this.state.dateRangeIncludeBlanks||(this.state.dateRangeIncludeBlanks={}),void 0===this.state.dateRangeIncludeBlanks[t.key]&&(this.state.dateRangeIncludeBlanks[t.key]=!0)}else this.state.rangeIncludeBlanks||(this.state.rangeIncludeBlanks={}),void 0===this.state.rangeIncludeBlanks[t.key]&&(this.state.rangeIncludeBlanks[t.key]=!0);else"values"===a&&(delete this.state.rangeFilters[t.key],delete this.state.dateRangeFilters[t.key]);setTimeout((()=>{this.adjustDropdownPosition(e)}),0)}))}));const c=e.querySelector(".range-min"),d=e.querySelector(".range-max"),u=e.querySelector(".number-range-slider"),h=e.querySelector(".range-include-blank-checkbox");if(c&&d&&u){const t=u.querySelector(".number-range-track"),n=u.querySelector(".number-range-thumb-min"),a=u.querySelector(".number-range-thumb-max"),r=parseFloat(u.dataset.min),i=parseFloat(u.dataset.max)-r,s=parseInt(u.dataset.decimalPlaces)||0,o=()=>{const o=parseFloat(c.value),l=parseFloat(d.value),u=(o-r)/i*100,h=(l-r)/i*100;n.style.left=`${u}%`,a.style.left=`${h}%`,t.style.left=`${u}%`,t.style.width=h-u+"%";const p=e.querySelector(".range-description");p&&(p.textContent=this.i18n.t("filter.rangeDescription",{min:g.formatNumberValue(o,s),max:g.formatNumberValue(l,s)}))};o(),c.addEventListener("input",(()=>{let e=parseFloat(c.value);const t=parseFloat(d.value);e>t&&(c.value=t),o(),y()})),d.addEventListener("input",(()=>{let e=parseFloat(d.value);const t=parseFloat(c.value);e<t&&(d.value=t),o(),y()}));let l=!1,h=null;const p=(e,t)=>{l=!0,h=t,e.preventDefault()},m=e=>{if(!l||!h)return;const t=u.getBoundingClientRect(),n=(e.clientX||(e.touches?.[0]?.clientX??0))-t.left,a=Math.max(0,Math.min(100,n/t.width*100)),p=r+a/100*i,m=s>0?Math.round(p*Math.pow(10,s))/Math.pow(10,s):Math.round(p);if("min"===h.dataset.type){const e=parseFloat(d.value),t=m<=e?m:e;c.value=g.formatNumberValue(t,s)}else{const e=parseFloat(c.value),t=m>=e?m:e;d.value=g.formatNumberValue(t,s)}o(),y()},f=()=>{l=!1,h=null};n.addEventListener("mousedown",(e=>p(e,n))),a.addEventListener("mousedown",(e=>p(e,a))),document.addEventListener("mousemove",m),document.addEventListener("mouseup",f),n.addEventListener("touchstart",(e=>p(e,n)),{passive:!1}),a.addEventListener("touchstart",(e=>p(e,a)),{passive:!1}),document.addEventListener("touchmove",m,{passive:!1}),document.addEventListener("touchend",f)}h&&h.addEventListener("change",(()=>{this.state.rangeIncludeBlanks||(this.state.rangeIncludeBlanks={}),this.state.rangeIncludeBlanks[t.key]=h.checked,y()}));const p=e.querySelector(".date-range-min"),m=e.querySelector(".date-range-max"),f=e.querySelector(".date-range-include-blank-checkbox");p&&m&&(p.addEventListener("input",(()=>{y()})),m.addEventListener("input",(()=>{y()}))),f&&f.addEventListener("change",(()=>{this.state.dateRangeIncludeBlanks||(this.state.dateRangeIncludeBlanks={}),this.state.dateRangeIncludeBlanks[t.key]=f.checked,y()}));const y=()=>{if(this.isNumericColumn(t)){if("range"===(this.state.filterModes[t.key]||"values")){const n=e.querySelector(".range-min"),a=e.querySelector(".range-max");if(n&&a){const e=parseFloat(n.value),r=parseFloat(a.value);this.state.rangeFilters[t.key]={min:e,max:r},delete this.state.filters[t.key],this.applyFilters(),this.renderBody(),this.renderPagination()}}else{const n=Array.from(e.querySelectorAll(".filter-checkbox:checked")).map((e=>e.dataset.value)).filter((e=>"__all__"!==e)).map((e=>"null"===e||"undefined"===e||""===e||null==e?null:parseFloat(e)));delete this.state.rangeFilters[t.key];const a=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"])');n.length===a.length?this.handleFilter(t.key,[]):this.handleFilter(t.key,n)}}else if("date-hierarchy"===t.filterType){if("range"===(this.state.filterModes[t.key]||"values")){const n=e.querySelector(".date-range-min"),a=e.querySelector(".date-range-max");n&&a&&(this.state.dateRangeFilters[t.key]={startDate:n.value,endDate:a.value},delete this.state.filters[t.key],this.applyFilters(),this.renderBody(),this.renderPagination())}else{const n=Array.from(e.querySelectorAll(".filter-checkbox:checked, .date-filter-checkbox:checked")).map((e=>e.dataset.value)).filter((e=>"__all__"!==e));delete this.state.dateRangeFilters[t.key];const a=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]), .date-filter-checkbox');n.length===a.length?this.handleFilter(t.key,[]):this.handleFilter(t.key,n)}}else{const n=Array.from(e.querySelectorAll(".filter-checkbox:checked")).map((e=>e.dataset.value)).filter((e=>"__all__"!==e)),a=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"])');n.length===a.length?this.handleFilter(t.key,[]):this.handleFilter(t.key,n)}this.updateFilterButtonState(t.key)};e.querySelector(".filter-btn-cancel").addEventListener("click",(()=>{this.state.filters=n,this.state.rangeFilters=a,this.state.dateRangeFilters=r,this.state.filterModes=i,this.state.rangeIncludeBlanks=s,this.state.dateRangeIncludeBlanks=o,this.state.currentPage=1,this.applyFilters(),this.renderBody(),this.renderPagination(),this.closeFilter(),this.updateFilterButtonState(t.key)}));const b=e.querySelector(".filter-btn-clear-column");b&&b.addEventListener("click",(()=>{delete this.state.filters[t.key],delete this.state.rangeFilters[t.key],delete this.state.dateRangeFilters[t.key],this.state.rangeIncludeBlanks&&delete this.state.rangeIncludeBlanks[t.key],this.state.dateRangeIncludeBlanks&&delete this.state.dateRangeIncludeBlanks[t.key],this.state.filterModes&&delete this.state.filterModes[t.key],this.applyFilters(),this.renderBody(),this.renderPagination(),this.closeFilter(),this.autoSaveSettings()})),e.querySelector(".filter-btn-confirm").addEventListener("click",(()=>{if("values"===(this.state.filterModes[t.key]||"values")){let n;if("date-hierarchy"===t.filterType){const t=e.querySelector(".expand-control-btn.active"),a=t?t.dataset.level:"year";n="year"===a?Array.from(e.querySelectorAll(".date-filter-group-header .date-filter-checkbox:checked")):"month"===a?Array.from(e.querySelectorAll(".date-filter-month-header .date-filter-checkbox:checked")):Array.from(e.querySelectorAll(".date-filter-day .date-filter-checkbox:checked"))}else n=Array.from(e.querySelectorAll(".filter-checkbox:checked"));const a=n.map((e=>e.dataset.value)).filter((e=>"__all__"!==e));a.length>0?this.state.filters[t.key]=a:delete this.state.filters[t.key],delete this.state.rangeFilters[t.key],delete this.state.dateRangeFilters[t.key]}this.applyFilters(),this.renderBody(),this.renderPagination(),this.saveStateDebounced&&this.saveStateDebounced(),this.updateFilterButtonState(t.key),this.closeFilter()}));const v=()=>{const t=e.querySelector(".filter-btn-confirm");if(!t)return;const n=e.querySelectorAll('.filter-checkbox:checked:not([data-value="__all__"]), .date-filter-checkbox:checked').length>0;t.disabled=!n},S=e.querySelector('[data-value="__all__"]');S&&S.addEventListener("change",(t=>{const n=e.querySelector(".filter-search-input");if(n?n.value.toLowerCase().trim():""){e.querySelectorAll(".filter-option:not(.select-all)").forEach((e=>{if("none"!==e.style.display){const n=e.querySelector(".filter-checkbox");n&&(n.checked=t.target.checked)}}))}else{e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]), .date-filter-checkbox').forEach((e=>e.checked=t.target.checked))}t.target.indeterminate=!1,v(),y()}));let w='.filter-checkbox:not([data-value="__all__"])';"date-hierarchy"!==t.filterType&&(w+=", .date-filter-checkbox");const x=e.querySelectorAll(w);x.forEach((n=>{n.addEventListener("change",(()=>{if(this.isNumericColumn(t))this.updateRangeFromCheckbox(e,t);else if(S){e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]), .date-filter-checkbox'),e.querySelectorAll('.filter-checkbox:checked:not([data-value="__all__"]), .date-filter-checkbox:checked');g.updateSelectAllState(S,x)}v(),y()}))})),v();const C=e.querySelector(".filter-search-input");C&&C.addEventListener("input",(n=>{const a=n.target.value.toLowerCase().trim(),r=e.querySelectorAll(".filter-option:not(.select-all)"),i=e.querySelector('[data-value="__all__"]');if(r.forEach((e=>{const t=e.querySelector(".filter-option-text")?.textContent.toLowerCase()||"",n=e.querySelector(".filter-checkbox"),r=t.includes(a);e.style.display=r||""===a?"block":"none",""!==a&&r?n.checked=!0:""===a||r||(n.checked=!1)})),i){const t=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"])'),n=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]):checked'),a=t.length,r=n.length;0===r?(i.checked=!1,i.indeterminate=!1):r===a?(i.checked=!0,i.indeterminate=!1):(i.checked=!1,i.indeterminate=!0)}if(v(),""!==a&&y(),"date-hierarchy"===t.filterType){e.querySelectorAll(".date-filter-group").forEach((e=>{const t=e.querySelector(".date-filter-text")?.textContent.toLowerCase()||"",n=e.querySelectorAll(".date-filter-month");e.querySelectorAll(".date-filter-day");let r=!1;(t.includes(a)||""===a)&&(r=!0),n.forEach((e=>{const t=(e.querySelector(".date-filter-text")?.textContent.toLowerCase()||"").includes(a)||""===a;e.style.display=t?"block":"none",t&&(r=!0);e.querySelectorAll(".date-filter-day").forEach((e=>{const t=e.querySelector(".date-filter-text")?.textContent.toLowerCase()||"";e.style.display=t.includes(a)||""===a?"block":"none"}))})),e.style.display=r?"block":"none"}))}})),this.attachRangeSliderEvents(e,t,y),this.attachDateRangeSliderEvents(e,t,y),"date-hierarchy"===t.filterType&&this.attachDateHierarchyEvents(e,t,y),this.updateSelectAllCheckboxState(e,t)}updateSelectAllCheckboxState(e,t){const n=e.querySelector('[data-value="__all__"]');if(!n)return;const a=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]), .date-filter-checkbox'),r=e.querySelectorAll('.filter-checkbox:checked:not([data-value="__all__"]), .date-filter-checkbox:checked');"indeterminate"===n.dataset.state?(n.indeterminate=!0,n.checked=!1):0===r.length?(n.checked=!1,n.indeterminate=!1):r.length===a.length?(n.checked=!0,n.indeterminate=!1):(n.checked=!1,n.indeterminate=!0)}updateSliderFromCheckboxes(e,t){if(!this.isNumericColumn(t))return;const n=e.querySelector(".range-min"),a=e.querySelector(".range-max");if(!n||!a)return;const r=e.querySelectorAll('.filter-checkbox:checked:not([data-value="__all__"])');if(0===r.length)return;const i=Array.from(r).map((e=>parseFloat(e.dataset.value))).filter((e=>!isNaN(e)));if(i.length>0){const e=Math.min(...i),t=Math.max(...i),r=parseInt(n.dataset.decimalPlaces)||0;n.value=g.formatNumberValue(e,r),a.value=g.formatNumberValue(t,r)}}updateDateSliderFromCheckboxes(e,t){const n=e.querySelector(".date-range-min"),a=e.querySelector(".date-range-max");if(!n||!a)return;const r=e.querySelectorAll(".date-filter-checkbox:checked");if(0===r.length)return;const i=Array.from(r).map((e=>e.dataset.value)).filter((e=>e&&"__all__"!==e&&/^\d{4}-\d{2}-\d{2}$/.test(e))).map((e=>new Date(e))).filter((e=>!isNaN(e.getTime())));if(i.length>0){const e=new Date(Math.min(...i)),t=new Date(Math.max(...i));n.value=e.toISOString().split("T")[0],a.value=t.toISOString().split("T")[0]}}updateDateCheckboxFromRange(e,t){const n=e.querySelector(".date-range-min"),a=e.querySelector(".date-range-max");if(!n||!a)return;const r=new Date(n.value),i=new Date(a.value);if(isNaN(r.getTime())||isNaN(i.getTime()))return;e.querySelectorAll(".date-filter-checkbox").forEach((e=>{const t=e.dataset.value;if(t&&"__all__"!==t)if(/^\d{4}-\d{2}-\d{2}$/.test(t)){const n=new Date(t);e.checked=n>=r&&n<=i}else if(/^\d{4}$/.test(t)){parseInt(t),r.getFullYear(),i.getFullYear()}else if(/^\d{4}-.+$/.test(t)){const[e,n]=t.split("-");new Date(Date.parse(n+" 1, 2000")).getMonth()}})),this.updateDateParentCheckboxes(e)}updateHierarchicalCheckboxState(e,t){if(!e||!t||0===t.length)return;const n=Array.from(t).filter((e=>e.checked)).length;0===n?(e.checked=!1,e.indeterminate=!1):n===t.length?(e.checked=!0,e.indeterminate=!1):(e.checked=!1,e.indeterminate=!0)}propagateCheckboxStateToChildren(e,t){if(!e||!t)return;const n=e.checked;Array.from(t).forEach((e=>{e.checked=n,e.indeterminate=!1})),e.indeterminate=!1}updateDateParentCheckboxes(e){e.querySelectorAll(".date-filter-month").forEach((e=>{const t=e.querySelector(".date-filter-checkbox"),n=e.querySelectorAll(".date-filter-days .date-filter-checkbox");this.updateHierarchicalCheckboxState(t,n)}));e.querySelectorAll(".date-filter-group").forEach((e=>{const t=e.querySelector(".date-filter-checkbox"),n=e.querySelectorAll(".date-filter-children .date-filter-checkbox");this.updateHierarchicalCheckboxState(t,n)}))}handleDateHierarchyCheckboxChange(e,t,n){const a=e.target,r=this.getDateHierarchyLevel(a);switch(r){case"year":this.handleYearCheckboxChange(a,t);break;case"month":this.handleMonthCheckboxChange(a,t);break;case"day":this.handleDayCheckboxChange(a,t);break;default:console.warn("⚠️ Unknown hierarchy level:",r)}n&&"function"==typeof n&&setTimeout((()=>n()),0)}getDateHierarchyLevel(e){return e.closest(".date-filter-group-header")?"year":e.closest(".date-filter-month-header")?"month":e.closest(".date-filter-day")?"day":"unknown"}handleYearCheckboxChange(e,t){const n=e.closest(".date-filter-group"),a=n.querySelectorAll(".date-filter-month .date-filter-checkbox"),r=n.querySelectorAll(".date-filter-day .date-filter-checkbox");this.propagateCheckboxStateToChildren(e,a),this.propagateCheckboxStateToChildren(e,r)}handleMonthCheckboxChange(e,t){const n=e.closest(".date-filter-month").querySelectorAll(".date-filter-day .date-filter-checkbox");this.propagateCheckboxStateToChildren(e,n),this.updateDateParentCheckboxes(t)}handleDayCheckboxChange(e,t){this.updateDateParentCheckboxes(t)}adjustDropdownPosition(e){if(!e)return;const t=e.querySelector(".filter-dropdown");if(!t)return;const n=window.innerWidth,a=window.innerHeight,r=a-20-20;t.style.maxHeight=`${r}px`,t.offsetHeight;const i=t.getBoundingClientRect();let s=parseFloat(e.style.left)||0,o=parseFloat(e.style.top)||0;o+i.height>a-20&&(o=a-i.height-20),o<20&&(o=20),s+i.width>n-5&&(s=n-i.width-5),s<5&&(s=5),e.style.left=`${s}px`,e.style.top=`${o}px`}closeFilter(){const e=document.querySelector(".filter-dropdown-wrapper");e&&(e._clickOutsideHandler&&document.removeEventListener("click",e._clickOutsideHandler),e._escapeKeyHandler&&document.removeEventListener("keydown",e._escapeKeyHandler),e._backdrop&&e._backdrop.remove(),e.remove());const t=document.querySelector(".filter-dropdown-backdrop");t&&t.remove(),this.state.openFilter=null}showColumnSettings(){const e=document.createElement("div");e.className="column-settings-overlay";const t=document.createElement("div");t.className="column-settings-modal";let n=`\n      <div class="column-settings-header">\n        <h3>${this.i18n.t("settings.columnSettings")}</h3>\n        <button class="close-btn">×</button>\n      </div>\n      <div class="column-settings-content">\n        <div class="column-list">\n          <div class="column-item select-all-item">\n            <label class="column-label">\n              <input type="checkbox" class="column-checkbox-all" id="select-all-columns">\n              <span class="column-text">${this.i18n.t("filter.all")}</span>\n            </label>\n          </div>\n          ${this.options.columns.map((e=>`\n            <div class="column-item">\n              <label class="column-label">\n                <input type="checkbox" class="column-checkbox" data-column="${e.key}" ${this.state.visibleColumns[e.key]?"checked":""}>\n                <span class="column-text">${e.title}</span>\n              </label>\n              <label class="pin-label">\n                <input type="checkbox" class="pin-checkbox" data-column="${e.key}" ${this.state.pinnedColumns[e.key]?"checked":""}>\n                <span class="pin-icon">📌</span>\n              </label>\n            </div>\n          `)).join("")}\n        </div>\n      </div>\n      <div class="column-settings-footer">\n        <button class="cancel-btn">${this.i18n.t("filter.cancel")}</button>\n        <button class="confirm-btn">OK</button>\n      </div>\n    `;t.innerHTML=n,e.appendChild(t),document.body.appendChild(e),e.querySelector(".close-btn").addEventListener("click",(()=>e.remove())),e.querySelector(".cancel-btn").addEventListener("click",(()=>e.remove()));const a=e.querySelector(".column-checkbox-all"),r=e.querySelectorAll(".column-checkbox"),i=()=>{const e=Array.from(r).filter((e=>e.checked)).length,t=r.length;0===e?(a.checked=!1,a.indeterminate=!1):e===t?(a.checked=!0,a.indeterminate=!1):(a.checked=!1,a.indeterminate=!0)};i(),a.addEventListener("change",(e=>{r.forEach((t=>t.checked=e.target.checked)),i()})),r.forEach((e=>{e.addEventListener("change",i)})),e.querySelector(".confirm-btn").addEventListener("click",(()=>{e.querySelectorAll(".column-checkbox").forEach((e=>{this.state.visibleColumns[e.dataset.column]=e.checked})),e.querySelectorAll(".pin-checkbox").forEach((e=>{this.state.pinnedColumns[e.dataset.column]=e.checked})),this.render(),this.saveStateDebounced&&this.saveStateDebounced(),e.remove()})),e.addEventListener("click",(t=>{t.target===e&&e.remove()}))}attachRangeSliderEvents(e,t,n){const a=e.querySelector(".range-slider"),r=e.querySelector(".range-track"),i=e.querySelector(".range-thumb-min"),s=e.querySelector(".range-thumb-max"),o=e.querySelector(".range-min"),l=e.querySelector(".range-max");if(!(a&&r&&i&&s&&o&&l))return;const c=parseFloat(a.dataset.min),d=parseFloat(a.dataset.max)-c,u=()=>{const e=parseFloat(o.value),t=parseFloat(l.value),n=(e-c)/d*100,a=(t-c)/d*100;i.style.left=`${n}%`,s.style.left=`${a}%`,r.style.left=`${n}%`,r.style.width=a-n+"%"};this.updateSliderFromCheckboxes(e,t),u(),o.addEventListener("input",(()=>{a._isUpdatingFromSlider||(u(),this.updateCheckboxFromRange(e,t),n())})),l.addEventListener("input",(()=>{a._isUpdatingFromSlider||(u(),this.updateCheckboxFromRange(e,t),n())}));let h=!1,p=null;const m=(e,t)=>{h=!0,p=t,e.preventDefault()},f=r=>{if(!h||!p)return;const i=a.getBoundingClientRect(),s=(r.clientX||(r.touches?.[0]?.clientX??0))-i.left,m=Math.max(0,Math.min(100,s/i.width*100)),f=c+m/100*d,y=parseInt(o.dataset.decimalPlaces)||0;if("min"===p.dataset.type){const e=parseFloat(l.value),t=Math.min(f,e);o.value=g.formatNumberValue(t,y)}else{const e=parseFloat(o.value),t=Math.max(f,e);l.value=g.formatNumberValue(t,y)}u(),this.updateCheckboxFromRange(e,t),n()},y=()=>{h=!1,p=null};i.addEventListener("mousedown",(e=>m(e,i))),s.addEventListener("mousedown",(e=>m(e,s))),document.addEventListener("mousemove",f),document.addEventListener("mouseup",y),i.addEventListener("touchstart",(e=>m(e,i)),{passive:!1}),s.addEventListener("touchstart",(e=>m(e,s)),{passive:!1}),document.addEventListener("touchmove",f,{passive:!1}),document.addEventListener("touchend",y)}updateRangeFromCheckbox(e,t){const n=e.querySelector(".range-min"),a=e.querySelector(".range-max"),r=e.querySelector(".range-slider");if(!n||!a||!r)return;const i=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]):checked'),s=e.querySelector('[data-value="__all__"]');if(s){const t=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"])');g.updateSelectAllState(s,t)}if(0===i.length){const t=parseFloat(r.dataset.min),i=parseFloat(r.dataset.max);r._isUpdatingFromSlider=!0,n.value=t,a.value=i;const s=e.querySelector(".range-track"),o=e.querySelector(".range-thumb-min"),l=e.querySelector(".range-thumb-max");s&&o&&l&&(o.style.left="0%",l.style.left="100%",s.style.left="0%",s.style.width="100%"),setTimeout((()=>{r._isUpdatingFromSlider=!1}),0)}else{const t=Array.from(i).map((e=>parseFloat(e.dataset.value))),s=Math.min(...t),o=Math.max(...t),l=parseFloat(n.value),c=parseFloat(a.value);if(s!==l||o!==c){r._isUpdatingFromSlider=!0,n.value=s,a.value=o;const t=parseFloat(r.dataset.min),i=parseFloat(r.dataset.max)-t,l=(s-t)/i*100,c=(o-t)/i*100,d=e.querySelector(".range-track"),u=e.querySelector(".range-thumb-min"),h=e.querySelector(".range-thumb-max");d&&u&&h&&(u.style.left=`${l}%`,h.style.left=`${c}%`,d.style.left=`${l}%`,d.style.width=c-l+"%"),setTimeout((()=>{r._isUpdatingFromSlider=!1}),0)}}}updateCheckboxFromRange(e,t){const n=e.querySelector(".range-min"),a=e.querySelector(".range-max");if(!n||!a)return;const r=parseFloat(n.value),i=parseFloat(a.value);e.querySelectorAll('.filter-checkbox:not([data-value="__all__"])').forEach((e=>{const t=parseFloat(e.dataset.value);isNaN(t)||(e.checked=t>=r&&t<=i)}));const s=e.querySelector('[data-value="__all__"]');if(s){const t=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"]):checked').length,n=e.querySelectorAll('.filter-checkbox:not([data-value="__all__"])').length;0===t?(s.checked=!1,s.indeterminate=!1):t===n?(s.checked=!0,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0)}}attachDateRangeSliderEvents(e,t,n){const a=e.querySelector(".date-range-slider"),r=e.querySelector(".date-range-track"),i=e.querySelector(".date-range-thumb-min"),s=e.querySelector(".date-range-thumb-max"),o=e.querySelector(".date-range-min"),l=e.querySelector(".date-range-max");if(!(a&&r&&i&&s&&o&&l))return;const c=new Date(a.dataset.min).getTime(),d=new Date(a.dataset.max).getTime()-c,u=()=>{const e=new Date(o.value).getTime(),t=new Date(l.value).getTime(),n=(e-c)/d*100,a=(t-c)/d*100;i.style.left=`${n}%`,s.style.left=`${a}%`,r.style.left=`${n}%`,r.style.width=a-n+"%"},h=this.state.dateRangeFilters?.[t.key];h?(o.value=h.startDate,l.value=h.endDate):this.updateDateSliderFromCheckboxes(e,t),u(),o.addEventListener("input",(()=>{u(),this.updateDateCheckboxFromRange(e,t),n()})),l.addEventListener("input",(()=>{u(),this.updateDateCheckboxFromRange(e,t),n()}));let p=!1,m=null;const f=(e,t)=>{p=!0,m=t,e.preventDefault()},g=r=>{if(!p||!m)return;const i=a.getBoundingClientRect(),s=(r.clientX||(r.touches?.[0]?.clientX??0))-i.left,h=Math.max(0,Math.min(100,s/i.width*100)),f=new Date(c+h/100*d).toISOString().split("T")[0];if("min"===m.dataset.type){const e=l.value,t=f<=e?f:e;o.value=t}else{const e=o.value,t=f>=e?f:e;l.value=t}u(),this.updateDateCheckboxFromRange(e,t),n()},y=()=>{p=!1,m=null};i.addEventListener("mousedown",(e=>f(e,i))),s.addEventListener("mousedown",(e=>f(e,s))),document.addEventListener("mousemove",g),document.addEventListener("mouseup",y),i.addEventListener("touchstart",(e=>f(e,i)),{passive:!1}),s.addEventListener("touchstart",(e=>f(e,s)),{passive:!1}),document.addEventListener("touchmove",g,{passive:!1}),document.addEventListener("touchend",y)}attachDateHierarchyEvents(e,t,n){const a=e.querySelectorAll(".expand-control-btn"),r=(e.querySelector(".date-filter-content"),t=>{const n=e.querySelectorAll(".date-filter-group"),r=e.querySelectorAll(".date-filter-month"),i=e.querySelectorAll(".date-filter-day");a.forEach((e=>e.classList.remove("active")));const s=e.querySelector(`[data-level="${t}"]`);switch(s&&s.classList.add("active"),t){case"year":n.forEach((e=>{e.style.display="block";e.querySelector(".date-filter-children").style.display="none";e.querySelector(".expand-btn").textContent="▶"}));break;case"month":n.forEach((e=>{e.style.display="block";e.querySelector(".date-filter-children").style.display="block";e.querySelector(".expand-btn").textContent="▼"})),r.forEach((e=>{e.style.display="block";e.querySelector(".date-filter-days").style.display="none";e.querySelector(".expand-btn-month").textContent="▶"}));break;case"day":n.forEach((e=>{e.style.display="block";e.querySelector(".date-filter-children").style.display="block";e.querySelector(".expand-btn").textContent="▼"})),r.forEach((e=>{e.style.display="block";e.querySelector(".date-filter-days").style.display="block";e.querySelector(".expand-btn-month").textContent="▼"})),i.forEach((e=>{e.style.display="block"}))}});a.forEach((t=>{t.addEventListener("click",(n=>{n.preventDefault(),n.stopPropagation(),r(t.dataset.level),setTimeout((()=>{this.adjustDropdownPosition(e)}),0)}))})),r("year");e.querySelectorAll(".expand-btn:not(.expand-btn-month)").forEach((t=>{t.addEventListener("click",(n=>{n.stopPropagation();const a=t.closest(".date-filter-group").querySelector(".date-filter-children");"none"!==a.style.display&&a.style.display?(a.style.display="none",t.textContent="▶"):(a.style.display="block",t.textContent="▼"),setTimeout((()=>{this.adjustDropdownPosition(e)}),0)}))}));e.querySelectorAll(".expand-btn-month").forEach((t=>{t.addEventListener("click",(n=>{n.stopPropagation();const a=t.closest(".date-filter-month").querySelector(".date-filter-days");"none"!==a.style.display&&a.style.display?(a.style.display="none",t.textContent="▶"):(a.style.display="block",t.textContent="▼"),setTimeout((()=>{this.adjustDropdownPosition(e)}),0)}))})),void 0===this._applyRealtimeOnDateChange&&(this._applyRealtimeOnDateChange=!0);e.querySelectorAll(".date-filter-checkbox").forEach((t=>{t.addEventListener("change",(t=>{const a=this._applyRealtimeOnDateChange;this._applyRealtimeOnDateChange=!1,this.handleDateHierarchyCheckboxChange(t,e,(()=>{this._applyRealtimeOnDateChange=a,this._applyRealtimeOnDateChange&&n&&n()}))}))}))}handleRangeFilter(e,t,n){const a=this.options.columns.find((t=>t.key===e));a&&(this.state.filteredData=this.state.data.filter((e=>{const r=parseFloat(e[a.dataIndex]);return!isNaN(r)&&r>=t&&r<=n})),this.state.currentPage=1,this.applySorting(),this.renderBody(),this.renderPagination())}isYearSelected(e,t,n){if(0===n.length)return!0;if(n.includes(e))return!0;if(Object.keys(t).some((t=>n.includes(`${e}-${t}`))))return!0;for(const e in t){if(t[e].some((e=>n.includes(e))))return!0}return!1}isMonthSelected(e,t,n,a){return 0===a.length||(!!a.includes(e)||(!!a.includes(`${e}-${t}`)||n.some((e=>a.includes(e)))))}isNumericColumn(e){const t=this.state.data[0]?.[e.dataIndex];return"number"==typeof t||!isNaN(Number(t))}groupDatesByHierarchy(e){const t={};e.forEach((e=>{if(e){const n=new Date(e),a=n.getFullYear(),r=String(n.getMonth()+1).padStart(2,"0"),i=n.getMonth(),s=(this.i18n.getMessage("filter.monthNames",this.i18n.currentLocale)||["January","February","March","April","May","June","July","August","September","October","November","December"])[i];t[a]||(t[a]={}),t[a][r]||(t[a][r]={displayName:s,dates:[]}),t[a][r].dates.push(e)}}));const n={};return Object.keys(t).sort(((e,t)=>parseInt(e)-parseInt(t))).forEach((e=>{n[e]={};Object.keys(t[e]).sort(((e,t)=>parseInt(e)-parseInt(t))).forEach((a=>{const r=t[e][a],i=r.displayName;n[e][i]=r.dates.sort(((e,t)=>new Date(e)-new Date(t)))}))})),n}_deepCopyData(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){const n=[];return t.set(e,n),e.forEach(((e,a)=>{n[a]=this._deepCopyData(e,t)})),n}const n={};return t.set(e,n),Object.keys(e).forEach((a=>{n[a]=this._deepCopyData(e[a],t)})),n}getData(){try{if("undefined"!=typeof structuredClone)return structuredClone(this.state.data)}catch(e){}return this._deepCopyData(this.state.data)}setData(e){this.state.data=this._deepCopyData(e||[]),this.state.currentPage=1,this.render(),this.pluginSystem&&this.pluginSystem.emitHook("data:afterLoad",{newData:e,type:"setData"})}updateData(e){this.setData(e)}getFilters(){return{...this.state.filters}}setFilters(e){this.state.filters={...e},this.render()}clearFilters(){this.state.filters={},this.render()}clearAllFilters(){this.state.filters={},this.state.rangeFilters={},this.state.dateRangeFilters={},this.render(),this.autoSaveSettings()}setFontSize(e){this.state.fontSize=e,this.renderMenu(),this.applyCurrentStyling(),this.autoSaveSettings()}setCellPadding(e){this.state.cellPadding=e,this.renderMenu(),this.applyCurrentStyling(),this.autoSaveSettings()}setLanguage(e){this.i18n.setLocale(e)&&(this.renderMenu(),this.renderPagination(),this.autoSaveSettings())}applyTheme(e,t=!1){console.log("[Theme] Applying theme:",e),this.themeManager.applyPreset(e);const n=this.themeManager.getCSSVariables();console.log("[Theme] CSS Variables:",n),this.container?(Object.keys(n).forEach((e=>{this.container.style.setProperty(e,n[e])})),console.log("[Theme] Applied to container:",this.container.className)):console.error("[Theme] Container not found!"),t||this.renderMenu(),t||this.autoSaveSettings()}applyFontSize(){const e=m.FONT_SIZES[this.state.fontSize]||m.FONT_SIZES.medium;if(this.container.style.setProperty("--table-font-size",e),!this.tableContainer)return;this.tableContainer.style.setProperty("font-size",e,"important");this.tableContainer.querySelectorAll("\n      .table, \n      .table-cell, \n      .table-header, \n      .header-content, \n      .header-title,\n      .enhanced-table-pagination,\n      .pagination-info,\n      .page-info,\n      tbody tr td\n    ").forEach((t=>{t.style.setProperty("font-size",e,"important")}));this.container.querySelectorAll("\n      .table-menu-container,\n      .table-menu-btn,\n      .table-menu-dropdown,\n      .table-menu-item,\n      .table-submenu-dropdown\n    ").forEach((t=>{t.style.setProperty("font-size",e,"important")}));document.querySelectorAll("\n      .filter-dropdown-wrapper,\n      .filter-dropdown,\n      .filter-dropdown-header,\n      .filter-dropdown-title,\n      .filter-dropdown-search,\n      .filter-search-input,\n      .filter-dropdown-content,\n      .filter-option,\n      .filter-option-label,\n      .filter-option-text,\n      .filter-dropdown-footer,\n      .filter-btn-confirm,\n      .filter-btn-cancel,\n      .filter-btn-clear-column,\n      .range-filter,\n      .range-label,\n      .range-input,\n      .date-range-filter,\n      .date-range-label,\n      .date-range-input,\n      .date-filter-content,\n      .date-filter-label,\n      .date-filter-text,\n      .date-expand-controls,\n      .expand-control-label,\n      .expand-control-btn\n    ").forEach((t=>{t.style.setProperty("font-size",e,"important")}));document.querySelectorAll("\n      .column-settings-overlay,\n      .column-settings-modal,\n      .column-settings-header,\n      .column-settings-content,\n      .column-list,\n      .column-item,\n      .column-label,\n      .column-text,\n      .column-settings-footer,\n      .confirm-btn,\n      .cancel-btn\n    ").forEach((t=>{t.style.setProperty("font-size",e,"important")}))}applyCellPadding(){const e=m.CELL_PADDING[this.state.cellPadding]||m.CELL_PADDING.standard,t=`${e.vertical} ${e.horizontal}`;if(!this.tableContainer)return;const n=`${Math.round(.6*parseInt(e.vertical))+"px"} ${Math.round(.8*parseInt(e.horizontal))+"px"}`;this.tableContainer.querySelectorAll(".table-cell").forEach((e=>{e.style.setProperty("padding",t,"important")}));this.tableContainer.querySelectorAll(".header-content").forEach((e=>{e.style.setProperty("padding",t,"important")}));this.container.querySelectorAll("\n      .table-menu-item,\n      .table-menu-btn\n    ").forEach((e=>{e.style.setProperty("padding",n,"important")}));document.querySelectorAll("\n      .filter-option,\n      .filter-btn-confirm,\n      .filter-btn-cancel,\n      .filter-btn-clear-column,\n      .range-input,\n      .date-range-input,\n      .filter-search-input,\n      .expand-control-btn\n    ").forEach((e=>{e.style.setProperty("padding",n,"important")}));document.querySelectorAll("\n      .filter-dropdown-header,\n      .filter-dropdown-search,\n      .filter-dropdown-footer,\n      .date-expand-controls\n    ").forEach((e=>{e.style.setProperty("padding",t,"important")}));this.tableContainer.querySelectorAll("\n      .enhanced-table-pagination,\n      .pagination-controls button\n    ").forEach((e=>{e.style.setProperty("padding",n,"important")}));document.querySelectorAll("\n      .column-item,\n      .confirm-btn,\n      .cancel-btn\n    ").forEach((e=>{e.style.setProperty("padding",n,"important")}))}getSelectedRows(){return[]}addTooltipToCell(e,t){if(!e||!t)return;const n=e.textContent||e.innerText||"";let a=null;const r=t=>{if(e.scrollWidth<=e.clientWidth&&e.scrollHeight<=e.clientHeight)return;a=document.createElement("div"),a.className="cell-tooltip",a.textContent=n,document.body.appendChild(a);const r=e.getBoundingClientRect(),i=a.getBoundingClientRect();let s=r.left+window.scrollX,o=r.bottom+window.scrollY+5;s+i.width>window.innerWidth&&(s=window.innerWidth-i.width-10),s<10&&(s=10),o+i.height>window.innerHeight+window.scrollY&&(o=r.top+window.scrollY-i.height-5),a.style.left=`${s}px`,a.style.top=`${o}px`},i=()=>{a&&(document.body.removeChild(a),a=null)};e.addEventListener("mouseenter",r),e.addEventListener("mouseleave",i),e._tooltipCleanup=()=>{e.removeEventListener("mouseenter",r),e.removeEventListener("mouseleave",i),i()}}showLocalStorageClearConfirmation(){const e=document.createElement("div");e.className="modal-overlay",e.style.cssText="\n      position: fixed;\n      top: 0;\n      left: 0;\n      width: 100%;\n      height: 100%;\n      background: rgba(0, 0, 0, 0.5);\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      z-index: 10000;\n    ";const t=document.createElement("div");t.className="modal-content",t.style.cssText="\n      background: white;\n      padding: 24px;\n      border-radius: 8px;\n      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\n      max-width: 400px;\n      margin: 20px;\n    ",t.innerHTML=`\n      <h3 style="margin: 0 0 16px 0; color: #333;">${this.i18n.t("settings.clearStorageTitle")}</h3>\n      <p style="margin: 0 0 20px 0; line-height: 1.5; color: #666;">\n        ${this.i18n.t("settings.clearStorageMessage")}\n      </p>\n      <div style="margin: 0 0 20px 0;">\n        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">\n          <input type="radio" name="clear-scope" value="this" checked style="cursor: pointer;">\n          <span style="color: #333;">${this.i18n.t("settings.clearScopeThis")}</span>\n        </label>\n        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; margin-top: 8px;">\n          <input type="radio" name="clear-scope" value="all" style="cursor: pointer;">\n          <span style="color: #333;">${this.i18n.t("settings.clearScopeAll")}</span>\n        </label>\n      </div>\n      <div style="display: flex; gap: 12px; justify-content: flex-end;">\n        <button class="modal-cancel-btn" style="\n          padding: 8px 16px;\n          border: 1px solid #ddd;\n          background: white;\n          color: #333;\n          border-radius: 4px;\n          cursor: pointer;\n        ">${this.i18n.t("settings.clearStorageCancel")}</button>\n        <button class="modal-confirm-btn" style="\n          padding: 8px 16px;\n          border: none;\n          background: #ff4d4f;\n          color: white;\n          border-radius: 4px;\n          cursor: pointer;\n        ">${this.i18n.t("settings.clearStorageConfirm")}</button>\n      </div>\n    `,e.appendChild(t),document.body.appendChild(e);const n=()=>{document.body.removeChild(e)},a=t.querySelector(".modal-cancel-btn"),r=t.querySelector(".modal-confirm-btn");a.addEventListener("click",n),r.addEventListener("click",(async()=>{const e=t.querySelector('input[name="clear-scope"]:checked').value;await this.clearLocalStorageData(e),n()})),e.addEventListener("click",(t=>{t.target===e&&n()}));const i=e=>{"Escape"===e.key&&(n(),document.removeEventListener("keydown",i))};document.addEventListener("keydown",i)}showConditionalFormatting(){if(!this.conditionalFormatting){if(void 0===window.ConditionalFormatting)return console.error("ConditionalFormatting class not found. Please rebuild the project."),void alert("Conditional formatting feature is not available. Please rebuild or use the bundled dist files.");this.conditionalFormatting=new window.ConditionalFormatting(this)}this.conditionalFormatting.showManagementScreen()}initializeConditionalFormatting(){if(void 0!==window.ConditionalFormatting&&!this.conditionalFormatting)try{console.log("Auto-initializing conditional formatting plugin..."),this.conditionalFormatting=new window.ConditionalFormatting(this,{autoLoad:!0,autoApply:!0}),console.log("Conditional formatting plugin initialized successfully")}catch(e){console.warn("Failed to auto-initialize conditional formatting:",e)}}async clearLocalStorageData(e="all"){if(!this._clearingLocalStorage){this._clearingLocalStorage=!0;try{if(this.settingsManager&&await this.clearSettings(),"all"===e)Object.keys(localStorage).forEach((e=>{(e.startsWith("excelike_")||e.startsWith("excelike-")||e.startsWith("table-plugin-"))&&localStorage.removeItem(e)}));else{const e=this.tableId;Object.keys(localStorage).forEach((t=>{t.includes(e)&&localStorage.removeItem(t)}))}this.closeFilter(),this.state.columnWidths={},this.state.visibleColumns={},this.state.pinnedColumns={},this.state.filters={},this.state.sortState={},this.state.rangeFilters={},this.state.dateRangeFilters={},this.state.fontSize="medium",this.state.cellPadding="standard",this.state.currentPage=1,this.state.openFilter=null,this.state.columnFilters&&(this.state.columnFilters={}),this.state.filteredData=[...this.state.data],this.state.sortedData=[...this.state.data],this.showTemporaryMessage(this.i18n.t("settings.cleared"),"success"),setTimeout((()=>{window.location.reload()}),500)}catch(e){console.error("Error clearing LocalStorage data:",e);try{this.showTemporaryMessage(this.i18n.t("settings.clearError"),"error")}catch(e){console.error("Could not show error message:",e)}}finally{this._clearingLocalStorage=!1}}}applyDefaultVisualSettings(){if(!this.tableContainer)return void console.warn("Table container not found, skipping visual settings reset");this.state.fontSize="medium",this.state.cellPadding="standard",this.applyCurrentStyling();this.tableContainer.querySelectorAll("th").forEach((e=>{e.style.width="",e.style.minWidth="",e.style.maxWidth=""}));this.tableContainer.querySelectorAll("td").forEach((e=>{e.style.width="",e.style.minWidth="",e.style.maxWidth=""}));const e=this.tableContainer.querySelector(".table");e&&(e.style.fontSize="",e.classList.remove("font-smallest","font-small","font-large","font-largest"),e.classList.remove("padding-wide","padding-narrow"));this.tableContainer.querySelectorAll(".pinned-left").forEach((e=>{e.classList.remove("pinned-left"),e.style.position="",e.style.left="",e.style.zIndex="",e.style.backgroundColor=""}))}showTemporaryMessage(e,t="info"){const n=document.createElement("div");n.style.cssText=`\n      position: fixed;\n      top: 20px;\n      right: 20px;\n      padding: 12px 20px;\n      border-radius: 4px;\n      color: white;\n      font-size: 14px;\n      z-index: 10001;\n      animation: slideIn 0.3s ease-out;\n      background: ${"success"===t?"#52c41a":"error"===t?"#ff4d4f":"#1890ff"};\n      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n    `;const a=document.createElement("style");a.textContent="\n      @keyframes slideIn {\n        from { transform: translateX(100%); opacity: 0; }\n        to { transform: translateX(0); opacity: 1; }\n      }\n      @keyframes slideOut {\n        from { transform: translateX(0); opacity: 1; }\n        to { transform: translateX(100%); opacity: 0; }\n      }\n    ",document.head.appendChild(a),n.textContent=e,document.body.appendChild(n),setTimeout((()=>{n.style.animation="slideOut 0.3s ease-out",setTimeout((()=>{n.parentNode&&document.body.removeChild(n),a.parentNode&&document.head.removeChild(a)}),300)}),3e3)}destroy(){this.documentClickHandler&&document.removeEventListener("click",this.documentClickHandler),this.container.innerHTML="",this.closeFilter()}}return"undefined"!=typeof module&&module.exports&&(module.exports.ColumnHelpers=f),"undefined"!=typeof window&&(window.ExceLikeTable=S,window.ColumnHelpers=f),{ExceLikeTable:S,ColumnHelpers:f,TABLE_CONFIG:m}}));
//# sourceMappingURL=/sm/4c1d309ab164bf6e5dcab661303a4c48c49a3d959f927b3cea96dc8050641e80.map