dccxx-s3-explorer 1.0.1-coopbank → 1.0.2-coopbank

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -214,6 +214,6 @@ Valid keys: `+JSON.stringify(Object.keys(L),null," "));var ye=Je(Pe,Ne,Se,Ie,Ae
214
214
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yH(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function wH(t){if(Array.isArray(t))return Ng(t)}function LS(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function HS(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?LS(Object(n),!0).forEach(function(r){$S(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):LS(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function $S(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ic(t,e){return xH(t)||CH(t,e)||US(t,e)||bH()}function bH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
215
215
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function US(t,e){if(t){if(typeof t=="string")return Ng(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if(n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set")return Array.from(t);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Ng(t,e)}}function Ng(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function CH(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r=[],o=!0,a=!1,c,l;try{for(n=n.call(t);!(o=(c=n.next()).done)&&(r.push(c.value),!(e&&r.length===e));o=!0);}catch(f){a=!0,l=f}finally{try{!o&&n.return!=null&&n.return()}finally{if(a)throw l}}return r}}function xH(t){if(Array.isArray(t))return t}var _H=typeof kg=="function"?kg:kg.default,SH="file-invalid-type",TH="file-too-large",EH="file-too-small",AH="too-many-files",IH=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",n=e.split(","),r=n.length>1?"one of ".concat(n.join(", ")):n[0];return{code:SH,message:"File type must be ".concat(r)}},BS=function(e){return{code:TH,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},zS=function(e){return{code:EH,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},kH={code:AH,message:"Too many files"};function VS(t,e){var n=t.type==="application/x-moz-file"||_H(t,e);return[n,n?null:IH(e)]}function KS(t,e,n){if(Vi(t.size))if(Vi(e)&&Vi(n)){if(t.size>n)return[!1,BS(n)];if(t.size<e)return[!1,zS(e)]}else{if(Vi(e)&&t.size<e)return[!1,zS(e)];if(Vi(n)&&t.size>n)return[!1,BS(n)]}return[!0,null]}function Vi(t){return t!=null}function NH(t){var e=t.files,n=t.accept,r=t.minSize,o=t.maxSize,a=t.multiple,c=t.maxFiles,l=t.validator;return!a&&e.length>1||a&&c>=1&&e.length>c?!1:e.every(function(f){var h=VS(f,n),p=ic(h,1),g=p[0],y=KS(f,r,o),v=ic(y,1),x=v[0],w=l?l(f):null;return g&&x&&!w})}function Jd(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function Qd(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function GS(t){t.preventDefault()}function OH(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function PH(t){return t.indexOf("Edge/")!==-1}function MH(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return OH(t)||PH(t)}function lo(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return function(r){for(var o=arguments.length,a=new Array(o>1?o-1:0),c=1;c<o;c++)a[c-1]=arguments[c];return e.some(function(l){return!Jd(r)&&l&&l.apply(void 0,[r].concat(a)),Jd(r)})}}function RH(){return"showOpenFilePicker"in window}function DH(t){if(Vi(t)){var e=Object.entries(t).filter(function(n){var r=ic(n,2),o=r[0],a=r[1],c=!0;return jS(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),c=!1),(!Array.isArray(a)||!a.every(WS))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),c=!1),c}).reduce(function(n,r){var o=ic(r,2),a=o[0],c=o[1];return HS(HS({},n),{},$S({},a,c))},{});return[{description:"Files",accept:e}]}return t}function FH(t){if(Vi(t))return Object.entries(t).reduce(function(e,n){var r=ic(n,2),o=r[0],a=r[1];return[].concat(FS(e),[o],FS(a))},[]).filter(function(e){return jS(e)||WS(e)}).join(",")}function LH(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function HH(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function jS(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}function WS(t){return/^.*\.[\w]+$/.test(t)}var $H=["children"],UH=["open"],BH=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],zH=["refKey","onChange","onClick"];function VH(t){return jH(t)||GH(t)||qS(t)||KH()}function KH(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
216
216
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function GH(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function jH(t){if(Array.isArray(t))return Pg(t)}function Og(t,e){return YH(t)||qH(t,e)||qS(t,e)||WH()}function WH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
217
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qS(t,e){if(t){if(typeof t=="string")return Pg(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if(n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set")return Array.from(t);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Pg(t,e)}}function Pg(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function qH(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r=[],o=!0,a=!1,c,l;try{for(n=n.call(t);!(o=(c=n.next()).done)&&(r.push(c.value),!(e&&r.length===e));o=!0);}catch(f){a=!0,l=f}finally{try{!o&&n.return!=null&&n.return()}finally{if(a)throw l}}return r}}function YH(t){if(Array.isArray(t))return t}function YS(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function Ut(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?YS(Object(n),!0).forEach(function(r){Mg(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):YS(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Mg(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Xd(t,e){if(t==null)return{};var n=JH(t,e),r,o;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(o=0;o<a.length;o++)r=a[o],!(e.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function JH(t,e){if(t==null)return{};var n={},r=Object.keys(t),o,a;for(a=0;a<r.length;a++)o=r[a],!(e.indexOf(o)>=0)&&(n[o]=t[o]);return n}var Rg=M.forwardRef(function(t,e){var n=t.children,r=Xd(t,$H),o=QS(r),a=o.open,c=Xd(o,UH);return M.useImperativeHandle(e,function(){return{open:a}},[a]),M.createElement(M.Fragment,null,n(Ut(Ut({},c),{},{open:a})))});Rg.displayName="Dropzone";var JS={disabled:!1,getFilesFromEvent:cH,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};Rg.defaultProps=JS,Rg.propTypes={children:It.func,accept:It.objectOf(It.arrayOf(It.string)),multiple:It.bool,preventDropOnDocument:It.bool,noClick:It.bool,noKeyboard:It.bool,noDrag:It.bool,noDragEventsBubbling:It.bool,minSize:It.number,maxSize:It.number,maxFiles:It.number,disabled:It.bool,getFilesFromEvent:It.func,onFileDialogCancel:It.func,onFileDialogOpen:It.func,useFsAccessApi:It.bool,autoFocus:It.bool,onDragEnter:It.func,onDragLeave:It.func,onDragOver:It.func,onDrop:It.func,onDropAccepted:It.func,onDropRejected:It.func,onError:It.func,validator:It.func};var Dg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function QS(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=Ut(Ut({},JS),t),n=e.accept,r=e.disabled,o=e.getFilesFromEvent,a=e.maxSize,c=e.minSize,l=e.multiple,f=e.maxFiles,h=e.onDragEnter,p=e.onDragLeave,g=e.onDragOver,y=e.onDrop,v=e.onDropAccepted,x=e.onDropRejected,w=e.onFileDialogCancel,_=e.onFileDialogOpen,I=e.useFsAccessApi,k=e.autoFocus,O=e.preventDropOnDocument,R=e.noClick,E=e.noKeyboard,z=e.noDrag,j=e.noDragEventsBubbling,W=e.onError,ne=e.validator,q=M.useMemo(function(){return FH(n)},[n]),me=M.useMemo(function(){return DH(n)},[n]),he=M.useMemo(function(){return typeof _=="function"?_:XS},[_]),be=M.useMemo(function(){return typeof w=="function"?w:XS},[w]),G=M.useRef(null),X=M.useRef(null),Y=M.useReducer(QH,Dg),ae=Og(Y,2),Z=ae[0],J=ae[1],L=Z.isFocused,te=Z.isFileDialogActive,xe=M.useRef(typeof window<"u"&&window.isSecureContext&&I&&RH()),_e=function(){!xe.current&&te&&setTimeout(function(){if(X.current){var re=X.current.files;re.length||(J({type:"closeDialog"}),be())}},300)};M.useEffect(function(){return window.addEventListener("focus",_e,!1),function(){window.removeEventListener("focus",_e,!1)}},[X,te,be,xe]);var Se=M.useRef([]),Ie=function(re){G.current&&G.current.contains(re.target)||(re.preventDefault(),Se.current=[])};M.useEffect(function(){return O&&(document.addEventListener("dragover",GS,!1),document.addEventListener("drop",Ie,!1)),function(){O&&(document.removeEventListener("dragover",GS),document.removeEventListener("drop",Ie))}},[G,O]),M.useEffect(function(){return!r&&k&&G.current&&G.current.focus(),function(){}},[G,k,r]);var Ae=M.useCallback(function(H){W?W(H):console.error(H)},[W]),Pe=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H),Se.current=[].concat(VH(Se.current),[H.target]),Qd(H)&&Promise.resolve(o(H)).then(function(re){if(!(Jd(H)&&!j)){var pe=re.length,de=pe>0&&NH({files:re,accept:q,minSize:c,maxSize:a,multiple:l,maxFiles:f,validator:ne}),Ce=pe>0&&!de;J({isDragAccept:de,isDragReject:Ce,isDragActive:!0,type:"setDraggedFiles"}),h&&h(H)}}).catch(function(re){return Ae(re)})},[o,h,Ae,j,q,c,a,l,f,ne]),Le=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H);var re=Qd(H);if(re&&H.dataTransfer)try{H.dataTransfer.dropEffect="copy"}catch{}return re&&g&&g(H),!1},[g,j]),De=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H);var re=Se.current.filter(function(de){return G.current&&G.current.contains(de)}),pe=re.indexOf(H.target);pe!==-1&&re.splice(pe,1),Se.current=re,!(re.length>0)&&(J({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),Qd(H)&&p&&p(H))},[G,p,j]),Ne=M.useCallback(function(H,re){var pe=[],de=[];H.forEach(function(Ce){var We=VS(Ce,q),ht=Og(We,2),ft=ht[0],Bn=ht[1],or=KS(Ce,c,a),$t=Og(or,2),ir=$t[0],ar=$t[1],sr=ne?ne(Ce):null;if(ft&&ir&&!sr)pe.push(Ce);else{var He=[Bn,ar];sr&&(He=He.concat(sr)),de.push({file:Ce,errors:He.filter(function(ho){return ho})})}}),(!l&&pe.length>1||l&&f>=1&&pe.length>f)&&(pe.forEach(function(Ce){de.push({file:Ce,errors:[kH]})}),pe.splice(0)),J({acceptedFiles:pe,fileRejections:de,isDragReject:de.length>0,type:"setFiles"}),y&&y(pe,de,re),de.length>0&&x&&x(de,re),pe.length>0&&v&&v(pe,re)},[J,l,q,c,a,f,y,v,x,ne]),Je=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H),Se.current=[],Qd(H)&&Promise.resolve(o(H)).then(function(re){Jd(H)&&!j||Ne(re,H)}).catch(function(re){return Ae(re)}),J({type:"reset"})},[o,Ne,Ae,j]),ye=M.useCallback(function(){if(xe.current){J({type:"openDialog"}),he();var H={multiple:l,types:me};window.showOpenFilePicker(H).then(function(re){return o(re)}).then(function(re){Ne(re,null),J({type:"closeDialog"})}).catch(function(re){LH(re)?(be(re),J({type:"closeDialog"})):HH(re)?(xe.current=!1,X.current?(X.current.value=null,X.current.click()):Ae(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):Ae(re)});return}X.current&&(J({type:"openDialog"}),he(),X.current.value=null,X.current.click())},[J,he,be,I,Ne,Ae,me,l]),st=M.useCallback(function(H){!G.current||!G.current.isEqualNode(H.target)||(H.key===" "||H.key==="Enter"||H.keyCode===32||H.keyCode===13)&&(H.preventDefault(),ye())},[G,ye]),bt=M.useCallback(function(){J({type:"focus"})},[]),sn=M.useCallback(function(){J({type:"blur"})},[]),gn=M.useCallback(function(){R||(MH()?setTimeout(ye,0):ye())},[R,ye]),Rt=function(re){return r?null:re},$n=function(re){return E?null:Rt(re)},nn=function(re){return z?null:Rt(re)},Un=function(re){j&&re.stopPropagation()},Bt=M.useMemo(function(){return function(){var H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},re=H.refKey,pe=re===void 0?"ref":re,de=H.role,Ce=H.onKeyDown,We=H.onFocus,ht=H.onBlur,ft=H.onClick,Bn=H.onDragEnter,or=H.onDragOver,$t=H.onDragLeave,ir=H.onDrop,ar=Xd(H,BH);return Ut(Ut(Mg({onKeyDown:$n(lo(Ce,st)),onFocus:$n(lo(We,bt)),onBlur:$n(lo(ht,sn)),onClick:Rt(lo(ft,gn)),onDragEnter:nn(lo(Bn,Pe)),onDragOver:nn(lo(or,Le)),onDragLeave:nn(lo($t,De)),onDrop:nn(lo(ir,Je)),role:typeof de=="string"&&de!==""?de:"presentation"},pe,G),!r&&!E?{tabIndex:0}:{}),ar)}},[G,st,bt,sn,gn,Pe,Le,De,Je,E,z,r]),D=M.useCallback(function(H){H.stopPropagation()},[]),K=M.useMemo(function(){return function(){var H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},re=H.refKey,pe=re===void 0?"ref":re,de=H.onChange,Ce=H.onClick,We=Xd(H,zH),ht=Mg({accept:q,multiple:l,type:"file",style:{border:0,clip:"rect(0, 0, 0, 0)",clipPath:"inset(50%)",height:"1px",margin:"0 -1px -1px 0",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap"},onChange:Rt(lo(de,Je)),onClick:Rt(lo(Ce,D)),tabIndex:-1},pe,X);return Ut(Ut({},ht),We)}},[X,n,l,Je,r]);return Ut(Ut({},Z),{},{isFocused:L&&!r,getRootProps:Bt,getInputProps:K,rootRef:G,inputRef:X,open:Rt(ye)})}function QH(t,e){switch(e.type){case"focus":return Ut(Ut({},t),{},{isFocused:!0});case"blur":return Ut(Ut({},t),{},{isFocused:!1});case"openDialog":return Ut(Ut({},Dg),{},{isFileDialogActive:!0});case"closeDialog":return Ut(Ut({},t),{},{isFileDialogActive:!1});case"setDraggedFiles":return Ut(Ut({},t),{},{isDragActive:e.isDragActive,isDragAccept:e.isDragAccept,isDragReject:e.isDragReject});case"setFiles":return Ut(Ut({},t),{},{acceptedFiles:e.acceptedFiles,fileRejections:e.fileRejections,isDragReject:e.isDragReject});case"reset":return Ut({},Dg);default:return t}}function XS(){}const XH=({onFilesSelected:t,children:e})=>{const[n,r]=M.useState(!1),{getRootProps:o,getInputProps:a}=QS({noClick:!0,onDrop:c=>{if(c&&c.length>0)if(c[0].path.split("/").length>2){const f=c.map(h=>{const g=(h.path||h.relativePath||"").split("/").slice(1).join("/");return(!h.webkitRelativePath||h.webkitRelativePath==="")&&Object.defineProperty(h,"webkitRelativePath",{writable:!0,value:g,enumerable:!0,configurable:!0}),h});t(f,"folder")}else t(c,"files");r(!1)},onDragOver:c=>{c.preventDefault(),n||r(!0)},multiple:!0});return M.useEffect(()=>{const c=l=>{l.clientX===0&&l.clientY===0&&r(!1)};return document.addEventListener("dragleave",c),()=>{document.removeEventListener("dragleave",c)}},[]),u.jsxs("div",{...o(),className:"transition-opacity min-h-[600px]",children:[n?u.jsx("div",{className:"flex flex-col items-center justify-center p-4 border-2 border-dashed border-gray-300 rounded-lg bg-gray-50 h-screen"}):e,u.jsx("input",{...a()})]})},ZH=({isOpen:t,onClose:e,files:n})=>{const[r,o]=M.useState(null),a=l=>{o(f=>!f||f.key!==l?{key:l,direction:"asc"}:{key:l,direction:f.direction==="asc"?"desc":"asc"})},c=M.useMemo(()=>r?[...n].sort((l,f)=>{var g,y;const h=((g=l[r.key])==null?void 0:g.toString().toLowerCase())||"",p=((y=f[r.key])==null?void 0:y.toString().toLowerCase())||"";return h<p?r.direction==="asc"?-1:1:h>p?r.direction==="asc"?1:-1:0}):n,[n,r]);return u.jsx(pr,{open:t,onOpenChange:e,children:u.jsxs(Qn,{className:"sm:max-w-[825px]",children:[u.jsxs(Xn,{children:[u.jsx(Zn,{children:"Tài liệu đang xử lý"}),u.jsx(Mo,{children:"Đây là danh sách các tài liệu đang trong hàng đợi xử lý."})]}),u.jsx("div",{className:"max-h-96 overflow-y-auto",children:u.jsxs(js,{children:[u.jsx(Ws,{children:u.jsxs(er,{children:[u.jsxs(tr,{colSpan:2,className:"text-left cursor-pointer hover:underline",onClick:()=>a("type"),children:["Loại ",(r==null?void 0:r.key)==="type"&&(r.direction==="asc"?"↑":"↓")]}),u.jsxs(tr,{colSpan:3,className:"text-left cursor-pointer hover:underline",onClick:()=>a("name"),children:["Tên tệp"," ",(r==null?void 0:r.key)==="name"&&(r.direction==="asc"?"↑":"↓")]}),u.jsx(tr,{className:"text-left",children:"Ghi chú"})]})}),u.jsx(qs,{children:c.length>0&&c.map(l=>u.jsxs(er,{children:[u.jsx(pn,{colSpan:2,children:l.type}),u.jsx(pn,{colSpan:3,className:"font-medium text-left truncate max-w-[200px]",title:l.name,children:l.name}),u.jsx(pn,{children:l.unSupported&&!l.isFolder?`Không hỗ trợ file ${l.name.split(".").pop()}`:!!l.timeout&&u.jsx("span",{style:{color:"red"},children:"Parsing lỗi, vui lòng thử lại."})})]}))})]})})]})})},e$=({openDialogRename:t,setOpenDialogRename:e,apiBaseUrl:n,setFileToMove:r,fileToMove:o,refreshFiles:a,ignoreCache:c,autoSyncAfterFileOperation:l})=>{var O;const[f,h]=M.useState({}),[p,g]=M.useState(!1),[y,v]=M.useState(!1),[x,w]=M.useState(""),{toast:_}=Fd();M.useEffect(()=>{t&&I(x)},[x,t]);const I=async R=>{try{v(!0);const E=await Re.get(`${n}/api/list-s3-folders?prefix=${R}`,{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});h(E==null?void 0:E.data)}catch{_({title:"Error",description:"Unable to load S3 folder list",variant:"destructive"})}finally{v(!1)}},k=async()=>{g(!0);try{const R=o.key,E=R.endsWith("/")?R:`${R}/`,z=x.endsWith("/")?x:`${x}/`;if(E===z||R===x){_({title:"Lỗi",description:"Không thể di chuyển file đến cùng vị trí",variant:"destructive"}),g(!1);return}await Re.post(`${n}/api/move`,{oldPath:R,newPath:x},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),c.current=!0,await a(),_({title:"Đã di chuyển",description:`Đã di chuyển thành công "${o.name}" đến "${x}"`}),e(!1),r(null),w(""),l&&await l("move")}catch(R){console.error("Error renaming item:",R),_({title:"Lỗi",description:"Không thể đổi tên",variant:"destructive"})}finally{g(!1)}};return u.jsx(pr,{open:t,onOpenChange:R=>{R||(e(!1),r(null),w(""))},children:u.jsxs(Qn,{className:"max-h-[700px] pb-3 px-1 s3-explr-input-group max-w-5xl w-[90%] p-6 bg-white rounded-lg shadow-lg",children:[u.jsxs(Xn,{className:"mb-4 w-full h-full",children:[u.jsx("nav",{className:"mb-4",children:u.jsxs("ul",{className:"flex items-center space-x-2 text-sm text-gray-600",children:[u.jsx("li",{className:"cursor-pointer hover:text-blue-600 transition-colors",onClick:()=>w(""),children:"Root"}),x.split("/").map((R,E,z)=>u.jsx("li",{className:"cursor-pointer hover:text-blue-600 transition-colors",onClick:()=>w(R==="Root"?"":z.slice(0,E+1).join("/")+"/"),children:R},E))]})}),u.jsxs(Zn,{className:"text-xl font-semibold text-gray-800",children:["Di chuyển"," ",u.jsxs("span",{className:"text-sm text-gray-500",children:["( file Hoặc folder sẽ được di chuyển đến thư mục"," ",x===""?"Root":x," )"]})]}),u.jsx(Mo,{className:"text-gray-600 w-full h-[50dvh] max-h-[500px] overflow-hidden overflow-y-auto",children:y?u.jsx("div",{className:"flex justify-center items-center py-4",children:u.jsx("div",{className:"loader ease-linear rounded-full border-4 border-t-4 border-gray-200 h-12 w-12"})}):u.jsx("ul",{className:"space-y-2",children:(O=Object.keys(f))==null?void 0:O.map(R=>u.jsx("li",{className:"cursor-pointer hover:bg-gray-100 p-2 rounded transition-colors",onClick:()=>w(R),children:R},R))})})]}),u.jsxs(Po,{className:"flex justify-end space-x-2",children:[u.jsx($e,{variant:"outline",onClick:()=>e(!1),className:"px-4 py-2 rounded border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors",children:"Cancel"}),u.jsx($e,{onClick:k,disabled:p,className:"s3-explr-crawl-btn",children:"Move"})]})]})})},t$="AIzaSyBI8KiTWudkw8iR5cjH7ZsA4JBN1NqJw8A",n$="726815747852-5deq413t8kd8j3mgj48d46eatjauapq5.apps.googleusercontent.com",r$="https://www.googleapis.com/auth/drive";No(Re,{retries:3,shouldResetTimeout:!0,retryCondition:t=>No.isRetryableError(t)&&t.config.method==="get"});const Hn={current:!1},ZS="crawl:jobs",Ka="crawl:current_job",o$=t=>{const[e,n]=M.useState(null),[r,o]=M.useState(0);return M.useEffect(()=>{const a=localStorage.getItem(Ka);if(a){const c=JSON.parse(a);n(c),c!=null&&c.startTime&&o(Math.floor((Date.now()-c.startTime)/1e3))}},[]),M.useEffect(()=>{if(!(e!=null&&e.startTime))return;const a=setInterval(()=>{o(Math.floor((Date.now()-e.startTime)/1e3))},1e3);return()=>clearInterval(a)},[e==null?void 0:e.startTime]),M.useEffect(()=>{if(!(e!=null&&e.id))return;const a=async()=>{try{const f=(await Re.get(`${t}/api/crawl/${e.id}?taskId=${e.taskId}`)).data;n(h=>{if(!h)return null;const p={...h,status:f};return localStorage.setItem(Ka,JSON.stringify(p)),(f.status==="completed"||f.status==="failed")&&setTimeout(()=>{n(null),localStorage.removeItem(Ka)},100),p})}catch(l){console.error("Error polling job status:",l)}},c=setInterval(a,3e3);return a(),()=>clearInterval(c)},[e==null?void 0:e.id,t]),{currentJob:e,elapsedTime:r,setCurrentJob:a=>{a&&!a.startTime&&(a.startTime=Date.now()),n(a),a?localStorage.setItem(Ka,JSON.stringify(a)):localStorage.removeItem(Ka)}}},Zd=(t,e)=>{const n=[],r=o=>{(t[o]||[]).forEach(c=>{n.push(c.key),c.isFolder&&r(c.key)})};return r(e),n},i$=(t,e)=>{const n=[];return(t[e]||[]).forEach(o=>{n.push(o.key),o.isFolder&&n.push(...Zd(t,o.key))}),n},a$=(t,e,n=[],r,o,a,c,l,f,h)=>{const[p,g]=M.useState({}),[y,v]=M.useState(!1),[x,w]=M.useState(null),[_,I]=M.useState(0),k=M.useRef(e);M.useEffect(()=>{k.current=e},[e]);const O=async()=>{v(!0);try{const E=await Re.get(`${t}/api/files`,{params:{cache:!1,displayPrefixes:JSON.stringify(n),prefix:k.current,excludePrivateFiles:c?"false":"true"},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:3e5}),z=[];vd.forEach(E.data,(j,W)=>{l!=null&&l.has(W)&&vd.forEach(j,ne=>{(f==null?void 0:f.current[ne.key])!==!1&&z.push(ne.key)})}),z.length&&(h==null||h(j=>{const W=new Set(j);return z.forEach(ne=>W.add(ne)),W})),g(E.data),w(null)}catch(E){w(E instanceof Error?E:new Error("Failed to fetch files"))}finally{v(!1),I(0),a("")}},R=async E=>{var z,j;try{if(!E)return;v(!0);const W=await Re.get(`${t}/api/search-db?query=${E}&rootPrefix=${e}&offset=${(o-1)*20}&limit=20`,{timeout:3e5,headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});return g({[e]:((z=W==null?void 0:W.data)==null?void 0:z.result)||[]}),I(((j=W==null?void 0:W.data)==null?void 0:j.estimatedTotalHits)||0),W}catch(W){w(W instanceof Error?W:new Error("Failed to fetch files"))}finally{v(!1)}};return M.useEffect(()=>{!r&&!y&&O(),r&&!y&&R(r)},[r,o]),{data:p,isLoading:y,error:x,estimatedTotalHits:_,refetch:O}},ac=t=>{var r,o,a;const e=((a=(o=(r=t==null?void 0:t.name)==null?void 0:r.split("."))==null?void 0:o.pop())==null?void 0:a.toLowerCase())??"";return["txt","md","json","js","ts","jsx","tsx","css","html","xml","yaml","yml"].includes(e||"")},s$={auth:{clientId:"584d5fa9-5123-4602-a1a5-a3746a83745f",authority:"https://login.microsoftonline.com/consumers",redirectUri:"http://localhost:5173/"}},c$=new Lh(s$),l$=M.memo(({homeLabel:t="Kho tài liệu",apiBaseUrl:e="http://localhost:3000",rootPrefix:n="coopbank-cagent-cmcts-ai/",rootUrlHostApi:r,asSelector:o=!1,onSelected:a=h=>console.log("Đã chọn:",h),displayPrefixes:c,preSelectedFiles:l,idCreator:f})=>{var Iu;const[h,p]=M.useState([]),[g,y]=M.useState(""),[v,x]=M.useState(new Set(l)),[w,_]=M.useState(n),[I,k]=M.useState(""),[O,R]=M.useState(!1),[E,z]=M.useState(""),[j,W]=M.useState(!1),[ne,q]=M.useState(null),[me,he]=M.useState(null),[be,G]=M.useState(!1),[X,Y]=M.useState(!1),[,ae]=M.useState(null),Z=M.useRef(null),{toast:J}=Fd(),[L,te]=M.useState(null),[xe,_e]=M.useState(null),[Se,Ie]=M.useState(""),[Ae,Pe]=M.useState(!1),[Le,De]=M.useState(!1),[Ne,Je]=M.useState(new Set),[ye,st]=M.useState(""),[bt,sn]=M.useState(!1),[gn,Rt]=M.useState(!1),[$n,nn]=M.useState("rename"),[Un,Bt]=M.useState(!1),[D,K]=M.useState(""),[H,re]=M.useState("1"),[pe,de]=M.useState(!1),[Ce,We]=M.useState(!1),[ht,ft]=M.useState(!1),[Bn,or]=M.useState(!1),[$t,ir]=M.useState(1),[ar,sr]=M.useState(!1),{currentJob:He,elapsedTime:ho,setCurrentJob:iu}=o$(e),[Br,vi]=M.useState(null),[Gi,ja]=M.useState(""),[zg,ji]=M.useState(!1),[Wi,au]=M.useState(""),[Vg,su]=M.useState(!1),[fc,cu]=M.useState(!1),[yi,lu]=M.useState([]),[qi,du]=M.useState(!1),[Wa,Kg]=M.useState(""),[uu,Gg]=M.useState({faqUploadSize:[],hdsdUploadSize:[],normalUploadSize:[],faqParsedSize:[],hdsdParsedSize:[],normalParsedSize:[]}),[jg,hc]=M.useState(!1),$o=M.useRef({}),Wg=async S=>{cu(!0);try{const N=await Re.get(`${r}get-knowledge-base/knowledge-base-name/${S}`,{headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAyOTliMmIwLTk4MGEtNGQ1Yy04NjkyLWJjNjllM2I1NzZlMiIsInVzZXJuYW1lIjoiY21jX3RzX2FkbWluIiwiaWF0IjoxNzQ3MTk0MTg3fQ.7LB2rgd0fQnhZP_cFgTTCPMSYl0_apwffcNEd7oqjeM"}});N.status===200&&lu(N.data.knowledgeBase.chatflows.map(U=>({...U,KnowledgeBaseId:N.data.knowledgeBase.knowledge_base_id})))}catch{}finally{cu(!1)}};M.useEffect(()=>{Wi&&r&&Wg(Wi)},[Wi]),M.useEffect(()=>{console.log("pre selected files",l)},[l]);const[kt,pc]=M.useState(null),[xT,qg]=M.useState(!1),[gc,mc]=M.useState(!1),[Yi,qa]=M.useState(!1),[fu,hu]=M.useState([]),[vc,yc]=M.useState([]),[Ji,wc]=M.useState([{id:"root",name:"OneDrive"}]),[Yg,Ya]=M.useState(!1),[Ja,bc]=M.useState([]),[pu,Uo]=M.useState(!1),[Qa,Cc]=M.useState([]),[xc,Xa]=M.useState([]),[Za,gu]=M.useState([]),[_c,Qi]=M.useState([{id:"root",name:"SharePoint"}]),[po,Xi]=M.useState(!1),[Sc,Tc]=M.useState([]),[pt,zr]=M.useState(null),[mu,Zi]=M.useState(!1),[Jg,ea]=M.useState(!1),vu=new URL(window.location.href).searchParams.get("prefix")||""||I||n,[_T,Zg]=M.useState(null),{data:go,isLoading:wi,error:em,estimatedTotalHits:ta,refetch:cn}=a$(e,vu,c,g,$t,y,f,v,$o,x),[Ec,gr]=M.useState(!1),Ac=M.useRef(null);M.useEffect(()=>{if(!Ec)return;function S(N){Ac.current&&!Ac.current.contains(N.target)&&gr(!1)}return document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S)}},[Ec]);const tm=async()=>{try{const S=await Re.get(`${e}/api/login-sharepoint`),{loginUrl:N}=S.data,U=window.open(N,"SharePoint Login","width=600,height=600");if(!U)throw new Error("Không thể mở cửa sổ pop-up");U.focus();const oe=setInterval(()=>{try{if(U.closed){clearInterval(oe);return}const fe=U.location.href;if(fe.includes("code=")){const we=new URL(fe).searchParams.get("code");we&&(yu(we),U.close(),clearInterval(oe))}}catch(fe){fe instanceof Error&&!fe.message.includes("cross-origin")&&console.error("SharePoint login error:",fe)}},1e3)}catch(S){rt.error("Lỗi khi đăng nhập SharePoint: "+(S instanceof Error?S.message:"Unknown error"))}},nm=async()=>{try{Cc([]),Qi([{id:"root",name:"SharePoint"}]),window.location.href="https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri="+encodeURIComponent(window.location.origin),J({title:"Success",description:"Logged out from SharePoint"})}catch(S){console.error("Error logging out from SharePoint:",S),J({title:"Error",description:"Failed to logout from SharePoint",variant:"destructive"})}},yu=async S=>{try{const N=await Re.post(`${e}/api/get-sharepoint-access-token`,{code:S,userId:"1"}),{accessToken:U}=N.data;localStorage.setItem("sharepoint_access_token",U),mc(!0),Xi(!0)}catch(N){console.error("❌ Error fetching SharePoint access token:",N),J({title:"Error",description:"Failed to connect to SharePoint",variant:"destructive"})}},rm=async()=>{try{Uo(!0);const N=(await Re.post(`${e}/api/list-site-sharepoint`,{userId:"1"})).data.sites.map(U=>{const oe=new URL(U.webUrl);return{id:U.id,name:U.name,description:U.description,hostname:U.hostname||oe.hostname,sitePath:U.sitePath||oe.pathname.replace(/^\/+/,"")}});Tc(N),Uo(!1)}catch(S){console.error("❌ Error fetching SharePoint sites:",S),J({title:"Error",description:"Failed to fetch SharePoint sites",variant:"destructive"}),Uo(!1)}},Nt=async S=>{zr(S),await mt("root",S.name,S.hostname||"",S.sitePath||"")},mt=async(S,N,U,oe)=>{try{Uo(!0);const we=(await Re.post(`${e}/api/list-file-sharepoint`,{folderId:S,userId:"1",hostname:U,sitePath:oe})).data.files.map(Te=>({id:Te.id,name:Te.name,size:Te.size??0,lastModified:Te.lastModifiedDateTime?new Date(Te.lastModifiedDateTime):new Date,contentType:Te.mimeType??void 0,isFolder:Te.type==="folder",parentId:Te.parentId??""}));Xa(we.filter(Te=>Te.isFolder)),Cc(we.filter(Te=>!Te.isFolder)),Xi(!0),Qi(Te=>Te.some(Tt=>Tt.id===S)?Te:[...Te,{id:S,name:N==="root"?"SharePoint":N}]),Uo(!1)}catch(fe){console.error("❌ Error fetching SharePoint files:",fe),J({title:"Error",description:"Failed to fetch SharePoint files",variant:"destructive"}),Uo(!1)}},om=S=>{gu(N=>N.some(oe=>oe.id===S.id)?N.filter(oe=>oe.id!==S.id):[...N,{id:S.id,name:S.name,size:S.size,lastModified:S.lastModified,contentType:S.contentType,isFolder:S.isFolder,parentId:S.parentId}])},im=S=>{var U;Qi(oe=>oe.slice(0,S+1));const N=(U=_c[S])==null?void 0:U.id;N&&mt(N,"SharePoint",(pt==null?void 0:pt.hostname)||"",(pt==null?void 0:pt.sitePath)||"")},am=async(S,N)=>{const U=localStorage.getItem("sharepoint_access_token");if(!U){rt.error("Không tìm thấy access token. Vui lòng đăng nhập lại.");return}const oe=rt.loading("Đang đồng bộ SharePoint...",{position:"bottom-right",autoClose:!1});try{const fe={prefix:N,folders:[],files:[],hostname:(pt==null?void 0:pt.hostname)||"",sitePath:(pt==null?void 0:pt.sitePath)||""};S.forEach(Te=>{Te.isFolder?fe.folders.push({id:Te.id,name:Te.name}):fe.files.push({id:Te.id,name:Te.name})});const we=await Re.post(`${e}/api/sync-sharepoint-to-s3`,fe,{headers:{Authorization:`Bearer ${U}`}});cn(),rt.update(oe,{render:`Đồng bộ thành công! Đã tải lên ${we.data.uploadedKeys.length} file.`,type:"success",isLoading:!1,autoClose:3e3,position:"bottom-right"}),Xi(!1)}catch(fe){console.error("Lỗi khi đồng bộ file từ SharePoint:",fe),rt.update(oe,{render:"Không thể đồng bộ file từ SharePoint.",type:"error",isLoading:!1,autoClose:3e3,position:"bottom-right"})}},wu=()=>{Xi(!1),Cc([]),gu([]),Qi([{id:"root",name:"SharePoint"}])};M.useEffect(()=>{if(po){const N=new URLSearchParams(window.location.search).get("code");N&&(yu(N),window.history.replaceState({},document.title,window.location.pathname))}},[po]),M.useEffect(()=>{c$.initialize().then(()=>{qg(!0)}).catch(S=>console.error("❌ Lỗi khởi tạo MSAL:",S))},[]),M.useEffect(()=>{sm()},[]);async function sm(){localStorage.getItem("onedrive_access_token")&&mc(!0)}const bu=S=>{bc(N=>N.some(oe=>oe.id===S.id)?N.filter(oe=>oe.id!==S.id):[...N,{id:S.id,name:S.name,size:S.size,lastModified:S.lastModified,contentType:S.contentType,isFolder:S.isFolder,parentId:S.parentId}])};function es(S){if(S===0)return"0 B";const N=1024,U=["B","KB","MB","GB","TB"],oe=Math.floor(Math.log(S)/Math.log(N));return parseFloat((S/Math.pow(N,oe)).toFixed(1))+" "+U[oe]}function cm(S){const N=new Date(S);return N.toLocaleDateString()+" "+N.toLocaleTimeString()}const rn=async()=>{try{const S=await Re.get(`${e}/api/login-one-drive`),{loginUrl:N}=S.data,U=window.open(N,"OneDrive Login","width=600,height=600");if(!U)throw new Error("Không thể mở cửa sổ pop-up");U.focus();const oe=setInterval(()=>{try{if(U.closed){clearInterval(oe);return}const fe=U.location.href;if(fe.includes("code=")){const we=new URL(fe).searchParams.get("code");we&&(Bo(we),U.close(),clearInterval(oe))}}catch(fe){fe instanceof Error&&!fe.message.includes("cross-origin")&&console.error("OneDrive login error:",fe)}},1e3)}catch(S){rt.error("Lỗi khi đăng nhập OneDrive: "+(S instanceof Error?S.message:"Unknown error"))}},Ic=async()=>{try{await Re.post(`${e}/api/logout-one-drive`),localStorage.removeItem("onedrive_access_token"),rt.success("Đã đăng xuất khỏi OneDrive"),window.location.href="https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri="+encodeURIComponent(window.location.origin)}catch(S){rt.error("Lỗi khi đăng xuất OneDrive: "+(S instanceof Error?S.message:"Unknown error"))}},Bo=async S=>{try{const U=await Re.post(`${e}/api/get-one-drive-access-token`,{authorizationCode:S,userId:"1"}),{accessToken:oe}=U.data;localStorage.setItem("onedrive_access_token",oe),mc(!0),qa(!0),await na("root","One Drive")}catch(N){console.error("❌ Lỗi khi lấy Access Token:",N)}},na=async(S,N)=>{try{Ya(!0);const fe=(await Re.post(`${e}/api/list-file-one-drive`,{folderId:S,userId:"1"})).data.map(we=>({id:we.id,name:we.name,size:we.size??0,lastModified:we.lastModifiedDateTime?new Date(we.lastModifiedDateTime):new Date,contentType:we.mimeType??void 0,isFolder:we.type==="folder",parentId:we.parentId??""}));hu(fe.filter(we=>we.isFolder)),yc(fe.filter(we=>!we.isFolder)),qa(!0),wc(we=>we.some(Te=>Te.id===S)?we:[...we,{id:S,name:N==="root"?"OneDrive":N}]),Ya(!1)}catch(U){console.error("Lỗi lấy danh sách file:",U),Ya(!1)}},kc=S=>{if(S===Ji.length-1)return;const N=Ji[S];N&&(wc(Ji.slice(0,S+1)),na(N.id,N.name))},zn=async(S,N)=>{const U=localStorage.getItem("onedrive_access_token");if(!U){rt.error("Không tìm thấy access token. Vui lòng đăng nhập lại.");return}const oe=rt.loading("Đang đồng bộ OneDrive...",{position:"bottom-right",autoClose:!1});try{const fe={prefix:N,folders:[],files:[]};S.forEach(Te=>{Te.isFolder?fe.folders.push({id:Te.id,name:Te.name}):fe.files.push({id:Te.id,name:Te.name})});const we=await Re.post(`${e}/api/sync-one-drive-to-s3`,fe,{headers:{Authorization:`Bearer ${U}`}});cn(),rt.update(oe,{render:`Đồng bộ thành công! Đã tải lên ${we.data.uploadedKeys.length} file.`,type:"success",isLoading:!1,autoClose:3e3,position:"bottom-right"})}catch(fe){console.error("Lỗi khi đồng bộ file từ OneDrive:",fe),rt.update(oe,{render:"Không thể đồng bộ file từ OneDrive.",type:"error",isLoading:!1,autoClose:3e3,position:"bottom-right"})}},Nc=()=>{qa(!1),wc([{id:"root",name:"OneDrive"}]),hu([]),yc([]),bc([]),Ya(!1)},Cu=pP({onSuccess:S=>{Zg(S.access_token),localStorage.setItem("google_access_token",S.access_token),xu(S.access_token)},onError:()=>{console.log("Đăng nhập thất bại!")},scope:r$}),xu=S=>{const N=document.createElement("script");N.src="https://apis.google.com/js/api.js",N.onload=()=>{window.gapi.load("picker",()=>_u(S))},document.body.appendChild(N)},_u=S=>{const N=new window.google.picker.DocsView(window.google.picker.ViewId.DOCS).setIncludeFolders(!0).setSelectFolderEnabled(!0).setOwnedByMe(!1),U=new window.google.picker.DocsView(window.google.picker.ViewId.DRIVE).setIncludeFolders(!0).setSelectFolderEnabled(!0);new window.google.picker.PickerBuilder().setDeveloperKey(t$).setOAuthToken(S).enableFeature(window.google.picker.Feature.MULTISELECT_ENABLED).setLocale("vi").addView(N).addView(U).setCallback(async fe=>{if(fe.action===window.google.picker.Action.PICKED){const we=fe.docs.map(Te=>({id:Te.id,name:Te.name,mimeType:Te.mimeType}));await Su(we,w)}}).build().setVisible(!0)},Su=async(S,N="")=>{const U=localStorage.getItem("google_access_token");if(!U){console.error("❌ Không tìm thấy access token. Vui lòng đăng nhập lại."),rt.error("Không tìm thấy access token. Vui lòng đăng nhập lại.",{position:"bottom-right"});return}const oe=rt.loading("Đang đồng bộ...",{position:"bottom-right",autoClose:!1});try{const fe={prefix:N,folders:[],files:[]};S.forEach(Te=>{Te.mimeType==="application/vnd.google-apps.folder"?fe.folders.push({id:Te.id,name:Te.name}):fe.files.push({id:Te.id,name:Te.name})});const we=await Re.post(`${e}/api/sync-drive-to-s3`,fe,{headers:{Authorization:`Bearer ${U}`}});Hn.current=!0,cn(),rt.update(oe,{render:`Đồng bộ thành công! Đã tải lên ${we.data.uploadedKeys.length} file.`,type:"success",isLoading:!1,autoClose:3e3,position:"bottom-right"})}catch(fe){console.error("❌ Lỗi khi đồng bộ file từ Google Drive:",fe),rt.update(oe,{render:"Không thể đồng bộ file từ Google Drive.",type:"error",isLoading:!1,autoClose:3e3,position:"bottom-right"})}};M.useEffect(()=>{const S=N=>{if(N.data.action==="logout"){const U=document.createElement("iframe");U.style.display="none",U.src="https://accounts.google.com/Logout",document.body.appendChild(U),setTimeout(()=>document.body.removeChild(U),2e3)}};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]),M.useEffect(()=>{const S=new Set(l);x(S)},[]),M.useEffect(()=>{He!=null&&He.status&&(He.status.status==="completed"?(J({title:"Thu thập website hoàn tất",description:`Đã thu thập thành công ${He.url} với ${He.status.completed} trang`}),Hn.current=!0,cn()):He.status.status==="failed"&&J({title:"Thu thập website thất bại",description:`Không thể thu thập ${He.url}. Vui lòng thử lại.`,variant:"destructive"}))},[(Iu=He==null?void 0:He.status)==null?void 0:Iu.status]);const ts=M.useMemo(()=>go[w]||[],[go,w]),Kt=M.useMemo(()=>ts,[ts,w,go]);M.useEffect(()=>{const S=async U=>{var oe;try{return(oe=(await Re.get(`${e}/api/files`,{params:{prefix:U,cache:!1,displayPrefixes:JSON.stringify([]),excludePrivateFiles:"true"},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:3e5})).data)==null?void 0:oe[U]}catch(fe){return console.error("Error: ",fe),[]}};(async()=>{let U=n||"vib-sample/";U.endsWith("/")||(U+="/");const oe=`${n}Pilot/FAQ/Uploads/`,fe=`${n}Pilot/HDSD/Uploads/`,we=`${n}Pilot/Normal_Files/Uploads/`,Te=`${n}Pilot/FAQ/FAQs/`,Tt=`${n}Pilot/HDSD/general/`,mn=`${n}Pilot/Normal_Files/processed/`,[_n,_i,lr,mr,Ko,Gt]=await Promise.all([S(oe),S(fe),S(we),S(Te),S(Tt),S(mn)]);Gg({faqUploadSize:_n,hdsdUploadSize:_i,normalUploadSize:lr,faqParsedSize:mr,hdsdParsedSize:Ko,normalParsedSize:Gt})})()},[JSON.stringify(ts)]);const zo=M.useMemo(()=>{const S=_n=>_n.key&&!(`${_n.key}`.endsWith(".docx")||`${_n.key}`.endsWith(".xlsx")||`${_n.key}`.endsWith(".pdf")),{faqUploadSize:N,hdsdUploadSize:U,normalUploadSize:oe,faqParsedSize:fe,hdsdParsedSize:we,normalParsedSize:Te}=uu,Tt=[],mn=(_n,_i,lr,mr)=>{(_n||[]).forEach(Gt=>{var vr;if(S(Gt)&&!(Gt!=null&&Gt.isFolder))Tt.push({...Gt,type:mr,unSupported:!0});else{let en=(vr=(Gt==null?void 0:Gt.key)||"")==null?void 0:vr.replace(".docx","").replace(".xlsx","").replace(".txt","").replace("/Uploads/",`/${lr}/`);en.endsWith("/")||(en+="/"),(_i||[]).find(Et=>{let Yt=((Et==null?void 0:Et.key)||"").replace(".txt","");return Yt.endsWith("/")||(Yt+="/"),Yt===en})||Tt.push({...Gt,type:mr,timeout:Date.now()-new Date(Gt.lastModified).getTime()>36e5})}})};return mn(N,fe,"FAQs","FAQ"),mn(U,we,"general","Hướng dẫn sử dụng"),mn(oe,Te,"processed","Normal"),Tt},[JSON.stringify(uu)]),ln=M.useMemo(()=>{const S={};return Kt.forEach((N,U)=>{v.has(N.key)&&(S[U]=!0)}),S},[v,Kt]),lm=S=>{const N=Zd(go,S);if(N.length===0)return v.has(S)?"all":"none";const U=N.filter(oe=>v.has(oe)).length;return U===0?"none":U===N.length?"all":"partial"},Vo=(S,N=!0)=>{if(w!==S){if(f&&!w)sr(!0),k(S+f),_(S+f);else if(sr(!0),k(S),_(S),N&&!o){const U=window.location.pathname==="/"?"":window.location.pathname,oe=S?`${window.location.origin}${U}?prefix=${encodeURIComponent(S)}`:`${window.location.origin}${U}`;window.history.pushState({path:oe},"",oe)}}};M.useEffect(()=>{ar&&(Hn.current=!0,cn().finally(()=>sr(!1)))},[ar]);const mo=async(S,N)=>{var U,oe;W(!0);try{if(Kt.some(Tt=>Tt.isFolder&&Tt.name.toLowerCase()===S.toLowerCase())){J({title:"Lỗi",description:`Thư mục "${S}" đã tồn tại trong thư mục hiện tại.`,variant:"destructive"}),W(!1);return}const we=`${N}${S}/`;if((await Re.post(`${e}/api/create-folder`,{prefix:we},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}})).status!==200){J({title:"Lỗi",description:"Không thể tạo thư mục",variant:"destructive"});return}Hn.current=!0,await cn(),J({title:"Đã tạo thư mục",description:`Đã tạo thành công thư mục "${S}"`}),z(""),R(!1)}catch(fe){console.error("Error creating folder:",fe);const we=((oe=(U=fe==null?void 0:fe.response)==null?void 0:U.data)==null?void 0:oe.error)||"Không thể tạo thư mục";J({title:"Lỗi",description:we,variant:"destructive"})}finally{W(!1)}},bi=async(S,N,U)=>{var oe,fe,we,Te,Tt,mn,_n,_i,lr;ae(U),ft(!0);try{if(Array.from(S).reduce((Yt,ra)=>Yt+ra.size,0)>=100*1024*1024){J({title:"Lỗi",description:"Tổng kích thước các tập tin vượt quá 100 MB",variant:"destructive"}),ae(null),ft(!1);return}const Ko=Array.from(S).filter(Yt=>Yt.size===0);if(Ko.length>0){const Yt=Ko.map(ra=>ra.name).join(", ");J({title:"Lỗi tải lên",description:`Không thể tải lên tập tin rỗng: ${Yt}`,variant:"destructive"}),ft(!1),ae(null);return}let Gt=localStorage.getItem("dataLogin"),vr;try{Gt&&(Gt=JSON.parse(Gt),vr=Gt.user)}catch{Gt=null}const en=new FormData;if(vr!=null&&vr.id&&en.append("metadata",JSON.stringify({creator:vr.username,creatorId:vr.id,DataSource:"Tệp tải lên"})),U==="folder"&&S[0]){const Yt=S[0].webkitRelativePath.split("/")[0];Yt&&en.append("folderName",Yt)}en.append("prefix",N),Array.from(S).forEach(Yt=>U==="folder"?en.append("files",Yt,Yt.webkitRelativePath):en.append("files",Yt)),Hn.current=!0;const Et=await Re.post(`${e}/api/check-files-existed`,en,{headers:{"Content-Type":"multipart/form-data",Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});if(((oe=Et==null?void 0:Et.data)==null?void 0:oe.status)===200)await Re.post(`${e}/api/upload`,en,{headers:{"Content-Type":"multipart/form-data",Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:0}),y(""),k(N),setTimeout(async()=>{ae(null),await cn(),ft(!1),await vo("upload")},500);else{if(((we=(fe=Et==null?void 0:Et.data)==null?void 0:fe.names)==null?void 0:we.length)>0&&!((Te=Et==null?void 0:Et.data)!=null&&Te.isFolder)){const Yt=Array.from(S).filter(ra=>Et.data.names.includes(ra.name));vi(Yt),ji(!0)}(Tt=Et==null?void 0:Et.data)!=null&&Tt.isFolder&&((mn=Et==null?void 0:Et.data)!=null&&mn.name)&&(ja((_n=Et==null?void 0:Et.data)==null?void 0:_n.name),vi(S),ji(!0))}}catch(mr){console.error("Lỗi tải lên:",mr);const Ko=((lr=(_i=mr==null?void 0:mr.response)==null?void 0:_i.data)==null?void 0:lr.error)||"Không thể tải lên tập tin";J({title:"Lỗi",description:Ko,variant:"destructive"}),ae(null),ft(!1)}},Oc=async()=>{var S,N;try{ft(!0);const U=new FormData;if(Br){ae(Gi?"folder":"files"),ji(!1);let oe=localStorage.getItem("dataLogin"),fe;try{oe&&(oe=JSON.parse(oe),fe=oe.user)}catch{oe=null}if(fe!=null&&fe.id&&U.append("metadata",JSON.stringify({creator:fe.username,creatorId:fe.id,DataSource:"Tệp tải lên"})),Gi&&Br[0]){const we=Br[0].webkitRelativePath.split("/")[0];we&&U.append("folderName",we)}U.append("prefix",w),Array.from(Br).forEach(we=>Gi&&Br[0]?U.append("files",we,we.webkitRelativePath):U.append("files",we)),fe!=null&&fe.id&&U.append("metadata",JSON.stringify({creator:fe.username,creatorId:fe.id,DataSource:"Tệp tải lên"})),await Re.post(`${e}/api/upload`,U,{headers:{"Content-Type":"multipart/form-data",Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:0}),y(""),k(w),Hn.current=!0}}catch(U){console.error("Lỗi tải lên:",U);const oe=((N=(S=U==null?void 0:U.response)==null?void 0:S.data)==null?void 0:N.error)||"Không thể tải lên tập tin";J({title:"Lỗi",description:oe,variant:"destructive"})}finally{setTimeout(async()=>{ae(null),await cn(),ft(!1),ja(""),vi(null),await vo("overwrite")},500)}},Ot=async S=>{var N;try{if(await Re.delete(`${e}/api/files`,{data:{paths:[S.key]},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),v.has(S.key)){const oe=new Set(v);oe.delete(S.key),x(oe)}const U=((N=S.key)==null?void 0:N.replace(/^(.*?)(\/.*)?$/,(oe,fe,we)=>!we||we==="/"?"":fe+"/"))||"";k(U),Hn.current=!0,J({title:"Đã xóa tập tin",description:`Đã xóa thành công "${S.name}"`}),q(null),await vo("delete")}catch(U){console.error("Error deleting file:",U),J({title:"Lỗi",description:"Không thể xóa tập tin",variant:"destructive"})}finally{or(!1),await cn()}},cr=S=>{const N=new Set(v),U=typeof S=="function"?S(ln):S;new Set(Object.keys(ln).map(Number)).forEach(fe=>{const we=Kt[fe];we&&(U[fe]||(N.delete(we.key),we.isFolder&&Zd(go,we.key).forEach(Te=>N.delete(Te))))}),Object.entries(U).forEach(([fe,we])=>{const Te=parseInt(fe),Tt=Kt[Te];Tt&&we&&(N.add(Tt.key),Tt.isFolder&&Zd(go,Tt.key).forEach(mn=>N.add(mn)))}),x(N)},Pc=async()=>{var S;G(!0);try{const N=Array.from(v),U=N.map(fe=>Object.values(go).flat().find(we=>we.key===fe)).filter(fe=>fe!==void 0);if(U.length===0){J({title:"Lỗi",description:"Không có tập tin nào được chọn để xóa",variant:"destructive"});return}await Re.delete(`${e}/api/files`,{data:{paths:N},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});const oe=((S=U[0])==null?void 0:S.key.replace(/^(.*?)(\/.*)?$/,(fe,we,Te)=>!Te||Te==="/"?"":we+"/"))||"";k(oe),Hn.current=!0,cn(),J({title:"Đã xóa tập tin",description:`Đã xóa thành công ${U.length} mục`}),Y(!1),x(new Set),await vo("bulk-delete")}catch(N){console.error("Error deleting files:",N),J({title:"Lỗi",description:"Không thể xóa các tập tin đã chọn",variant:"destructive"})}finally{G(!1)}},dm=async(S,N)=>{if(!w.trim()){J({title:"Lỗi",description:"Không thể đổi tên tập tin hoặc thư mục ở thư mục gốc. Chỉ có thể xóa.",variant:"destructive"});return}De(!0);try{const U=S.key;let oe;S.isFolder?oe=U.split("/").slice(0,-2).join("/")+"/":oe=U.substring(0,U.lastIndexOf("/")+1);const fe=oe+N+(S.isFolder?"/":"");await Re.post(`${e}/api/rename`,{oldPath:U,newPath:fe},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),Hn.current=!0,await cn(),J({title:"Đã đổi tên",description:`Đã đổi tên thành công "${S.name}" thành "${N}"`}),te(null),Ie(""),_e(null),await vo("rename")}catch(U){console.error("Error renaming item:",U),J({title:"Lỗi",description:"Không thể đổi tên",variant:"destructive"})}finally{De(!1)}},ns=async S=>{Je(N=>new Set([...N,...S]));try{const N=await Re.post(`${e}/api/download`,{paths:S},{responseType:"blob",headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),U=window.URL.createObjectURL(N.data),oe=document.createElement("a");oe.href=U;const fe=N.headers["Content-Disposition"]||N.headers["content-disposition"],we=fe==null?void 0:fe.match(/filename="(.+)"/),Te=we?decodeURIComponent(we[1]):"download.zip";oe.setAttribute("download",Te),document.body.appendChild(oe),oe.click(),document.body.removeChild(oe),window.URL.revokeObjectURL(U),J({title:"Bắt đầu tải xuống",description:`Đã bắt đầu tải xuống ${S.length} mục${S.length>1,""}`})}catch(N){console.error("Error downloading files:",N),J({title:"Lỗi",description:"Không thể tải xuống tập tin",variant:"destructive"})}finally{Je(N=>{const U=new Set(N);return S.forEach(oe=>U.delete(oe)),U})}},Tu=w?w.replace(n,"").split("/").filter(Boolean):[],um=()=>{let S=Array.from(v).map(U=>({key:U}));S.length>1&&(S=S.filter(U=>U.key!==n));const N=U=>vd.findIndex(S,oe=>!oe.key.endsWith("/")&&oe.key.startsWith(U))!==-1;return S=S.filter(U=>U.key.endsWith("/")?!N(U.key):!0),S},Eu=M.useMemo(()=>{const S=[{id:"select",header:()=>{const N=i$(go,w),U=N.length>0&&N.every(fe=>v.has(fe)),oe=N.some(fe=>v.has(fe));return u.jsx(Bp,{checked:U?!0:oe?"indeterminate":!1,onCheckedChange:fe=>{if(fe){const we=Kt.reduce((Te,Tt,mn)=>(Te[mn]=!0,Te),{});cr(we)}else{for(const we of Array.from(v))we.startsWith(w)&&(v.delete(we),$o.current[we]=!1);vd.forEach($o.current,(we,Te)=>{Te.startsWith(w)&&($o.current[Te]=!1)}),cr({})}},"aria-label":"Chọn tất cả"})},cell:({row:N})=>{const U=N.original;let fe=U.isFolder?lm(U.key):v.has(U.key)?"all":"none";if(fe==="none"&&U.key.endsWith("/")){for(const we of Array.from(v))if(we.startsWith(U.key)){fe="all";break}}return u.jsx("div",{className:"flex items-center",children:u.jsx(Bp,{checked:fe==="partial"?"indeterminate":fe==="all",onCheckedChange:we=>{var Tt,mn;const Te={...ln};if(we?Te[N.index]=!0:delete Te[N.index],$o.current[((Tt=N.original)==null?void 0:Tt.key)||"_"]=!!we,(mn=N.original)!=null&&mn.key.endsWith("/"))for(const _n of Array.from(v))_n.startsWith(N.original.key)&&($o.current[N.original.key]=!1,v.delete(_n));cr(Te)},"aria-label":"Chọn dòng"})})},enableSorting:!1},{id:"stt",header:()=>"STT",size:20,cell:({row:N})=>u.jsx("div",{className:"flex flex-col group",children:u.jsx("div",{className:"flex items-center",children:N.index+1})})},{id:"fileName",header:({column:N})=>u.jsxs($e,{variant:"ghost",onClick:()=>N.toggleSorting(N.getIsSorted()==="asc"),children:["Tên tập tin",u.jsx(kp,{})]}),accessorKey:"name",cell:({row:N})=>{const U=N.original,oe=U.key.substring(0,U.key.lastIndexOf("/"))||"/",fe=g.trim()!==""&&oe!==w,we=oe.split("/").filter(Boolean);return u.jsxs("div",{className:"flex flex-col group",children:[u.jsxs("div",{className:"flex items-center",children:[u.jsxs("div",{className:`flex items-center gap-2 ${U.isFolder?"cursor-pointer hover:text-blue-600":""}`,onClick:()=>{U.isFolder&&Vo(U.key)},children:[U.isFolder?u.jsx(Os,{className:"h-5 w-5 text-blue-500"}):null,U.name]}),u.jsx("button",{className:"ml-2 opacity-0 group-hover:opacity-100 transition-opacity",onClick:Te=>{Te.stopPropagation(),navigator.clipboard.writeText(U.key),J({title:"Copied to clipboard",description:`Path: ${U.key}`,duration:2e3})},title:"Copy path to clipboard",children:u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),u.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),fe&&u.jsxs("div",{className:"text-sm text-gray-500 flex items-center",children:[u.jsx(Os,{className:"h-4 w-4 text-gray-500 my-auto"}),u.jsxs("span",{className:"flex items-center ml-1",children:[u.jsx("span",{className:"cursor-pointer hover:text-blue-600",onClick:()=>{Vo("")},children:"/"}),we.map((Te,Tt)=>u.jsxs("span",{className:"flex items-center",children:[u.jsx("span",{className:"cursor-pointer hover:text-blue-600",onClick:()=>{Vo(we.slice(0,Tt+1).join("/")+"/")},children:Te}),Tt<we.length-1&&u.jsx("span",{children:"/"})]},Tt))]})]})]})}}];return o||S.push({id:"size",header:({column:N})=>u.jsxs($e,{variant:"ghost",onClick:()=>N.toggleSorting(N.getIsSorted()==="asc"),children:["Kích thước",u.jsx(kp,{})]}),accessorKey:"size",cell:({getValue:N,row:U})=>{const oe=N();return u.jsx("span",{children:U.original.isFolder?"-":es(oe)})}},{id:"lastModified",header:({column:N})=>u.jsxs($e,{variant:"ghost",onClick:()=>N.toggleSorting(N.getIsSorted()==="asc"),className:"px-0 w-full flex-row justify-end",children:["Sửa đổi lần cuối",u.jsx(kp,{})]}),accessorKey:"lastModified",cell:({row:N})=>{const U=N.original.lastModified;return u.jsx("div",{className:"w-full flex-row justify-end items-center text-right",children:u.jsx("span",{children:U&&qC(U).isValid()?qC(U).format("DD/MM/YYYY HH:mm"):"-"})})},size:200},{id:"actions",header:()=>u.jsx("span",{children:"Hành động"}),accessorKey:"key",cell:({row:N})=>u.jsxs("div",{className:"flex items-center gap-2",children:[w===""&&r&&u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>{au(N.original.key),su(!0)},className:"h-8 w-8 p-0",children:Ne.has(N.original.key)?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):u.jsx(gN,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Những Flow sử dụng Folder này làm Data"})]})}),u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>ns([N.original.key]),className:"h-8 w-8 p-0",disabled:Ne.has(N.original.key),children:Ne.has(N.original.key)?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):u.jsx(qw,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Tải xuống"})]})}),w.trim()!==""&&u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>{te(N.original),Ie(N.original.name)},className:"h-8 w-8 p-0",children:u.jsx(xN,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Đổi tên"})]})}),u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>{Pe(!0),he(N.original)},className:"h-8 w-8 p-0",children:u.jsx(KM,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Di chuyển"})]})}),u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>q(N.original),className:"h-8 w-8 p-0",children:u.jsx(Yw,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Xóa"})]})})]})}),S},[v,Kt,ln,Ne,o]),rs=oC({data:Kt,columns:Eu,state:{rowSelection:ln,sorting:h},onSortingChange:p,enableRowSelection:!0,onRowSelectionChange:cr,getCoreRowModel:rC(),getSortedRowModel:qP()}),os=async S=>{var N,U;sn(!0);try{if(ac(S)){const oe=await Re.get(`${e}/api/read-text`,{params:{path:S.key},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});st(oe.data.content)}try{const oe=await Re.get(`${e}/api/read-json`,{params:{path:S.key+".metadata.json"},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),fe=((U=(N=oe==null?void 0:oe.data)==null?void 0:N.content)==null?void 0:U.metadataAttributes)||null;return _e({fullPath:L==null?void 0:L.key,...fe})}catch{return _e("Lỗi phân tích siêu dữ liệu")}}catch(oe){console.error("Error loading file content:",oe),J({title:"Lỗi",description:"Không thể tải nội dung tập tin",variant:"destructive"})}finally{sn(!1)}},Ci=async(S,N)=>{Rt(!0);try{await Re.post(`${e}/api/modify-text`,{path:S.key,content:N},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),J({title:"Đã lưu tập tin",description:"Nội dung tập tin đã được cập nhật thành công"}),Hn.current=!0,await cn(),te(null),st(""),nn("rename"),await vo("edit-content")}catch(U){console.error("Error saving file content:",U),J({title:"Lỗi",description:"Không thể lưu nội dung tập tin",variant:"destructive"})}finally{Rt(!1)}},fm=async S=>{Rt(!0);try{await Re.post(`${e}/api/modify-json`,{path:S.key+".metadata.json",content:{metadataAttributes:xe}},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),J({title:"Đã lưu tập tin",description:"Nội dung tập tin đã được cập nhật thành công"}),Hn.current=!0,await cn(),te(null),st(""),nn("rename")}catch(N){console.error("Error saving file content:",N),J({title:"Lỗi",description:"Không thể lưu nội dung tập tin",variant:"destructive"})}finally{Rt(!1)}};M.useEffect(()=>{L&&(L.isFolder||os(L),nn("rename"))},[L]);const Mc=async(S,N)=>{var U;if(He){J({title:"Đang thu thập website",description:"Vui lòng đợi cho công việc thu thập hiện tại hoàn thành.",variant:"destructive"});return}de(!0);try{const{data:oe}=await Re.post(`${e}/api/crawl`,{url:S,limit:N,prefix:w});if(oe.id){iu({id:oe.id,url:S,limit:N,prefix:w,taskId:((U=oe.task)==null?void 0:U.id)||""});const fe=localStorage.getItem(ZS),we=fe?JSON.parse(fe):[];we.some(Te=>Te.id===oe.id)||(we.unshift({url:S,id:oe.id,limit:N,prefix:w,timestamp:Date.now()}),we.length>20&&(we.length=20),localStorage.setItem(ZS,JSON.stringify(we))),J({title:"Bắt đầu thu thập website",description:`Đã thêm nhiệm vụ thu thập ${S} với giới hạn ${N}. Dữ liệu sẽ có sẵn sau khi thu thập hoàn tất.`}),Bt(!1),K(""),re("1")}}catch(oe){console.error("Error crawling website:",oe),J({title:"Lỗi",description:"Không thể bắt đầu thu thập website",variant:"destructive"})}finally{de(!1)}},Au=async()=>{try{if(!(He!=null&&He.id))return;iu(null),localStorage.removeItem(Ka),J({title:"Đã dừng thu thập",description:`Đã dừng thu thập website ${He.url}`})}catch(S){console.error("Error stopping job:",S),J({title:"Lỗi",description:"Không thể dừng thu thập website",variant:"destructive"})}};M.useEffect(()=>{if(o)return;const S=(N=!0)=>{const oe=new URL(window.location.href).searchParams.get("prefix")||"";oe?Vo(oe,!1):(N&&!l&&x(new Set),k(n),_(n),Hn.current=!0,setTimeout(()=>{cn()},0))};return S(!1),window.addEventListener("popstate",()=>S(!0)),()=>{window.removeEventListener("popstate",()=>S(!0))}},[]);const is=async()=>{du(!0);try{await Re.post(`${e}/api/prediction-report`),J({title:"Xuất báo cáo thành công",description:"Báo cáo dự đoán đã được xuất"})}catch(S){console.error("Error exporting report:",S),J({title:"Lỗi",description:"Không thể xuất báo cáo dự đoán",variant:"destructive"})}finally{du(!1)}},Rc=async()=>{try{const S=GR();S&&(await Re.post(`${e}/api/start-ingestion-job`,{prefix:w,user_id:S.id,userName:S.username},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}})).status===200&&await xi()}catch(S){We(!1),console.log(S)}},vo=async S=>{try{Wa&&w.includes(Wa)&&(console.log(`Auto syncing knowledge base after ${S} operation`),await xi())}catch(N){console.log(`Error auto syncing after ${S}:`,N)}},yo=M.useRef(),xi=async()=>{try{We(!0);const S=await Re.post(`${e}/api/ingestion-job-status`,{prefix:w},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),{status:N}=S==null?void 0:S.data;N==="FAILED"||N==="COMPLETE"||N==="STOPPED"||N==="STOPPING"||!N?(We(!1),yo.current&&(clearInterval(yo.current),yo.current=null),pc(S==null?void 0:S.data)):(yo.current||(yo.current=setInterval(()=>xi(),5e3)),pc(S==null?void 0:S.data))}catch(S){console.log(S)}},Dc=()=>{const S=Array.from(v);let N;return w?N=S.filter(U=>U.startsWith(w)&&U!==w).length:N=new Set(S.filter(U=>U.split("/").shift())).size,`Đang chọn: ${N}`};return M.useEffect(()=>{const S=w==null?void 0:w.split("/")[0];return S!==Wa&&(We(!1),yo.current&&(clearInterval(yo.current),yo.current=null),Kg(S||""),pc(null),S&&xi()),()=>{}},[Wa,w]),M.useEffect(()=>{po&&Sc.length===0&&(rm(),zr(null))},[po]),M.useEffect(()=>{if(l)for(const S of Array.from(l))$o.current[S]=!0},[]),u.jsxs("div",{className:"space-y-4 s3-explr-container",children:[u.jsx(C_,{}),u.jsx(pr,{open:zg,onOpenChange:S=>{ji(S),S||(ja(""),vi(null),ft(!1),ae(null))},children:u.jsxs(Qn,{children:[u.jsxs(Xn,{children:[u.jsx(Zn,{children:"Cảnh báo trùng lặp"}),u.jsxs(Mo,{children:[Gi&&u.jsxs(u.Fragment,{children:["Folder $",Gi," đã có."]}),Br&&Br.length>0&&u.jsxs(u.Fragment,{children:["Những tệp sau bị lặp:",u.jsx("ul",{className:"mt-2 list-disc pl-5 text-sm text-red-600",children:Array.from(Br).map((S,N)=>u.jsx("li",{children:S.name},N))})]})]})]}),u.jsxs(Po,{children:[u.jsx($e,{variant:"outline",onClick:()=>{ji(!1),ja(""),vi(null),ft(!1),ae(null)},children:"Bỏ qua"}),u.jsx($e,{variant:"destructive",onClick:()=>Oc(),children:"Ghi đè"})]})]})}),u.jsx(bd,{className:"s3-explr-breadcrumb",children:u.jsxs(Cd,{className:"s3-explr-breadcrumb-list",children:[u.jsx(Vs,{className:"s3-explr-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>Vo(n),className:"flex items-center gap-1 cursor-pointer s3-explr-breadcrumb-home",children:t})}),!f&&Tu.map((S,N)=>u.jsxs("div",{className:"flex items-center",children:[u.jsx(xd,{className:"s3-explr-breadcrumb-separator"},`sep-${N}`),u.jsx(Vs,{className:"s3-explr-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>Vo(n+Tu.slice(0,N+1).join("/")+"/"),className:"cursor-pointer s3-explr-breadcrumb-link",children:S})},`item-${S}`)]},N))]})}),u.jsxs("div",{className:"flex items-center space-x-4 s3-explr-toolbar",children:[u.jsx("div",{className:"relative max-w-sm w-full s3-explr-search-container",children:u.jsx(q2,{ref:Z,onChange:S=>y(S)})}),u.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{k(w),Hn.current=!0,cn()},disabled:wi,className:"flex items-center gap-2 s3-explr-refresh-btn",children:[u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${wi?"animate-spin":""}`}),"Làm mới"]}),w&&w!=="/"&&u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{wi||Ce||(We(!0),Rc())},"aria-disabled":wi||Ce,className:"flex items-center gap-2 s3-explr-refresh-btn aria-disabled:opacity-50",children:[u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${Ce?"animate-spin":""}`}),"Đồng bộ KB"]})}),kt&&u.jsx(Hr,{side:"right",sideOffset:5,children:u.jsxs("div",{className:"space-y-2 p-3 max-w-md",children:[u.jsx("p",{className:"font-semibold text-lg border-b pb-1",children:"Thông tin đồng bộ"}),u.jsx("div",{className:"space-y-1",children:u.jsxs("p",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"font-medium",children:"Trạng thái:"}),u.jsxs("span",{className:`flex items-center gap-1 font-semibold ${kt.status==="COMPLETE"?"text-green-600":kt.status==="FAILED"?"text-red-600":"text-yellow-600"}`,children:[kt.status==="COMPLETE"&&u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),kt.status==="FAILED"&&u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),kt.status!=="COMPLETE"&&kt.status!=="FAILED"&&u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 animate-spin",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),kt.status]})]})}),kt.statistics&&u.jsxs("div",{className:"space-y-1 border-t pt-2",children:[u.jsx("p",{className:"font-medium text-gray-50",children:"Thống kê xử lý:"}),u.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-sm",children:[u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu quét:"}),u.jsx("span",{className:"font-medium",children:kt.statistics.numberOfDocumentsScanned})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Metadata quét:"}),u.jsx("span",{className:"font-medium",children:kt.statistics.numberOfMetadataDocumentsScanned})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu mới:"}),u.jsx("span",{className:"font-medium text-green-600",children:kt.statistics.numberOfNewDocumentsIndexed})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu sửa:"}),u.jsx("span",{className:"font-medium text-blue-600",children:kt.statistics.numberOfModifiedDocumentsIndexed})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Metadata sửa:"}),u.jsx("span",{className:"font-medium text-blue-600",children:kt.statistics.numberOfMetadataDocumentsModified})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu xóa:"}),u.jsx("span",{className:"font-medium text-orange-600",children:kt.statistics.numberOfDocumentsDeleted})]}),u.jsxs("div",{className:"flex justify-between col-span-2",children:[u.jsx("span",{children:"Tài liệu lỗi:"}),u.jsx("span",{className:"font-medium text-red-600",children:kt.statistics.numberOfDocumentsFailed})]})]})]}),u.jsxs("div",{className:"space-y-1 border-t pt-2 text-sm text-gray-200",children:[u.jsx("p",{className:"font-medium text-gray-50",children:"Chi tiết Job:"}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"DataSource ID:"})," ",kt.dataSourceId]}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"Ingestion Job ID:"})," ",kt.ingestionJobId]}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"Knowledge Base ID:"})," ",kt.knowledgeBaseId]}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"Job trong queue:"})," ",kt.is_still_in_stock?"Còn":"Không"]})]}),kt.errorMessage&&u.jsxs("div",{className:"border-t pt-2",children:[u.jsx("p",{className:"text-red-600 font-medium",children:"Lỗi:"}),u.jsx("p",{className:"text-red-600 text-sm bg-red-50 p-2 rounded",children:kt.errorMessage})]}),kt.failureReasons&&kt.failureReasons.length>0&&u.jsx(Y2,{failureReasons:kt.failureReasons})]})})]})}),Array.isArray(zo)&&!!zo.length&&u.jsxs(u.Fragment,{children:[u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-refresh-btn aria-disabled:opacity-50",onClick:()=>hc(!0),children:[u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${zo.filter(S=>S.timeout===!1).length>0?"animate-spin":""}`}),zo.filter(S=>S.timeout===!1).length>0?`Tài liệu đang xử lý: ${zo.length}`:`Tài liệu lỗi hoặc không hỗ trợ: ${zo.length}`]}),u.jsx(ZH,{isOpen:jg,onClose:()=>hc(!1),files:zo})]}),u.jsxs("div",{className:"relative",ref:Ac,children:[u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-file-btn bg-[#1682fe] hover:bg-[#0f6cd4] text-white rounded-md px-4 py-2 transition-colors",onClick:()=>gr(S=>!S),children:[u.jsx(SN,{className:"w-4 h-4"}),"Add file"]}),Ec&&u.jsxs("div",{className:"absolute z-50 mt-2 right-0 w-56 bg-white border rounded-lg shadow-lg py-2 flex flex-col",children:[u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left",onClick:()=>{gr(!1);const S=document.createElement("input");S.type="file",S.multiple=!0,S.onchange=N=>{const U=N.target.files;U&&bi(U,w,"files")},S.click()},children:[u.jsx(Hh,{className:"h-4 w-4 mr-2"})," Tải tệp tin"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left",onClick:()=>{gr(!1);const S=document.createElement("input");S.type="file",S.multiple=!0,S.webkitdirectory=!0,S.onchange=N=>{const U=N.target.files;U&&bi(U,w,"folder")},S.click()},children:[u.jsx(Os,{className:"h-4 w-4 mr-2"})," Tải lên thư mục"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left",disabled:!!c&&!w,onClick:()=>R(!0),children:[u.jsx(vN,{className:"h-4 w-4 mr-2 s3-explr-folder-plus-icon"}),"Thư mục mới"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),Bt(!0)},children:[u.jsx(bN,{className:"h-4 w-4 mr-2"})," Thêm Website"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),Cu()},children:[u.jsxs("svg",{viewBox:"0 0 87.3 78",xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 mr-2",children:[u.jsx("path",{d:"m6.6 66.85 3.85 6.65c.8 1.4 1.95 2.5 3.3 3.3l13.75-23.8h-27.5c0 1.55.4 3.1 1.2 4.5z",fill:"#0066da"}),u.jsx("path",{d:"m43.65 25-13.75-23.8c-1.35.8-2.5 1.9-3.3 3.3l-25.4 44a9.06 9.06 0 0 0 -1.2 4.5h27.5z",fill:"#00ac47"}),u.jsx("path",{d:"m73.55 76.8c1.35-.8 2.5-1.9 3.3-3.3l1.6-2.75 7.65-13.25c.8-1.4 1.2-2.95 1.2-4.5h-27.502l5.852 11.5z",fill:"#ea4335"}),u.jsx("path",{d:"m43.65 25 13.75-23.8c-1.35-.8-2.9-1.2-4.5-1.2h-18.5c-1.6 0-3.15.45-4.5 1.2z",fill:"#00832d"}),u.jsx("path",{d:"m59.8 53h-32.3l-13.75 23.8c1.35.8 2.9 1.2 4.5 1.2h50.8c1.6 0 3.15-.45 4.5-1.2z",fill:"#2684fc"}),u.jsx("path",{d:"m73.4 26.5-12.7-22c-.8-1.4-1.95-2.5-3.3-3.3l-13.75 23.8 16.15 28h27.45c0-1.55-.4-3.1-1.2-4.5z",fill:"#ffba00"})]})," ","Đồng bộ Google Drive"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),rn()},children:[u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",className:"h-4 w-4 mr-2",children:[u.jsx("path",{fill:"#094ab2",d:"M47.3 28.2C45.3 18.6 37.1 12 28 12c-8.5 0-15.9 5.6-18.4 13.5C4.2 27.2 0 32.2 0 38c0 6.6 5.4 12 12 12h36c8.3 0 16-6.6 16-15.5 0-6.8-4.9-12.4-11.7-13.3z"}),u.jsx("path",{fill:"#0067c5",d:"M44.9 30.1c-.2 0-.4-.1-.6-.1H26c-3.3 0-6 2.7-6 6 0 .9.2 1.8.6 2.6-1.7-.7-3.5-1.1-5.5-1.1C7.6 37.5 4 41.5 4 46s3.6 8.5 8.1 8.5h34.3c6.8 0 12.6-5.4 12.6-12s-5.5-11.6-11.1-12.4z"})]})," ","Đồng bộ OneDrive"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),tm()},children:[u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",className:"h-4 w-4 mr-2",children:[u.jsx("path",{fill:"#036C70",d:"M19 14.5v-9c0-.28-.22-.5-.5-.5h-13c-.28 0-.5.22-.5.5v9c0 .28.22.5.5.5h13c.28 0 .5-.22.5-.5z"}),u.jsx("path",{fill:"#17828F",d:"M16 17.5v-9c0-.28-.22-.5-.5-.5h-13c-.28 0-.5.22-.5.5v9c0 .28.22.5.5.5h13c.28 0 .5-.22.5-.5z"}),u.jsx("path",{fill:"#4DB6AC",d:"M13 20.5v-9c0-.28-.22-.5-.5-.5h-13c-.28 0-.5.22-.5.5v9c0 .28.22.5.5.5h13c.28 0 .5-.22.5-.5z"}),u.jsx("path",{fill:"#fff",d:"M4.5 15.5v-3c0-.28.22-.5.5-.5h3c.28 0 .5.22.5.5v3c0 .28-.22.5-.5.5H5c-.28 0-.5-.22-.5-.5z"})]})," ","Đồng bộ SharePoint"]})]})]}),!o&&u.jsxs(u.Fragment,{children:[v.size>0&&u.jsxs(u.Fragment,{children:[u.jsxs($e,{variant:"outline",size:"sm",onClick:()=>ns(Array.from(v)),disabled:Array.from(v).some(S=>Ne.has(S)),className:"flex items-center gap-2 s3-explr-download-selected-btn",children:[Array.from(v).some(S=>Ne.has(S))?u.jsx(Vt,{className:"h-4 w-4 animate-spin mr-2 s3-explr-loader"}):u.jsx(qw,{className:"h-4 w-4 s3-explr-download-icon"}),"Tải xuống đã chọn (",v.size,")"]}),u.jsxs(pr,{open:X,onOpenChange:Y,children:[u.jsx(Gs,{asChild:!0,children:u.jsxs($e,{variant:"destructive",size:"sm",className:"flex items-center gap-2 s3-explr-bulk-delete-btn",children:[u.jsx(Yw,{className:"h-4 w-4 s3-explr-trash-icon"}),"Xóa đã chọn (",v.size,")"]})}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Xác nhận xóa hàng loạt"}),u.jsxs(Mo,{className:"s3-explr-dialog-description",children:["Bạn có chắc chắn muốn xóa ",v.size," mục đã chọn? Hành động này không thể hoàn tác."]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>Y(!1),className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:Pc,disabled:be,className:"s3-explr-confirm-delete-btn",children:be?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang xóa..."]}):"Xóa đã chọn"})]})]})]})]}),!f&&u.jsxs(pr,{open:O,onOpenChange:R,children:[u.jsx(Gs,{asChild:!0}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsx(Xn,{className:"s3-explr-dialog-header",children:u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Tạo thư mục mới"})}),u.jsxs("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:[u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"name",className:"s3-explr-label",children:"Tên thư mục"}),u.jsx(no,{disabled:j,id:"name",value:E,onChange:S=>z(S.target.value),placeholder:"Nhập tên thư mục",className:"s3-explr-input"})]}),u.jsxs($e,{onClick:()=>{E.trim()&&mo(E,w)},disabled:j,className:"s3-explr-create-btn",children:[j&&u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),j?"Đang tạo...":"Tạo"]})]})]})]}),f&&!w?u.jsx(u.Fragment,{}):u.jsxs("div",{className:"flex items-center gap-2 s3-explr-upload-group",children:[He?u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-website-btn",disabled:!0,children:[u.jsx(Vt,{className:"h-4 w-4 animate-spin s3-explr-loader"}),He.status?u.jsxs(u.Fragment,{children:[He.status.isProcessing?"Đang thu thập ":"Đang quét sitemap ","(",He.status.completed,"/",He.status.total,") -"," ",Math.floor(ho/60),":",String(ho%60).padStart(2,"0")]}):"Đang thu thập..."]}),u.jsxs($e,{variant:"destructive",size:"sm",onClick:()=>void Au(),className:"flex items-center gap-2",children:[u.jsx("span",{className:"sr-only",children:"Dừng thu thập"}),u.jsx(EN,{className:"h-4 w-4"})]})]})}),He.status&&u.jsx(Hr,{side:"right",sideOffset:5,children:u.jsxs("div",{className:"space-y-1 p-2",children:[u.jsxs("p",{className:"font-semibold",children:["Đang thu thập ",He==null?void 0:He.url]}),u.jsxs("p",{children:["Tiến độ: ",He==null?void 0:He.status.completed,"/",He==null?void 0:He.status.total," ","trang"]}),u.jsxs("p",{children:["Thời gian: ",Math.floor(ho/60),":",String(ho%60).padStart(2,"0")]}),u.jsxs("p",{children:["Trạng thái:"," ",(He==null?void 0:He.status.status)==="scraping"?"Đang thu thập":(He==null?void 0:He.status.status)==="completed"?"Hoàn thành":"Thất bại"]})]})})]})}):!f&&u.jsxs(pr,{open:Un,onOpenChange:Bt,children:[u.jsx(Gs,{asChild:!0}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Thêm website"}),u.jsx(Mo,{className:"s3-explr-dialog-description",children:"Nhập URL website để thu thập và thêm vào S3."})]}),u.jsxs("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:[u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"websiteUrl",className:"s3-explr-label",children:"URL Website"}),u.jsx(no,{id:"websiteUrl",value:D,onChange:S=>K(S.target.value),placeholder:"https://example.com",type:"url",disabled:pe,className:"s3-explr-input"})]}),u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"crawlLimit",className:"s3-explr-label",children:"Giới hạn thu thập"}),u.jsx(no,{id:"crawlLimit",value:H,onChange:S=>{const N=S.target.value;/^\d*$/.test(N)&&re(N)},placeholder:"1",type:"text",disabled:pe,className:"s3-explr-input"}),u.jsx("p",{className:"text-sm text-gray-500",children:"Số lượng liên kết cần thu thập (mặc định: 1)"})]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>{Bt(!1),K(""),re("1")},disabled:pe,className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{onClick:()=>{D.trim()&&Mc(D.trim(),parseInt(H)||1)},disabled:pe||!D.trim(),className:"s3-explr-crawl-btn",children:pe?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang thu thập..."]}):"Bắt đầu thu thập"})]})]})]}),w.startsWith("BKTTW/")&&u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-website-btn",disabled:!!c&&!w,onClick:is,children:[qi&&u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${qi?"animate-spin":""}`}),"Xuất báo cáo"]})}),(He==null?void 0:He.status)&&u.jsx(Hr,{side:"right",sideOffset:5,children:u.jsxs("div",{className:"space-y-1 p-2",children:[u.jsxs("p",{className:"font-semibold",children:["Đang thu thập ",He.url]}),u.jsxs("p",{children:["Tiến độ: ",He.status.completed,"/",He.status.total," ","trang"]}),u.jsxs("p",{children:["Thời gian: ",Math.floor(ho/60),":",String(ho%60).padStart(2,"0")]}),u.jsxs("p",{children:["Trạng thái:"," ",He.status.status==="scraping"?"Đang thu thập":He.status.status==="completed"?"Hoàn thành":"Thất bại"]})]})})]})}),u.jsxs(pr,{open:Un,onOpenChange:Bt,children:[u.jsx(Gs,{asChild:!0}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Thêm website"}),u.jsx(Mo,{className:"s3-explr-dialog-description",children:"Nhập URL website để thu thập và thêm vào S3."})]}),u.jsxs("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:[u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"websiteUrl",className:"s3-explr-label",children:"URL Website"}),u.jsx(no,{id:"websiteUrl",value:D,onChange:S=>K(S.target.value),placeholder:"https://example.com",type:"url",disabled:pe,className:"s3-explr-input"})]}),u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"crawlLimit",className:"s3-explr-label",children:"Giới hạn thu thập"}),u.jsx(no,{id:"crawlLimit",value:H,onChange:S=>{const N=S.target.value;/^\d*$/.test(N)&&re(N)},placeholder:"1",type:"text",disabled:pe,className:"s3-explr-input"}),u.jsx("p",{className:"text-sm text-gray-500",children:"Số lượng liên kết cần thu thập (mặc định: 1)"})]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>{Bt(!1),K(""),re("1")},disabled:pe,className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{onClick:()=>{D.trim()&&Mc(D.trim(),parseInt(H)||1)},disabled:pe||!D.trim(),className:"s3-explr-crawl-btn",children:pe?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang thu thập..."]}):"Bắt đầu thu thập"})]})]})]})]}),w.startsWith("BKTTW/")&&u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-website-btn",disabled:!!c&&!w,onClick:is,children:[qi&&u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${qi?"animate-spin":""}`}),"Xuất báo cáo"]})}),qi&&u.jsx(Hr,{sideOffset:5,children:"Đang xuất báo cáo"})]})}),u.jsxs("div",{className:"flex items-center gap-4",children:[Yi&&u.jsxs(Ps,{open:Yi,onOpenChange:qa,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-50"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[700px] max-w-[90vw] max-h-[80vh] z-50 flex flex-col",children:[u.jsxs("div",{className:"relative",children:[u.jsx(Qh,{asChild:!0,children:u.jsx("button",{className:"absolute top-2 right-2 text-gray-600",onClick:Nc,children:"✖"})}),u.jsx("h2",{className:"text-lg font-semibold",children:"My OneDrive"}),u.jsx(bd,{className:"onedrive-breadcrumb",children:u.jsx(Cd,{className:"onedrive-breadcrumb-list",children:Ji.map((S,N)=>u.jsxs("div",{className:"flex items-center",children:[N>0&&u.jsx(xd,{className:"onedrive-breadcrumb-separator"}),u.jsx(Vs,{className:"onedrive-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>kc(N),className:"cursor-pointer onedrive-breadcrumb-link",children:S.name})})]},N))})})]}),u.jsx("div",{className:"space-y-2 mt-4 flex-1 overflow-y-auto",children:Yg?u.jsx("div",{className:"text-sm text-gray-500",children:"Đang tải nội dung thư mục... Vui lòng đợi."}):u.jsx(u.Fragment,{children:[...fu,...vc].length>0?[...fu,...vc].map(S=>u.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg hover:bg-gray-100 ${Ja.some(N=>N.id===S.id)?"bg-blue-100":""}`,children:[u.jsx("input",{type:"checkbox",checked:Ja.some(N=>N.id===S.id),onChange:N=>{N.stopPropagation(),bu(S)},className:"cursor-pointer"}),S.isFolder?u.jsx(Os,{className:"text-blue-500 w-5 h-5 cursor-pointer",onClick:()=>na(S.id,S.name)}):u.jsx(Hh,{className:"text-gray-500 w-5 h-5"}),u.jsxs("div",{className:"flex-1",children:[u.jsx("div",{className:`font-medium ${S.isFolder?"cursor-pointer text-blue-600":""}`,onClick:()=>{S.isFolder?na(S.id,S.name):bu(S)},children:S.name}),!S.isFolder&&u.jsxs("div",{className:"text-xs text-gray-500",children:[es(S.size)," •"," ",cm(S.lastModified.toISOString())]})]})]},S.id)):u.jsx("div",{className:"text-sm text-gray-500",children:"Không có thư mục hoặc tệp nào."})})}),u.jsx("div",{className:"mt-4 flex flex-wrap justify-end gap-2",children:u.jsx($e,{onClick:()=>{zn(Ja,w),Nc()},className:"bg-[#1682fe] hover:bg-[#0f6cd4] text-white rounded-md px-4 py-2 transition-colors",disabled:Ja.length===0,children:"Đồng bộ"})}),u.jsx("button",{onClick:()=>ea(!0),className:"absolute bottom-4 left-4 text-gray-600 hover:text-gray-800",title:"Đăng xuất OneDrive",children:u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),u.jsx("polyline",{points:"16 17 21 12 16 7"}),u.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}),u.jsxs(Ps,{open:Jg,onOpenChange:ea,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-[60]"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[400px] max-w-[90vw] z-[60]",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Xác nhận đăng xuất"}),u.jsx("p",{className:"text-gray-600 mb-6",children:"Bạn có chắc chắn muốn đăng xuất khỏi OneDrive?"}),u.jsxs("div",{className:"flex justify-end gap-2",children:[u.jsx($e,{variant:"outline",onClick:()=>ea(!1),children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>{Ic(),ea(!1)},children:"Đăng xuất"})]})]})]}),po&&u.jsxs(Ps,{open:po,onOpenChange:Xi,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-50"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[700px] max-w-[90vw] max-h-[80vh] z-50 flex flex-col",children:[u.jsxs("div",{className:"relative",children:[u.jsx(Qh,{asChild:!0,children:u.jsx("button",{className:"absolute top-2 right-2 text-gray-600",onClick:wu,children:"✖"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[pt&&u.jsx("button",{onClick:()=>zr(null),className:"text-gray-600 hover:text-gray-800",children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M19 12H5M12 19l-7-7 7-7"})})}),u.jsx("h2",{className:"text-lg font-semibold",children:"My SharePoint"})]}),pt&&u.jsx(bd,{className:"sharepoint-breadcrumb",children:u.jsx(Cd,{className:"sharepoint-breadcrumb-list",children:_c.map((S,N)=>u.jsxs("div",{className:"flex items-center",children:[N>0&&u.jsx(xd,{className:"sharepoint-breadcrumb-separator"}),u.jsx(Vs,{className:"sharepoint-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>im(N),className:"cursor-pointer sharepoint-breadcrumb-link",children:S.name})})]},N))})})]}),u.jsx("div",{className:"space-y-2 mt-4 flex-1 overflow-y-auto",children:pu?u.jsx("div",{className:"text-sm text-gray-500",children:"Đang tải nội dung thư mục... Vui lòng đợi."}):pt?[...xc,...Qa].length===0?u.jsx("div",{className:"text-sm text-gray-500",children:"Không có thư mục hoặc tệp nào."}):[...xc,...Qa].map(S=>{const N=Za.some(U=>U.id===S.id);return u.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg hover:bg-gray-100 ${N?"bg-blue-100":""}`,children:[u.jsx("input",{type:"checkbox",checked:N,onChange:U=>{U.stopPropagation(),om(S)},className:"cursor-pointer"}),S.isFolder?u.jsx(Os,{className:"text-blue-500 w-5 h-5 cursor-pointer",onClick:()=>mt(S.id,S.name,(pt==null?void 0:pt.hostname)||"",(pt==null?void 0:pt.sitePath)||"")}):u.jsx(Hh,{className:"text-gray-500 w-5 h-5"}),u.jsxs("div",{className:"flex-1",children:[u.jsx("div",{className:`font-medium ${S.isFolder?"cursor-pointer text-blue-600":""}`,onClick:()=>{S.isFolder&&mt(S.id,S.name,(pt==null?void 0:pt.hostname)||"",(pt==null?void 0:pt.sitePath)||"")},children:S.name}),!S.isFolder&&u.jsxs("div",{className:"text-xs text-gray-500",children:[es(S.size)," •"," ",S.lastModified.toLocaleString()]})]})]},S.id)}):u.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6",children:Sc.map(S=>u.jsxs("div",{className:"cursor-pointer bg-white shadow-md rounded-xl p-5 flex flex-col justify-center items-start transition-shadow duration-200 hover:shadow-lg border border-gray-100 min-h-[120px]",style:{overflow:"hidden",wordBreak:"break-word",textOverflow:"ellipsis",whiteSpace:"normal"},onClick:()=>Nt(S),children:[u.jsx("div",{className:"font-bold text-lg mb-1 truncate w-full",title:S.name,children:S.name}),u.jsx("div",{className:"text-sm text-gray-500 truncate w-full",title:S.description,children:S.description})]},S.id))})}),u.jsx("div",{className:"mt-4 flex flex-wrap justify-end gap-2",children:pt&&u.jsxs(u.Fragment,{children:[u.jsx($e,{onClick:()=>{am(Za,w),wu()},className:"bg-[#1682fe] hover:bg-[#0f6cd4] text-white rounded-md px-4 py-2 transition-colors",disabled:Za.length===0,children:"Đồng bộ"}),u.jsx($e,{onClick:()=>zr(null),children:"Quay lại"})]})}),u.jsx("button",{onClick:()=>Zi(!0),className:"absolute bottom-4 left-4 text-gray-600 hover:text-gray-800",title:"Đăng xuất SharePoint",children:u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),u.jsx("polyline",{points:"16 17 21 12 16 7"}),u.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}),u.jsxs(Ps,{open:mu,onOpenChange:Zi,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-[60]"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[400px] max-w-[90vw] z-[60]",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Xác nhận đăng xuất"}),u.jsx("p",{className:"text-gray-600 mb-6",children:"Bạn có chắc chắn muốn đăng xuất khỏi SharePoint?"}),u.jsxs("div",{className:"flex justify-end gap-2",children:[u.jsx($e,{variant:"outline",onClick:()=>Zi(!1),children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>{nm(),Zi(!1)},children:"Đăng xuất"})]})]})]})]}),u.jsx(pr,{open:!!Vg,onOpenChange:S=>{S||(su(!1),lu([]),au(""))},children:u.jsxs(Qn,{className:"max-h-[700px] pb-3 px-1 s3-explr-input-group max-w-5xl w-[90%] p-6 bg-white rounded-lg shadow-lg",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:u.jsxs("h3",{className:"font-medium mb-2",children:["Danh sách flows đang sử dụng dữ liệu từ folder(",u.jsx("span",{className:"font-bold",children:Wi}),"):"," "]})}),u.jsx(Mo,{className:"s3-explr-dialog-description",children:fc?u.jsxs("div",{className:"flex items-center justify-center py-4",children:[u.jsx(Vt,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"ml-2",children:"Đang tải thông tin flows..."})]}):u.jsx("div",{children:yi&&Array.isArray(yi)&&yi.length>0?u.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:u.jsxs("table",{className:"w-full border-collapse",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"bg-gray-100",children:[u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"Tên Flow"}),u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"KnowledgeBase Id"}),u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"Loại"}),u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"Ngày tạo"})]})}),u.jsx("tbody",{children:yi.map((S,N)=>u.jsxs("tr",{className:N%2===0?"bg-white":"bg-gray-50",children:[u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.name}),u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.KnowledgeBaseId}),u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.type==="MULTIAGENT"?"Agent Flow":"Chat Flow"}),u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.createdDate?new Date(S.createdDate).toLocaleString("vi-VN"):"N/A"})]},N))})]})}):u.jsx("div",{className:"text-gray-500 italic py-2",children:"Không có flow nào sử dụng dữ liệu từ folder này"})})})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>q(null),className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>Ot(ne),disabled:Bn,className:"s3-explr-confirm-delete-btn",children:Bn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang xóa..."]}):"Xóa"})]})]})}),u.jsx(pr,{open:!!ne,onOpenChange:S=>!S&&q(null),children:u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Xác nhận xóa"}),u.jsxs(Mo,{className:"s3-explr-dialog-description",children:["Bạn có chắc chắn muốn xóa ",ne==null?void 0:ne.name,"? Hành động này không thể hoàn tác."]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>q(null),className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>Ot(ne),disabled:Bn,className:"s3-explr-confirm-delete-btn",children:Bn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang xóa..."]}):"Xóa"})]})]})}),u.jsx(pr,{open:!!L,onOpenChange:S=>{S||(te(null),_e(null),Ie(""),st(""),nn("rename"))},children:u.jsxs(Qn,{className:"s3-explr-dialog-content max-w-5xl w-[90%]",children:[u.jsx(Xn,{className:"s3-explr-dialog-header",children:u.jsx(Zn,{className:"s3-explr-dialog-title",children:L!=null&&L.isFolder?"Đổi tên thư mục":ac(L)?"Quản lý tập tin":"Đổi tên tập tin"})}),L&&u.jsxs(TD,{value:$n,onValueChange:S=>nn(S),children:[u.jsxs(Wx,{"aria-checked":!ac(L),"aria-disabled":L.isFolder,className:"grid w-full grid-cols-3 aria-checked:grid-cols-2 aria-disabled:grid-cols-1",children:[u.jsx(Nd,{value:"rename",children:"Đổi tên"}),!L.isFolder&&u.jsxs(u.Fragment,{children:[ac(L)&&u.jsx(Nd,{value:"edit",children:"Sửa nội dung"}),u.jsx(Nd,{value:"edit-metadata",children:"Sửa metadata file"})]})]}),u.jsx(Od,{value:"rename",children:u.jsx("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:u.jsxs("div",{className:"h-[70dvh] min-h-[500px] overflow-hidden overflow-y-auto pb-3 px-1 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"newName",className:"s3-explr-label",children:"Tên mới"}),u.jsx(no,{id:"newName",value:Se,onChange:S=>Ie(S.target.value),placeholder:"Nhập tên mới",disabled:Le,className:"s3-explr-input"})]})})}),!L.isFolder&&u.jsxs(u.Fragment,{children:[ac(L)&&u.jsx(Od,{value:"edit",children:u.jsx("div",{className:"space-y-4 py-4",children:bt?u.jsx("div",{className:"flex items-center justify-center py-4",children:u.jsx(Vt,{className:"h-6 w-6 animate-spin"})}):u.jsxs("div",{className:"h-[70dvh] min-h-[500px] overflow-hidden overflow-y-auto pb-3 px-1",children:[u.jsx(Ro,{htmlFor:"content",className:"s3-explr-label",children:"Nội dung tập tin"}),u.jsx(Js,{id:"content",value:ye,onChange:S=>st(S.target.value),placeholder:"Nhập nội dung tập tin",className:"min-h-[200px] font-mono",disabled:gn})]})})}),u.jsx(Od,{value:"edit-metadata",children:u.jsx("div",{className:"space-y-4 py-4",children:bt?u.jsx("div",{className:"flex items-center justify-center py-4",children:u.jsx(Vt,{className:"h-6 w-6 animate-spin"})}):u.jsx("div",{className:"h-[70dvh] min-h-[500px] overflow-hidden overflow-y-auto pb-3 px-1",children:xe&&typeof xe=="object"&&Object.entries(xe).map(([S,N],U)=>u.jsxs("div",{className:"pb-3 flex flex-col gap-2",children:[u.jsxs(Ro,{htmlFor:S,className:"s3-explr-label flex items-center gap-1",children:[aR[S]||S,Rp(S)&&u.jsx(GM,{className:"h-[12px] w-[12px] text-red-500"})]}),sR(S)?u.jsx(Js,{id:S,value:typeof N=="string"?N:JSON.stringify(N),onChange:oe=>{const fe={...xe,[S]:oe.target.value};_e(fe)},placeholder:"Nhập nội dung tập tin",className:"min-h-[200px] font-mono",disabled:gn||Rp(S)}):u.jsx(no,{id:S,value:typeof N=="string"?N:JSON.stringify(N),onChange:oe=>{const fe={...xe,[S]:oe.target.value};_e(fe)},placeholder:"Nhập nội dung",className:"s3-explr-input",disabled:gn||Rp(S)})]},U))})})})]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>{te(null),_e(null),Ie(""),st("")},className:"s3-explr-cancel-btn",children:"Hủy"}),$n==="edit"?u.jsx($e,{onClick:()=>L&&Ci(L,ye),disabled:gn||bt,className:"s3-explr-save-btn",children:gn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang lưu..."]}):"Lưu thay đổi"}):$n==="edit-metadata"?u.jsx($e,{onClick:()=>xe&&typeof xe=="object"&&L&&fm(L),disabled:gn||bt,className:"s3-explr-save-btn",children:gn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang lưu..."]}):"Lưu thay đổi"}):u.jsx($e,{onClick:()=>{Se.trim()&&L&&dm(L,Se.trim())},disabled:Le||!Se.trim()||Se.trim()===(L==null?void 0:L.name),className:"s3-explr-rename-btn",children:Le?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang đổi tên..."]}):"Đổi tên"})]})]})}),me&&Ae&&u.jsx(e$,{openDialogRename:Ae,setOpenDialogRename:Pe,apiBaseUrl:e,setFileToMove:he,fileToMove:me,refreshFiles:cn,ignoreCache:Hn,autoSyncAfterFileOperation:vo})]})]}),em&&u.jsx("div",{className:"bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative s3-explr-error",children:"Đã xảy ra lỗi khi tải danh sách tập tin"}),u.jsx(XH,{onFilesSelected:(S,N)=>bi(S,w,N),children:u.jsx("div",{className:"rounded-md border s3-explr-table-container",children:u.jsxs(js,{className:"s3-explr-table",children:[u.jsx(Ws,{className:"s3-explr-table-header",children:rs.getHeaderGroups().map(S=>u.jsx(er,{className:"hover:bg-transparent s3-explr-header-row",children:S.headers.map(N=>u.jsx(tr,{className:"s3-explr-header-cell",children:N.isPlaceholder?null:nd(N.column.columnDef.header,N.getContext())},N.id))},S.id))}),u.jsx(qs,{className:"s3-explr-table-body",children:rs.getRowModel().rows.length===0?u.jsx(er,{className:"s3-explr-empty-row",children:u.jsx(pn,{colSpan:Eu.length,className:"h-24 text-center s3-explr-empty-cell",children:g?u.jsxs("div",{className:"text-gray-500 s3-explr-no-results",children:['Không tìm thấy tập tin hoặc thư mục nào khớp với "',g,'"']}):u.jsx("div",{className:"text-gray-500 s3-explr-empty-message",children:wi?"Đang tải nội dung thư mục... Vui lòng đợi":"Thư mục này không chứa tập tin hoặc thư mục con nào"})})}):rs.getRowModel().rows.map(S=>u.jsx(er,{className:"h-12 s3-explr-row",children:S.getVisibleCells().map(N=>u.jsx(pn,{className:"align-middle s3-explr-cell",children:nd(N.column.columnDef.cell,N.getContext())},N.id))},S.id))})]})})}),g&&ta!==0&&u.jsx(u.Fragment,{children:u.jsx(Sd,{children:u.jsxs(Td,{children:[u.jsx(Ed,{onClick:()=>ir(S=>Math.max(S-1,1)),"aria-disabled":$t===1,className:"cursor-pointer aria-disabled:pointer-events-none"}),Array.from({length:Math.ceil(ta/20)},(S,N)=>{const U=N+1,oe=Math.ceil(ta/20);return oe>7&&!(U===1||U===oe||U>=$t-1&&U<=$t+1)?U===$t-2&&$t>4||U===$t+2&&$t<oe-3?u.jsx(Id,{className:"pointer-events-none",children:"..."},N):null:u.jsx(Dr,{className:"cursor-pointer",children:u.jsx(La,{isActive:$t===U,onClick:()=>ir(U),className:`${$t===U?"bg-blue-500 text-white":"bg-white text-black"} hover:bg-blue-100`,children:U})},N)}),u.jsx(Dr,{children:u.jsx(Ad,{onClick:()=>ir(S=>Math.min(S+1,Math.ceil(ta/20))),"aria-disabled":$t===Math.ceil(ta/20),className:"cursor-pointer aria-disabled:pointer-events-none"})})]})})}),o&&a&&u.jsxs("div",{className:"flex justify-between items-center mt-4 s3-explr-selector-footer",children:[u.jsx("div",{className:"text-sm text-gray-500 s3-explr-selection-count",children:Dc()}),u.jsx($e,{variant:"default",onClick:()=>a(um()),disabled:v.size===0,className:"s3-explr-ok-btn",children:"OK"})]})]})}),d$=t=>u.jsx(fP,{clientId:n$,children:u.jsx(l$,{...t})});var sc=t=>t.type==="checkbox",Ki=t=>t instanceof Date,kn=t=>t==null;const eT=t=>typeof t=="object";var qt=t=>!kn(t)&&!Array.isArray(t)&&eT(t)&&!Ki(t),u$=t=>qt(t)&&t.target?sc(t.target)?t.target.checked:t.target.value:t,f$=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,h$=(t,e)=>t.has(f$(e)),p$=t=>{const e=t.constructor&&t.constructor.prototype;return qt(e)&&e.hasOwnProperty("isPrototypeOf")},Fg=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function xn(t){let e;const n=Array.isArray(t),r=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(Fg&&(t instanceof Blob||r))&&(n||qt(t)))if(e=n?[]:{},!n&&!p$(t))e=t;else for(const o in t)t.hasOwnProperty(o)&&(e[o]=xn(t[o]));else return t;return e}var eu=t=>Array.isArray(t)?t.filter(Boolean):[],Zt=t=>t===void 0,Me=(t,e,n)=>{if(!e||!qt(t))return n;const r=eu(e.split(/[,[\].]+?/)).reduce((o,a)=>kn(o)?o:o[a],t);return Zt(r)||r===t?Zt(t[e])?n:t[e]:r},uo=t=>typeof t=="boolean",Lg=t=>/^\w*$/.test(t),tT=t=>eu(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Ft=(t,e,n)=>{let r=-1;const o=Lg(e)?[e]:tT(e),a=o.length,c=a-1;for(;++r<a;){const l=o[r];let f=n;if(r!==c){const h=t[l];f=qt(h)||Array.isArray(h)?h:isNaN(+o[r+1])?{}:[]}if(l==="__proto__"||l==="constructor"||l==="prototype")return;t[l]=f,t=t[l]}};const nT={BLUR:"blur",FOCUS_OUT:"focusout"},$r={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ho={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};M.createContext(null);var g$=(t,e,n,r=!0)=>{const o={defaultValues:e._defaultValues};for(const a in t)Object.defineProperty(o,a,{get:()=>{const c=a;return e._proxyFormState[c]!==$r.all&&(e._proxyFormState[c]=!r||$r.all),t[c]}});return o};const m$=typeof window<"u"?b.useLayoutEffect:b.useEffect;var fo=t=>typeof t=="string",v$=(t,e,n,r,o)=>fo(t)?(r&&e.watch.add(t),Me(n,t,o)):Array.isArray(t)?t.map(a=>(r&&e.watch.add(a),Me(n,a))):(r&&(e.watchAll=!0),n),y$=(t,e,n,r,o)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[r]:o||!0}}:{},cc=t=>Array.isArray(t)?t:[t],rT=()=>{let t=[];return{get observers(){return t},next:o=>{for(const a of t)a.next&&a.next(o)},subscribe:o=>(t.push(o),{unsubscribe:()=>{t=t.filter(a=>a!==o)}}),unsubscribe:()=>{t=[]}}},Hg=t=>kn(t)||!eT(t);function mi(t,e){if(Hg(t)||Hg(e))return t===e;if(Ki(t)&&Ki(e))return t.getTime()===e.getTime();const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(const o of n){const a=t[o];if(!r.includes(o))return!1;if(o!=="ref"){const c=e[o];if(Ki(a)&&Ki(c)||qt(a)&&qt(c)||Array.isArray(a)&&Array.isArray(c)?!mi(a,c):a!==c)return!1}}return!0}var Nn=t=>qt(t)&&!Object.keys(t).length,$g=t=>t.type==="file",Ur=t=>typeof t=="function",tu=t=>{if(!Fg)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},oT=t=>t.type==="select-multiple",Ug=t=>t.type==="radio",w$=t=>Ug(t)||sc(t),Bg=t=>tu(t)&&t.isConnected;function b$(t,e){const n=e.slice(0,-1).length;let r=0;for(;r<n;)t=Zt(t)?r++:t[e[r++]];return t}function C$(t){for(const e in t)if(t.hasOwnProperty(e)&&!Zt(t[e]))return!1;return!0}function tn(t,e){const n=Array.isArray(e)?e:Lg(e)?[e]:tT(e),r=n.length===1?t:b$(t,n),o=n.length-1,a=n[o];return r&&delete r[a],o!==0&&(qt(r)&&Nn(r)||Array.isArray(r)&&C$(r))&&tn(t,n.slice(0,-1)),t}var iT=t=>{for(const e in t)if(Ur(t[e]))return!0;return!1};function nu(t,e={}){const n=Array.isArray(t);if(qt(t)||n)for(const r in t)Array.isArray(t[r])||qt(t[r])&&!iT(t[r])?(e[r]=Array.isArray(t[r])?[]:{},nu(t[r],e[r])):kn(t[r])||(e[r]=!0);return e}function aT(t,e,n){const r=Array.isArray(t);if(qt(t)||r)for(const o in t)Array.isArray(t[o])||qt(t[o])&&!iT(t[o])?Zt(e)||Hg(n[o])?n[o]=Array.isArray(t[o])?nu(t[o],[]):{...nu(t[o])}:aT(t[o],kn(e)?{}:e[o],n[o]):n[o]=!mi(t[o],e[o]);return n}var lc=(t,e)=>aT(t,e,nu(e));const sT={value:!1,isValid:!1},cT={value:!0,isValid:!0};var lT=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!Zt(t[0].attributes.value)?Zt(t[0].value)||t[0].value===""?cT:{value:t[0].value,isValid:!0}:cT:sT}return sT},dT=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:r})=>Zt(t)?t:e?t===""?NaN:t&&+t:n&&fo(t)?new Date(t):r?r(t):t;const uT={isValid:!1,value:null};var fT=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,uT):uT;function hT(t){const e=t.ref;return $g(e)?e.files:Ug(e)?fT(t.refs).value:oT(e)?[...e.selectedOptions].map(({value:n})=>n):sc(e)?lT(t.refs).value:dT(Zt(e.value)?t.ref.value:e.value,t)}var x$=(t,e,n,r)=>{const o={};for(const a of t){const c=Me(e,a);c&&Ft(o,a,c._f)}return{criteriaMode:n,names:[...t],fields:o,shouldUseNativeValidation:r}},ru=t=>t instanceof RegExp,dc=t=>Zt(t)?t:ru(t)?t.source:qt(t)?ru(t.value)?t.value.source:t.value:t,pT=t=>({isOnSubmit:!t||t===$r.onSubmit,isOnBlur:t===$r.onBlur,isOnChange:t===$r.onChange,isOnAll:t===$r.all,isOnTouch:t===$r.onTouched});const gT="AsyncFunction";var _$=t=>!!t&&!!t.validate&&!!(Ur(t.validate)&&t.validate.constructor.name===gT||qt(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===gT)),S$=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),mT=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(r=>t.startsWith(r)&&/^\.\w+/.test(t.slice(r.length))));const uc=(t,e,n,r)=>{for(const o of n||Object.keys(t)){const a=Me(t,o);if(a){const{_f:c,...l}=a;if(c){if(c.refs&&c.refs[0]&&e(c.refs[0],o)&&!r)return!0;if(c.ref&&e(c.ref,c.name)&&!r)return!0;if(uc(l,e))break}else if(qt(l)&&uc(l,e))break}}};function vT(t,e,n){const r=Me(t,n);if(r||Lg(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const a=o.join("."),c=Me(e,a),l=Me(t,a);if(c&&!Array.isArray(c)&&n!==a)return{name:n};if(l&&l.type)return{name:a,error:l};o.pop()}return{name:n}}var T$=(t,e,n,r)=>{n(t);const{name:o,...a}=t;return Nn(a)||Object.keys(a).length>=Object.keys(e).length||Object.keys(a).find(c=>e[c]===(!r||$r.all))},E$=(t,e,n)=>!t||!e||t===e||cc(t).some(r=>r&&(n?r===e:r.startsWith(e)||e.startsWith(r))),A$=(t,e,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(e||t):(n?r.isOnBlur:o.isOnBlur)?!t:(n?r.isOnChange:o.isOnChange)?t:!0,I$=(t,e)=>!eu(Me(t,e)).length&&tn(t,e),k$=(t,e,n)=>{const r=cc(Me(t,n));return Ft(r,"root",e[n]),Ft(t,n,r),t},ou=t=>fo(t);function yT(t,e,n="validate"){if(ou(t)||Array.isArray(t)&&t.every(ou)||uo(t)&&!t)return{type:n,message:ou(t)?t:"",ref:e}}var Ga=t=>qt(t)&&!ru(t)?t:{value:t,message:""},wT=async(t,e,n,r,o,a)=>{const{ref:c,refs:l,required:f,maxLength:h,minLength:p,min:g,max:y,pattern:v,validate:x,name:w,valueAsNumber:_,mount:I}=t._f,k=Me(n,w);if(!I||e.has(w))return{};const O=l?l[0]:c,R=he=>{o&&O.reportValidity&&(O.setCustomValidity(uo(he)?"":he||""),O.reportValidity())},E={},z=Ug(c),j=sc(c),W=z||j,ne=(_||$g(c))&&Zt(c.value)&&Zt(k)||tu(c)&&c.value===""||k===""||Array.isArray(k)&&!k.length,q=y$.bind(null,w,r,E),me=(he,be,G,X=Ho.maxLength,Y=Ho.minLength)=>{const ae=he?be:G;E[w]={type:he?X:Y,message:ae,ref:c,...q(he?X:Y,ae)}};if(a?!Array.isArray(k)||!k.length:f&&(!W&&(ne||kn(k))||uo(k)&&!k||j&&!lT(l).isValid||z&&!fT(l).isValid)){const{value:he,message:be}=ou(f)?{value:!!f,message:f}:Ga(f);if(he&&(E[w]={type:Ho.required,message:be,ref:O,...q(Ho.required,be)},!r))return R(be),E}if(!ne&&(!kn(g)||!kn(y))){let he,be;const G=Ga(y),X=Ga(g);if(!kn(k)&&!isNaN(k)){const Y=c.valueAsNumber||k&&+k;kn(G.value)||(he=Y>G.value),kn(X.value)||(be=Y<X.value)}else{const Y=c.valueAsDate||new Date(k),ae=L=>new Date(new Date().toDateString()+" "+L),Z=c.type=="time",J=c.type=="week";fo(G.value)&&k&&(he=Z?ae(k)>ae(G.value):J?k>G.value:Y>new Date(G.value)),fo(X.value)&&k&&(be=Z?ae(k)<ae(X.value):J?k<X.value:Y<new Date(X.value))}if((he||be)&&(me(!!he,G.message,X.message,Ho.max,Ho.min),!r))return R(E[w].message),E}if((h||p)&&!ne&&(fo(k)||a&&Array.isArray(k))){const he=Ga(h),be=Ga(p),G=!kn(he.value)&&k.length>+he.value,X=!kn(be.value)&&k.length<+be.value;if((G||X)&&(me(G,he.message,be.message),!r))return R(E[w].message),E}if(v&&!ne&&fo(k)){const{value:he,message:be}=Ga(v);if(ru(he)&&!k.match(he)&&(E[w]={type:Ho.pattern,message:be,ref:c,...q(Ho.pattern,be)},!r))return R(be),E}if(x){if(Ur(x)){const he=await x(k,n),be=yT(he,O);if(be&&(E[w]={...be,...q(Ho.validate,be.message)},!r))return R(be.message),E}else if(qt(x)){let he={};for(const be in x){if(!Nn(he)&&!r)break;const G=yT(await x[be](k,n),O,be);G&&(he={...G,...q(be,G.message)},R(G.message),r&&(E[w]=he))}if(!Nn(he)&&(E[w]={ref:O,...he},!r))return E}}return R(!0),E};const N$={mode:$r.onSubmit,reValidateMode:$r.onChange,shouldFocusError:!0};function O$(t={}){let e={...N$,...t},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:Ur(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1};const r={};let o=qt(e.defaultValues)||qt(e.values)?xn(e.defaultValues||e.values)||{}:{},a=e.shouldUnregister?{}:xn(o),c={action:!1,mount:!1,watch:!1},l={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},f,h=0;const p={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let g={...p};const y={array:rT(),state:rT()},v=pT(e.mode),x=pT(e.reValidateMode),w=e.criteriaMode===$r.all,_=D=>K=>{clearTimeout(h),h=setTimeout(D,K)},I=async D=>{if(!e.disabled&&(p.isValid||g.isValid||D)){const K=e.resolver?Nn((await ne()).errors):await me(r,!0);K!==n.isValid&&y.state.next({isValid:K})}},k=(D,K)=>{!e.disabled&&(p.isValidating||p.validatingFields||g.isValidating||g.validatingFields)&&((D||Array.from(l.mount)).forEach(H=>{H&&(K?Ft(n.validatingFields,H,K):tn(n.validatingFields,H))}),y.state.next({validatingFields:n.validatingFields,isValidating:!Nn(n.validatingFields)}))},O=(D,K=[],H,re,pe=!0,de=!0)=>{if(re&&H&&!e.disabled){if(c.action=!0,de&&Array.isArray(Me(r,D))){const Ce=H(Me(r,D),re.argA,re.argB);pe&&Ft(r,D,Ce)}if(de&&Array.isArray(Me(n.errors,D))){const Ce=H(Me(n.errors,D),re.argA,re.argB);pe&&Ft(n.errors,D,Ce),I$(n.errors,D)}if((p.touchedFields||g.touchedFields)&&de&&Array.isArray(Me(n.touchedFields,D))){const Ce=H(Me(n.touchedFields,D),re.argA,re.argB);pe&&Ft(n.touchedFields,D,Ce)}(p.dirtyFields||g.dirtyFields)&&(n.dirtyFields=lc(o,a)),y.state.next({name:D,isDirty:be(D,K),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ft(a,D,K)},R=(D,K)=>{Ft(n.errors,D,K),y.state.next({errors:n.errors})},E=D=>{n.errors=D,y.state.next({errors:n.errors,isValid:!1})},z=(D,K,H,re)=>{const pe=Me(r,D);if(pe){const de=Me(a,D,Zt(H)?Me(o,D):H);Zt(de)||re&&re.defaultChecked||K?Ft(a,D,K?de:hT(pe._f)):Y(D,de),c.mount&&I()}},j=(D,K,H,re,pe)=>{let de=!1,Ce=!1;const We={name:D};if(!e.disabled){if(!H||re){(p.isDirty||g.isDirty)&&(Ce=n.isDirty,n.isDirty=We.isDirty=be(),de=Ce!==We.isDirty);const ht=mi(Me(o,D),K);Ce=!!Me(n.dirtyFields,D),ht?tn(n.dirtyFields,D):Ft(n.dirtyFields,D,!0),We.dirtyFields=n.dirtyFields,de=de||(p.dirtyFields||g.dirtyFields)&&Ce!==!ht}if(H){const ht=Me(n.touchedFields,D);ht||(Ft(n.touchedFields,D,H),We.touchedFields=n.touchedFields,de=de||(p.touchedFields||g.touchedFields)&&ht!==H)}de&&pe&&y.state.next(We)}return de?We:{}},W=(D,K,H,re)=>{const pe=Me(n.errors,D),de=(p.isValid||g.isValid)&&uo(K)&&n.isValid!==K;if(e.delayError&&H?(f=_(()=>R(D,H)),f(e.delayError)):(clearTimeout(h),f=null,H?Ft(n.errors,D,H):tn(n.errors,D)),(H?!mi(pe,H):pe)||!Nn(re)||de){const Ce={...re,...de&&uo(K)?{isValid:K}:{},errors:n.errors,name:D};n={...n,...Ce},y.state.next(Ce)}},ne=async D=>{k(D,!0);const K=await e.resolver(a,e.context,x$(D||l.mount,r,e.criteriaMode,e.shouldUseNativeValidation));return k(D),K},q=async D=>{const{errors:K}=await ne(D);if(D)for(const H of D){const re=Me(K,H);re?Ft(n.errors,H,re):tn(n.errors,H)}else n.errors=K;return K},me=async(D,K,H={valid:!0})=>{for(const re in D){const pe=D[re];if(pe){const{_f:de,...Ce}=pe;if(de){const We=l.array.has(de.name),ht=pe._f&&_$(pe._f);ht&&p.validatingFields&&k([re],!0);const ft=await wT(pe,l.disabled,a,w,e.shouldUseNativeValidation&&!K,We);if(ht&&p.validatingFields&&k([re]),ft[de.name]&&(H.valid=!1,K))break;!K&&(Me(ft,de.name)?We?k$(n.errors,ft,de.name):Ft(n.errors,de.name,ft[de.name]):tn(n.errors,de.name))}!Nn(Ce)&&await me(Ce,K,H)}}return H.valid},he=()=>{for(const D of l.unMount){const K=Me(r,D);K&&(K._f.refs?K._f.refs.every(H=>!Bg(H)):!Bg(K._f.ref))&&De(D)}l.unMount=new Set},be=(D,K)=>!e.disabled&&(D&&K&&Ft(a,D,K),!mi(xe(),o)),G=(D,K,H)=>v$(D,l,{...c.mount?a:Zt(K)?o:fo(D)?{[D]:K}:K},H,K),X=D=>eu(Me(c.mount?a:o,D,e.shouldUnregister?Me(o,D,[]):[])),Y=(D,K,H={})=>{const re=Me(r,D);let pe=K;if(re){const de=re._f;de&&(!de.disabled&&Ft(a,D,dT(K,de)),pe=tu(de.ref)&&kn(K)?"":K,oT(de.ref)?[...de.ref.options].forEach(Ce=>Ce.selected=pe.includes(Ce.value)):de.refs?sc(de.ref)?de.refs.length>1?de.refs.forEach(Ce=>(!Ce.defaultChecked||!Ce.disabled)&&(Ce.checked=Array.isArray(pe)?!!pe.find(We=>We===Ce.value):pe===Ce.value)):de.refs[0]&&(de.refs[0].checked=!!pe):de.refs.forEach(Ce=>Ce.checked=Ce.value===pe):$g(de.ref)?de.ref.value="":(de.ref.value=pe,de.ref.type||y.state.next({name:D,values:xn(a)})))}(H.shouldDirty||H.shouldTouch)&&j(D,pe,H.shouldTouch,H.shouldDirty,!0),H.shouldValidate&&te(D)},ae=(D,K,H)=>{for(const re in K){const pe=K[re],de=`${D}.${re}`,Ce=Me(r,de);(l.array.has(D)||qt(pe)||Ce&&!Ce._f)&&!Ki(pe)?ae(de,pe,H):Y(de,pe,H)}},Z=(D,K,H={})=>{const re=Me(r,D),pe=l.array.has(D),de=xn(K);Ft(a,D,de),pe?(y.array.next({name:D,values:xn(a)}),(p.isDirty||p.dirtyFields||g.isDirty||g.dirtyFields)&&H.shouldDirty&&y.state.next({name:D,dirtyFields:lc(o,a),isDirty:be(D,de)})):re&&!re._f&&!kn(de)?ae(D,de,H):Y(D,de,H),mT(D,l)&&y.state.next({...n}),y.state.next({name:c.mount?D:void 0,values:xn(a)})},J=async D=>{c.mount=!0;const K=D.target;let H=K.name,re=!0;const pe=Me(r,H),de=Ce=>{re=Number.isNaN(Ce)||Ki(Ce)&&isNaN(Ce.getTime())||mi(Ce,Me(a,H,Ce))};if(pe){let Ce,We;const ht=K.type?hT(pe._f):u$(D),ft=D.type===nT.BLUR||D.type===nT.FOCUS_OUT,Bn=!S$(pe._f)&&!e.resolver&&!Me(n.errors,H)&&!pe._f.deps||A$(ft,Me(n.touchedFields,H),n.isSubmitted,x,v),or=mT(H,l,ft);Ft(a,H,ht),ft?(pe._f.onBlur&&pe._f.onBlur(D),f&&f(0)):pe._f.onChange&&pe._f.onChange(D);const $t=j(H,ht,ft),ir=!Nn($t)||or;if(!ft&&y.state.next({name:H,type:D.type,values:xn(a)}),Bn)return(p.isValid||g.isValid)&&(e.mode==="onBlur"?ft&&I():ft||I()),ir&&y.state.next({name:H,...or?{}:$t});if(!ft&&or&&y.state.next({...n}),e.resolver){const{errors:ar}=await ne([H]);if(de(ht),re){const sr=vT(n.errors,r,H),He=vT(ar,r,sr.name||H);Ce=He.error,H=He.name,We=Nn(ar)}}else k([H],!0),Ce=(await wT(pe,l.disabled,a,w,e.shouldUseNativeValidation))[H],k([H]),de(ht),re&&(Ce?We=!1:(p.isValid||g.isValid)&&(We=await me(r,!0)));re&&(pe._f.deps&&te(pe._f.deps),W(H,We,Ce,$t))}},L=(D,K)=>{if(Me(n.errors,K)&&D.focus)return D.focus(),1},te=async(D,K={})=>{let H,re;const pe=cc(D);if(e.resolver){const de=await q(Zt(D)?D:pe);H=Nn(de),re=D?!pe.some(Ce=>Me(de,Ce)):H}else D?(re=(await Promise.all(pe.map(async de=>{const Ce=Me(r,de);return await me(Ce&&Ce._f?{[de]:Ce}:Ce)}))).every(Boolean),!(!re&&!n.isValid)&&I()):re=H=await me(r);return y.state.next({...!fo(D)||(p.isValid||g.isValid)&&H!==n.isValid?{}:{name:D},...e.resolver||!D?{isValid:H}:{},errors:n.errors}),K.shouldFocus&&!re&&uc(r,L,D?pe:l.mount),re},xe=D=>{const K={...c.mount?a:o};return Zt(D)?K:fo(D)?Me(K,D):D.map(H=>Me(K,H))},_e=(D,K)=>({invalid:!!Me((K||n).errors,D),isDirty:!!Me((K||n).dirtyFields,D),error:Me((K||n).errors,D),isValidating:!!Me(n.validatingFields,D),isTouched:!!Me((K||n).touchedFields,D)}),Se=D=>{D&&cc(D).forEach(K=>tn(n.errors,K)),y.state.next({errors:D?n.errors:{}})},Ie=(D,K,H)=>{const re=(Me(r,D,{_f:{}})._f||{}).ref,pe=Me(n.errors,D)||{},{ref:de,message:Ce,type:We,...ht}=pe;Ft(n.errors,D,{...ht,...K,ref:re}),y.state.next({name:D,errors:n.errors,isValid:!1}),H&&H.shouldFocus&&re&&re.focus&&re.focus()},Ae=(D,K)=>Ur(D)?y.state.subscribe({next:H=>D(G(void 0,K),H)}):G(D,K,!0),Pe=D=>y.state.subscribe({next:K=>{E$(D.name,K.name,D.exact)&&T$(K,D.formState||p,nn,D.reRenderRoot)&&D.callback({values:{...a},...n,...K})}}).unsubscribe,Le=D=>(c.mount=!0,g={...g,...D.formState},Pe({...D,formState:g})),De=(D,K={})=>{for(const H of D?cc(D):l.mount)l.mount.delete(H),l.array.delete(H),K.keepValue||(tn(r,H),tn(a,H)),!K.keepError&&tn(n.errors,H),!K.keepDirty&&tn(n.dirtyFields,H),!K.keepTouched&&tn(n.touchedFields,H),!K.keepIsValidating&&tn(n.validatingFields,H),!e.shouldUnregister&&!K.keepDefaultValue&&tn(o,H);y.state.next({values:xn(a)}),y.state.next({...n,...K.keepDirty?{isDirty:be()}:{}}),!K.keepIsValid&&I()},Ne=({disabled:D,name:K})=>{(uo(D)&&c.mount||D||l.disabled.has(K))&&(D?l.disabled.add(K):l.disabled.delete(K))},Je=(D,K={})=>{let H=Me(r,D);const re=uo(K.disabled)||uo(e.disabled);return Ft(r,D,{...H||{},_f:{...H&&H._f?H._f:{ref:{name:D}},name:D,mount:!0,...K}}),l.mount.add(D),H?Ne({disabled:uo(K.disabled)?K.disabled:e.disabled,name:D}):z(D,!0,K.value),{...re?{disabled:K.disabled||e.disabled}:{},...e.progressive?{required:!!K.required,min:dc(K.min),max:dc(K.max),minLength:dc(K.minLength),maxLength:dc(K.maxLength),pattern:dc(K.pattern)}:{},name:D,onChange:J,onBlur:J,ref:pe=>{if(pe){Je(D,K),H=Me(r,D);const de=Zt(pe.value)&&pe.querySelectorAll&&pe.querySelectorAll("input,select,textarea")[0]||pe,Ce=w$(de),We=H._f.refs||[];if(Ce?We.find(ht=>ht===de):de===H._f.ref)return;Ft(r,D,{_f:{...H._f,...Ce?{refs:[...We.filter(Bg),de,...Array.isArray(Me(o,D))?[{}]:[]],ref:{type:de.type,name:D}}:{ref:de}}}),z(D,!1,void 0,de)}else H=Me(r,D,{}),H._f&&(H._f.mount=!1),(e.shouldUnregister||K.shouldUnregister)&&!(h$(l.array,D)&&c.action)&&l.unMount.add(D)}}},ye=()=>e.shouldFocusError&&uc(r,L,l.mount),st=D=>{uo(D)&&(y.state.next({disabled:D}),uc(r,(K,H)=>{const re=Me(r,H);re&&(K.disabled=re._f.disabled||D,Array.isArray(re._f.refs)&&re._f.refs.forEach(pe=>{pe.disabled=re._f.disabled||D}))},0,!1))},bt=(D,K)=>async H=>{let re;H&&(H.preventDefault&&H.preventDefault(),H.persist&&H.persist());let pe=xn(a);if(y.state.next({isSubmitting:!0}),e.resolver){const{errors:de,values:Ce}=await ne();n.errors=de,pe=Ce}else await me(r);if(l.disabled.size)for(const de of l.disabled)Ft(pe,de,void 0);if(tn(n.errors,"root"),Nn(n.errors)){y.state.next({errors:{}});try{await D(pe,H)}catch(de){re=de}}else K&&await K({...n.errors},H),ye(),setTimeout(ye);if(y.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Nn(n.errors)&&!re,submitCount:n.submitCount+1,errors:n.errors}),re)throw re},sn=(D,K={})=>{Me(r,D)&&(Zt(K.defaultValue)?Z(D,xn(Me(o,D))):(Z(D,K.defaultValue),Ft(o,D,xn(K.defaultValue))),K.keepTouched||tn(n.touchedFields,D),K.keepDirty||(tn(n.dirtyFields,D),n.isDirty=K.defaultValue?be(D,xn(Me(o,D))):be()),K.keepError||(tn(n.errors,D),p.isValid&&I()),y.state.next({...n}))},gn=(D,K={})=>{const H=D?xn(D):o,re=xn(H),pe=Nn(D),de=pe?o:re;if(K.keepDefaultValues||(o=H),!K.keepValues){if(K.keepDirtyValues){const Ce=new Set([...l.mount,...Object.keys(lc(o,a))]);for(const We of Array.from(Ce))Me(n.dirtyFields,We)?Ft(de,We,Me(a,We)):Z(We,Me(de,We))}else{if(Fg&&Zt(D))for(const Ce of l.mount){const We=Me(r,Ce);if(We&&We._f){const ht=Array.isArray(We._f.refs)?We._f.refs[0]:We._f.ref;if(tu(ht)){const ft=ht.closest("form");if(ft){ft.reset();break}}}}for(const Ce of l.mount)Z(Ce,Me(de,Ce))}a=xn(de),y.array.next({values:{...de}}),y.state.next({values:{...de}})}l={mount:K.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!p.isValid||!!K.keepIsValid||!!K.keepDirtyValues,c.watch=!!e.shouldUnregister,y.state.next({submitCount:K.keepSubmitCount?n.submitCount:0,isDirty:pe?!1:K.keepDirty?n.isDirty:!!(K.keepDefaultValues&&!mi(D,o)),isSubmitted:K.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:pe?{}:K.keepDirtyValues?K.keepDefaultValues&&a?lc(o,a):n.dirtyFields:K.keepDefaultValues&&D?lc(o,D):K.keepDirty?n.dirtyFields:{},touchedFields:K.keepTouched?n.touchedFields:{},errors:K.keepErrors?n.errors:{},isSubmitSuccessful:K.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Rt=(D,K)=>gn(Ur(D)?D(a):D,K),$n=(D,K={})=>{const H=Me(r,D),re=H&&H._f;if(re){const pe=re.refs?re.refs[0]:re.ref;pe.focus&&(pe.focus(),K.shouldSelect&&Ur(pe.select)&&pe.select())}},nn=D=>{n={...n,...D}},Bt={control:{register:Je,unregister:De,getFieldState:_e,handleSubmit:bt,setError:Ie,_subscribe:Pe,_runSchema:ne,_getWatch:G,_getDirty:be,_setValid:I,_setFieldArray:O,_setDisabledField:Ne,_setErrors:E,_getFieldArray:X,_reset:gn,_resetDefaultValues:()=>Ur(e.defaultValues)&&e.defaultValues().then(D=>{Rt(D,e.resetOptions),y.state.next({isLoading:!1})}),_removeUnmounted:he,_disableForm:st,_subjects:y,_proxyFormState:p,get _fields(){return r},get _formValues(){return a},get _state(){return c},set _state(D){c=D},get _defaultValues(){return o},get _names(){return l},set _names(D){l=D},get _formState(){return n},get _options(){return e},set _options(D){e={...e,...D}}},subscribe:Le,trigger:te,register:Je,handleSubmit:bt,watch:Ae,setValue:Z,getValues:xe,reset:Rt,resetField:sn,clearErrors:Se,unregister:De,setError:Ie,setFocus:$n,getFieldState:_e};return{...Bt,formControl:Bt}}function P$(t={}){const e=M.useRef(void 0),n=M.useRef(void 0),[r,o]=M.useState({isDirty:!1,isValidating:!1,isLoading:Ur(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:Ur(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...t.formControl?t.formControl:O$(t),formState:r},t.formControl&&t.defaultValues&&!Ur(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions));const a=e.current.control;return a._options=t,m$(()=>{const c=a._subscribe({formState:a._proxyFormState,callback:()=>o({...a._formState}),reRenderRoot:!0});return o(l=>({...l,isReady:!0})),a._formState.isReady=!0,c},[a]),M.useEffect(()=>a._disableForm(t.disabled),[a,t.disabled]),M.useEffect(()=>{t.mode&&(a._options.mode=t.mode),t.reValidateMode&&(a._options.reValidateMode=t.reValidateMode),t.errors&&!Nn(t.errors)&&a._setErrors(t.errors)},[a,t.errors,t.mode,t.reValidateMode]),M.useEffect(()=>{t.shouldUnregister&&a._subjects.state.next({values:a._getWatch()})},[a,t.shouldUnregister]),M.useEffect(()=>{if(a._proxyFormState.isDirty){const c=a._getDirty();c!==r.isDirty&&a._subjects.state.next({isDirty:c})}},[a,r.isDirty]),M.useEffect(()=>{t.values&&!mi(t.values,n.current)?(a._reset(t.values,a._options.resetOptions),n.current=t.values,o(c=>({...c}))):a._resetDefaultValues()},[a,t.values]),M.useEffect(()=>{a._state.mount||(a._setValid(),a._state.mount=!0),a._state.watch&&(a._state.watch=!1,a._subjects.state.next({...a._formState})),a._removeUnmounted()}),e.current.formState=g$(r,a),e.current}const bT=({className:t,children:e,content:n,side:r})=>{const[o,a]=M.useState(!1);return u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{open:o,children:[u.jsx(co,{asChild:!0,children:u.jsx("button",{type:"button",className:qe("cursor-pointer",t),onClick:()=>a(!o),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onTouchStart:()=>a(!o),onKeyDown:c=>{c.preventDefault(),c.key==="Enter"&&a(!o)},children:e})}),u.jsx(Hr,{side:r,className:n?"":"hidden",children:u.jsx("span",{className:"inline-block",children:n})})]})})},M$=(t,e)=>{const[n,r]=M.useState(t);return M.useEffect(()=>{const o=setTimeout(()=>{r(t)},e);return()=>{clearTimeout(o)}},[t,e]),n},R$=({apiBaseUrl:t="http://localhost:3000"})=>{var z,j;const[e,n]=M.useState([]),[r,o]=M.useState(!1),[a,c]=M.useState([]),[l,f]=M.useState(1),[h,p]=M.useState(1),[g,y]=M.useState(null),[v,x]=M.useState(""),w=M$(v,500),_=W=>{const ne=W.match(/\d{6}/);if(!ne)return{month:"",year:""};const q=ne[0],me=q.substring(0,2),he=q.substring(2);return{month:me,year:he}},I=W=>W.map(q=>{let me=(q==null?void 0:q.month)||"",he=(q==null?void 0:q.year)||"";if((!me||!he)&&(q!=null&&q.file_name)){const be=_(q.file_name);me=me||be.month,he=he||be.year}return{id:q==null?void 0:q.id,prefix:(q==null?void 0:q.prefix)||"",model:(q==null?void 0:q.model)||"",fileName:(q==null?void 0:q.file_name)||"",code:(q==null?void 0:q.stock_id)||"",month:me,year:he,content:(q==null?void 0:q.text_summary)||"",status:(q==null?void 0:q.status)||"",note:(q==null?void 0:q.note)||"",lastUpdate:q==null?void 0:q.updated_at,stock_id:q==null?void 0:q.stock_id}}),k=W=>{if(!(W!=null&&W.data))return[];const ne=I(W==null?void 0:W.data);n(ne),p(W.pagination.totalPages)},O=async(W=1,ne=15)=>{y(W),o(!0);try{const q=await Re.get(`${t}/api/latest-summaries`,{params:{page:W,limit:ne,search:v}});(q==null?void 0:q.status)===200?k(q.data):console.error(q)}catch(q){console.error("Error fetching data:",q)}finally{y(null),o(!1)}};M.useEffect(()=>{w&&f(1),O(l)},[l,w]);const R=M.useMemo(()=>[{id:"code",header:"Mã",accessorKey:"code",cell:({row:ne})=>u.jsx("span",{className:"flex flex-col",children:ne.original.code})},{id:"month",header:"Tháng",accessorKey:"month",cell:({row:ne})=>{const q=ne.original.month,me=ne.original.year;return u.jsx("span",{className:"flex flex-col",children:`${q.toString().padStart(2,"0")}/${me}`})}},{id:"content",header:"Nội dung",accessorKey:"content",cell:({row:ne})=>{const q=ne.getValue("content");return u.jsx("div",{className:"text-start truncate text-ellipsis overflow-hidden whitespace-nowrap max-w-[30dvw]",children:q})}},{id:"status",header:"Trạng thái",accessorKey:"status",cell:({row:ne})=>{const me=ne.original.status!=="unpublish";return u.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0 text-[10px] font-bold ${me?"bg-green-50 text-green-700 ring-1 ring-inset ring-green-600/20":"bg-gray-50 text-gray-600 ring-1 ring-inset ring-gray-500/20"}`,children:me?"PUBLISHED":"UNPUBLISHED"})}},{id:"note",header:"Ghi chú",accessorKey:"note",cell:({row:ne})=>u.jsx(bT,{content:u.jsx("div",{className:"font-medium text-[16px] max-w-[90dvw]",children:ne.original.note}),children:u.jsx("div",{className:"text-start truncate text-ellipsis overflow-hidden whitespace-nowrap max-w-[20dvw]",children:ne.original.note})})},{id:"last-update",header:"Cập nhật",accessorKey:"last-update",cell:({row:ne})=>{const q=new Date(ne.original.lastUpdate),me=q.getDate(),he=q.getMonth()+1,be=`ngày ${me} tháng ${he}`;return u.jsx("span",{className:"flex flex-col",children:be})}},{accessorKey:"actions",header:()=>u.jsx("div",{className:"font-medium text-right",children:"Hành động"}),cell:({row:ne})=>{const[q,me]=M.useState(!1),[he,be]=M.useState(!1),[G,X]=M.useState(!1),{handleSubmit:Y,register:ae,reset:Z}=P$(),J=ne.original.id,L=ne.getValue("status"),te=ne.getValue("content"),[xe,_e]=M.useState(!1),Se=async()=>{try{_e(!0);const Ae=L==="unpublish"?"published":"unpublish",Pe=await Re.patch(`${t}/api/toggle-publish/${J}`,{id:J,typeAction:"update",status:L,idInput:J,stock_id:ne.original.stock_id,prefix:ne.original.prefix,model:ne.original.model,summary_result:ne.original.content,note:ne.original.note});Pe.status===200?n(Le=>Le.map(De=>De.id===J?{...De,status:Ae}:De)):console.error("Failed to toggle publish status:",Pe)}catch(Ae){console.error("Error toggling publish status:",Ae)}finally{_e(!1)}},Ie=async Ae=>{me(!0);try{const Pe=await Re.patch(`${t}/api/update-summary`,{note:Ae.note,text_summary:Ae.content,id:J});Pe.status===200?(await O(l),be(!1)):console.error("Failed to update summary:",Pe)}catch(Pe){console.error("Error updating summary:",Pe)}return me(!1)};return u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx($e,{variant:"outline",size:"sm",onClick:()=>X(!0),className:"px-2 py-0.5 h-7",children:u.jsx(VM,{className:"h-4 w-4"})}),u.jsx(pr,{open:G,onOpenChange:X,children:u.jsxs(Qn,{className:"max-w-3xl max-h-[80vh]",children:[u.jsx(Xn,{children:u.jsx(Zn,{children:"Nội dung chi tiết"})}),u.jsx("div",{className:"mt-4 overflow-y-auto max-h-[60vh]",children:u.jsx("div",{className:"whitespace-pre-wrap text-[16px] leading-relaxed",children:te})})]})}),u.jsxs(pr,{open:he,onOpenChange:Ae=>{be(Ae),Ae?Z({content:ne.original.content,note:ne.original.note}):Z()},children:[u.jsx(Gs,{asChild:!0,children:u.jsx($e,{variant:"outline",size:"sm",onClick:()=>be(!0),className:"px-2 py-0.5 h-7",children:"Sửa"})}),u.jsx(Qn,{className:"rounded-lg sm:px-3 h-[calc(100dvh-200px)] min-w-[calc(100dvw-112px)]",children:u.jsxs(Xn,{className:"flex flex-col gap-3",children:[u.jsx(Zn,{className:"max-sm:hidden text-center",children:"Sửa summary"}),u.jsxs("form",{className:"flex flex-col gap-3 h-full justify-between",onSubmit:Y(Ie),children:[u.jsxs("div",{className:"flex flex-col gap-2",children:[u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Nội dung:"}),u.jsx(Js,{placeholder:"Nội dung",className:"w-full input-scroll-bar",defaultValue:ne.original.answer||"",rows:10,...ae("content")})]}),u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Ghi chú:"}),u.jsx(Js,{placeholder:"Nội dung",className:"w-full input-scroll-bar",defaultValue:ne.original.note||"",rows:1,...ae("note")})]})]}),u.jsx("div",{className:"flex justify-end",children:u.jsx($e,{disabled:q,type:"submit",variant:"default",children:q?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):"Ok"})})]})]})})]}),u.jsx($e,{variant:"outline",size:"sm",onClick:Se,disabled:xe,className:"w-[70px] px-2 py-0.5 h-7",children:xe?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):L==="unpublish"?"Publish":"Unpublish"})]})}}],[]),E=oC({data:e,columns:R,state:{columnFilters:a},enableRowSelection:!0,onColumnFiltersChange:c,getFilteredRowModel:WP(),getCoreRowModel:rC()});return u.jsxs("div",{className:"space-y-4 s3-explr-container",children:[u.jsx("div",{className:"flex items-center space-x-4 s3-explr-toolbar",children:u.jsxs("div",{className:"relative max-w-sm",children:[u.jsx(no,{placeholder:"Tìm kiếm theo mã...",value:v,onChange:W=>x(W.target.value),className:"pr-8"}),v&&u.jsx($e,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0",onClick:()=>x(""),children:u.jsx(Op,{className:"h-4 w-4"})})]})}),u.jsx("div",{className:"rounded-md border s3-explr-table-container",children:u.jsxs(js,{className:"s3-explr-table",children:[u.jsx(Ws,{className:"s3-explr-table-header",children:E.getHeaderGroups().map(W=>u.jsx(er,{className:"hover:bg-transparent s3-explr-header-row",children:W.headers.map(ne=>u.jsx(tr,{className:"s3-explr-header-cell",children:ne.isPlaceholder?null:nd(ne.column.columnDef.header,ne.getContext())},ne.id))},W.id))}),u.jsx(qs,{className:"s3-explr-table-body",children:r?u.jsx(er,{children:u.jsx(pn,{colSpan:R.length,className:"h-24 text-center",children:"Đang tải dữ liệu..."})}):(z=E.getRowModel().rows)!=null&&z.length?(j=E.getRowModel().rows)==null?void 0:j.map(W=>u.jsx(er,{className:"h-12 s3-explr-row",children:W.getVisibleCells().map(ne=>u.jsx(pn,{className:"align-middle s3-explr-cell",children:nd(ne.column.columnDef.cell,ne.getContext())},ne.id))},W.id)):u.jsx(er,{children:u.jsx(pn,{colSpan:R.length,className:"h-24 text-center",children:"Không có kết quả."})})})]})}),u.jsx("div",{className:"mt-4",children:u.jsx(Sd,{children:u.jsxs(Td,{children:[u.jsx(Dr,{children:u.jsx(Ed,{onClick:()=>f(W=>Math.max(1,W-1)),className:l===1?"pointer-events-none opacity-50":"cursor-pointer"})}),Array.from({length:h},(W,ne)=>ne+1).filter(W=>W===1||W===h||Math.abs(W-l)<=1).map((W,ne,q)=>u.jsxs(u.Fragment,{children:[ne>0&&q[ne-1]!==W-1&&u.jsx(Dr,{children:u.jsx(Id,{})},W+"..."),u.jsx(Dr,{children:u.jsx(La,{onClick:()=>f(W),isActive:l===W,className:`cursor-pointer ${r?"pointer-events-none":""}`,children:g===W?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):W})},W)]})),u.jsx(Dr,{children:u.jsx(Ad,{onClick:()=>f(W=>Math.min(h,W+1)),className:l===h||g!==null?"pointer-events-none opacity-50":"cursor-pointer"})})]})})})]})},CT=10,D$=M.memo(({apiBaseUrl:t="http://localhost:3000"})=>{const[e,n]=M.useState(1),[r,o]=M.useState([]),[a,c]=M.useState({total:0,page:1,limit:CT,totalPages:1}),[l,f]=M.useState(!0),[h,p]=M.useState(null),[g,y]=M.useState(new Set),{toast:v}=Fd(),[x,w]=M.useState(!1),_=async E=>{try{p(E);const z=await Re.get(`${t}/api/jobs`,{params:{page:E.toString(),limit:CT.toString()}});o(z.data.data),c(z.data.pagination)}catch{v({variant:"destructive",title:"Error",description:"Failed to fetch jobs. Please try again."})}finally{p(null),f(!1)}};M.useEffect(()=>{_(e)},[e,t]);const I=async E=>{y(z=>new Set(z).add(E.toString()));try{await Re.post(`${t}/api/retry-job`,{jobId:E},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),v({title:"Job Restarted",description:`Job ${E} has been successfully restarted.`}),_(e)}catch{v({variant:"destructive",title:"Retry Failed",description:`Failed to restart job ${E}. Please try again.`})}finally{y(z=>{const j=new Set(z);return j.delete(E.toString()),j})}},k=async()=>{w(!0),n(1),await _(1),w(!1)},O=E=>new Date(E).toLocaleString(),R=E=>{if(E=parseFloat(E),E<60)return`${E.toFixed(2)}s`;const z=Math.floor(E/60),j=(E%60).toFixed(0);return`${z}m ${j}s`};return u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[u.jsx($M,{className:"w-8 h-8 text-primary"}),u.jsx("h2",{className:"text-3xl font-bold tracking-tight",children:"Job Management"}),u.jsx($e,{variant:"outline",size:"icon",onClick:k,disabled:x||l,className:"ml-2",children:u.jsx(jM,{className:`h-4 w-4 ${x?"animate-spin":""}`})})]}),u.jsx("div",{className:"rounded-md border",children:u.jsxs(js,{children:[u.jsx(Ws,{children:u.jsxs(er,{children:[u.jsx(tr,{children:"ID"}),u.jsx(tr,{children:"Tên Công Việc"}),u.jsx(tr,{children:"Thời Gian Bắt Đầu"}),u.jsx(tr,{children:"Thời Gian Cập Nhật"}),u.jsx(tr,{children:"Thời Gian Thực Thi"}),u.jsx(tr,{children:"Trạng Thái"}),u.jsx(tr,{children:"Thao Tác"})]})}),u.jsx(qs,{children:l&&r.length===0?u.jsx(er,{children:u.jsx(pn,{colSpan:7,className:"text-center py-4",children:u.jsx(Vt,{className:"w-6 h-6 animate-spin mx-auto"})})}):r.map(E=>{var z,j;return u.jsxs(er,{children:[u.jsx(pn,{className:"!w-[100px]",children:E.id}),u.jsx(pn,{className:"font-medium",children:(z=E.job_name)==null?void 0:z.replace("Upload file","Summary")}),u.jsx(pn,{className:"!w-[200px]",children:O(E.created_at)}),u.jsx(pn,{className:"!w-[200px]",children:O(E.updated_at)}),u.jsx(pn,{className:"!w-[150px]",children:R(E.execution_time_seconds)}),u.jsx(pn,{className:"!w-[200px]",children:u.jsx(bT,{content:E.status==="fail"&&E.error?u.jsx("div",{className:"font-medium text-[16px] max-w-[90dvw]",children:E.error}):null,children:u.jsx("div",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium truncate text-ellipsis overflow-hidden whitespace-nowrap max-w-[30dvw]
217
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qS(t,e){if(t){if(typeof t=="string")return Pg(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if(n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set")return Array.from(t);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Pg(t,e)}}function Pg(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function qH(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r=[],o=!0,a=!1,c,l;try{for(n=n.call(t);!(o=(c=n.next()).done)&&(r.push(c.value),!(e&&r.length===e));o=!0);}catch(f){a=!0,l=f}finally{try{!o&&n.return!=null&&n.return()}finally{if(a)throw l}}return r}}function YH(t){if(Array.isArray(t))return t}function YS(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function Ut(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?YS(Object(n),!0).forEach(function(r){Mg(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):YS(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Mg(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Xd(t,e){if(t==null)return{};var n=JH(t,e),r,o;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(o=0;o<a.length;o++)r=a[o],!(e.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}function JH(t,e){if(t==null)return{};var n={},r=Object.keys(t),o,a;for(a=0;a<r.length;a++)o=r[a],!(e.indexOf(o)>=0)&&(n[o]=t[o]);return n}var Rg=M.forwardRef(function(t,e){var n=t.children,r=Xd(t,$H),o=QS(r),a=o.open,c=Xd(o,UH);return M.useImperativeHandle(e,function(){return{open:a}},[a]),M.createElement(M.Fragment,null,n(Ut(Ut({},c),{},{open:a})))});Rg.displayName="Dropzone";var JS={disabled:!1,getFilesFromEvent:cH,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};Rg.defaultProps=JS,Rg.propTypes={children:It.func,accept:It.objectOf(It.arrayOf(It.string)),multiple:It.bool,preventDropOnDocument:It.bool,noClick:It.bool,noKeyboard:It.bool,noDrag:It.bool,noDragEventsBubbling:It.bool,minSize:It.number,maxSize:It.number,maxFiles:It.number,disabled:It.bool,getFilesFromEvent:It.func,onFileDialogCancel:It.func,onFileDialogOpen:It.func,useFsAccessApi:It.bool,autoFocus:It.bool,onDragEnter:It.func,onDragLeave:It.func,onDragOver:It.func,onDrop:It.func,onDropAccepted:It.func,onDropRejected:It.func,onError:It.func,validator:It.func};var Dg={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function QS(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=Ut(Ut({},JS),t),n=e.accept,r=e.disabled,o=e.getFilesFromEvent,a=e.maxSize,c=e.minSize,l=e.multiple,f=e.maxFiles,h=e.onDragEnter,p=e.onDragLeave,g=e.onDragOver,y=e.onDrop,v=e.onDropAccepted,x=e.onDropRejected,w=e.onFileDialogCancel,_=e.onFileDialogOpen,I=e.useFsAccessApi,k=e.autoFocus,O=e.preventDropOnDocument,R=e.noClick,E=e.noKeyboard,z=e.noDrag,j=e.noDragEventsBubbling,W=e.onError,ne=e.validator,q=M.useMemo(function(){return FH(n)},[n]),me=M.useMemo(function(){return DH(n)},[n]),he=M.useMemo(function(){return typeof _=="function"?_:XS},[_]),be=M.useMemo(function(){return typeof w=="function"?w:XS},[w]),G=M.useRef(null),X=M.useRef(null),Y=M.useReducer(QH,Dg),ae=Og(Y,2),Z=ae[0],J=ae[1],L=Z.isFocused,te=Z.isFileDialogActive,xe=M.useRef(typeof window<"u"&&window.isSecureContext&&I&&RH()),_e=function(){!xe.current&&te&&setTimeout(function(){if(X.current){var re=X.current.files;re.length||(J({type:"closeDialog"}),be())}},300)};M.useEffect(function(){return window.addEventListener("focus",_e,!1),function(){window.removeEventListener("focus",_e,!1)}},[X,te,be,xe]);var Se=M.useRef([]),Ie=function(re){G.current&&G.current.contains(re.target)||(re.preventDefault(),Se.current=[])};M.useEffect(function(){return O&&(document.addEventListener("dragover",GS,!1),document.addEventListener("drop",Ie,!1)),function(){O&&(document.removeEventListener("dragover",GS),document.removeEventListener("drop",Ie))}},[G,O]),M.useEffect(function(){return!r&&k&&G.current&&G.current.focus(),function(){}},[G,k,r]);var Ae=M.useCallback(function(H){W?W(H):console.error(H)},[W]),Pe=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H),Se.current=[].concat(VH(Se.current),[H.target]),Qd(H)&&Promise.resolve(o(H)).then(function(re){if(!(Jd(H)&&!j)){var pe=re.length,de=pe>0&&NH({files:re,accept:q,minSize:c,maxSize:a,multiple:l,maxFiles:f,validator:ne}),Ce=pe>0&&!de;J({isDragAccept:de,isDragReject:Ce,isDragActive:!0,type:"setDraggedFiles"}),h&&h(H)}}).catch(function(re){return Ae(re)})},[o,h,Ae,j,q,c,a,l,f,ne]),Le=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H);var re=Qd(H);if(re&&H.dataTransfer)try{H.dataTransfer.dropEffect="copy"}catch{}return re&&g&&g(H),!1},[g,j]),De=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H);var re=Se.current.filter(function(de){return G.current&&G.current.contains(de)}),pe=re.indexOf(H.target);pe!==-1&&re.splice(pe,1),Se.current=re,!(re.length>0)&&(J({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),Qd(H)&&p&&p(H))},[G,p,j]),Ne=M.useCallback(function(H,re){var pe=[],de=[];H.forEach(function(Ce){var We=VS(Ce,q),ht=Og(We,2),ft=ht[0],Bn=ht[1],or=KS(Ce,c,a),$t=Og(or,2),ir=$t[0],ar=$t[1],sr=ne?ne(Ce):null;if(ft&&ir&&!sr)pe.push(Ce);else{var He=[Bn,ar];sr&&(He=He.concat(sr)),de.push({file:Ce,errors:He.filter(function(ho){return ho})})}}),(!l&&pe.length>1||l&&f>=1&&pe.length>f)&&(pe.forEach(function(Ce){de.push({file:Ce,errors:[kH]})}),pe.splice(0)),J({acceptedFiles:pe,fileRejections:de,isDragReject:de.length>0,type:"setFiles"}),y&&y(pe,de,re),de.length>0&&x&&x(de,re),pe.length>0&&v&&v(pe,re)},[J,l,q,c,a,f,y,v,x,ne]),Je=M.useCallback(function(H){H.preventDefault(),H.persist(),Un(H),Se.current=[],Qd(H)&&Promise.resolve(o(H)).then(function(re){Jd(H)&&!j||Ne(re,H)}).catch(function(re){return Ae(re)}),J({type:"reset"})},[o,Ne,Ae,j]),ye=M.useCallback(function(){if(xe.current){J({type:"openDialog"}),he();var H={multiple:l,types:me};window.showOpenFilePicker(H).then(function(re){return o(re)}).then(function(re){Ne(re,null),J({type:"closeDialog"})}).catch(function(re){LH(re)?(be(re),J({type:"closeDialog"})):HH(re)?(xe.current=!1,X.current?(X.current.value=null,X.current.click()):Ae(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):Ae(re)});return}X.current&&(J({type:"openDialog"}),he(),X.current.value=null,X.current.click())},[J,he,be,I,Ne,Ae,me,l]),st=M.useCallback(function(H){!G.current||!G.current.isEqualNode(H.target)||(H.key===" "||H.key==="Enter"||H.keyCode===32||H.keyCode===13)&&(H.preventDefault(),ye())},[G,ye]),bt=M.useCallback(function(){J({type:"focus"})},[]),sn=M.useCallback(function(){J({type:"blur"})},[]),gn=M.useCallback(function(){R||(MH()?setTimeout(ye,0):ye())},[R,ye]),Rt=function(re){return r?null:re},$n=function(re){return E?null:Rt(re)},nn=function(re){return z?null:Rt(re)},Un=function(re){j&&re.stopPropagation()},Bt=M.useMemo(function(){return function(){var H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},re=H.refKey,pe=re===void 0?"ref":re,de=H.role,Ce=H.onKeyDown,We=H.onFocus,ht=H.onBlur,ft=H.onClick,Bn=H.onDragEnter,or=H.onDragOver,$t=H.onDragLeave,ir=H.onDrop,ar=Xd(H,BH);return Ut(Ut(Mg({onKeyDown:$n(lo(Ce,st)),onFocus:$n(lo(We,bt)),onBlur:$n(lo(ht,sn)),onClick:Rt(lo(ft,gn)),onDragEnter:nn(lo(Bn,Pe)),onDragOver:nn(lo(or,Le)),onDragLeave:nn(lo($t,De)),onDrop:nn(lo(ir,Je)),role:typeof de=="string"&&de!==""?de:"presentation"},pe,G),!r&&!E?{tabIndex:0}:{}),ar)}},[G,st,bt,sn,gn,Pe,Le,De,Je,E,z,r]),D=M.useCallback(function(H){H.stopPropagation()},[]),K=M.useMemo(function(){return function(){var H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},re=H.refKey,pe=re===void 0?"ref":re,de=H.onChange,Ce=H.onClick,We=Xd(H,zH),ht=Mg({accept:q,multiple:l,type:"file",style:{border:0,clip:"rect(0, 0, 0, 0)",clipPath:"inset(50%)",height:"1px",margin:"0 -1px -1px 0",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap"},onChange:Rt(lo(de,Je)),onClick:Rt(lo(Ce,D)),tabIndex:-1},pe,X);return Ut(Ut({},ht),We)}},[X,n,l,Je,r]);return Ut(Ut({},Z),{},{isFocused:L&&!r,getRootProps:Bt,getInputProps:K,rootRef:G,inputRef:X,open:Rt(ye)})}function QH(t,e){switch(e.type){case"focus":return Ut(Ut({},t),{},{isFocused:!0});case"blur":return Ut(Ut({},t),{},{isFocused:!1});case"openDialog":return Ut(Ut({},Dg),{},{isFileDialogActive:!0});case"closeDialog":return Ut(Ut({},t),{},{isFileDialogActive:!1});case"setDraggedFiles":return Ut(Ut({},t),{},{isDragActive:e.isDragActive,isDragAccept:e.isDragAccept,isDragReject:e.isDragReject});case"setFiles":return Ut(Ut({},t),{},{acceptedFiles:e.acceptedFiles,fileRejections:e.fileRejections,isDragReject:e.isDragReject});case"reset":return Ut({},Dg);default:return t}}function XS(){}const XH=({onFilesSelected:t,children:e})=>{const[n,r]=M.useState(!1),{getRootProps:o,getInputProps:a}=QS({noClick:!0,onDrop:c=>{if(c&&c.length>0)if(c[0].path.split("/").length>2){const f=c.map(h=>{const g=(h.path||h.relativePath||"").split("/").slice(1).join("/");return(!h.webkitRelativePath||h.webkitRelativePath==="")&&Object.defineProperty(h,"webkitRelativePath",{writable:!0,value:g,enumerable:!0,configurable:!0}),h});t(f,"folder")}else t(c,"files");r(!1)},onDragOver:c=>{c.preventDefault(),n||r(!0)},multiple:!0});return M.useEffect(()=>{const c=l=>{l.clientX===0&&l.clientY===0&&r(!1)};return document.addEventListener("dragleave",c),()=>{document.removeEventListener("dragleave",c)}},[]),u.jsxs("div",{...o(),className:"transition-opacity min-h-[600px]",children:[n?u.jsx("div",{className:"flex flex-col items-center justify-center p-4 border-2 border-dashed border-gray-300 rounded-lg bg-gray-50 h-screen"}):e,u.jsx("input",{...a()})]})},ZH=({isOpen:t,onClose:e,files:n})=>{const[r,o]=M.useState(null),a=l=>{o(f=>!f||f.key!==l?{key:l,direction:"asc"}:{key:l,direction:f.direction==="asc"?"desc":"asc"})},c=M.useMemo(()=>r?[...n].sort((l,f)=>{var g,y;const h=((g=l[r.key])==null?void 0:g.toString().toLowerCase())||"",p=((y=f[r.key])==null?void 0:y.toString().toLowerCase())||"";return h<p?r.direction==="asc"?-1:1:h>p?r.direction==="asc"?1:-1:0}):n,[n,r]);return u.jsx(pr,{open:t,onOpenChange:e,children:u.jsxs(Qn,{className:"sm:max-w-[825px]",children:[u.jsxs(Xn,{children:[u.jsx(Zn,{children:"Tài liệu đang xử lý"}),u.jsx(Mo,{children:"Đây là danh sách các tài liệu đang trong hàng đợi xử lý."})]}),u.jsx("div",{className:"max-h-96 overflow-y-auto",children:u.jsxs(js,{children:[u.jsx(Ws,{children:u.jsxs(er,{children:[u.jsxs(tr,{colSpan:2,className:"text-left cursor-pointer hover:underline",onClick:()=>a("type"),children:["Loại ",(r==null?void 0:r.key)==="type"&&(r.direction==="asc"?"↑":"↓")]}),u.jsxs(tr,{colSpan:3,className:"text-left cursor-pointer hover:underline",onClick:()=>a("name"),children:["Tên tệp"," ",(r==null?void 0:r.key)==="name"&&(r.direction==="asc"?"↑":"↓")]}),u.jsx(tr,{className:"text-left",children:"Ghi chú"})]})}),u.jsx(qs,{children:c.length>0&&c.map(l=>u.jsxs(er,{children:[u.jsx(pn,{colSpan:2,children:l.type}),u.jsx(pn,{colSpan:3,className:"font-medium text-left truncate max-w-[200px]",title:l.name,children:l.name}),u.jsx(pn,{children:l.unSupported&&!l.isFolder?`Không hỗ trợ file ${l.name.split(".").pop()}`:!!l.timeout&&u.jsx("span",{style:{color:"red"},children:"Parsing lỗi, vui lòng thử lại."})})]}))})]})})]})})},e$=({openDialogRename:t,setOpenDialogRename:e,apiBaseUrl:n,setFileToMove:r,fileToMove:o,refreshFiles:a,ignoreCache:c,autoSyncAfterFileOperation:l})=>{var O;const[f,h]=M.useState({}),[p,g]=M.useState(!1),[y,v]=M.useState(!1),[x,w]=M.useState(""),{toast:_}=Fd();M.useEffect(()=>{t&&I(x)},[x,t]);const I=async R=>{try{v(!0);const E=await Re.get(`${n}/api/list-s3-folders?prefix=${R}`,{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});h(E==null?void 0:E.data)}catch{_({title:"Error",description:"Unable to load S3 folder list",variant:"destructive"})}finally{v(!1)}},k=async()=>{g(!0);try{const R=o.key,E=R.endsWith("/")?R:`${R}/`,z=x.endsWith("/")?x:`${x}/`;if(E===z||R===x){_({title:"Lỗi",description:"Không thể di chuyển file đến cùng vị trí",variant:"destructive"}),g(!1);return}await Re.post(`${n}/api/move`,{oldPath:R,newPath:x},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),c.current=!0,await a(),_({title:"Đã di chuyển",description:`Đã di chuyển thành công "${o.name}" đến "${x}"`}),e(!1),r(null),w(""),l&&await l("move")}catch(R){console.error("Error renaming item:",R),_({title:"Lỗi",description:"Không thể đổi tên",variant:"destructive"})}finally{g(!1)}};return u.jsx(pr,{open:t,onOpenChange:R=>{R||(e(!1),r(null),w(""))},children:u.jsxs(Qn,{className:"max-h-[700px] pb-3 px-1 s3-explr-input-group max-w-5xl w-[90%] p-6 bg-white rounded-lg shadow-lg",children:[u.jsxs(Xn,{className:"mb-4 w-full h-full",children:[u.jsx("nav",{className:"mb-4",children:u.jsxs("ul",{className:"flex items-center space-x-2 text-sm text-gray-600",children:[u.jsx("li",{className:"cursor-pointer hover:text-blue-600 transition-colors",onClick:()=>w(""),children:"Root"}),x.split("/").map((R,E,z)=>u.jsx("li",{className:"cursor-pointer hover:text-blue-600 transition-colors",onClick:()=>w(R==="Root"?"":z.slice(0,E+1).join("/")+"/"),children:R},E))]})}),u.jsxs(Zn,{className:"text-xl font-semibold text-gray-800",children:["Di chuyển"," ",u.jsxs("span",{className:"text-sm text-gray-500",children:["( file Hoặc folder sẽ được di chuyển đến thư mục"," ",x===""?"Root":x," )"]})]}),u.jsx(Mo,{className:"text-gray-600 w-full h-[50dvh] max-h-[500px] overflow-hidden overflow-y-auto",children:y?u.jsx("div",{className:"flex justify-center items-center py-4",children:u.jsx("div",{className:"loader ease-linear rounded-full border-4 border-t-4 border-gray-200 h-12 w-12"})}):u.jsx("ul",{className:"space-y-2",children:(O=Object.keys(f))==null?void 0:O.map(R=>u.jsx("li",{className:"cursor-pointer hover:bg-gray-100 p-2 rounded transition-colors",onClick:()=>w(R),children:R},R))})})]}),u.jsxs(Po,{className:"flex justify-end space-x-2",children:[u.jsx($e,{variant:"outline",onClick:()=>e(!1),className:"px-4 py-2 rounded border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors",children:"Cancel"}),u.jsx($e,{onClick:k,disabled:p,className:"s3-explr-crawl-btn",children:"Move"})]})]})})},t$="AIzaSyBI8KiTWudkw8iR5cjH7ZsA4JBN1NqJw8A",n$="726815747852-5deq413t8kd8j3mgj48d46eatjauapq5.apps.googleusercontent.com",r$="https://www.googleapis.com/auth/drive";No(Re,{retries:3,shouldResetTimeout:!0,retryCondition:t=>No.isRetryableError(t)&&t.config.method==="get"});const Hn={current:!1},ZS="crawl:jobs",Ka="crawl:current_job",o$=t=>{const[e,n]=M.useState(null),[r,o]=M.useState(0);return M.useEffect(()=>{const a=localStorage.getItem(Ka);if(a){const c=JSON.parse(a);n(c),c!=null&&c.startTime&&o(Math.floor((Date.now()-c.startTime)/1e3))}},[]),M.useEffect(()=>{if(!(e!=null&&e.startTime))return;const a=setInterval(()=>{o(Math.floor((Date.now()-e.startTime)/1e3))},1e3);return()=>clearInterval(a)},[e==null?void 0:e.startTime]),M.useEffect(()=>{if(!(e!=null&&e.id))return;const a=async()=>{try{const f=(await Re.get(`${t}/api/crawl/${e.id}?taskId=${e.taskId}`)).data;n(h=>{if(!h)return null;const p={...h,status:f};return localStorage.setItem(Ka,JSON.stringify(p)),(f.status==="completed"||f.status==="failed")&&setTimeout(()=>{n(null),localStorage.removeItem(Ka)},100),p})}catch(l){console.error("Error polling job status:",l)}},c=setInterval(a,3e3);return a(),()=>clearInterval(c)},[e==null?void 0:e.id,t]),{currentJob:e,elapsedTime:r,setCurrentJob:a=>{a&&!a.startTime&&(a.startTime=Date.now()),n(a),a?localStorage.setItem(Ka,JSON.stringify(a)):localStorage.removeItem(Ka)}}},Zd=(t,e)=>{const n=[],r=o=>{(t[o]||[]).forEach(c=>{n.push(c.key),c.isFolder&&r(c.key)})};return r(e),n},i$=(t,e)=>{const n=[];return(t[e]||[]).forEach(o=>{n.push(o.key),o.isFolder&&n.push(...Zd(t,o.key))}),n},a$=(t,e,n=[],r,o,a,c,l,f,h)=>{const[p,g]=M.useState({}),[y,v]=M.useState(!1),[x,w]=M.useState(null),[_,I]=M.useState(0),k=M.useRef(e);M.useEffect(()=>{k.current=e},[e]);const O=async()=>{v(!0);try{const E=await Re.get(`${t}/api/files`,{params:{cache:!1,displayPrefixes:JSON.stringify(n),prefix:k.current,excludePrivateFiles:c?"false":"true"},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:3e5}),z=[];vd.forEach(E.data,(j,W)=>{l!=null&&l.has(W)&&vd.forEach(j,ne=>{(f==null?void 0:f.current[ne.key])!==!1&&z.push(ne.key)})}),z.length&&(h==null||h(j=>{const W=new Set(j);return z.forEach(ne=>W.add(ne)),W})),g(E.data),w(null)}catch(E){w(E instanceof Error?E:new Error("Failed to fetch files"))}finally{v(!1),I(0),a("")}},R=async E=>{var z,j;try{if(!E)return;v(!0);const W=await Re.get(`${t}/api/search-db?query=${E}&rootPrefix=${e}&offset=${(o-1)*20}&limit=20`,{timeout:3e5,headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});return g({[e]:((z=W==null?void 0:W.data)==null?void 0:z.result)||[]}),I(((j=W==null?void 0:W.data)==null?void 0:j.estimatedTotalHits)||0),W}catch(W){w(W instanceof Error?W:new Error("Failed to fetch files"))}finally{v(!1)}};return M.useEffect(()=>{!r&&!y&&O(),r&&!y&&R(r)},[r,o]),{data:p,isLoading:y,error:x,estimatedTotalHits:_,refetch:O}},ac=t=>{var r,o,a;const e=((a=(o=(r=t==null?void 0:t.name)==null?void 0:r.split("."))==null?void 0:o.pop())==null?void 0:a.toLowerCase())??"";return["txt","md","json","js","ts","jsx","tsx","css","html","xml","yaml","yml"].includes(e||"")},s$={auth:{clientId:"584d5fa9-5123-4602-a1a5-a3746a83745f",authority:"https://login.microsoftonline.com/consumers",redirectUri:"http://localhost:5173/"}},c$=new Lh(s$),l$=M.memo(({homeLabel:t="Kho tài liệu",apiBaseUrl:e="http://localhost:3000",rootPrefix:n="coopbank-cagent-cmcts-ai/",rootUrlHostApi:r,asSelector:o=!1,onSelected:a=h=>console.log("Đã chọn:",h),displayPrefixes:c,preSelectedFiles:l,idCreator:f})=>{var Iu;const[h,p]=M.useState([]),[g,y]=M.useState(""),[v,x]=M.useState(new Set(l)),[w,_]=M.useState(n),[I,k]=M.useState(""),[O,R]=M.useState(!1),[E,z]=M.useState(""),[j,W]=M.useState(!1),[ne,q]=M.useState(null),[me,he]=M.useState(null),[be,G]=M.useState(!1),[X,Y]=M.useState(!1),[,ae]=M.useState(null),Z=M.useRef(null),{toast:J}=Fd(),[L,te]=M.useState(null),[xe,_e]=M.useState(null),[Se,Ie]=M.useState(""),[Ae,Pe]=M.useState(!1),[Le,De]=M.useState(!1),[Ne,Je]=M.useState(new Set),[ye,st]=M.useState(""),[bt,sn]=M.useState(!1),[gn,Rt]=M.useState(!1),[$n,nn]=M.useState("rename"),[Un,Bt]=M.useState(!1),[D,K]=M.useState(""),[H,re]=M.useState("1"),[pe,de]=M.useState(!1),[Ce,We]=M.useState(!1),[ht,ft]=M.useState(!1),[Bn,or]=M.useState(!1),[$t,ir]=M.useState(1),[ar,sr]=M.useState(!1),{currentJob:He,elapsedTime:ho,setCurrentJob:iu}=o$(e),[Br,vi]=M.useState(null),[Gi,ja]=M.useState(""),[zg,ji]=M.useState(!1),[Wi,au]=M.useState(""),[Vg,su]=M.useState(!1),[fc,cu]=M.useState(!1),[yi,lu]=M.useState([]),[qi,du]=M.useState(!1),[Wa,Kg]=M.useState(""),[uu,Gg]=M.useState({faqUploadSize:[],hdsdUploadSize:[],normalUploadSize:[],faqParsedSize:[],hdsdParsedSize:[],normalParsedSize:[]}),[jg,hc]=M.useState(!1),$o=M.useRef({}),Wg=async S=>{cu(!0);try{const N=await Re.get(`${r}get-knowledge-base/knowledge-base-name/${S}`,{headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAyOTliMmIwLTk4MGEtNGQ1Yy04NjkyLWJjNjllM2I1NzZlMiIsInVzZXJuYW1lIjoiY21jX3RzX2FkbWluIiwiaWF0IjoxNzQ3MTk0MTg3fQ.7LB2rgd0fQnhZP_cFgTTCPMSYl0_apwffcNEd7oqjeM"}});N.status===200&&lu(N.data.knowledgeBase.chatflows.map(U=>({...U,KnowledgeBaseId:N.data.knowledgeBase.knowledge_base_id})))}catch{}finally{cu(!1)}};M.useEffect(()=>{Wi&&r&&Wg(Wi)},[Wi]),M.useEffect(()=>{console.log("pre selected files",l)},[l]);const[kt,pc]=M.useState(null),[xT,qg]=M.useState(!1),[gc,mc]=M.useState(!1),[Yi,qa]=M.useState(!1),[fu,hu]=M.useState([]),[vc,yc]=M.useState([]),[Ji,wc]=M.useState([{id:"root",name:"OneDrive"}]),[Yg,Ya]=M.useState(!1),[Ja,bc]=M.useState([]),[pu,Uo]=M.useState(!1),[Qa,Cc]=M.useState([]),[xc,Xa]=M.useState([]),[Za,gu]=M.useState([]),[_c,Qi]=M.useState([{id:"root",name:"SharePoint"}]),[po,Xi]=M.useState(!1),[Sc,Tc]=M.useState([]),[pt,zr]=M.useState(null),[mu,Zi]=M.useState(!1),[Jg,ea]=M.useState(!1),vu=new URL(window.location.href).searchParams.get("prefix")||""||I||n,[_T,Zg]=M.useState(null),{data:go,isLoading:wi,error:em,estimatedTotalHits:ta,refetch:cn}=a$(e,vu,c,g,$t,y,f,v,$o,x),[Ec,gr]=M.useState(!1),Ac=M.useRef(null);M.useEffect(()=>{if(!Ec)return;function S(N){Ac.current&&!Ac.current.contains(N.target)&&gr(!1)}return document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S)}},[Ec]);const tm=async()=>{try{const S=await Re.get(`${e}/api/login-sharepoint`),{loginUrl:N}=S.data,U=window.open(N,"SharePoint Login","width=600,height=600");if(!U)throw new Error("Không thể mở cửa sổ pop-up");U.focus();const oe=setInterval(()=>{try{if(U.closed){clearInterval(oe);return}const fe=U.location.href;if(fe.includes("code=")){const we=new URL(fe).searchParams.get("code");we&&(yu(we),U.close(),clearInterval(oe))}}catch(fe){fe instanceof Error&&!fe.message.includes("cross-origin")&&console.error("SharePoint login error:",fe)}},1e3)}catch(S){rt.error("Lỗi khi đăng nhập SharePoint: "+(S instanceof Error?S.message:"Unknown error"))}},nm=async()=>{try{Cc([]),Qi([{id:"root",name:"SharePoint"}]),window.location.href="https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri="+encodeURIComponent(window.location.origin),J({title:"Success",description:"Logged out from SharePoint"})}catch(S){console.error("Error logging out from SharePoint:",S),J({title:"Error",description:"Failed to logout from SharePoint",variant:"destructive"})}},yu=async S=>{try{const N=await Re.post(`${e}/api/get-sharepoint-access-token`,{code:S,userId:"1"}),{accessToken:U}=N.data;localStorage.setItem("sharepoint_access_token",U),mc(!0),Xi(!0)}catch(N){console.error("❌ Error fetching SharePoint access token:",N),J({title:"Error",description:"Failed to connect to SharePoint",variant:"destructive"})}},rm=async()=>{try{Uo(!0);const N=(await Re.post(`${e}/api/list-site-sharepoint`,{userId:"1"})).data.sites.map(U=>{const oe=new URL(U.webUrl);return{id:U.id,name:U.name,description:U.description,hostname:U.hostname||oe.hostname,sitePath:U.sitePath||oe.pathname.replace(/^\/+/,"")}});Tc(N),Uo(!1)}catch(S){console.error("❌ Error fetching SharePoint sites:",S),J({title:"Error",description:"Failed to fetch SharePoint sites",variant:"destructive"}),Uo(!1)}},Nt=async S=>{zr(S),await mt("root",S.name,S.hostname||"",S.sitePath||"")},mt=async(S,N,U,oe)=>{try{Uo(!0);const we=(await Re.post(`${e}/api/list-file-sharepoint`,{folderId:S,userId:"1",hostname:U,sitePath:oe})).data.files.map(Te=>({id:Te.id,name:Te.name,size:Te.size??0,lastModified:Te.lastModifiedDateTime?new Date(Te.lastModifiedDateTime):new Date,contentType:Te.mimeType??void 0,isFolder:Te.type==="folder",parentId:Te.parentId??""}));Xa(we.filter(Te=>Te.isFolder)),Cc(we.filter(Te=>!Te.isFolder)),Xi(!0),Qi(Te=>Te.some(Tt=>Tt.id===S)?Te:[...Te,{id:S,name:N==="root"?"SharePoint":N}]),Uo(!1)}catch(fe){console.error("❌ Error fetching SharePoint files:",fe),J({title:"Error",description:"Failed to fetch SharePoint files",variant:"destructive"}),Uo(!1)}},om=S=>{gu(N=>N.some(oe=>oe.id===S.id)?N.filter(oe=>oe.id!==S.id):[...N,{id:S.id,name:S.name,size:S.size,lastModified:S.lastModified,contentType:S.contentType,isFolder:S.isFolder,parentId:S.parentId}])},im=S=>{var U;Qi(oe=>oe.slice(0,S+1));const N=(U=_c[S])==null?void 0:U.id;N&&mt(N,"SharePoint",(pt==null?void 0:pt.hostname)||"",(pt==null?void 0:pt.sitePath)||"")},am=async(S,N)=>{const U=localStorage.getItem("sharepoint_access_token");if(!U){rt.error("Không tìm thấy access token. Vui lòng đăng nhập lại.");return}const oe=rt.loading("Đang đồng bộ SharePoint...",{position:"bottom-right",autoClose:!1});try{const fe={prefix:N,folders:[],files:[],hostname:(pt==null?void 0:pt.hostname)||"",sitePath:(pt==null?void 0:pt.sitePath)||""};S.forEach(Te=>{Te.isFolder?fe.folders.push({id:Te.id,name:Te.name}):fe.files.push({id:Te.id,name:Te.name})});const we=await Re.post(`${e}/api/sync-sharepoint-to-s3`,fe,{headers:{Authorization:`Bearer ${U}`}});cn(),rt.update(oe,{render:`Đồng bộ thành công! Đã tải lên ${we.data.uploadedKeys.length} file.`,type:"success",isLoading:!1,autoClose:3e3,position:"bottom-right"}),Xi(!1)}catch(fe){console.error("Lỗi khi đồng bộ file từ SharePoint:",fe),rt.update(oe,{render:"Không thể đồng bộ file từ SharePoint.",type:"error",isLoading:!1,autoClose:3e3,position:"bottom-right"})}},wu=()=>{Xi(!1),Cc([]),gu([]),Qi([{id:"root",name:"SharePoint"}])};M.useEffect(()=>{if(po){const N=new URLSearchParams(window.location.search).get("code");N&&(yu(N),window.history.replaceState({},document.title,window.location.pathname))}},[po]),M.useEffect(()=>{c$.initialize().then(()=>{qg(!0)}).catch(S=>console.error("❌ Lỗi khởi tạo MSAL:",S))},[]),M.useEffect(()=>{sm()},[]);async function sm(){localStorage.getItem("onedrive_access_token")&&mc(!0)}const bu=S=>{bc(N=>N.some(oe=>oe.id===S.id)?N.filter(oe=>oe.id!==S.id):[...N,{id:S.id,name:S.name,size:S.size,lastModified:S.lastModified,contentType:S.contentType,isFolder:S.isFolder,parentId:S.parentId}])};function es(S){if(S===0)return"0 B";const N=1024,U=["B","KB","MB","GB","TB"],oe=Math.floor(Math.log(S)/Math.log(N));return parseFloat((S/Math.pow(N,oe)).toFixed(1))+" "+U[oe]}function cm(S){const N=new Date(S);return N.toLocaleDateString()+" "+N.toLocaleTimeString()}const rn=async()=>{try{const S=await Re.get(`${e}/api/login-one-drive`),{loginUrl:N}=S.data,U=window.open(N,"OneDrive Login","width=600,height=600");if(!U)throw new Error("Không thể mở cửa sổ pop-up");U.focus();const oe=setInterval(()=>{try{if(U.closed){clearInterval(oe);return}const fe=U.location.href;if(fe.includes("code=")){const we=new URL(fe).searchParams.get("code");we&&(Bo(we),U.close(),clearInterval(oe))}}catch(fe){fe instanceof Error&&!fe.message.includes("cross-origin")&&console.error("OneDrive login error:",fe)}},1e3)}catch(S){rt.error("Lỗi khi đăng nhập OneDrive: "+(S instanceof Error?S.message:"Unknown error"))}},Ic=async()=>{try{await Re.post(`${e}/api/logout-one-drive`),localStorage.removeItem("onedrive_access_token"),rt.success("Đã đăng xuất khỏi OneDrive"),window.location.href="https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri="+encodeURIComponent(window.location.origin)}catch(S){rt.error("Lỗi khi đăng xuất OneDrive: "+(S instanceof Error?S.message:"Unknown error"))}},Bo=async S=>{try{const U=await Re.post(`${e}/api/get-one-drive-access-token`,{authorizationCode:S,userId:"1"}),{accessToken:oe}=U.data;localStorage.setItem("onedrive_access_token",oe),mc(!0),qa(!0),await na("root","One Drive")}catch(N){console.error("❌ Lỗi khi lấy Access Token:",N)}},na=async(S,N)=>{try{Ya(!0);const fe=(await Re.post(`${e}/api/list-file-one-drive`,{folderId:S,userId:"1"})).data.map(we=>({id:we.id,name:we.name,size:we.size??0,lastModified:we.lastModifiedDateTime?new Date(we.lastModifiedDateTime):new Date,contentType:we.mimeType??void 0,isFolder:we.type==="folder",parentId:we.parentId??""}));hu(fe.filter(we=>we.isFolder)),yc(fe.filter(we=>!we.isFolder)),qa(!0),wc(we=>we.some(Te=>Te.id===S)?we:[...we,{id:S,name:N==="root"?"OneDrive":N}]),Ya(!1)}catch(U){console.error("Lỗi lấy danh sách file:",U),Ya(!1)}},kc=S=>{if(S===Ji.length-1)return;const N=Ji[S];N&&(wc(Ji.slice(0,S+1)),na(N.id,N.name))},zn=async(S,N)=>{const U=localStorage.getItem("onedrive_access_token");if(!U){rt.error("Không tìm thấy access token. Vui lòng đăng nhập lại.");return}const oe=rt.loading("Đang đồng bộ OneDrive...",{position:"bottom-right",autoClose:!1});try{const fe={prefix:N,folders:[],files:[]};S.forEach(Te=>{Te.isFolder?fe.folders.push({id:Te.id,name:Te.name}):fe.files.push({id:Te.id,name:Te.name})});const we=await Re.post(`${e}/api/sync-one-drive-to-s3`,fe,{headers:{Authorization:`Bearer ${U}`}});cn(),rt.update(oe,{render:`Đồng bộ thành công! Đã tải lên ${we.data.uploadedKeys.length} file.`,type:"success",isLoading:!1,autoClose:3e3,position:"bottom-right"})}catch(fe){console.error("Lỗi khi đồng bộ file từ OneDrive:",fe),rt.update(oe,{render:"Không thể đồng bộ file từ OneDrive.",type:"error",isLoading:!1,autoClose:3e3,position:"bottom-right"})}},Nc=()=>{qa(!1),wc([{id:"root",name:"OneDrive"}]),hu([]),yc([]),bc([]),Ya(!1)},Cu=pP({onSuccess:S=>{Zg(S.access_token),localStorage.setItem("google_access_token",S.access_token),xu(S.access_token)},onError:()=>{console.log("Đăng nhập thất bại!")},scope:r$}),xu=S=>{const N=document.createElement("script");N.src="https://apis.google.com/js/api.js",N.onload=()=>{window.gapi.load("picker",()=>_u(S))},document.body.appendChild(N)},_u=S=>{const N=new window.google.picker.DocsView(window.google.picker.ViewId.DOCS).setIncludeFolders(!0).setSelectFolderEnabled(!0).setOwnedByMe(!1),U=new window.google.picker.DocsView(window.google.picker.ViewId.DRIVE).setIncludeFolders(!0).setSelectFolderEnabled(!0);new window.google.picker.PickerBuilder().setDeveloperKey(t$).setOAuthToken(S).enableFeature(window.google.picker.Feature.MULTISELECT_ENABLED).setLocale("vi").addView(N).addView(U).setCallback(async fe=>{if(fe.action===window.google.picker.Action.PICKED){const we=fe.docs.map(Te=>({id:Te.id,name:Te.name,mimeType:Te.mimeType}));await Su(we,w)}}).build().setVisible(!0)},Su=async(S,N="")=>{const U=localStorage.getItem("google_access_token");if(!U){console.error("❌ Không tìm thấy access token. Vui lòng đăng nhập lại."),rt.error("Không tìm thấy access token. Vui lòng đăng nhập lại.",{position:"bottom-right"});return}const oe=rt.loading("Đang đồng bộ...",{position:"bottom-right",autoClose:!1});try{const fe={prefix:N,folders:[],files:[]};S.forEach(Te=>{Te.mimeType==="application/vnd.google-apps.folder"?fe.folders.push({id:Te.id,name:Te.name}):fe.files.push({id:Te.id,name:Te.name})});const we=await Re.post(`${e}/api/sync-drive-to-s3`,fe,{headers:{Authorization:`Bearer ${U}`}});Hn.current=!0,cn(),rt.update(oe,{render:`Đồng bộ thành công! Đã tải lên ${we.data.uploadedKeys.length} file.`,type:"success",isLoading:!1,autoClose:3e3,position:"bottom-right"})}catch(fe){console.error("❌ Lỗi khi đồng bộ file từ Google Drive:",fe),rt.update(oe,{render:"Không thể đồng bộ file từ Google Drive.",type:"error",isLoading:!1,autoClose:3e3,position:"bottom-right"})}};M.useEffect(()=>{const S=N=>{if(N.data.action==="logout"){const U=document.createElement("iframe");U.style.display="none",U.src="https://accounts.google.com/Logout",document.body.appendChild(U),setTimeout(()=>document.body.removeChild(U),2e3)}};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]),M.useEffect(()=>{const S=new Set(l);x(S)},[]),M.useEffect(()=>{He!=null&&He.status&&(He.status.status==="completed"?(J({title:"Thu thập website hoàn tất",description:`Đã thu thập thành công ${He.url} với ${He.status.completed} trang`}),Hn.current=!0,cn()):He.status.status==="failed"&&J({title:"Thu thập website thất bại",description:`Không thể thu thập ${He.url}. Vui lòng thử lại.`,variant:"destructive"}))},[(Iu=He==null?void 0:He.status)==null?void 0:Iu.status]);const ts=M.useMemo(()=>go[w]||[],[go,w]),Kt=M.useMemo(()=>ts,[ts,w,go]);M.useEffect(()=>{const S=async U=>{var oe;try{return(oe=(await Re.get(`${e}/api/files`,{params:{prefix:U,cache:!1,displayPrefixes:JSON.stringify([]),excludePrivateFiles:"true"},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:3e5})).data)==null?void 0:oe[U]}catch(fe){return console.error("Error: ",fe),[]}};(async()=>{let U=n||"vib-sample/";U.endsWith("/")||(U+="/");const oe=`${n}POC/FAQ/Uploads/`,fe=`${n}POC/HDSD/Uploads/`,we=`${n}POC/Normal_Files/Uploads/`,Te=`${n}POC/FAQ/FAQs/`,Tt=`${n}POC/HDSD/general/`,mn=`${n}POC/Normal_Files/processed/`,[_n,_i,lr,mr,Ko,Gt]=await Promise.all([S(oe),S(fe),S(we),S(Te),S(Tt),S(mn)]);Gg({faqUploadSize:_n,hdsdUploadSize:_i,normalUploadSize:lr,faqParsedSize:mr,hdsdParsedSize:Ko,normalParsedSize:Gt})})()},[JSON.stringify(ts)]);const zo=M.useMemo(()=>{const S=_n=>_n.key&&!(`${_n.key}`.endsWith(".docx")||`${_n.key}`.endsWith(".xlsx")||`${_n.key}`.endsWith(".pdf")),{faqUploadSize:N,hdsdUploadSize:U,normalUploadSize:oe,faqParsedSize:fe,hdsdParsedSize:we,normalParsedSize:Te}=uu,Tt=[],mn=(_n,_i,lr,mr)=>{(_n||[]).forEach(Gt=>{var vr;if(S(Gt)&&!(Gt!=null&&Gt.isFolder))Tt.push({...Gt,type:mr,unSupported:!0});else{let en=(vr=(Gt==null?void 0:Gt.key)||"")==null?void 0:vr.replace(".docx","").replace(".xlsx","").replace(".pdf","").replace(".txt","").replace("/Uploads/",`/${lr}/`);en.endsWith("/")||(en+="/"),(_i||[]).find(Et=>{let Yt=((Et==null?void 0:Et.key)||"").replace(".txt","");return Yt.endsWith("/")||(Yt+="/"),Yt===en})||Tt.push({...Gt,type:mr,timeout:Date.now()-new Date(Gt.lastModified).getTime()>36e5})}})};return mn(N,fe,"FAQs","FAQ"),mn(U,we,"general","Hướng dẫn sử dụng"),mn(oe,Te,"processed","Normal"),Tt},[JSON.stringify(uu)]),ln=M.useMemo(()=>{const S={};return Kt.forEach((N,U)=>{v.has(N.key)&&(S[U]=!0)}),S},[v,Kt]),lm=S=>{const N=Zd(go,S);if(N.length===0)return v.has(S)?"all":"none";const U=N.filter(oe=>v.has(oe)).length;return U===0?"none":U===N.length?"all":"partial"},Vo=(S,N=!0)=>{if(w!==S){if(f&&!w)sr(!0),k(S+f),_(S+f);else if(sr(!0),k(S),_(S),N&&!o){const U=window.location.pathname==="/"?"":window.location.pathname,oe=S?`${window.location.origin}${U}?prefix=${encodeURIComponent(S)}`:`${window.location.origin}${U}`;window.history.pushState({path:oe},"",oe)}}};M.useEffect(()=>{ar&&(Hn.current=!0,cn().finally(()=>sr(!1)))},[ar]);const mo=async(S,N)=>{var U,oe;W(!0);try{if(Kt.some(Tt=>Tt.isFolder&&Tt.name.toLowerCase()===S.toLowerCase())){J({title:"Lỗi",description:`Thư mục "${S}" đã tồn tại trong thư mục hiện tại.`,variant:"destructive"}),W(!1);return}const we=`${N}${S}/`;if((await Re.post(`${e}/api/create-folder`,{prefix:we},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}})).status!==200){J({title:"Lỗi",description:"Không thể tạo thư mục",variant:"destructive"});return}Hn.current=!0,await cn(),J({title:"Đã tạo thư mục",description:`Đã tạo thành công thư mục "${S}"`}),z(""),R(!1)}catch(fe){console.error("Error creating folder:",fe);const we=((oe=(U=fe==null?void 0:fe.response)==null?void 0:U.data)==null?void 0:oe.error)||"Không thể tạo thư mục";J({title:"Lỗi",description:we,variant:"destructive"})}finally{W(!1)}},bi=async(S,N,U)=>{var oe,fe,we,Te,Tt,mn,_n,_i,lr;ae(U),ft(!0);try{if(Array.from(S).reduce((Yt,ra)=>Yt+ra.size,0)>=100*1024*1024){J({title:"Lỗi",description:"Tổng kích thước các tập tin vượt quá 100 MB",variant:"destructive"}),ae(null),ft(!1);return}const Ko=Array.from(S).filter(Yt=>Yt.size===0);if(Ko.length>0){const Yt=Ko.map(ra=>ra.name).join(", ");J({title:"Lỗi tải lên",description:`Không thể tải lên tập tin rỗng: ${Yt}`,variant:"destructive"}),ft(!1),ae(null);return}let Gt=localStorage.getItem("dataLogin"),vr;try{Gt&&(Gt=JSON.parse(Gt),vr=Gt.user)}catch{Gt=null}const en=new FormData;if(vr!=null&&vr.id&&en.append("metadata",JSON.stringify({creator:vr.username,creatorId:vr.id,DataSource:"Tệp tải lên"})),U==="folder"&&S[0]){const Yt=S[0].webkitRelativePath.split("/")[0];Yt&&en.append("folderName",Yt)}en.append("prefix",N),Array.from(S).forEach(Yt=>U==="folder"?en.append("files",Yt,Yt.webkitRelativePath):en.append("files",Yt)),Hn.current=!0;const Et=await Re.post(`${e}/api/check-files-existed`,en,{headers:{"Content-Type":"multipart/form-data",Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});if(((oe=Et==null?void 0:Et.data)==null?void 0:oe.status)===200)await Re.post(`${e}/api/upload`,en,{headers:{"Content-Type":"multipart/form-data",Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:0}),y(""),k(N),setTimeout(async()=>{ae(null),await cn(),ft(!1),await vo("upload")},500);else{if(((we=(fe=Et==null?void 0:Et.data)==null?void 0:fe.names)==null?void 0:we.length)>0&&!((Te=Et==null?void 0:Et.data)!=null&&Te.isFolder)){const Yt=Array.from(S).filter(ra=>Et.data.names.includes(ra.name));vi(Yt),ji(!0)}(Tt=Et==null?void 0:Et.data)!=null&&Tt.isFolder&&((mn=Et==null?void 0:Et.data)!=null&&mn.name)&&(ja((_n=Et==null?void 0:Et.data)==null?void 0:_n.name),vi(S),ji(!0))}}catch(mr){console.error("Lỗi tải lên:",mr);const Ko=((lr=(_i=mr==null?void 0:mr.response)==null?void 0:_i.data)==null?void 0:lr.error)||"Không thể tải lên tập tin";J({title:"Lỗi",description:Ko,variant:"destructive"}),ae(null),ft(!1)}},Oc=async()=>{var S,N;try{ft(!0);const U=new FormData;if(Br){ae(Gi?"folder":"files"),ji(!1);let oe=localStorage.getItem("dataLogin"),fe;try{oe&&(oe=JSON.parse(oe),fe=oe.user)}catch{oe=null}if(fe!=null&&fe.id&&U.append("metadata",JSON.stringify({creator:fe.username,creatorId:fe.id,DataSource:"Tệp tải lên"})),Gi&&Br[0]){const we=Br[0].webkitRelativePath.split("/")[0];we&&U.append("folderName",we)}U.append("prefix",w),Array.from(Br).forEach(we=>Gi&&Br[0]?U.append("files",we,we.webkitRelativePath):U.append("files",we)),fe!=null&&fe.id&&U.append("metadata",JSON.stringify({creator:fe.username,creatorId:fe.id,DataSource:"Tệp tải lên"})),await Re.post(`${e}/api/upload`,U,{headers:{"Content-Type":"multipart/form-data",Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="},timeout:0}),y(""),k(w),Hn.current=!0}}catch(U){console.error("Lỗi tải lên:",U);const oe=((N=(S=U==null?void 0:U.response)==null?void 0:S.data)==null?void 0:N.error)||"Không thể tải lên tập tin";J({title:"Lỗi",description:oe,variant:"destructive"})}finally{setTimeout(async()=>{ae(null),await cn(),ft(!1),ja(""),vi(null),await vo("overwrite")},500)}},Ot=async S=>{var N;try{if(await Re.delete(`${e}/api/files`,{data:{paths:[S.key]},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),v.has(S.key)){const oe=new Set(v);oe.delete(S.key),x(oe)}const U=((N=S.key)==null?void 0:N.replace(/^(.*?)(\/.*)?$/,(oe,fe,we)=>!we||we==="/"?"":fe+"/"))||"";k(U),Hn.current=!0,J({title:"Đã xóa tập tin",description:`Đã xóa thành công "${S.name}"`}),q(null),await vo("delete")}catch(U){console.error("Error deleting file:",U),J({title:"Lỗi",description:"Không thể xóa tập tin",variant:"destructive"})}finally{or(!1),await cn()}},cr=S=>{const N=new Set(v),U=typeof S=="function"?S(ln):S;new Set(Object.keys(ln).map(Number)).forEach(fe=>{const we=Kt[fe];we&&(U[fe]||(N.delete(we.key),we.isFolder&&Zd(go,we.key).forEach(Te=>N.delete(Te))))}),Object.entries(U).forEach(([fe,we])=>{const Te=parseInt(fe),Tt=Kt[Te];Tt&&we&&(N.add(Tt.key),Tt.isFolder&&Zd(go,Tt.key).forEach(mn=>N.add(mn)))}),x(N)},Pc=async()=>{var S;G(!0);try{const N=Array.from(v),U=N.map(fe=>Object.values(go).flat().find(we=>we.key===fe)).filter(fe=>fe!==void 0);if(U.length===0){J({title:"Lỗi",description:"Không có tập tin nào được chọn để xóa",variant:"destructive"});return}await Re.delete(`${e}/api/files`,{data:{paths:N},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});const oe=((S=U[0])==null?void 0:S.key.replace(/^(.*?)(\/.*)?$/,(fe,we,Te)=>!Te||Te==="/"?"":we+"/"))||"";k(oe),Hn.current=!0,cn(),J({title:"Đã xóa tập tin",description:`Đã xóa thành công ${U.length} mục`}),Y(!1),x(new Set),await vo("bulk-delete")}catch(N){console.error("Error deleting files:",N),J({title:"Lỗi",description:"Không thể xóa các tập tin đã chọn",variant:"destructive"})}finally{G(!1)}},dm=async(S,N)=>{if(!w.trim()){J({title:"Lỗi",description:"Không thể đổi tên tập tin hoặc thư mục ở thư mục gốc. Chỉ có thể xóa.",variant:"destructive"});return}De(!0);try{const U=S.key;let oe;S.isFolder?oe=U.split("/").slice(0,-2).join("/")+"/":oe=U.substring(0,U.lastIndexOf("/")+1);const fe=oe+N+(S.isFolder?"/":"");await Re.post(`${e}/api/rename`,{oldPath:U,newPath:fe},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),Hn.current=!0,await cn(),J({title:"Đã đổi tên",description:`Đã đổi tên thành công "${S.name}" thành "${N}"`}),te(null),Ie(""),_e(null),await vo("rename")}catch(U){console.error("Error renaming item:",U),J({title:"Lỗi",description:"Không thể đổi tên",variant:"destructive"})}finally{De(!1)}},ns=async S=>{Je(N=>new Set([...N,...S]));try{const N=await Re.post(`${e}/api/download`,{paths:S},{responseType:"blob",headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),U=window.URL.createObjectURL(N.data),oe=document.createElement("a");oe.href=U;const fe=N.headers["Content-Disposition"]||N.headers["content-disposition"],we=fe==null?void 0:fe.match(/filename="(.+)"/),Te=we?decodeURIComponent(we[1]):"download.zip";oe.setAttribute("download",Te),document.body.appendChild(oe),oe.click(),document.body.removeChild(oe),window.URL.revokeObjectURL(U),J({title:"Bắt đầu tải xuống",description:`Đã bắt đầu tải xuống ${S.length} mục${S.length>1,""}`})}catch(N){console.error("Error downloading files:",N),J({title:"Lỗi",description:"Không thể tải xuống tập tin",variant:"destructive"})}finally{Je(N=>{const U=new Set(N);return S.forEach(oe=>U.delete(oe)),U})}},Tu=w?w.replace(n,"").split("/").filter(Boolean):[],um=()=>{let S=Array.from(v).map(U=>({key:U}));S.length>1&&(S=S.filter(U=>U.key!==n));const N=U=>vd.findIndex(S,oe=>!oe.key.endsWith("/")&&oe.key.startsWith(U))!==-1;return S=S.filter(U=>U.key.endsWith("/")?!N(U.key):!0),S},Eu=M.useMemo(()=>{const S=[{id:"select",header:()=>{const N=i$(go,w),U=N.length>0&&N.every(fe=>v.has(fe)),oe=N.some(fe=>v.has(fe));return u.jsx(Bp,{checked:U?!0:oe?"indeterminate":!1,onCheckedChange:fe=>{if(fe){const we=Kt.reduce((Te,Tt,mn)=>(Te[mn]=!0,Te),{});cr(we)}else{for(const we of Array.from(v))we.startsWith(w)&&(v.delete(we),$o.current[we]=!1);vd.forEach($o.current,(we,Te)=>{Te.startsWith(w)&&($o.current[Te]=!1)}),cr({})}},"aria-label":"Chọn tất cả"})},cell:({row:N})=>{const U=N.original;let fe=U.isFolder?lm(U.key):v.has(U.key)?"all":"none";if(fe==="none"&&U.key.endsWith("/")){for(const we of Array.from(v))if(we.startsWith(U.key)){fe="all";break}}return u.jsx("div",{className:"flex items-center",children:u.jsx(Bp,{checked:fe==="partial"?"indeterminate":fe==="all",onCheckedChange:we=>{var Tt,mn;const Te={...ln};if(we?Te[N.index]=!0:delete Te[N.index],$o.current[((Tt=N.original)==null?void 0:Tt.key)||"_"]=!!we,(mn=N.original)!=null&&mn.key.endsWith("/"))for(const _n of Array.from(v))_n.startsWith(N.original.key)&&($o.current[N.original.key]=!1,v.delete(_n));cr(Te)},"aria-label":"Chọn dòng"})})},enableSorting:!1},{id:"stt",header:()=>"STT",size:20,cell:({row:N})=>u.jsx("div",{className:"flex flex-col group",children:u.jsx("div",{className:"flex items-center",children:N.index+1})})},{id:"fileName",header:({column:N})=>u.jsxs($e,{variant:"ghost",onClick:()=>N.toggleSorting(N.getIsSorted()==="asc"),children:["Tên tập tin",u.jsx(kp,{})]}),accessorKey:"name",cell:({row:N})=>{const U=N.original,oe=U.key.substring(0,U.key.lastIndexOf("/"))||"/",fe=g.trim()!==""&&oe!==w,we=oe.split("/").filter(Boolean);return u.jsxs("div",{className:"flex flex-col group",children:[u.jsxs("div",{className:"flex items-center",children:[u.jsxs("div",{className:`flex items-center gap-2 ${U.isFolder?"cursor-pointer hover:text-blue-600":""}`,onClick:()=>{U.isFolder&&Vo(U.key)},children:[U.isFolder?u.jsx(Os,{className:"h-5 w-5 text-blue-500"}):null,U.name]}),u.jsx("button",{className:"ml-2 opacity-0 group-hover:opacity-100 transition-opacity",onClick:Te=>{Te.stopPropagation(),navigator.clipboard.writeText(U.key),J({title:"Copied to clipboard",description:`Path: ${U.key}`,duration:2e3})},title:"Copy path to clipboard",children:u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),u.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),fe&&u.jsxs("div",{className:"text-sm text-gray-500 flex items-center",children:[u.jsx(Os,{className:"h-4 w-4 text-gray-500 my-auto"}),u.jsxs("span",{className:"flex items-center ml-1",children:[u.jsx("span",{className:"cursor-pointer hover:text-blue-600",onClick:()=>{Vo("")},children:"/"}),we.map((Te,Tt)=>u.jsxs("span",{className:"flex items-center",children:[u.jsx("span",{className:"cursor-pointer hover:text-blue-600",onClick:()=>{Vo(we.slice(0,Tt+1).join("/")+"/")},children:Te}),Tt<we.length-1&&u.jsx("span",{children:"/"})]},Tt))]})]})]})}}];return o||S.push({id:"size",header:({column:N})=>u.jsxs($e,{variant:"ghost",onClick:()=>N.toggleSorting(N.getIsSorted()==="asc"),children:["Kích thước",u.jsx(kp,{})]}),accessorKey:"size",cell:({getValue:N,row:U})=>{const oe=N();return u.jsx("span",{children:U.original.isFolder?"-":es(oe)})}},{id:"lastModified",header:({column:N})=>u.jsxs($e,{variant:"ghost",onClick:()=>N.toggleSorting(N.getIsSorted()==="asc"),className:"px-0 w-full flex-row justify-end",children:["Sửa đổi lần cuối",u.jsx(kp,{})]}),accessorKey:"lastModified",cell:({row:N})=>{const U=N.original.lastModified;return u.jsx("div",{className:"w-full flex-row justify-end items-center text-right",children:u.jsx("span",{children:U&&qC(U).isValid()?qC(U).format("DD/MM/YYYY HH:mm"):"-"})})},size:200},{id:"actions",header:()=>u.jsx("span",{children:"Hành động"}),accessorKey:"key",cell:({row:N})=>u.jsxs("div",{className:"flex items-center gap-2",children:[w===""&&r&&u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>{au(N.original.key),su(!0)},className:"h-8 w-8 p-0",children:Ne.has(N.original.key)?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):u.jsx(gN,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Những Flow sử dụng Folder này làm Data"})]})}),u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>ns([N.original.key]),className:"h-8 w-8 p-0",disabled:Ne.has(N.original.key),children:Ne.has(N.original.key)?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):u.jsx(qw,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Tải xuống"})]})}),w.trim()!==""&&u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>{te(N.original),Ie(N.original.name)},className:"h-8 w-8 p-0",children:u.jsx(xN,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Đổi tên"})]})}),u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>{Pe(!0),he(N.original)},className:"h-8 w-8 p-0",children:u.jsx(KM,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Di chuyển"})]})}),u.jsx(ao,{children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"icon",onClick:()=>q(N.original),className:"h-8 w-8 p-0",children:u.jsx(Yw,{className:"h-4 w-4"})})}),u.jsx(Hr,{children:"Xóa"})]})})]})}),S},[v,Kt,ln,Ne,o]),rs=oC({data:Kt,columns:Eu,state:{rowSelection:ln,sorting:h},onSortingChange:p,enableRowSelection:!0,onRowSelectionChange:cr,getCoreRowModel:rC(),getSortedRowModel:qP()}),os=async S=>{var N,U;sn(!0);try{if(ac(S)){const oe=await Re.get(`${e}/api/read-text`,{params:{path:S.key},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}});st(oe.data.content)}try{const oe=await Re.get(`${e}/api/read-json`,{params:{path:S.key+".metadata.json"},headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),fe=((U=(N=oe==null?void 0:oe.data)==null?void 0:N.content)==null?void 0:U.metadataAttributes)||null;return _e({fullPath:L==null?void 0:L.key,...fe})}catch{return _e("Lỗi phân tích siêu dữ liệu")}}catch(oe){console.error("Error loading file content:",oe),J({title:"Lỗi",description:"Không thể tải nội dung tập tin",variant:"destructive"})}finally{sn(!1)}},Ci=async(S,N)=>{Rt(!0);try{await Re.post(`${e}/api/modify-text`,{path:S.key,content:N},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),J({title:"Đã lưu tập tin",description:"Nội dung tập tin đã được cập nhật thành công"}),Hn.current=!0,await cn(),te(null),st(""),nn("rename"),await vo("edit-content")}catch(U){console.error("Error saving file content:",U),J({title:"Lỗi",description:"Không thể lưu nội dung tập tin",variant:"destructive"})}finally{Rt(!1)}},fm=async S=>{Rt(!0);try{await Re.post(`${e}/api/modify-json`,{path:S.key+".metadata.json",content:{metadataAttributes:xe}},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),J({title:"Đã lưu tập tin",description:"Nội dung tập tin đã được cập nhật thành công"}),Hn.current=!0,await cn(),te(null),st(""),nn("rename")}catch(N){console.error("Error saving file content:",N),J({title:"Lỗi",description:"Không thể lưu nội dung tập tin",variant:"destructive"})}finally{Rt(!1)}};M.useEffect(()=>{L&&(L.isFolder||os(L),nn("rename"))},[L]);const Mc=async(S,N)=>{var U;if(He){J({title:"Đang thu thập website",description:"Vui lòng đợi cho công việc thu thập hiện tại hoàn thành.",variant:"destructive"});return}de(!0);try{const{data:oe}=await Re.post(`${e}/api/crawl`,{url:S,limit:N,prefix:w});if(oe.id){iu({id:oe.id,url:S,limit:N,prefix:w,taskId:((U=oe.task)==null?void 0:U.id)||""});const fe=localStorage.getItem(ZS),we=fe?JSON.parse(fe):[];we.some(Te=>Te.id===oe.id)||(we.unshift({url:S,id:oe.id,limit:N,prefix:w,timestamp:Date.now()}),we.length>20&&(we.length=20),localStorage.setItem(ZS,JSON.stringify(we))),J({title:"Bắt đầu thu thập website",description:`Đã thêm nhiệm vụ thu thập ${S} với giới hạn ${N}. Dữ liệu sẽ có sẵn sau khi thu thập hoàn tất.`}),Bt(!1),K(""),re("1")}}catch(oe){console.error("Error crawling website:",oe),J({title:"Lỗi",description:"Không thể bắt đầu thu thập website",variant:"destructive"})}finally{de(!1)}},Au=async()=>{try{if(!(He!=null&&He.id))return;iu(null),localStorage.removeItem(Ka),J({title:"Đã dừng thu thập",description:`Đã dừng thu thập website ${He.url}`})}catch(S){console.error("Error stopping job:",S),J({title:"Lỗi",description:"Không thể dừng thu thập website",variant:"destructive"})}};M.useEffect(()=>{if(o)return;const S=(N=!0)=>{const oe=new URL(window.location.href).searchParams.get("prefix")||"";oe?Vo(oe,!1):(N&&!l&&x(new Set),k(n),_(n),Hn.current=!0,setTimeout(()=>{cn()},0))};return S(!1),window.addEventListener("popstate",()=>S(!0)),()=>{window.removeEventListener("popstate",()=>S(!0))}},[]);const is=async()=>{du(!0);try{await Re.post(`${e}/api/prediction-report`),J({title:"Xuất báo cáo thành công",description:"Báo cáo dự đoán đã được xuất"})}catch(S){console.error("Error exporting report:",S),J({title:"Lỗi",description:"Không thể xuất báo cáo dự đoán",variant:"destructive"})}finally{du(!1)}},Rc=async()=>{try{const S=GR();S&&(await Re.post(`${e}/api/start-ingestion-job`,{prefix:w,user_id:S.id,userName:S.username},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}})).status===200&&await xi()}catch(S){We(!1),console.log(S)}},vo=async S=>{try{Wa&&w.includes(Wa)&&(console.log(`Auto syncing knowledge base after ${S} operation`),await xi())}catch(N){console.log(`Error auto syncing after ${S}:`,N)}},yo=M.useRef(),xi=async()=>{try{We(!0);const S=await Re.post(`${e}/api/ingestion-job-status`,{prefix:w},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),{status:N}=S==null?void 0:S.data;N==="FAILED"||N==="COMPLETE"||N==="STOPPED"||N==="STOPPING"||!N?(We(!1),yo.current&&(clearInterval(yo.current),yo.current=null),pc(S==null?void 0:S.data)):(yo.current||(yo.current=setInterval(()=>xi(),5e3)),pc(S==null?void 0:S.data))}catch(S){console.log(S)}},Dc=()=>{const S=Array.from(v);let N;return w?N=S.filter(U=>U.startsWith(w)&&U!==w).length:N=new Set(S.filter(U=>U.split("/").shift())).size,`Đang chọn: ${N}`};return M.useEffect(()=>{const S=w==null?void 0:w.split("/")[0];return S!==Wa&&(We(!1),yo.current&&(clearInterval(yo.current),yo.current=null),Kg(S||""),pc(null),S&&xi()),()=>{}},[Wa,w]),M.useEffect(()=>{po&&Sc.length===0&&(rm(),zr(null))},[po]),M.useEffect(()=>{if(l)for(const S of Array.from(l))$o.current[S]=!0},[]),u.jsxs("div",{className:"space-y-4 s3-explr-container",children:[u.jsx(C_,{}),u.jsx(pr,{open:zg,onOpenChange:S=>{ji(S),S||(ja(""),vi(null),ft(!1),ae(null))},children:u.jsxs(Qn,{children:[u.jsxs(Xn,{children:[u.jsx(Zn,{children:"Cảnh báo trùng lặp"}),u.jsxs(Mo,{children:[Gi&&u.jsxs(u.Fragment,{children:["Folder $",Gi," đã có."]}),Br&&Br.length>0&&u.jsxs(u.Fragment,{children:["Những tệp sau bị lặp:",u.jsx("ul",{className:"mt-2 list-disc pl-5 text-sm text-red-600",children:Array.from(Br).map((S,N)=>u.jsx("li",{children:S.name},N))})]})]})]}),u.jsxs(Po,{children:[u.jsx($e,{variant:"outline",onClick:()=>{ji(!1),ja(""),vi(null),ft(!1),ae(null)},children:"Bỏ qua"}),u.jsx($e,{variant:"destructive",onClick:()=>Oc(),children:"Ghi đè"})]})]})}),u.jsx(bd,{className:"s3-explr-breadcrumb",children:u.jsxs(Cd,{className:"s3-explr-breadcrumb-list",children:[u.jsx(Vs,{className:"s3-explr-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>Vo(n),className:"flex items-center gap-1 cursor-pointer s3-explr-breadcrumb-home",children:t})}),!f&&Tu.map((S,N)=>u.jsxs("div",{className:"flex items-center",children:[u.jsx(xd,{className:"s3-explr-breadcrumb-separator"},`sep-${N}`),u.jsx(Vs,{className:"s3-explr-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>Vo(n+Tu.slice(0,N+1).join("/")+"/"),className:"cursor-pointer s3-explr-breadcrumb-link",children:S})},`item-${S}`)]},N))]})}),u.jsxs("div",{className:"flex items-center space-x-4 s3-explr-toolbar",children:[u.jsx("div",{className:"relative max-w-sm w-full s3-explr-search-container",children:u.jsx(q2,{ref:Z,onChange:S=>y(S)})}),u.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{k(w),Hn.current=!0,cn()},disabled:wi,className:"flex items-center gap-2 s3-explr-refresh-btn",children:[u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${wi?"animate-spin":""}`}),"Làm mới"]}),w&&w!=="/"&&u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{wi||Ce||(We(!0),Rc())},"aria-disabled":wi||Ce,className:"flex items-center gap-2 s3-explr-refresh-btn aria-disabled:opacity-50",children:[u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${Ce?"animate-spin":""}`}),"Đồng bộ KB"]})}),kt&&u.jsx(Hr,{side:"right",sideOffset:5,children:u.jsxs("div",{className:"space-y-2 p-3 max-w-md",children:[u.jsx("p",{className:"font-semibold text-lg border-b pb-1",children:"Thông tin đồng bộ"}),u.jsx("div",{className:"space-y-1",children:u.jsxs("p",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"font-medium",children:"Trạng thái:"}),u.jsxs("span",{className:`flex items-center gap-1 font-semibold ${kt.status==="COMPLETE"?"text-green-600":kt.status==="FAILED"?"text-red-600":"text-yellow-600"}`,children:[kt.status==="COMPLETE"&&u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),kt.status==="FAILED"&&u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),kt.status!=="COMPLETE"&&kt.status!=="FAILED"&&u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 animate-spin",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),kt.status]})]})}),kt.statistics&&u.jsxs("div",{className:"space-y-1 border-t pt-2",children:[u.jsx("p",{className:"font-medium text-gray-50",children:"Thống kê xử lý:"}),u.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-sm",children:[u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu quét:"}),u.jsx("span",{className:"font-medium",children:kt.statistics.numberOfDocumentsScanned})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Metadata quét:"}),u.jsx("span",{className:"font-medium",children:kt.statistics.numberOfMetadataDocumentsScanned})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu mới:"}),u.jsx("span",{className:"font-medium text-green-600",children:kt.statistics.numberOfNewDocumentsIndexed})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu sửa:"}),u.jsx("span",{className:"font-medium text-blue-600",children:kt.statistics.numberOfModifiedDocumentsIndexed})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Metadata sửa:"}),u.jsx("span",{className:"font-medium text-blue-600",children:kt.statistics.numberOfMetadataDocumentsModified})]}),u.jsxs("div",{className:"flex justify-between",children:[u.jsx("span",{children:"Tài liệu xóa:"}),u.jsx("span",{className:"font-medium text-orange-600",children:kt.statistics.numberOfDocumentsDeleted})]}),u.jsxs("div",{className:"flex justify-between col-span-2",children:[u.jsx("span",{children:"Tài liệu lỗi:"}),u.jsx("span",{className:"font-medium text-red-600",children:kt.statistics.numberOfDocumentsFailed})]})]})]}),u.jsxs("div",{className:"space-y-1 border-t pt-2 text-sm text-gray-200",children:[u.jsx("p",{className:"font-medium text-gray-50",children:"Chi tiết Job:"}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"DataSource ID:"})," ",kt.dataSourceId]}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"Ingestion Job ID:"})," ",kt.ingestionJobId]}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"Knowledge Base ID:"})," ",kt.knowledgeBaseId]}),u.jsxs("p",{children:[u.jsx("span",{className:"font-medium",children:"Job trong queue:"})," ",kt.is_still_in_stock?"Còn":"Không"]})]}),kt.errorMessage&&u.jsxs("div",{className:"border-t pt-2",children:[u.jsx("p",{className:"text-red-600 font-medium",children:"Lỗi:"}),u.jsx("p",{className:"text-red-600 text-sm bg-red-50 p-2 rounded",children:kt.errorMessage})]}),kt.failureReasons&&kt.failureReasons.length>0&&u.jsx(Y2,{failureReasons:kt.failureReasons})]})})]})}),Array.isArray(zo)&&!!zo.length&&u.jsxs(u.Fragment,{children:[u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-refresh-btn aria-disabled:opacity-50",onClick:()=>hc(!0),children:[u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${zo.filter(S=>S.timeout===!1).length>0?"animate-spin":""}`}),zo.filter(S=>S.timeout===!1).length>0?`Tài liệu đang xử lý: ${zo.length}`:`Tài liệu lỗi hoặc không hỗ trợ: ${zo.length}`]}),u.jsx(ZH,{isOpen:jg,onClose:()=>hc(!1),files:zo})]}),u.jsxs("div",{className:"relative",ref:Ac,children:[u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-file-btn bg-[#1682fe] hover:bg-[#0f6cd4] text-white rounded-md px-4 py-2 transition-colors",onClick:()=>gr(S=>!S),children:[u.jsx(SN,{className:"w-4 h-4"}),"Add file"]}),Ec&&u.jsxs("div",{className:"absolute z-50 mt-2 right-0 w-56 bg-white border rounded-lg shadow-lg py-2 flex flex-col",children:[u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left",onClick:()=>{gr(!1);const S=document.createElement("input");S.type="file",S.multiple=!0,S.onchange=N=>{const U=N.target.files;U&&bi(U,w,"files")},S.click()},children:[u.jsx(Hh,{className:"h-4 w-4 mr-2"})," Tải tệp tin"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left",onClick:()=>{gr(!1);const S=document.createElement("input");S.type="file",S.multiple=!0,S.webkitdirectory=!0,S.onchange=N=>{const U=N.target.files;U&&bi(U,w,"folder")},S.click()},children:[u.jsx(Os,{className:"h-4 w-4 mr-2"})," Tải lên thư mục"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left",disabled:!!c&&!w,onClick:()=>R(!0),children:[u.jsx(vN,{className:"h-4 w-4 mr-2 s3-explr-folder-plus-icon"}),"Thư mục mới"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),Bt(!0)},children:[u.jsx(bN,{className:"h-4 w-4 mr-2"})," Thêm Website"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),Cu()},children:[u.jsxs("svg",{viewBox:"0 0 87.3 78",xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 mr-2",children:[u.jsx("path",{d:"m6.6 66.85 3.85 6.65c.8 1.4 1.95 2.5 3.3 3.3l13.75-23.8h-27.5c0 1.55.4 3.1 1.2 4.5z",fill:"#0066da"}),u.jsx("path",{d:"m43.65 25-13.75-23.8c-1.35.8-2.5 1.9-3.3 3.3l-25.4 44a9.06 9.06 0 0 0 -1.2 4.5h27.5z",fill:"#00ac47"}),u.jsx("path",{d:"m73.55 76.8c1.35-.8 2.5-1.9 3.3-3.3l1.6-2.75 7.65-13.25c.8-1.4 1.2-2.95 1.2-4.5h-27.502l5.852 11.5z",fill:"#ea4335"}),u.jsx("path",{d:"m43.65 25 13.75-23.8c-1.35-.8-2.9-1.2-4.5-1.2h-18.5c-1.6 0-3.15.45-4.5 1.2z",fill:"#00832d"}),u.jsx("path",{d:"m59.8 53h-32.3l-13.75 23.8c1.35.8 2.9 1.2 4.5 1.2h50.8c1.6 0 3.15-.45 4.5-1.2z",fill:"#2684fc"}),u.jsx("path",{d:"m73.4 26.5-12.7-22c-.8-1.4-1.95-2.5-3.3-3.3l-13.75 23.8 16.15 28h27.45c0-1.55-.4-3.1-1.2-4.5z",fill:"#ffba00"})]})," ","Đồng bộ Google Drive"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),rn()},children:[u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",className:"h-4 w-4 mr-2",children:[u.jsx("path",{fill:"#094ab2",d:"M47.3 28.2C45.3 18.6 37.1 12 28 12c-8.5 0-15.9 5.6-18.4 13.5C4.2 27.2 0 32.2 0 38c0 6.6 5.4 12 12 12h36c8.3 0 16-6.6 16-15.5 0-6.8-4.9-12.4-11.7-13.3z"}),u.jsx("path",{fill:"#0067c5",d:"M44.9 30.1c-.2 0-.4-.1-.6-.1H26c-3.3 0-6 2.7-6 6 0 .9.2 1.8.6 2.6-1.7-.7-3.5-1.1-5.5-1.1C7.6 37.5 4 41.5 4 46s3.6 8.5 8.1 8.5h34.3c6.8 0 12.6-5.4 12.6-12s-5.5-11.6-11.1-12.4z"})]})," ","Đồng bộ OneDrive"]}),u.jsxs("button",{className:"flex items-center px-4 py-2 text-sm hover:bg-gray-100 text-left hidden",onClick:()=>{gr(!1),tm()},children:[u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",className:"h-4 w-4 mr-2",children:[u.jsx("path",{fill:"#036C70",d:"M19 14.5v-9c0-.28-.22-.5-.5-.5h-13c-.28 0-.5.22-.5.5v9c0 .28.22.5.5.5h13c.28 0 .5-.22.5-.5z"}),u.jsx("path",{fill:"#17828F",d:"M16 17.5v-9c0-.28-.22-.5-.5-.5h-13c-.28 0-.5.22-.5.5v9c0 .28.22.5.5.5h13c.28 0 .5-.22.5-.5z"}),u.jsx("path",{fill:"#4DB6AC",d:"M13 20.5v-9c0-.28-.22-.5-.5-.5h-13c-.28 0-.5.22-.5.5v9c0 .28.22.5.5.5h13c.28 0 .5-.22.5-.5z"}),u.jsx("path",{fill:"#fff",d:"M4.5 15.5v-3c0-.28.22-.5.5-.5h3c.28 0 .5.22.5.5v3c0 .28-.22.5-.5.5H5c-.28 0-.5-.22-.5-.5z"})]})," ","Đồng bộ SharePoint"]})]})]}),!o&&u.jsxs(u.Fragment,{children:[v.size>0&&u.jsxs(u.Fragment,{children:[u.jsxs($e,{variant:"outline",size:"sm",onClick:()=>ns(Array.from(v)),disabled:Array.from(v).some(S=>Ne.has(S)),className:"flex items-center gap-2 s3-explr-download-selected-btn",children:[Array.from(v).some(S=>Ne.has(S))?u.jsx(Vt,{className:"h-4 w-4 animate-spin mr-2 s3-explr-loader"}):u.jsx(qw,{className:"h-4 w-4 s3-explr-download-icon"}),"Tải xuống đã chọn (",v.size,")"]}),u.jsxs(pr,{open:X,onOpenChange:Y,children:[u.jsx(Gs,{asChild:!0,children:u.jsxs($e,{variant:"destructive",size:"sm",className:"flex items-center gap-2 s3-explr-bulk-delete-btn",children:[u.jsx(Yw,{className:"h-4 w-4 s3-explr-trash-icon"}),"Xóa đã chọn (",v.size,")"]})}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Xác nhận xóa hàng loạt"}),u.jsxs(Mo,{className:"s3-explr-dialog-description",children:["Bạn có chắc chắn muốn xóa ",v.size," mục đã chọn? Hành động này không thể hoàn tác."]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>Y(!1),className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:Pc,disabled:be,className:"s3-explr-confirm-delete-btn",children:be?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang xóa..."]}):"Xóa đã chọn"})]})]})]})]}),!f&&u.jsxs(pr,{open:O,onOpenChange:R,children:[u.jsx(Gs,{asChild:!0}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsx(Xn,{className:"s3-explr-dialog-header",children:u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Tạo thư mục mới"})}),u.jsxs("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:[u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"name",className:"s3-explr-label",children:"Tên thư mục"}),u.jsx(no,{disabled:j,id:"name",value:E,onChange:S=>z(S.target.value),placeholder:"Nhập tên thư mục",className:"s3-explr-input"})]}),u.jsxs($e,{onClick:()=>{E.trim()&&mo(E,w)},disabled:j,className:"s3-explr-create-btn",children:[j&&u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),j?"Đang tạo...":"Tạo"]})]})]})]}),f&&!w?u.jsx(u.Fragment,{}):u.jsxs("div",{className:"flex items-center gap-2 s3-explr-upload-group",children:[He?u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-website-btn",disabled:!0,children:[u.jsx(Vt,{className:"h-4 w-4 animate-spin s3-explr-loader"}),He.status?u.jsxs(u.Fragment,{children:[He.status.isProcessing?"Đang thu thập ":"Đang quét sitemap ","(",He.status.completed,"/",He.status.total,") -"," ",Math.floor(ho/60),":",String(ho%60).padStart(2,"0")]}):"Đang thu thập..."]}),u.jsxs($e,{variant:"destructive",size:"sm",onClick:()=>void Au(),className:"flex items-center gap-2",children:[u.jsx("span",{className:"sr-only",children:"Dừng thu thập"}),u.jsx(EN,{className:"h-4 w-4"})]})]})}),He.status&&u.jsx(Hr,{side:"right",sideOffset:5,children:u.jsxs("div",{className:"space-y-1 p-2",children:[u.jsxs("p",{className:"font-semibold",children:["Đang thu thập ",He==null?void 0:He.url]}),u.jsxs("p",{children:["Tiến độ: ",He==null?void 0:He.status.completed,"/",He==null?void 0:He.status.total," ","trang"]}),u.jsxs("p",{children:["Thời gian: ",Math.floor(ho/60),":",String(ho%60).padStart(2,"0")]}),u.jsxs("p",{children:["Trạng thái:"," ",(He==null?void 0:He.status.status)==="scraping"?"Đang thu thập":(He==null?void 0:He.status.status)==="completed"?"Hoàn thành":"Thất bại"]})]})})]})}):!f&&u.jsxs(pr,{open:Un,onOpenChange:Bt,children:[u.jsx(Gs,{asChild:!0}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Thêm website"}),u.jsx(Mo,{className:"s3-explr-dialog-description",children:"Nhập URL website để thu thập và thêm vào S3."})]}),u.jsxs("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:[u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"websiteUrl",className:"s3-explr-label",children:"URL Website"}),u.jsx(no,{id:"websiteUrl",value:D,onChange:S=>K(S.target.value),placeholder:"https://example.com",type:"url",disabled:pe,className:"s3-explr-input"})]}),u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"crawlLimit",className:"s3-explr-label",children:"Giới hạn thu thập"}),u.jsx(no,{id:"crawlLimit",value:H,onChange:S=>{const N=S.target.value;/^\d*$/.test(N)&&re(N)},placeholder:"1",type:"text",disabled:pe,className:"s3-explr-input"}),u.jsx("p",{className:"text-sm text-gray-500",children:"Số lượng liên kết cần thu thập (mặc định: 1)"})]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>{Bt(!1),K(""),re("1")},disabled:pe,className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{onClick:()=>{D.trim()&&Mc(D.trim(),parseInt(H)||1)},disabled:pe||!D.trim(),className:"s3-explr-crawl-btn",children:pe?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang thu thập..."]}):"Bắt đầu thu thập"})]})]})]}),w.startsWith("BKTTW/")&&u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-website-btn",disabled:!!c&&!w,onClick:is,children:[qi&&u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${qi?"animate-spin":""}`}),"Xuất báo cáo"]})}),(He==null?void 0:He.status)&&u.jsx(Hr,{side:"right",sideOffset:5,children:u.jsxs("div",{className:"space-y-1 p-2",children:[u.jsxs("p",{className:"font-semibold",children:["Đang thu thập ",He.url]}),u.jsxs("p",{children:["Tiến độ: ",He.status.completed,"/",He.status.total," ","trang"]}),u.jsxs("p",{children:["Thời gian: ",Math.floor(ho/60),":",String(ho%60).padStart(2,"0")]}),u.jsxs("p",{children:["Trạng thái:"," ",He.status.status==="scraping"?"Đang thu thập":He.status.status==="completed"?"Hoàn thành":"Thất bại"]})]})})]})}),u.jsxs(pr,{open:Un,onOpenChange:Bt,children:[u.jsx(Gs,{asChild:!0}),u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Thêm website"}),u.jsx(Mo,{className:"s3-explr-dialog-description",children:"Nhập URL website để thu thập và thêm vào S3."})]}),u.jsxs("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:[u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"websiteUrl",className:"s3-explr-label",children:"URL Website"}),u.jsx(no,{id:"websiteUrl",value:D,onChange:S=>K(S.target.value),placeholder:"https://example.com",type:"url",disabled:pe,className:"s3-explr-input"})]}),u.jsxs("div",{className:"space-y-2 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"crawlLimit",className:"s3-explr-label",children:"Giới hạn thu thập"}),u.jsx(no,{id:"crawlLimit",value:H,onChange:S=>{const N=S.target.value;/^\d*$/.test(N)&&re(N)},placeholder:"1",type:"text",disabled:pe,className:"s3-explr-input"}),u.jsx("p",{className:"text-sm text-gray-500",children:"Số lượng liên kết cần thu thập (mặc định: 1)"})]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>{Bt(!1),K(""),re("1")},disabled:pe,className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{onClick:()=>{D.trim()&&Mc(D.trim(),parseInt(H)||1)},disabled:pe||!D.trim(),className:"s3-explr-crawl-btn",children:pe?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang thu thập..."]}):"Bắt đầu thu thập"})]})]})]})]}),w.startsWith("BKTTW/")&&u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{children:[u.jsx(co,{asChild:!0,children:u.jsxs($e,{variant:"outline",size:"sm",className:"flex items-center gap-2 s3-explr-add-website-btn",disabled:!!c&&!w,onClick:is,children:[qi&&u.jsx(Ns,{className:`h-4 w-4 s3-explr-refresh-icon ${qi?"animate-spin":""}`}),"Xuất báo cáo"]})}),qi&&u.jsx(Hr,{sideOffset:5,children:"Đang xuất báo cáo"})]})}),u.jsxs("div",{className:"flex items-center gap-4",children:[Yi&&u.jsxs(Ps,{open:Yi,onOpenChange:qa,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-50"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[700px] max-w-[90vw] max-h-[80vh] z-50 flex flex-col",children:[u.jsxs("div",{className:"relative",children:[u.jsx(Qh,{asChild:!0,children:u.jsx("button",{className:"absolute top-2 right-2 text-gray-600",onClick:Nc,children:"✖"})}),u.jsx("h2",{className:"text-lg font-semibold",children:"My OneDrive"}),u.jsx(bd,{className:"onedrive-breadcrumb",children:u.jsx(Cd,{className:"onedrive-breadcrumb-list",children:Ji.map((S,N)=>u.jsxs("div",{className:"flex items-center",children:[N>0&&u.jsx(xd,{className:"onedrive-breadcrumb-separator"}),u.jsx(Vs,{className:"onedrive-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>kc(N),className:"cursor-pointer onedrive-breadcrumb-link",children:S.name})})]},N))})})]}),u.jsx("div",{className:"space-y-2 mt-4 flex-1 overflow-y-auto",children:Yg?u.jsx("div",{className:"text-sm text-gray-500",children:"Đang tải nội dung thư mục... Vui lòng đợi."}):u.jsx(u.Fragment,{children:[...fu,...vc].length>0?[...fu,...vc].map(S=>u.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg hover:bg-gray-100 ${Ja.some(N=>N.id===S.id)?"bg-blue-100":""}`,children:[u.jsx("input",{type:"checkbox",checked:Ja.some(N=>N.id===S.id),onChange:N=>{N.stopPropagation(),bu(S)},className:"cursor-pointer"}),S.isFolder?u.jsx(Os,{className:"text-blue-500 w-5 h-5 cursor-pointer",onClick:()=>na(S.id,S.name)}):u.jsx(Hh,{className:"text-gray-500 w-5 h-5"}),u.jsxs("div",{className:"flex-1",children:[u.jsx("div",{className:`font-medium ${S.isFolder?"cursor-pointer text-blue-600":""}`,onClick:()=>{S.isFolder?na(S.id,S.name):bu(S)},children:S.name}),!S.isFolder&&u.jsxs("div",{className:"text-xs text-gray-500",children:[es(S.size)," •"," ",cm(S.lastModified.toISOString())]})]})]},S.id)):u.jsx("div",{className:"text-sm text-gray-500",children:"Không có thư mục hoặc tệp nào."})})}),u.jsx("div",{className:"mt-4 flex flex-wrap justify-end gap-2",children:u.jsx($e,{onClick:()=>{zn(Ja,w),Nc()},className:"bg-[#1682fe] hover:bg-[#0f6cd4] text-white rounded-md px-4 py-2 transition-colors",disabled:Ja.length===0,children:"Đồng bộ"})}),u.jsx("button",{onClick:()=>ea(!0),className:"absolute bottom-4 left-4 text-gray-600 hover:text-gray-800",title:"Đăng xuất OneDrive",children:u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),u.jsx("polyline",{points:"16 17 21 12 16 7"}),u.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}),u.jsxs(Ps,{open:Jg,onOpenChange:ea,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-[60]"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[400px] max-w-[90vw] z-[60]",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Xác nhận đăng xuất"}),u.jsx("p",{className:"text-gray-600 mb-6",children:"Bạn có chắc chắn muốn đăng xuất khỏi OneDrive?"}),u.jsxs("div",{className:"flex justify-end gap-2",children:[u.jsx($e,{variant:"outline",onClick:()=>ea(!1),children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>{Ic(),ea(!1)},children:"Đăng xuất"})]})]})]}),po&&u.jsxs(Ps,{open:po,onOpenChange:Xi,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-50"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[700px] max-w-[90vw] max-h-[80vh] z-50 flex flex-col",children:[u.jsxs("div",{className:"relative",children:[u.jsx(Qh,{asChild:!0,children:u.jsx("button",{className:"absolute top-2 right-2 text-gray-600",onClick:wu,children:"✖"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[pt&&u.jsx("button",{onClick:()=>zr(null),className:"text-gray-600 hover:text-gray-800",children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M19 12H5M12 19l-7-7 7-7"})})}),u.jsx("h2",{className:"text-lg font-semibold",children:"My SharePoint"})]}),pt&&u.jsx(bd,{className:"sharepoint-breadcrumb",children:u.jsx(Cd,{className:"sharepoint-breadcrumb-list",children:_c.map((S,N)=>u.jsxs("div",{className:"flex items-center",children:[N>0&&u.jsx(xd,{className:"sharepoint-breadcrumb-separator"}),u.jsx(Vs,{className:"sharepoint-breadcrumb-item",children:u.jsx(Ks,{onClick:()=>im(N),className:"cursor-pointer sharepoint-breadcrumb-link",children:S.name})})]},N))})})]}),u.jsx("div",{className:"space-y-2 mt-4 flex-1 overflow-y-auto",children:pu?u.jsx("div",{className:"text-sm text-gray-500",children:"Đang tải nội dung thư mục... Vui lòng đợi."}):pt?[...xc,...Qa].length===0?u.jsx("div",{className:"text-sm text-gray-500",children:"Không có thư mục hoặc tệp nào."}):[...xc,...Qa].map(S=>{const N=Za.some(U=>U.id===S.id);return u.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg hover:bg-gray-100 ${N?"bg-blue-100":""}`,children:[u.jsx("input",{type:"checkbox",checked:N,onChange:U=>{U.stopPropagation(),om(S)},className:"cursor-pointer"}),S.isFolder?u.jsx(Os,{className:"text-blue-500 w-5 h-5 cursor-pointer",onClick:()=>mt(S.id,S.name,(pt==null?void 0:pt.hostname)||"",(pt==null?void 0:pt.sitePath)||"")}):u.jsx(Hh,{className:"text-gray-500 w-5 h-5"}),u.jsxs("div",{className:"flex-1",children:[u.jsx("div",{className:`font-medium ${S.isFolder?"cursor-pointer text-blue-600":""}`,onClick:()=>{S.isFolder&&mt(S.id,S.name,(pt==null?void 0:pt.hostname)||"",(pt==null?void 0:pt.sitePath)||"")},children:S.name}),!S.isFolder&&u.jsxs("div",{className:"text-xs text-gray-500",children:[es(S.size)," •"," ",S.lastModified.toLocaleString()]})]})]},S.id)}):u.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6",children:Sc.map(S=>u.jsxs("div",{className:"cursor-pointer bg-white shadow-md rounded-xl p-5 flex flex-col justify-center items-start transition-shadow duration-200 hover:shadow-lg border border-gray-100 min-h-[120px]",style:{overflow:"hidden",wordBreak:"break-word",textOverflow:"ellipsis",whiteSpace:"normal"},onClick:()=>Nt(S),children:[u.jsx("div",{className:"font-bold text-lg mb-1 truncate w-full",title:S.name,children:S.name}),u.jsx("div",{className:"text-sm text-gray-500 truncate w-full",title:S.description,children:S.description})]},S.id))})}),u.jsx("div",{className:"mt-4 flex flex-wrap justify-end gap-2",children:pt&&u.jsxs(u.Fragment,{children:[u.jsx($e,{onClick:()=>{am(Za,w),wu()},className:"bg-[#1682fe] hover:bg-[#0f6cd4] text-white rounded-md px-4 py-2 transition-colors",disabled:Za.length===0,children:"Đồng bộ"}),u.jsx($e,{onClick:()=>zr(null),children:"Quay lại"})]})}),u.jsx("button",{onClick:()=>Zi(!0),className:"absolute bottom-4 left-4 text-gray-600 hover:text-gray-800",title:"Đăng xuất SharePoint",children:u.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),u.jsx("polyline",{points:"16 17 21 12 16 7"}),u.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}),u.jsxs(Ps,{open:mu,onOpenChange:Zi,children:[u.jsx(Oa,{className:"fixed inset-0 bg-black bg-opacity-50 z-[60]"}),u.jsxs(Pa,{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-lg w-[400px] max-w-[90vw] z-[60]",children:[u.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Xác nhận đăng xuất"}),u.jsx("p",{className:"text-gray-600 mb-6",children:"Bạn có chắc chắn muốn đăng xuất khỏi SharePoint?"}),u.jsxs("div",{className:"flex justify-end gap-2",children:[u.jsx($e,{variant:"outline",onClick:()=>Zi(!1),children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>{nm(),Zi(!1)},children:"Đăng xuất"})]})]})]})]}),u.jsx(pr,{open:!!Vg,onOpenChange:S=>{S||(su(!1),lu([]),au(""))},children:u.jsxs(Qn,{className:"max-h-[700px] pb-3 px-1 s3-explr-input-group max-w-5xl w-[90%] p-6 bg-white rounded-lg shadow-lg",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:u.jsxs("h3",{className:"font-medium mb-2",children:["Danh sách flows đang sử dụng dữ liệu từ folder(",u.jsx("span",{className:"font-bold",children:Wi}),"):"," "]})}),u.jsx(Mo,{className:"s3-explr-dialog-description",children:fc?u.jsxs("div",{className:"flex items-center justify-center py-4",children:[u.jsx(Vt,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"ml-2",children:"Đang tải thông tin flows..."})]}):u.jsx("div",{children:yi&&Array.isArray(yi)&&yi.length>0?u.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:u.jsxs("table",{className:"w-full border-collapse",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"bg-gray-100",children:[u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"Tên Flow"}),u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"KnowledgeBase Id"}),u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"Loại"}),u.jsx("th",{className:"border border-gray-300 px-4 py-2 text-left",children:"Ngày tạo"})]})}),u.jsx("tbody",{children:yi.map((S,N)=>u.jsxs("tr",{className:N%2===0?"bg-white":"bg-gray-50",children:[u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.name}),u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.KnowledgeBaseId}),u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.type==="MULTIAGENT"?"Agent Flow":"Chat Flow"}),u.jsx("td",{className:"border border-gray-300 px-4 py-2",children:S.createdDate?new Date(S.createdDate).toLocaleString("vi-VN"):"N/A"})]},N))})]})}):u.jsx("div",{className:"text-gray-500 italic py-2",children:"Không có flow nào sử dụng dữ liệu từ folder này"})})})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>q(null),className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>Ot(ne),disabled:Bn,className:"s3-explr-confirm-delete-btn",children:Bn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang xóa..."]}):"Xóa"})]})]})}),u.jsx(pr,{open:!!ne,onOpenChange:S=>!S&&q(null),children:u.jsxs(Qn,{className:"s3-explr-dialog-content",children:[u.jsxs(Xn,{className:"s3-explr-dialog-header",children:[u.jsx(Zn,{className:"s3-explr-dialog-title",children:"Xác nhận xóa"}),u.jsxs(Mo,{className:"s3-explr-dialog-description",children:["Bạn có chắc chắn muốn xóa ",ne==null?void 0:ne.name,"? Hành động này không thể hoàn tác."]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>q(null),className:"s3-explr-cancel-btn",children:"Hủy"}),u.jsx($e,{variant:"destructive",onClick:()=>Ot(ne),disabled:Bn,className:"s3-explr-confirm-delete-btn",children:Bn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang xóa..."]}):"Xóa"})]})]})}),u.jsx(pr,{open:!!L,onOpenChange:S=>{S||(te(null),_e(null),Ie(""),st(""),nn("rename"))},children:u.jsxs(Qn,{className:"s3-explr-dialog-content max-w-5xl w-[90%]",children:[u.jsx(Xn,{className:"s3-explr-dialog-header",children:u.jsx(Zn,{className:"s3-explr-dialog-title",children:L!=null&&L.isFolder?"Đổi tên thư mục":ac(L)?"Quản lý tập tin":"Đổi tên tập tin"})}),L&&u.jsxs(TD,{value:$n,onValueChange:S=>nn(S),children:[u.jsxs(Wx,{"aria-checked":!ac(L),"aria-disabled":L.isFolder,className:"grid w-full grid-cols-3 aria-checked:grid-cols-2 aria-disabled:grid-cols-1",children:[u.jsx(Nd,{value:"rename",children:"Đổi tên"}),!L.isFolder&&u.jsxs(u.Fragment,{children:[ac(L)&&u.jsx(Nd,{value:"edit",children:"Sửa nội dung"}),u.jsx(Nd,{value:"edit-metadata",children:"Sửa metadata file"})]})]}),u.jsx(Od,{value:"rename",children:u.jsx("div",{className:"space-y-4 py-4 s3-explr-dialog-body",children:u.jsxs("div",{className:"h-[70dvh] min-h-[500px] overflow-hidden overflow-y-auto pb-3 px-1 s3-explr-input-group",children:[u.jsx(Ro,{htmlFor:"newName",className:"s3-explr-label",children:"Tên mới"}),u.jsx(no,{id:"newName",value:Se,onChange:S=>Ie(S.target.value),placeholder:"Nhập tên mới",disabled:Le,className:"s3-explr-input"})]})})}),!L.isFolder&&u.jsxs(u.Fragment,{children:[ac(L)&&u.jsx(Od,{value:"edit",children:u.jsx("div",{className:"space-y-4 py-4",children:bt?u.jsx("div",{className:"flex items-center justify-center py-4",children:u.jsx(Vt,{className:"h-6 w-6 animate-spin"})}):u.jsxs("div",{className:"h-[70dvh] min-h-[500px] overflow-hidden overflow-y-auto pb-3 px-1",children:[u.jsx(Ro,{htmlFor:"content",className:"s3-explr-label",children:"Nội dung tập tin"}),u.jsx(Js,{id:"content",value:ye,onChange:S=>st(S.target.value),placeholder:"Nhập nội dung tập tin",className:"min-h-[200px] font-mono",disabled:gn})]})})}),u.jsx(Od,{value:"edit-metadata",children:u.jsx("div",{className:"space-y-4 py-4",children:bt?u.jsx("div",{className:"flex items-center justify-center py-4",children:u.jsx(Vt,{className:"h-6 w-6 animate-spin"})}):u.jsx("div",{className:"h-[70dvh] min-h-[500px] overflow-hidden overflow-y-auto pb-3 px-1",children:xe&&typeof xe=="object"&&Object.entries(xe).map(([S,N],U)=>u.jsxs("div",{className:"pb-3 flex flex-col gap-2",children:[u.jsxs(Ro,{htmlFor:S,className:"s3-explr-label flex items-center gap-1",children:[aR[S]||S,Rp(S)&&u.jsx(GM,{className:"h-[12px] w-[12px] text-red-500"})]}),sR(S)?u.jsx(Js,{id:S,value:typeof N=="string"?N:JSON.stringify(N),onChange:oe=>{const fe={...xe,[S]:oe.target.value};_e(fe)},placeholder:"Nhập nội dung tập tin",className:"min-h-[200px] font-mono",disabled:gn||Rp(S)}):u.jsx(no,{id:S,value:typeof N=="string"?N:JSON.stringify(N),onChange:oe=>{const fe={...xe,[S]:oe.target.value};_e(fe)},placeholder:"Nhập nội dung",className:"s3-explr-input",disabled:gn||Rp(S)})]},U))})})})]})]}),u.jsxs(Po,{className:"s3-explr-dialog-footer",children:[u.jsx($e,{variant:"outline",onClick:()=>{te(null),_e(null),Ie(""),st("")},className:"s3-explr-cancel-btn",children:"Hủy"}),$n==="edit"?u.jsx($e,{onClick:()=>L&&Ci(L,ye),disabled:gn||bt,className:"s3-explr-save-btn",children:gn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang lưu..."]}):"Lưu thay đổi"}):$n==="edit-metadata"?u.jsx($e,{onClick:()=>xe&&typeof xe=="object"&&L&&fm(L),disabled:gn||bt,className:"s3-explr-save-btn",children:gn?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang lưu..."]}):"Lưu thay đổi"}):u.jsx($e,{onClick:()=>{Se.trim()&&L&&dm(L,Se.trim())},disabled:Le||!Se.trim()||Se.trim()===(L==null?void 0:L.name),className:"s3-explr-rename-btn",children:Le?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin s3-explr-loader"}),"Đang đổi tên..."]}):"Đổi tên"})]})]})}),me&&Ae&&u.jsx(e$,{openDialogRename:Ae,setOpenDialogRename:Pe,apiBaseUrl:e,setFileToMove:he,fileToMove:me,refreshFiles:cn,ignoreCache:Hn,autoSyncAfterFileOperation:vo})]})]}),em&&u.jsx("div",{className:"bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative s3-explr-error",children:"Đã xảy ra lỗi khi tải danh sách tập tin"}),u.jsx(XH,{onFilesSelected:(S,N)=>bi(S,w,N),children:u.jsx("div",{className:"rounded-md border s3-explr-table-container",children:u.jsxs(js,{className:"s3-explr-table",children:[u.jsx(Ws,{className:"s3-explr-table-header",children:rs.getHeaderGroups().map(S=>u.jsx(er,{className:"hover:bg-transparent s3-explr-header-row",children:S.headers.map(N=>u.jsx(tr,{className:"s3-explr-header-cell",children:N.isPlaceholder?null:nd(N.column.columnDef.header,N.getContext())},N.id))},S.id))}),u.jsx(qs,{className:"s3-explr-table-body",children:rs.getRowModel().rows.length===0?u.jsx(er,{className:"s3-explr-empty-row",children:u.jsx(pn,{colSpan:Eu.length,className:"h-24 text-center s3-explr-empty-cell",children:g?u.jsxs("div",{className:"text-gray-500 s3-explr-no-results",children:['Không tìm thấy tập tin hoặc thư mục nào khớp với "',g,'"']}):u.jsx("div",{className:"text-gray-500 s3-explr-empty-message",children:wi?"Đang tải nội dung thư mục... Vui lòng đợi":"Thư mục này không chứa tập tin hoặc thư mục con nào"})})}):rs.getRowModel().rows.map(S=>u.jsx(er,{className:"h-12 s3-explr-row",children:S.getVisibleCells().map(N=>u.jsx(pn,{className:"align-middle s3-explr-cell",children:nd(N.column.columnDef.cell,N.getContext())},N.id))},S.id))})]})})}),g&&ta!==0&&u.jsx(u.Fragment,{children:u.jsx(Sd,{children:u.jsxs(Td,{children:[u.jsx(Ed,{onClick:()=>ir(S=>Math.max(S-1,1)),"aria-disabled":$t===1,className:"cursor-pointer aria-disabled:pointer-events-none"}),Array.from({length:Math.ceil(ta/20)},(S,N)=>{const U=N+1,oe=Math.ceil(ta/20);return oe>7&&!(U===1||U===oe||U>=$t-1&&U<=$t+1)?U===$t-2&&$t>4||U===$t+2&&$t<oe-3?u.jsx(Id,{className:"pointer-events-none",children:"..."},N):null:u.jsx(Dr,{className:"cursor-pointer",children:u.jsx(La,{isActive:$t===U,onClick:()=>ir(U),className:`${$t===U?"bg-blue-500 text-white":"bg-white text-black"} hover:bg-blue-100`,children:U})},N)}),u.jsx(Dr,{children:u.jsx(Ad,{onClick:()=>ir(S=>Math.min(S+1,Math.ceil(ta/20))),"aria-disabled":$t===Math.ceil(ta/20),className:"cursor-pointer aria-disabled:pointer-events-none"})})]})})}),o&&a&&u.jsxs("div",{className:"flex justify-between items-center mt-4 s3-explr-selector-footer",children:[u.jsx("div",{className:"text-sm text-gray-500 s3-explr-selection-count",children:Dc()}),u.jsx($e,{variant:"default",onClick:()=>a(um()),disabled:v.size===0,className:"s3-explr-ok-btn",children:"OK"})]})]})}),d$=t=>u.jsx(fP,{clientId:n$,children:u.jsx(l$,{...t})});var sc=t=>t.type==="checkbox",Ki=t=>t instanceof Date,kn=t=>t==null;const eT=t=>typeof t=="object";var qt=t=>!kn(t)&&!Array.isArray(t)&&eT(t)&&!Ki(t),u$=t=>qt(t)&&t.target?sc(t.target)?t.target.checked:t.target.value:t,f$=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,h$=(t,e)=>t.has(f$(e)),p$=t=>{const e=t.constructor&&t.constructor.prototype;return qt(e)&&e.hasOwnProperty("isPrototypeOf")},Fg=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function xn(t){let e;const n=Array.isArray(t),r=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(Fg&&(t instanceof Blob||r))&&(n||qt(t)))if(e=n?[]:{},!n&&!p$(t))e=t;else for(const o in t)t.hasOwnProperty(o)&&(e[o]=xn(t[o]));else return t;return e}var eu=t=>Array.isArray(t)?t.filter(Boolean):[],Zt=t=>t===void 0,Me=(t,e,n)=>{if(!e||!qt(t))return n;const r=eu(e.split(/[,[\].]+?/)).reduce((o,a)=>kn(o)?o:o[a],t);return Zt(r)||r===t?Zt(t[e])?n:t[e]:r},uo=t=>typeof t=="boolean",Lg=t=>/^\w*$/.test(t),tT=t=>eu(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Ft=(t,e,n)=>{let r=-1;const o=Lg(e)?[e]:tT(e),a=o.length,c=a-1;for(;++r<a;){const l=o[r];let f=n;if(r!==c){const h=t[l];f=qt(h)||Array.isArray(h)?h:isNaN(+o[r+1])?{}:[]}if(l==="__proto__"||l==="constructor"||l==="prototype")return;t[l]=f,t=t[l]}};const nT={BLUR:"blur",FOCUS_OUT:"focusout"},$r={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ho={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};M.createContext(null);var g$=(t,e,n,r=!0)=>{const o={defaultValues:e._defaultValues};for(const a in t)Object.defineProperty(o,a,{get:()=>{const c=a;return e._proxyFormState[c]!==$r.all&&(e._proxyFormState[c]=!r||$r.all),t[c]}});return o};const m$=typeof window<"u"?b.useLayoutEffect:b.useEffect;var fo=t=>typeof t=="string",v$=(t,e,n,r,o)=>fo(t)?(r&&e.watch.add(t),Me(n,t,o)):Array.isArray(t)?t.map(a=>(r&&e.watch.add(a),Me(n,a))):(r&&(e.watchAll=!0),n),y$=(t,e,n,r,o)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[r]:o||!0}}:{},cc=t=>Array.isArray(t)?t:[t],rT=()=>{let t=[];return{get observers(){return t},next:o=>{for(const a of t)a.next&&a.next(o)},subscribe:o=>(t.push(o),{unsubscribe:()=>{t=t.filter(a=>a!==o)}}),unsubscribe:()=>{t=[]}}},Hg=t=>kn(t)||!eT(t);function mi(t,e){if(Hg(t)||Hg(e))return t===e;if(Ki(t)&&Ki(e))return t.getTime()===e.getTime();const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(const o of n){const a=t[o];if(!r.includes(o))return!1;if(o!=="ref"){const c=e[o];if(Ki(a)&&Ki(c)||qt(a)&&qt(c)||Array.isArray(a)&&Array.isArray(c)?!mi(a,c):a!==c)return!1}}return!0}var Nn=t=>qt(t)&&!Object.keys(t).length,$g=t=>t.type==="file",Ur=t=>typeof t=="function",tu=t=>{if(!Fg)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},oT=t=>t.type==="select-multiple",Ug=t=>t.type==="radio",w$=t=>Ug(t)||sc(t),Bg=t=>tu(t)&&t.isConnected;function b$(t,e){const n=e.slice(0,-1).length;let r=0;for(;r<n;)t=Zt(t)?r++:t[e[r++]];return t}function C$(t){for(const e in t)if(t.hasOwnProperty(e)&&!Zt(t[e]))return!1;return!0}function tn(t,e){const n=Array.isArray(e)?e:Lg(e)?[e]:tT(e),r=n.length===1?t:b$(t,n),o=n.length-1,a=n[o];return r&&delete r[a],o!==0&&(qt(r)&&Nn(r)||Array.isArray(r)&&C$(r))&&tn(t,n.slice(0,-1)),t}var iT=t=>{for(const e in t)if(Ur(t[e]))return!0;return!1};function nu(t,e={}){const n=Array.isArray(t);if(qt(t)||n)for(const r in t)Array.isArray(t[r])||qt(t[r])&&!iT(t[r])?(e[r]=Array.isArray(t[r])?[]:{},nu(t[r],e[r])):kn(t[r])||(e[r]=!0);return e}function aT(t,e,n){const r=Array.isArray(t);if(qt(t)||r)for(const o in t)Array.isArray(t[o])||qt(t[o])&&!iT(t[o])?Zt(e)||Hg(n[o])?n[o]=Array.isArray(t[o])?nu(t[o],[]):{...nu(t[o])}:aT(t[o],kn(e)?{}:e[o],n[o]):n[o]=!mi(t[o],e[o]);return n}var lc=(t,e)=>aT(t,e,nu(e));const sT={value:!1,isValid:!1},cT={value:!0,isValid:!0};var lT=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!Zt(t[0].attributes.value)?Zt(t[0].value)||t[0].value===""?cT:{value:t[0].value,isValid:!0}:cT:sT}return sT},dT=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:r})=>Zt(t)?t:e?t===""?NaN:t&&+t:n&&fo(t)?new Date(t):r?r(t):t;const uT={isValid:!1,value:null};var fT=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,uT):uT;function hT(t){const e=t.ref;return $g(e)?e.files:Ug(e)?fT(t.refs).value:oT(e)?[...e.selectedOptions].map(({value:n})=>n):sc(e)?lT(t.refs).value:dT(Zt(e.value)?t.ref.value:e.value,t)}var x$=(t,e,n,r)=>{const o={};for(const a of t){const c=Me(e,a);c&&Ft(o,a,c._f)}return{criteriaMode:n,names:[...t],fields:o,shouldUseNativeValidation:r}},ru=t=>t instanceof RegExp,dc=t=>Zt(t)?t:ru(t)?t.source:qt(t)?ru(t.value)?t.value.source:t.value:t,pT=t=>({isOnSubmit:!t||t===$r.onSubmit,isOnBlur:t===$r.onBlur,isOnChange:t===$r.onChange,isOnAll:t===$r.all,isOnTouch:t===$r.onTouched});const gT="AsyncFunction";var _$=t=>!!t&&!!t.validate&&!!(Ur(t.validate)&&t.validate.constructor.name===gT||qt(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===gT)),S$=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),mT=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(r=>t.startsWith(r)&&/^\.\w+/.test(t.slice(r.length))));const uc=(t,e,n,r)=>{for(const o of n||Object.keys(t)){const a=Me(t,o);if(a){const{_f:c,...l}=a;if(c){if(c.refs&&c.refs[0]&&e(c.refs[0],o)&&!r)return!0;if(c.ref&&e(c.ref,c.name)&&!r)return!0;if(uc(l,e))break}else if(qt(l)&&uc(l,e))break}}};function vT(t,e,n){const r=Me(t,n);if(r||Lg(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const a=o.join("."),c=Me(e,a),l=Me(t,a);if(c&&!Array.isArray(c)&&n!==a)return{name:n};if(l&&l.type)return{name:a,error:l};o.pop()}return{name:n}}var T$=(t,e,n,r)=>{n(t);const{name:o,...a}=t;return Nn(a)||Object.keys(a).length>=Object.keys(e).length||Object.keys(a).find(c=>e[c]===(!r||$r.all))},E$=(t,e,n)=>!t||!e||t===e||cc(t).some(r=>r&&(n?r===e:r.startsWith(e)||e.startsWith(r))),A$=(t,e,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(e||t):(n?r.isOnBlur:o.isOnBlur)?!t:(n?r.isOnChange:o.isOnChange)?t:!0,I$=(t,e)=>!eu(Me(t,e)).length&&tn(t,e),k$=(t,e,n)=>{const r=cc(Me(t,n));return Ft(r,"root",e[n]),Ft(t,n,r),t},ou=t=>fo(t);function yT(t,e,n="validate"){if(ou(t)||Array.isArray(t)&&t.every(ou)||uo(t)&&!t)return{type:n,message:ou(t)?t:"",ref:e}}var Ga=t=>qt(t)&&!ru(t)?t:{value:t,message:""},wT=async(t,e,n,r,o,a)=>{const{ref:c,refs:l,required:f,maxLength:h,minLength:p,min:g,max:y,pattern:v,validate:x,name:w,valueAsNumber:_,mount:I}=t._f,k=Me(n,w);if(!I||e.has(w))return{};const O=l?l[0]:c,R=he=>{o&&O.reportValidity&&(O.setCustomValidity(uo(he)?"":he||""),O.reportValidity())},E={},z=Ug(c),j=sc(c),W=z||j,ne=(_||$g(c))&&Zt(c.value)&&Zt(k)||tu(c)&&c.value===""||k===""||Array.isArray(k)&&!k.length,q=y$.bind(null,w,r,E),me=(he,be,G,X=Ho.maxLength,Y=Ho.minLength)=>{const ae=he?be:G;E[w]={type:he?X:Y,message:ae,ref:c,...q(he?X:Y,ae)}};if(a?!Array.isArray(k)||!k.length:f&&(!W&&(ne||kn(k))||uo(k)&&!k||j&&!lT(l).isValid||z&&!fT(l).isValid)){const{value:he,message:be}=ou(f)?{value:!!f,message:f}:Ga(f);if(he&&(E[w]={type:Ho.required,message:be,ref:O,...q(Ho.required,be)},!r))return R(be),E}if(!ne&&(!kn(g)||!kn(y))){let he,be;const G=Ga(y),X=Ga(g);if(!kn(k)&&!isNaN(k)){const Y=c.valueAsNumber||k&&+k;kn(G.value)||(he=Y>G.value),kn(X.value)||(be=Y<X.value)}else{const Y=c.valueAsDate||new Date(k),ae=L=>new Date(new Date().toDateString()+" "+L),Z=c.type=="time",J=c.type=="week";fo(G.value)&&k&&(he=Z?ae(k)>ae(G.value):J?k>G.value:Y>new Date(G.value)),fo(X.value)&&k&&(be=Z?ae(k)<ae(X.value):J?k<X.value:Y<new Date(X.value))}if((he||be)&&(me(!!he,G.message,X.message,Ho.max,Ho.min),!r))return R(E[w].message),E}if((h||p)&&!ne&&(fo(k)||a&&Array.isArray(k))){const he=Ga(h),be=Ga(p),G=!kn(he.value)&&k.length>+he.value,X=!kn(be.value)&&k.length<+be.value;if((G||X)&&(me(G,he.message,be.message),!r))return R(E[w].message),E}if(v&&!ne&&fo(k)){const{value:he,message:be}=Ga(v);if(ru(he)&&!k.match(he)&&(E[w]={type:Ho.pattern,message:be,ref:c,...q(Ho.pattern,be)},!r))return R(be),E}if(x){if(Ur(x)){const he=await x(k,n),be=yT(he,O);if(be&&(E[w]={...be,...q(Ho.validate,be.message)},!r))return R(be.message),E}else if(qt(x)){let he={};for(const be in x){if(!Nn(he)&&!r)break;const G=yT(await x[be](k,n),O,be);G&&(he={...G,...q(be,G.message)},R(G.message),r&&(E[w]=he))}if(!Nn(he)&&(E[w]={ref:O,...he},!r))return E}}return R(!0),E};const N$={mode:$r.onSubmit,reValidateMode:$r.onChange,shouldFocusError:!0};function O$(t={}){let e={...N$,...t},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:Ur(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1};const r={};let o=qt(e.defaultValues)||qt(e.values)?xn(e.defaultValues||e.values)||{}:{},a=e.shouldUnregister?{}:xn(o),c={action:!1,mount:!1,watch:!1},l={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},f,h=0;const p={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let g={...p};const y={array:rT(),state:rT()},v=pT(e.mode),x=pT(e.reValidateMode),w=e.criteriaMode===$r.all,_=D=>K=>{clearTimeout(h),h=setTimeout(D,K)},I=async D=>{if(!e.disabled&&(p.isValid||g.isValid||D)){const K=e.resolver?Nn((await ne()).errors):await me(r,!0);K!==n.isValid&&y.state.next({isValid:K})}},k=(D,K)=>{!e.disabled&&(p.isValidating||p.validatingFields||g.isValidating||g.validatingFields)&&((D||Array.from(l.mount)).forEach(H=>{H&&(K?Ft(n.validatingFields,H,K):tn(n.validatingFields,H))}),y.state.next({validatingFields:n.validatingFields,isValidating:!Nn(n.validatingFields)}))},O=(D,K=[],H,re,pe=!0,de=!0)=>{if(re&&H&&!e.disabled){if(c.action=!0,de&&Array.isArray(Me(r,D))){const Ce=H(Me(r,D),re.argA,re.argB);pe&&Ft(r,D,Ce)}if(de&&Array.isArray(Me(n.errors,D))){const Ce=H(Me(n.errors,D),re.argA,re.argB);pe&&Ft(n.errors,D,Ce),I$(n.errors,D)}if((p.touchedFields||g.touchedFields)&&de&&Array.isArray(Me(n.touchedFields,D))){const Ce=H(Me(n.touchedFields,D),re.argA,re.argB);pe&&Ft(n.touchedFields,D,Ce)}(p.dirtyFields||g.dirtyFields)&&(n.dirtyFields=lc(o,a)),y.state.next({name:D,isDirty:be(D,K),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ft(a,D,K)},R=(D,K)=>{Ft(n.errors,D,K),y.state.next({errors:n.errors})},E=D=>{n.errors=D,y.state.next({errors:n.errors,isValid:!1})},z=(D,K,H,re)=>{const pe=Me(r,D);if(pe){const de=Me(a,D,Zt(H)?Me(o,D):H);Zt(de)||re&&re.defaultChecked||K?Ft(a,D,K?de:hT(pe._f)):Y(D,de),c.mount&&I()}},j=(D,K,H,re,pe)=>{let de=!1,Ce=!1;const We={name:D};if(!e.disabled){if(!H||re){(p.isDirty||g.isDirty)&&(Ce=n.isDirty,n.isDirty=We.isDirty=be(),de=Ce!==We.isDirty);const ht=mi(Me(o,D),K);Ce=!!Me(n.dirtyFields,D),ht?tn(n.dirtyFields,D):Ft(n.dirtyFields,D,!0),We.dirtyFields=n.dirtyFields,de=de||(p.dirtyFields||g.dirtyFields)&&Ce!==!ht}if(H){const ht=Me(n.touchedFields,D);ht||(Ft(n.touchedFields,D,H),We.touchedFields=n.touchedFields,de=de||(p.touchedFields||g.touchedFields)&&ht!==H)}de&&pe&&y.state.next(We)}return de?We:{}},W=(D,K,H,re)=>{const pe=Me(n.errors,D),de=(p.isValid||g.isValid)&&uo(K)&&n.isValid!==K;if(e.delayError&&H?(f=_(()=>R(D,H)),f(e.delayError)):(clearTimeout(h),f=null,H?Ft(n.errors,D,H):tn(n.errors,D)),(H?!mi(pe,H):pe)||!Nn(re)||de){const Ce={...re,...de&&uo(K)?{isValid:K}:{},errors:n.errors,name:D};n={...n,...Ce},y.state.next(Ce)}},ne=async D=>{k(D,!0);const K=await e.resolver(a,e.context,x$(D||l.mount,r,e.criteriaMode,e.shouldUseNativeValidation));return k(D),K},q=async D=>{const{errors:K}=await ne(D);if(D)for(const H of D){const re=Me(K,H);re?Ft(n.errors,H,re):tn(n.errors,H)}else n.errors=K;return K},me=async(D,K,H={valid:!0})=>{for(const re in D){const pe=D[re];if(pe){const{_f:de,...Ce}=pe;if(de){const We=l.array.has(de.name),ht=pe._f&&_$(pe._f);ht&&p.validatingFields&&k([re],!0);const ft=await wT(pe,l.disabled,a,w,e.shouldUseNativeValidation&&!K,We);if(ht&&p.validatingFields&&k([re]),ft[de.name]&&(H.valid=!1,K))break;!K&&(Me(ft,de.name)?We?k$(n.errors,ft,de.name):Ft(n.errors,de.name,ft[de.name]):tn(n.errors,de.name))}!Nn(Ce)&&await me(Ce,K,H)}}return H.valid},he=()=>{for(const D of l.unMount){const K=Me(r,D);K&&(K._f.refs?K._f.refs.every(H=>!Bg(H)):!Bg(K._f.ref))&&De(D)}l.unMount=new Set},be=(D,K)=>!e.disabled&&(D&&K&&Ft(a,D,K),!mi(xe(),o)),G=(D,K,H)=>v$(D,l,{...c.mount?a:Zt(K)?o:fo(D)?{[D]:K}:K},H,K),X=D=>eu(Me(c.mount?a:o,D,e.shouldUnregister?Me(o,D,[]):[])),Y=(D,K,H={})=>{const re=Me(r,D);let pe=K;if(re){const de=re._f;de&&(!de.disabled&&Ft(a,D,dT(K,de)),pe=tu(de.ref)&&kn(K)?"":K,oT(de.ref)?[...de.ref.options].forEach(Ce=>Ce.selected=pe.includes(Ce.value)):de.refs?sc(de.ref)?de.refs.length>1?de.refs.forEach(Ce=>(!Ce.defaultChecked||!Ce.disabled)&&(Ce.checked=Array.isArray(pe)?!!pe.find(We=>We===Ce.value):pe===Ce.value)):de.refs[0]&&(de.refs[0].checked=!!pe):de.refs.forEach(Ce=>Ce.checked=Ce.value===pe):$g(de.ref)?de.ref.value="":(de.ref.value=pe,de.ref.type||y.state.next({name:D,values:xn(a)})))}(H.shouldDirty||H.shouldTouch)&&j(D,pe,H.shouldTouch,H.shouldDirty,!0),H.shouldValidate&&te(D)},ae=(D,K,H)=>{for(const re in K){const pe=K[re],de=`${D}.${re}`,Ce=Me(r,de);(l.array.has(D)||qt(pe)||Ce&&!Ce._f)&&!Ki(pe)?ae(de,pe,H):Y(de,pe,H)}},Z=(D,K,H={})=>{const re=Me(r,D),pe=l.array.has(D),de=xn(K);Ft(a,D,de),pe?(y.array.next({name:D,values:xn(a)}),(p.isDirty||p.dirtyFields||g.isDirty||g.dirtyFields)&&H.shouldDirty&&y.state.next({name:D,dirtyFields:lc(o,a),isDirty:be(D,de)})):re&&!re._f&&!kn(de)?ae(D,de,H):Y(D,de,H),mT(D,l)&&y.state.next({...n}),y.state.next({name:c.mount?D:void 0,values:xn(a)})},J=async D=>{c.mount=!0;const K=D.target;let H=K.name,re=!0;const pe=Me(r,H),de=Ce=>{re=Number.isNaN(Ce)||Ki(Ce)&&isNaN(Ce.getTime())||mi(Ce,Me(a,H,Ce))};if(pe){let Ce,We;const ht=K.type?hT(pe._f):u$(D),ft=D.type===nT.BLUR||D.type===nT.FOCUS_OUT,Bn=!S$(pe._f)&&!e.resolver&&!Me(n.errors,H)&&!pe._f.deps||A$(ft,Me(n.touchedFields,H),n.isSubmitted,x,v),or=mT(H,l,ft);Ft(a,H,ht),ft?(pe._f.onBlur&&pe._f.onBlur(D),f&&f(0)):pe._f.onChange&&pe._f.onChange(D);const $t=j(H,ht,ft),ir=!Nn($t)||or;if(!ft&&y.state.next({name:H,type:D.type,values:xn(a)}),Bn)return(p.isValid||g.isValid)&&(e.mode==="onBlur"?ft&&I():ft||I()),ir&&y.state.next({name:H,...or?{}:$t});if(!ft&&or&&y.state.next({...n}),e.resolver){const{errors:ar}=await ne([H]);if(de(ht),re){const sr=vT(n.errors,r,H),He=vT(ar,r,sr.name||H);Ce=He.error,H=He.name,We=Nn(ar)}}else k([H],!0),Ce=(await wT(pe,l.disabled,a,w,e.shouldUseNativeValidation))[H],k([H]),de(ht),re&&(Ce?We=!1:(p.isValid||g.isValid)&&(We=await me(r,!0)));re&&(pe._f.deps&&te(pe._f.deps),W(H,We,Ce,$t))}},L=(D,K)=>{if(Me(n.errors,K)&&D.focus)return D.focus(),1},te=async(D,K={})=>{let H,re;const pe=cc(D);if(e.resolver){const de=await q(Zt(D)?D:pe);H=Nn(de),re=D?!pe.some(Ce=>Me(de,Ce)):H}else D?(re=(await Promise.all(pe.map(async de=>{const Ce=Me(r,de);return await me(Ce&&Ce._f?{[de]:Ce}:Ce)}))).every(Boolean),!(!re&&!n.isValid)&&I()):re=H=await me(r);return y.state.next({...!fo(D)||(p.isValid||g.isValid)&&H!==n.isValid?{}:{name:D},...e.resolver||!D?{isValid:H}:{},errors:n.errors}),K.shouldFocus&&!re&&uc(r,L,D?pe:l.mount),re},xe=D=>{const K={...c.mount?a:o};return Zt(D)?K:fo(D)?Me(K,D):D.map(H=>Me(K,H))},_e=(D,K)=>({invalid:!!Me((K||n).errors,D),isDirty:!!Me((K||n).dirtyFields,D),error:Me((K||n).errors,D),isValidating:!!Me(n.validatingFields,D),isTouched:!!Me((K||n).touchedFields,D)}),Se=D=>{D&&cc(D).forEach(K=>tn(n.errors,K)),y.state.next({errors:D?n.errors:{}})},Ie=(D,K,H)=>{const re=(Me(r,D,{_f:{}})._f||{}).ref,pe=Me(n.errors,D)||{},{ref:de,message:Ce,type:We,...ht}=pe;Ft(n.errors,D,{...ht,...K,ref:re}),y.state.next({name:D,errors:n.errors,isValid:!1}),H&&H.shouldFocus&&re&&re.focus&&re.focus()},Ae=(D,K)=>Ur(D)?y.state.subscribe({next:H=>D(G(void 0,K),H)}):G(D,K,!0),Pe=D=>y.state.subscribe({next:K=>{E$(D.name,K.name,D.exact)&&T$(K,D.formState||p,nn,D.reRenderRoot)&&D.callback({values:{...a},...n,...K})}}).unsubscribe,Le=D=>(c.mount=!0,g={...g,...D.formState},Pe({...D,formState:g})),De=(D,K={})=>{for(const H of D?cc(D):l.mount)l.mount.delete(H),l.array.delete(H),K.keepValue||(tn(r,H),tn(a,H)),!K.keepError&&tn(n.errors,H),!K.keepDirty&&tn(n.dirtyFields,H),!K.keepTouched&&tn(n.touchedFields,H),!K.keepIsValidating&&tn(n.validatingFields,H),!e.shouldUnregister&&!K.keepDefaultValue&&tn(o,H);y.state.next({values:xn(a)}),y.state.next({...n,...K.keepDirty?{isDirty:be()}:{}}),!K.keepIsValid&&I()},Ne=({disabled:D,name:K})=>{(uo(D)&&c.mount||D||l.disabled.has(K))&&(D?l.disabled.add(K):l.disabled.delete(K))},Je=(D,K={})=>{let H=Me(r,D);const re=uo(K.disabled)||uo(e.disabled);return Ft(r,D,{...H||{},_f:{...H&&H._f?H._f:{ref:{name:D}},name:D,mount:!0,...K}}),l.mount.add(D),H?Ne({disabled:uo(K.disabled)?K.disabled:e.disabled,name:D}):z(D,!0,K.value),{...re?{disabled:K.disabled||e.disabled}:{},...e.progressive?{required:!!K.required,min:dc(K.min),max:dc(K.max),minLength:dc(K.minLength),maxLength:dc(K.maxLength),pattern:dc(K.pattern)}:{},name:D,onChange:J,onBlur:J,ref:pe=>{if(pe){Je(D,K),H=Me(r,D);const de=Zt(pe.value)&&pe.querySelectorAll&&pe.querySelectorAll("input,select,textarea")[0]||pe,Ce=w$(de),We=H._f.refs||[];if(Ce?We.find(ht=>ht===de):de===H._f.ref)return;Ft(r,D,{_f:{...H._f,...Ce?{refs:[...We.filter(Bg),de,...Array.isArray(Me(o,D))?[{}]:[]],ref:{type:de.type,name:D}}:{ref:de}}}),z(D,!1,void 0,de)}else H=Me(r,D,{}),H._f&&(H._f.mount=!1),(e.shouldUnregister||K.shouldUnregister)&&!(h$(l.array,D)&&c.action)&&l.unMount.add(D)}}},ye=()=>e.shouldFocusError&&uc(r,L,l.mount),st=D=>{uo(D)&&(y.state.next({disabled:D}),uc(r,(K,H)=>{const re=Me(r,H);re&&(K.disabled=re._f.disabled||D,Array.isArray(re._f.refs)&&re._f.refs.forEach(pe=>{pe.disabled=re._f.disabled||D}))},0,!1))},bt=(D,K)=>async H=>{let re;H&&(H.preventDefault&&H.preventDefault(),H.persist&&H.persist());let pe=xn(a);if(y.state.next({isSubmitting:!0}),e.resolver){const{errors:de,values:Ce}=await ne();n.errors=de,pe=Ce}else await me(r);if(l.disabled.size)for(const de of l.disabled)Ft(pe,de,void 0);if(tn(n.errors,"root"),Nn(n.errors)){y.state.next({errors:{}});try{await D(pe,H)}catch(de){re=de}}else K&&await K({...n.errors},H),ye(),setTimeout(ye);if(y.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Nn(n.errors)&&!re,submitCount:n.submitCount+1,errors:n.errors}),re)throw re},sn=(D,K={})=>{Me(r,D)&&(Zt(K.defaultValue)?Z(D,xn(Me(o,D))):(Z(D,K.defaultValue),Ft(o,D,xn(K.defaultValue))),K.keepTouched||tn(n.touchedFields,D),K.keepDirty||(tn(n.dirtyFields,D),n.isDirty=K.defaultValue?be(D,xn(Me(o,D))):be()),K.keepError||(tn(n.errors,D),p.isValid&&I()),y.state.next({...n}))},gn=(D,K={})=>{const H=D?xn(D):o,re=xn(H),pe=Nn(D),de=pe?o:re;if(K.keepDefaultValues||(o=H),!K.keepValues){if(K.keepDirtyValues){const Ce=new Set([...l.mount,...Object.keys(lc(o,a))]);for(const We of Array.from(Ce))Me(n.dirtyFields,We)?Ft(de,We,Me(a,We)):Z(We,Me(de,We))}else{if(Fg&&Zt(D))for(const Ce of l.mount){const We=Me(r,Ce);if(We&&We._f){const ht=Array.isArray(We._f.refs)?We._f.refs[0]:We._f.ref;if(tu(ht)){const ft=ht.closest("form");if(ft){ft.reset();break}}}}for(const Ce of l.mount)Z(Ce,Me(de,Ce))}a=xn(de),y.array.next({values:{...de}}),y.state.next({values:{...de}})}l={mount:K.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!p.isValid||!!K.keepIsValid||!!K.keepDirtyValues,c.watch=!!e.shouldUnregister,y.state.next({submitCount:K.keepSubmitCount?n.submitCount:0,isDirty:pe?!1:K.keepDirty?n.isDirty:!!(K.keepDefaultValues&&!mi(D,o)),isSubmitted:K.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:pe?{}:K.keepDirtyValues?K.keepDefaultValues&&a?lc(o,a):n.dirtyFields:K.keepDefaultValues&&D?lc(o,D):K.keepDirty?n.dirtyFields:{},touchedFields:K.keepTouched?n.touchedFields:{},errors:K.keepErrors?n.errors:{},isSubmitSuccessful:K.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Rt=(D,K)=>gn(Ur(D)?D(a):D,K),$n=(D,K={})=>{const H=Me(r,D),re=H&&H._f;if(re){const pe=re.refs?re.refs[0]:re.ref;pe.focus&&(pe.focus(),K.shouldSelect&&Ur(pe.select)&&pe.select())}},nn=D=>{n={...n,...D}},Bt={control:{register:Je,unregister:De,getFieldState:_e,handleSubmit:bt,setError:Ie,_subscribe:Pe,_runSchema:ne,_getWatch:G,_getDirty:be,_setValid:I,_setFieldArray:O,_setDisabledField:Ne,_setErrors:E,_getFieldArray:X,_reset:gn,_resetDefaultValues:()=>Ur(e.defaultValues)&&e.defaultValues().then(D=>{Rt(D,e.resetOptions),y.state.next({isLoading:!1})}),_removeUnmounted:he,_disableForm:st,_subjects:y,_proxyFormState:p,get _fields(){return r},get _formValues(){return a},get _state(){return c},set _state(D){c=D},get _defaultValues(){return o},get _names(){return l},set _names(D){l=D},get _formState(){return n},get _options(){return e},set _options(D){e={...e,...D}}},subscribe:Le,trigger:te,register:Je,handleSubmit:bt,watch:Ae,setValue:Z,getValues:xe,reset:Rt,resetField:sn,clearErrors:Se,unregister:De,setError:Ie,setFocus:$n,getFieldState:_e};return{...Bt,formControl:Bt}}function P$(t={}){const e=M.useRef(void 0),n=M.useRef(void 0),[r,o]=M.useState({isDirty:!1,isValidating:!1,isLoading:Ur(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:Ur(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...t.formControl?t.formControl:O$(t),formState:r},t.formControl&&t.defaultValues&&!Ur(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions));const a=e.current.control;return a._options=t,m$(()=>{const c=a._subscribe({formState:a._proxyFormState,callback:()=>o({...a._formState}),reRenderRoot:!0});return o(l=>({...l,isReady:!0})),a._formState.isReady=!0,c},[a]),M.useEffect(()=>a._disableForm(t.disabled),[a,t.disabled]),M.useEffect(()=>{t.mode&&(a._options.mode=t.mode),t.reValidateMode&&(a._options.reValidateMode=t.reValidateMode),t.errors&&!Nn(t.errors)&&a._setErrors(t.errors)},[a,t.errors,t.mode,t.reValidateMode]),M.useEffect(()=>{t.shouldUnregister&&a._subjects.state.next({values:a._getWatch()})},[a,t.shouldUnregister]),M.useEffect(()=>{if(a._proxyFormState.isDirty){const c=a._getDirty();c!==r.isDirty&&a._subjects.state.next({isDirty:c})}},[a,r.isDirty]),M.useEffect(()=>{t.values&&!mi(t.values,n.current)?(a._reset(t.values,a._options.resetOptions),n.current=t.values,o(c=>({...c}))):a._resetDefaultValues()},[a,t.values]),M.useEffect(()=>{a._state.mount||(a._setValid(),a._state.mount=!0),a._state.watch&&(a._state.watch=!1,a._subjects.state.next({...a._formState})),a._removeUnmounted()}),e.current.formState=g$(r,a),e.current}const bT=({className:t,children:e,content:n,side:r})=>{const[o,a]=M.useState(!1);return u.jsx(ao,{delayDuration:0,children:u.jsxs(so,{open:o,children:[u.jsx(co,{asChild:!0,children:u.jsx("button",{type:"button",className:qe("cursor-pointer",t),onClick:()=>a(!o),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onTouchStart:()=>a(!o),onKeyDown:c=>{c.preventDefault(),c.key==="Enter"&&a(!o)},children:e})}),u.jsx(Hr,{side:r,className:n?"":"hidden",children:u.jsx("span",{className:"inline-block",children:n})})]})})},M$=(t,e)=>{const[n,r]=M.useState(t);return M.useEffect(()=>{const o=setTimeout(()=>{r(t)},e);return()=>{clearTimeout(o)}},[t,e]),n},R$=({apiBaseUrl:t="http://localhost:3000"})=>{var z,j;const[e,n]=M.useState([]),[r,o]=M.useState(!1),[a,c]=M.useState([]),[l,f]=M.useState(1),[h,p]=M.useState(1),[g,y]=M.useState(null),[v,x]=M.useState(""),w=M$(v,500),_=W=>{const ne=W.match(/\d{6}/);if(!ne)return{month:"",year:""};const q=ne[0],me=q.substring(0,2),he=q.substring(2);return{month:me,year:he}},I=W=>W.map(q=>{let me=(q==null?void 0:q.month)||"",he=(q==null?void 0:q.year)||"";if((!me||!he)&&(q!=null&&q.file_name)){const be=_(q.file_name);me=me||be.month,he=he||be.year}return{id:q==null?void 0:q.id,prefix:(q==null?void 0:q.prefix)||"",model:(q==null?void 0:q.model)||"",fileName:(q==null?void 0:q.file_name)||"",code:(q==null?void 0:q.stock_id)||"",month:me,year:he,content:(q==null?void 0:q.text_summary)||"",status:(q==null?void 0:q.status)||"",note:(q==null?void 0:q.note)||"",lastUpdate:q==null?void 0:q.updated_at,stock_id:q==null?void 0:q.stock_id}}),k=W=>{if(!(W!=null&&W.data))return[];const ne=I(W==null?void 0:W.data);n(ne),p(W.pagination.totalPages)},O=async(W=1,ne=15)=>{y(W),o(!0);try{const q=await Re.get(`${t}/api/latest-summaries`,{params:{page:W,limit:ne,search:v}});(q==null?void 0:q.status)===200?k(q.data):console.error(q)}catch(q){console.error("Error fetching data:",q)}finally{y(null),o(!1)}};M.useEffect(()=>{w&&f(1),O(l)},[l,w]);const R=M.useMemo(()=>[{id:"code",header:"Mã",accessorKey:"code",cell:({row:ne})=>u.jsx("span",{className:"flex flex-col",children:ne.original.code})},{id:"month",header:"Tháng",accessorKey:"month",cell:({row:ne})=>{const q=ne.original.month,me=ne.original.year;return u.jsx("span",{className:"flex flex-col",children:`${q.toString().padStart(2,"0")}/${me}`})}},{id:"content",header:"Nội dung",accessorKey:"content",cell:({row:ne})=>{const q=ne.getValue("content");return u.jsx("div",{className:"text-start truncate text-ellipsis overflow-hidden whitespace-nowrap max-w-[30dvw]",children:q})}},{id:"status",header:"Trạng thái",accessorKey:"status",cell:({row:ne})=>{const me=ne.original.status!=="unpublish";return u.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0 text-[10px] font-bold ${me?"bg-green-50 text-green-700 ring-1 ring-inset ring-green-600/20":"bg-gray-50 text-gray-600 ring-1 ring-inset ring-gray-500/20"}`,children:me?"PUBLISHED":"UNPUBLISHED"})}},{id:"note",header:"Ghi chú",accessorKey:"note",cell:({row:ne})=>u.jsx(bT,{content:u.jsx("div",{className:"font-medium text-[16px] max-w-[90dvw]",children:ne.original.note}),children:u.jsx("div",{className:"text-start truncate text-ellipsis overflow-hidden whitespace-nowrap max-w-[20dvw]",children:ne.original.note})})},{id:"last-update",header:"Cập nhật",accessorKey:"last-update",cell:({row:ne})=>{const q=new Date(ne.original.lastUpdate),me=q.getDate(),he=q.getMonth()+1,be=`ngày ${me} tháng ${he}`;return u.jsx("span",{className:"flex flex-col",children:be})}},{accessorKey:"actions",header:()=>u.jsx("div",{className:"font-medium text-right",children:"Hành động"}),cell:({row:ne})=>{const[q,me]=M.useState(!1),[he,be]=M.useState(!1),[G,X]=M.useState(!1),{handleSubmit:Y,register:ae,reset:Z}=P$(),J=ne.original.id,L=ne.getValue("status"),te=ne.getValue("content"),[xe,_e]=M.useState(!1),Se=async()=>{try{_e(!0);const Ae=L==="unpublish"?"published":"unpublish",Pe=await Re.patch(`${t}/api/toggle-publish/${J}`,{id:J,typeAction:"update",status:L,idInput:J,stock_id:ne.original.stock_id,prefix:ne.original.prefix,model:ne.original.model,summary_result:ne.original.content,note:ne.original.note});Pe.status===200?n(Le=>Le.map(De=>De.id===J?{...De,status:Ae}:De)):console.error("Failed to toggle publish status:",Pe)}catch(Ae){console.error("Error toggling publish status:",Ae)}finally{_e(!1)}},Ie=async Ae=>{me(!0);try{const Pe=await Re.patch(`${t}/api/update-summary`,{note:Ae.note,text_summary:Ae.content,id:J});Pe.status===200?(await O(l),be(!1)):console.error("Failed to update summary:",Pe)}catch(Pe){console.error("Error updating summary:",Pe)}return me(!1)};return u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx($e,{variant:"outline",size:"sm",onClick:()=>X(!0),className:"px-2 py-0.5 h-7",children:u.jsx(VM,{className:"h-4 w-4"})}),u.jsx(pr,{open:G,onOpenChange:X,children:u.jsxs(Qn,{className:"max-w-3xl max-h-[80vh]",children:[u.jsx(Xn,{children:u.jsx(Zn,{children:"Nội dung chi tiết"})}),u.jsx("div",{className:"mt-4 overflow-y-auto max-h-[60vh]",children:u.jsx("div",{className:"whitespace-pre-wrap text-[16px] leading-relaxed",children:te})})]})}),u.jsxs(pr,{open:he,onOpenChange:Ae=>{be(Ae),Ae?Z({content:ne.original.content,note:ne.original.note}):Z()},children:[u.jsx(Gs,{asChild:!0,children:u.jsx($e,{variant:"outline",size:"sm",onClick:()=>be(!0),className:"px-2 py-0.5 h-7",children:"Sửa"})}),u.jsx(Qn,{className:"rounded-lg sm:px-3 h-[calc(100dvh-200px)] min-w-[calc(100dvw-112px)]",children:u.jsxs(Xn,{className:"flex flex-col gap-3",children:[u.jsx(Zn,{className:"max-sm:hidden text-center",children:"Sửa summary"}),u.jsxs("form",{className:"flex flex-col gap-3 h-full justify-between",onSubmit:Y(Ie),children:[u.jsxs("div",{className:"flex flex-col gap-2",children:[u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Nội dung:"}),u.jsx(Js,{placeholder:"Nội dung",className:"w-full input-scroll-bar",defaultValue:ne.original.answer||"",rows:10,...ae("content")})]}),u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{children:"Ghi chú:"}),u.jsx(Js,{placeholder:"Nội dung",className:"w-full input-scroll-bar",defaultValue:ne.original.note||"",rows:1,...ae("note")})]})]}),u.jsx("div",{className:"flex justify-end",children:u.jsx($e,{disabled:q,type:"submit",variant:"default",children:q?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):"Ok"})})]})]})})]}),u.jsx($e,{variant:"outline",size:"sm",onClick:Se,disabled:xe,className:"w-[70px] px-2 py-0.5 h-7",children:xe?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):L==="unpublish"?"Publish":"Unpublish"})]})}}],[]),E=oC({data:e,columns:R,state:{columnFilters:a},enableRowSelection:!0,onColumnFiltersChange:c,getFilteredRowModel:WP(),getCoreRowModel:rC()});return u.jsxs("div",{className:"space-y-4 s3-explr-container",children:[u.jsx("div",{className:"flex items-center space-x-4 s3-explr-toolbar",children:u.jsxs("div",{className:"relative max-w-sm",children:[u.jsx(no,{placeholder:"Tìm kiếm theo mã...",value:v,onChange:W=>x(W.target.value),className:"pr-8"}),v&&u.jsx($e,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0",onClick:()=>x(""),children:u.jsx(Op,{className:"h-4 w-4"})})]})}),u.jsx("div",{className:"rounded-md border s3-explr-table-container",children:u.jsxs(js,{className:"s3-explr-table",children:[u.jsx(Ws,{className:"s3-explr-table-header",children:E.getHeaderGroups().map(W=>u.jsx(er,{className:"hover:bg-transparent s3-explr-header-row",children:W.headers.map(ne=>u.jsx(tr,{className:"s3-explr-header-cell",children:ne.isPlaceholder?null:nd(ne.column.columnDef.header,ne.getContext())},ne.id))},W.id))}),u.jsx(qs,{className:"s3-explr-table-body",children:r?u.jsx(er,{children:u.jsx(pn,{colSpan:R.length,className:"h-24 text-center",children:"Đang tải dữ liệu..."})}):(z=E.getRowModel().rows)!=null&&z.length?(j=E.getRowModel().rows)==null?void 0:j.map(W=>u.jsx(er,{className:"h-12 s3-explr-row",children:W.getVisibleCells().map(ne=>u.jsx(pn,{className:"align-middle s3-explr-cell",children:nd(ne.column.columnDef.cell,ne.getContext())},ne.id))},W.id)):u.jsx(er,{children:u.jsx(pn,{colSpan:R.length,className:"h-24 text-center",children:"Không có kết quả."})})})]})}),u.jsx("div",{className:"mt-4",children:u.jsx(Sd,{children:u.jsxs(Td,{children:[u.jsx(Dr,{children:u.jsx(Ed,{onClick:()=>f(W=>Math.max(1,W-1)),className:l===1?"pointer-events-none opacity-50":"cursor-pointer"})}),Array.from({length:h},(W,ne)=>ne+1).filter(W=>W===1||W===h||Math.abs(W-l)<=1).map((W,ne,q)=>u.jsxs(u.Fragment,{children:[ne>0&&q[ne-1]!==W-1&&u.jsx(Dr,{children:u.jsx(Id,{})},W+"..."),u.jsx(Dr,{children:u.jsx(La,{onClick:()=>f(W),isActive:l===W,className:`cursor-pointer ${r?"pointer-events-none":""}`,children:g===W?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):W})},W)]})),u.jsx(Dr,{children:u.jsx(Ad,{onClick:()=>f(W=>Math.min(h,W+1)),className:l===h||g!==null?"pointer-events-none opacity-50":"cursor-pointer"})})]})})})]})},CT=10,D$=M.memo(({apiBaseUrl:t="http://localhost:3000"})=>{const[e,n]=M.useState(1),[r,o]=M.useState([]),[a,c]=M.useState({total:0,page:1,limit:CT,totalPages:1}),[l,f]=M.useState(!0),[h,p]=M.useState(null),[g,y]=M.useState(new Set),{toast:v}=Fd(),[x,w]=M.useState(!1),_=async E=>{try{p(E);const z=await Re.get(`${t}/api/jobs`,{params:{page:E.toString(),limit:CT.toString()}});o(z.data.data),c(z.data.pagination)}catch{v({variant:"destructive",title:"Error",description:"Failed to fetch jobs. Please try again."})}finally{p(null),f(!1)}};M.useEffect(()=>{_(e)},[e,t]);const I=async E=>{y(z=>new Set(z).add(E.toString()));try{await Re.post(`${t}/api/retry-job`,{jobId:E},{headers:{Authorization:"Basic am9obkBleGFtcGxlLmNvbTphYmMxMjM="}}),v({title:"Job Restarted",description:`Job ${E} has been successfully restarted.`}),_(e)}catch{v({variant:"destructive",title:"Retry Failed",description:`Failed to restart job ${E}. Please try again.`})}finally{y(z=>{const j=new Set(z);return j.delete(E.toString()),j})}},k=async()=>{w(!0),n(1),await _(1),w(!1)},O=E=>new Date(E).toLocaleString(),R=E=>{if(E=parseFloat(E),E<60)return`${E.toFixed(2)}s`;const z=Math.floor(E/60),j=(E%60).toFixed(0);return`${z}m ${j}s`};return u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[u.jsx($M,{className:"w-8 h-8 text-primary"}),u.jsx("h2",{className:"text-3xl font-bold tracking-tight",children:"Job Management"}),u.jsx($e,{variant:"outline",size:"icon",onClick:k,disabled:x||l,className:"ml-2",children:u.jsx(jM,{className:`h-4 w-4 ${x?"animate-spin":""}`})})]}),u.jsx("div",{className:"rounded-md border",children:u.jsxs(js,{children:[u.jsx(Ws,{children:u.jsxs(er,{children:[u.jsx(tr,{children:"ID"}),u.jsx(tr,{children:"Tên Công Việc"}),u.jsx(tr,{children:"Thời Gian Bắt Đầu"}),u.jsx(tr,{children:"Thời Gian Cập Nhật"}),u.jsx(tr,{children:"Thời Gian Thực Thi"}),u.jsx(tr,{children:"Trạng Thái"}),u.jsx(tr,{children:"Thao Tác"})]})}),u.jsx(qs,{children:l&&r.length===0?u.jsx(er,{children:u.jsx(pn,{colSpan:7,className:"text-center py-4",children:u.jsx(Vt,{className:"w-6 h-6 animate-spin mx-auto"})})}):r.map(E=>{var z,j;return u.jsxs(er,{children:[u.jsx(pn,{className:"!w-[100px]",children:E.id}),u.jsx(pn,{className:"font-medium",children:(z=E.job_name)==null?void 0:z.replace("Upload file","Summary")}),u.jsx(pn,{className:"!w-[200px]",children:O(E.created_at)}),u.jsx(pn,{className:"!w-[200px]",children:O(E.updated_at)}),u.jsx(pn,{className:"!w-[150px]",children:R(E.execution_time_seconds)}),u.jsx(pn,{className:"!w-[200px]",children:u.jsx(bT,{content:E.status==="fail"&&E.error?u.jsx("div",{className:"font-medium text-[16px] max-w-[90dvw]",children:E.error}):null,children:u.jsx("div",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium truncate text-ellipsis overflow-hidden whitespace-nowrap max-w-[30dvw]
218
218
  ${E.status==="done"?"bg-green-100 text-green-800":E.status==="fail"?"bg-red-100 text-red-800":"bg-yellow-100 text-yellow-800"}`,children:E.status==="fail"?"FAILED":(j=E.status)==null?void 0:j.toUpperCase()})})}),u.jsx(pn,{className:"!w-[200px]",children:E.status==="fail"?u.jsx($e,{variant:"outline",size:"sm",onClick:()=>I(E.id),disabled:g.has(E.id.toString()),className:"h-[32px]",children:g.has(E.id.toString())?u.jsxs(u.Fragment,{children:[u.jsx(Vt,{className:"mr-2 h-4 w-4 animate-spin"}),"Đang thử lại..."]}):"Thử Lại"}):u.jsx("div",{className:"h-[32px]"})})]},E.id)})})]})}),u.jsx("div",{className:"mt-4",children:u.jsx(Sd,{children:u.jsxs(Td,{children:[u.jsx(Dr,{children:u.jsx(Ed,{onClick:()=>n(E=>Math.max(1,E-1)),className:e===1?"pointer-events-none opacity-50":"cursor-pointer"})}),Array.from({length:a.totalPages},(E,z)=>z+1).filter(E=>E===1||E===a.totalPages||Math.abs(E-e)<=1).map((E,z,j)=>u.jsxs(u.Fragment,{children:[z>0&&j[z-1]!==E-1&&u.jsx(Dr,{children:u.jsx(Id,{})},E+"..."),u.jsx(Dr,{children:u.jsx(La,{onClick:()=>n(E),isActive:e===E,className:`cursor-pointer ${h!==null?"pointer-events-none":""}`,children:h===E?u.jsx(Vt,{className:"h-4 w-4 animate-spin"}):E})},E)]})),u.jsx(Dr,{children:u.jsx(Ad,{onClick:()=>n(E=>Math.min(a.totalPages,E+1)),className:e===a.totalPages||h!==null?"pointer-events-none opacity-50":"cursor-pointer"})})]})})}),u.jsx(C_,{})]})});Sr.Job=D$,Sr.S3Explorer=d$,Sr.Summary=R$,Object.defineProperty(Sr,Symbol.toStringTag,{value:"Module"})});
219
219
  //# sourceMappingURL=s3-explorer.umd.cjs.map