@nice2dev/ui-platform 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +8 -8
- package/dist/index.mjs +4453 -4383
- package/package.json +3 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var yt=Object.defineProperty;var wt=(n,f,h)=>f in n?yt(n,f,{enumerable:!0,configurable:!0,writable:!0,value:h}):n[f]=h;var oe=(n,f,h)=>wt(n,typeof f!="symbol"?f+"":f,h);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),ue=e.createContext(null),vt=()=>{const n=e.useContext(ue);if(!n)throw new Error("useAutoStart must be used within NiceAutoStartProvider");return n},xt={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},_e=Object.assign(e.forwardRef((n,f)=>{const{tasks:h=[],config:k,splash:g,errorScreen:N,onComplete:R,onTaskComplete:G,onError:i,onRecovery:l,children:b}=n,E={...xt,...k},v=e.useRef(0),d=e.useRef(h),p=e.useRef(null),[I,B]=e.useState(E.showSplash),[q,z]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:h.length,results:[],recoveryAttempt:0,totalDuration:0}),Y=e.useCallback(async s=>{const r=Date.now();let a=0;const c=async()=>{try{const o=s.timeout||E.globalTimeout,S=new Promise((A,m)=>{setTimeout(()=>m(new Error("Task timeout")),o)});return await Promise.race([s.execute(),S]),{taskId:s.id,success:!0,duration:Date.now()-r,retriesUsed:a}}catch(o){const S=s.retries??0;return a<S?(a++,await new Promise(A=>setTimeout(A,500)),c()):{taskId:s.id,success:!1,error:o instanceof Error?o:new Error(String(o)),duration:Date.now()-r,retriesUsed:a}}};return c()},[E.globalTimeout]),K=e.useCallback(s=>{const r=[],a=[...s],c=new Set;for(;a.length>0;){const o=a.filter(A=>A.dependencies?A.dependencies.every(m=>c.has(m)):!0);if(o.length===0){r.push(...a);break}o.sort((A,m)=>(m.priority??0)-(A.priority??0));const S=o[0];r.push(S),c.add(S.id),a.splice(a.indexOf(S),1)}return r},[]),F=e.useCallback(async()=>{v.current=Date.now();const s=new AbortController;p.current=s;const r=K(d.current),a=[];z(o=>({...o,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:r.length,results:[]}));for(let o=0;o<r.length;o++){if(s.signal.aborted)return;const S=r[o];z(m=>({...m,currentTask:S.name,progress:Math.round(o/r.length*100)}));const A=await Y(S);if(s.signal.aborted)return;if(a.push(A),z(m=>({...m,completedTasks:o+1,results:[...m.results,A]})),G==null||G(A),!A.success&&S.critical){const m=A.error||new Error("Critical task failed");i==null||i(m,S.id),z(w=>({...w,phase:"error",isLoading:!1,hasError:!0,errorMessage:m.message}));return}}const c=Date.now()-v.current;if(z(o=>({...o,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:c})),R==null||R(a),E.autoHideSplash){const o=Date.now()-v.current,S=Math.max(0,E.splashDuration-o);setTimeout(()=>{B(!1)},S)}},[K,Y,E.autoHideSplash,E.splashDuration,G,i,R]),W=e.useCallback(async()=>{p.current&&p.current.abort(),z(s=>({...s,recoveryAttempt:0})),B(E.showSplash),await F()},[E.showSplash,F]),j=e.useCallback(()=>{p.current&&p.current.abort(),z(s=>({...s,phase:"ready",isLoading:!1,isReady:!0,progress:100})),B(!1)},[]),U=e.useCallback(()=>{B(!1)},[]),D=e.useCallback(async()=>{const s=q.recoveryAttempt+1;s>E.recoveryAttempts||(z(r=>({...r,phase:"recovery",recoveryAttempt:s})),l==null||l(s),await new Promise(r=>setTimeout(r,E.recoveryDelay)),await F())},[q.recoveryAttempt,E.recoveryAttempts,E.recoveryDelay,l,F]),P=e.useCallback(s=>{d.current=[...d.current,s]},[]),T=e.useCallback(s=>{d.current=d.current.filter(r=>r.id!==s)},[]),O=e.useCallback(s=>q.results.find(r=>r.taskId===s),[q.results]);e.useEffect(()=>{q.hasError&&E.autoRecovery&&q.recoveryAttempt<E.recoveryAttempts&&D()},[q.hasError,E.autoRecovery,E.recoveryAttempts,q.recoveryAttempt,D]),e.useEffect(()=>(F(),()=>{p.current&&p.current.abort()}),[]),e.useImperativeHandle(f,()=>({getState:()=>q,restart:W,skip:j,addTask:P,removeTask:T,getTaskResult:O,hideSplash:U,recover:D}),[q,W,j,P,T,O,U,D]);const y={...q,restart:W,skip:j,hideSplash:U};return q.hasError&&q.recoveryAttempt>=E.recoveryAttempts?t.jsx(ue.Provider,{value:y,children:N||t.jsxs("div",{className:"nice-auto-start__error",children:[t.jsx("div",{className:"nice-auto-start__error-icon","aria-hidden":"true",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert"})}),t.jsx("h2",{className:"nice-auto-start__error-title",children:"Startup Failed"}),t.jsx("p",{className:"nice-auto-start__error-message",children:q.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:W,children:"Retry"})]})}):I&&!q.isReady?t.jsx(ue.Provider,{value:y,children:g||t.jsx("div",{className:"nice-auto-start__splash",children:t.jsxs("div",{className:"nice-auto-start__splash-content",children:[t.jsx("div",{className:"nice-auto-start__splash-logo","aria-hidden":"true"}),t.jsx("h1",{className:"nice-auto-start__splash-title",children:"Loading..."}),E.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${q.progress}%`}})}),E.showTaskNames&&q.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:q.currentTask}),q.phase==="recovery"&&t.jsxs("div",{className:"nice-auto-start__splash-recovery",children:["Recovery attempt ",q.recoveryAttempt," of ",E.recoveryAttempts]})]})})}):t.jsx(ue.Provider,{value:y,children:b})}),{displayName:"NiceAutoStart"}),Ne=_e;process.env.NODE_ENV!=="production"&&(Ne.displayName="NiceAutoStartProvider");const je=e.createContext(null),Ie=()=>{const n=e.useContext(je);if(!n)throw new Error("useExternalDisplay must be used within NiceExternalDisplayProvider");return n},Ct={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},kt=()=>typeof window>"u"?!1:"getScreenDetails"in window,St=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,_t=n=>{const f=[];return n.width!==void 0&&f.push(`width=${n.width}`),n.height!==void 0&&f.push(`height=${n.height}`),n.left!==void 0&&f.push(`left=${n.left}`),n.top!==void 0&&f.push(`top=${n.top}`),n.menubar!==void 0&&f.push(`menubar=${n.menubar?"yes":"no"}`),n.toolbar!==void 0&&f.push(`toolbar=${n.toolbar?"yes":"no"}`),n.location!==void 0&&f.push(`location=${n.location?"yes":"no"}`),n.status!==void 0&&f.push(`status=${n.status?"yes":"no"}`),n.resizable!==void 0&&f.push(`resizable=${n.resizable?"yes":"no"}`),n.scrollbars!==void 0&&f.push(`scrollbars=${n.scrollbars?"yes":"no"}`),f.join(",")},be=()=>{var f;if(typeof window>"u")return{id:"primary",label:"Primary Display",width:0,height:0,availWidth:0,availHeight:0,left:0,top:0,devicePixelRatio:1,isPrimary:!0,orientation:"landscape-primary",colorDepth:24};const n=window.screen;return{id:"primary",label:"Primary Display",width:n.width,height:n.height,availWidth:n.availWidth,availHeight:n.availHeight,left:n.availLeft||0,top:n.availTop||0,devicePixelRatio:window.devicePixelRatio,isPrimary:!0,orientation:((f=n.orientation)==null?void 0:f.type)||"landscape-primary",colorDepth:n.colorDepth}},Nt=async()=>{try{return(await navigator.permissions.query({name:"window-management"})).state}catch{return"unknown"}},ye=async()=>(await window.getScreenDetails()).screens.map((f,h)=>{var k;return{id:`screen-${h}`,label:f.label||`Display ${h+1}`,width:f.width,height:f.height,availWidth:f.availWidth,availHeight:f.availHeight,left:f.left,top:f.top,devicePixelRatio:f.devicePixelRatio,isPrimary:f.isPrimary,isInternal:f.isInternal,orientation:((k=f.orientation)==null?void 0:k.type)||"landscape-primary",colorDepth:f.colorDepth}}),we=(n,f)=>JSON.stringify(n)===JSON.stringify(f),Ee=Object.assign(e.forwardRef((n,f)=>{const{config:h,onScreensChange:k,onWindowOpen:g,onWindowClose:N,onPermissionChange:R,children:G}=n,i={...Ct,...h},l=e.useRef(new Map),b=e.useRef(null),[E,v]=e.useState([be()]),[d,p]=e.useState([]),[I,B]=e.useState("unknown"),[q]=e.useState(kt),z=e.useRef(k),Y=e.useRef(R);e.useEffect(()=>{z.current=k,Y.current=R});const K=e.useRef([]),F=e.useCallback(m=>{var w;v(u=>we(u,m)?u:m),we(K.current,m)||(K.current=m,(w=z.current)==null||w.call(z,m))},[]),W=e.useRef("unknown"),j=e.useCallback(m=>{var w;W.current!==m&&(W.current=m,B(m),(w=Y.current)==null||w.call(Y,m))},[]),U=e.useCallback(async()=>{if(q){const w=await Nt();if(j(w),w==="granted")try{const u=await ye();return F(u),u}catch{}}const m=[be()];return F(m),m},[q,j,F]),D=e.useCallback(async()=>{if(!q)return j("denied"),!1;try{return F(await ye()),j("granted"),!0}catch(m){return j(m instanceof DOMException&&m.name==="NotAllowedError"?"denied":"unknown"),!1}},[q,j,F]),P=e.useCallback(async(m,w="about:blank",u={})=>{if(!i.allowMultiWindow&&d.length>0)return console.warn("Multi-window mode is disabled"),null;const C=St(),x={...i.defaultFeatures,...u,width:u.width??m.availWidth,height:u.height??m.availHeight,left:u.left??m.left,top:u.top??m.top},H=_t(x),_={window:null,screen:m,id:C,state:"opening",isFullscreen:!1,features:x};p(M=>[...M,_]);try{const M=window.open(w,C,H);if(!M)return p($=>$.map(Z=>Z.id===C?{...Z,state:"error"}:Z)),null;l.current.set(C,M);const L={..._,window:M,state:"open"};p($=>$.map(Z=>Z.id===C?L:Z));const X=setInterval(()=>{M.closed&&(clearInterval(X),l.current.delete(C),p($=>$.filter(Z=>Z.id!==C)),N==null||N(L))},500);return x.fullscreen&&M.addEventListener("load",()=>{var $,Z;(Z=($=M.document.documentElement).requestFullscreen)==null||Z.call($)}),g==null||g(L),L}catch(M){return console.error("Failed to open window:",M),p(L=>L.map(X=>X.id===C?{...X,state:"error"}:X)),null}},[i.allowMultiWindow,i.defaultFeatures,d.length,g,N]),T=e.useCallback(m=>{const w=l.current.get(m);w&&!w.closed&&w.close(),l.current.delete(m),p(u=>u.filter(C=>C.id!==m))},[]),O=e.useCallback(()=>{for(const[m,w]of l.current)w.closed||w.close(),l.current.delete(m);p([])},[]),y=e.useCallback((m,w)=>{const u=l.current.get(m);u&&!u.closed&&(u.moveTo(w.left,w.top),u.resizeTo(w.availWidth,w.availHeight),p(C=>C.map(x=>x.id===m?{...x,screen:w}:x)))},[]),s=e.useCallback(async m=>{const w=l.current.get(m);if(!w||w.closed)return!1;try{const u=!!w.document.fullscreenElement;return u?await w.document.exitFullscreen():await w.document.documentElement.requestFullscreen(),p(C=>C.map(x=>x.id===m?{...x,isFullscreen:!u}:x)),!0}catch{return!1}},[]),r=e.useCallback((m,w)=>{const u=l.current.get(m);u&&!u.closed&&u.postMessage(w,"*")},[]),a=e.useCallback(m=>{for(const w of l.current.values())w.closed||w.postMessage(m,"*")},[]);e.useEffect(()=>{i.autoDetect&&U()},[i.autoDetect,U]),e.useEffect(()=>(i.autoDetect&&i.pollInterval>0&&(b.current=setInterval(U,i.pollInterval)),()=>{b.current&&clearInterval(b.current)}),[i.autoDetect,i.pollInterval,U]),e.useEffect(()=>{if(!q)return;const m=()=>{U()};return window.addEventListener("screenschange",m),()=>{window.removeEventListener("screenschange",m)}},[q,U]),e.useEffect(()=>()=>{O()},[O]);const c=E.find(m=>m.isPrimary)||null,o=E.filter(m=>!m.isPrimary),S={screens:E,primaryScreen:c,externalScreens:o,windows:d,isApiAvailable:q,permissionState:I};e.useImperativeHandle(f,()=>({getState:()=>S,requestPermission:D,getScreens:U,openWindow:P,closeWindow:T,closeAllWindows:O,moveWindowToScreen:y,toggleFullscreen:s,sendMessage:r,broadcast:a}),[S,D,U,P,T,O,y,s,r,a]);const A={...S,requestPermission:D,openWindow:P,closeWindow:T,moveWindowToScreen:y};return t.jsx(je.Provider,{value:A,children:t.jsx("div",{className:"nice-external-display",children:G})})}),{displayName:"NiceExternalDisplay"}),De=Ee;process.env.NODE_ENV!=="production"&&(De.displayName="NiceExternalDisplayProvider");const Ae=({onSelect:n,selectedId:f,showPreview:h=!0,className:k})=>{const{screens:g,primaryScreen:N}=Ie(),R=b=>{n==null||n(b)},i=(()=>{let b=0,E=0,v=0,d=0;for(const p of g)b=Math.min(b,p.left),E=Math.min(E,p.top),v=Math.max(v,p.left+p.width),d=Math.max(d,p.top+p.height);return{minX:b,minY:E,maxX:v,maxY:d,width:v-b,height:d-E}})(),l=Math.min(280/i.width,160/i.height,1);return t.jsxs("div",{className:`nice-screen-selector ${k||""}`,children:[h&&t.jsx("div",{className:"nice-screen-selector__preview",style:{width:i.width*l,height:i.height*l},children:g.map(b=>t.jsx("button",{className:`nice-screen-selector__screen ${f===b.id?"nice-screen-selector__screen--selected":""} ${b.isPrimary?"nice-screen-selector__screen--primary":""}`,style:{left:(b.left-i.minX)*l,top:(b.top-i.minY)*l,width:b.width*l,height:b.height*l},onClick:()=>R(b),title:b.label,children:t.jsx("span",{className:"nice-screen-selector__screen-label",children:b.isPrimary?"P":g.indexOf(b)+1})},b.id))}),t.jsx("div",{className:"nice-screen-selector__list",children:g.map(b=>t.jsxs("button",{className:`nice-screen-selector__item ${f===b.id?"nice-screen-selector__item--selected":""}`,onClick:()=>R(b),children:[t.jsx("span",{className:"nice-screen-selector__item-name",children:b.label}),t.jsxs("span",{className:"nice-screen-selector__item-resolution",children:[b.width," × ",b.height]}),b.isPrimary&&t.jsx("span",{className:"nice-screen-selector__item-badge",children:"Primary"})]},b.id))})]})};process.env.NODE_ENV!=="production"&&(Ae.displayName="NiceScreenSelector");const Pe=e.createContext(null),jt=()=>{const n=e.useContext(Pe);if(!n)throw new Error("useKioskMode must be used within NiceKioskModeProvider");return n},It={autoFullscreen:!0,lockNavigation:!0,disableContextMenu:!0,disableShortcuts:!0,disableSelection:!0,disableCopyPaste:!0,exitPin:"1234",exitShortcut:"ctrl+shift+k",adminTapCount:5,adminTapTimeout:2e3,inactivityTimeout:300*1e3,showCursor:!0,allowScrolling:!0,className:""},Le=Object.assign(e.forwardRef((n,f)=>{const{config:h,children:k,screensaver:g,adminPanel:N,onModeChange:R,onFullscreenChange:G,onAdminAccess:i,onInactivity:l,onActivity:b,onExitRequest:E}=n,v={...It,...h},d=e.useRef(null),p=e.useRef(null),I=e.useRef({count:0,timer:null}),[B,q]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[z,Y]=e.useState(""),[K,F]=e.useState(!1),W=e.useCallback(async()=>{const u=d.current;if(u)try{u.requestFullscreen?await u.requestFullscreen():u.webkitRequestFullscreen?await u.webkitRequestFullscreen():u.msRequestFullscreen&&await u.msRequestFullscreen()}catch(C){console.warn("Failed to enter fullscreen:",C)}},[]),j=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(u){console.warn("Failed to exit fullscreen:",u)}},[]),U=e.useCallback(async()=>{B.isFullscreen?await j():await W()},[B.isFullscreen,W,j]),D=e.useCallback(()=>{q(u=>({...u,mode:"locked",isLocked:!0,isAdminMode:!1})),R==null||R("locked")},[R]),P=e.useCallback(u=>v.exitPin&&u!==v.exitPin?(F(!0),setTimeout(()=>F(!1),1e3),!1):(q(C=>({...C,mode:C.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),Y(""),!0),[v.exitPin]),T=e.useCallback(()=>{q(u=>({...u,isAdminMode:!0})),i==null||i()},[i]),O=e.useCallback(()=>{q(u=>({...u,isAdminMode:!1}))},[]),y=e.useCallback(()=>{I.current.timer&&clearTimeout(I.current.timer),I.current.count++,I.current.count>=v.adminTapCount?(I.current.count=0,T()):I.current.timer=setTimeout(()=>{I.current.count=0},v.adminTapTimeout)},[v.adminTapCount,v.adminTapTimeout,T]),s=e.useCallback(()=>{p.current&&clearTimeout(p.current),B.isScreensaverActive&&(q(u=>({...u,isScreensaverActive:!1})),b==null||b()),v.inactivityTimeout>0&&(p.current=setTimeout(()=>{q(u=>({...u,isScreensaverActive:!0})),l==null||l()},v.inactivityTimeout))},[v.inactivityTimeout,B.isScreensaverActive,b,l]),r=e.useCallback(()=>{q(u=>({...u,isScreensaverActive:!0}))},[]),a=e.useCallback(()=>{q(u=>({...u,isScreensaverActive:!1})),s()},[s]),c=e.useCallback(()=>{q(u=>({...u,isPinDialogOpen:!0})),Y(""),F(!1)},[]),o=e.useCallback(()=>{q(u=>({...u,isPinDialogOpen:!1})),Y(""),F(!1)},[]),S=e.useCallback(()=>{P(z)},[z,P]),A=e.useCallback(u=>{u.key==="Enter"&&S()},[S]);e.useEffect(()=>{const u=()=>{const C=!!document.fullscreenElement;q(x=>({...x,mode:x.isLocked?"locked":C?"fullscreen":"windowed",isFullscreen:C})),G==null||G(C)};return document.addEventListener("fullscreenchange",u),document.addEventListener("webkitfullscreenchange",u),()=>{document.removeEventListener("fullscreenchange",u),document.removeEventListener("webkitfullscreenchange",u)}},[G]),e.useEffect(()=>{if(!v.disableContextMenu)return;const u=C=>{B.isAdminMode||C.preventDefault()};return document.addEventListener("contextmenu",u),()=>document.removeEventListener("contextmenu",u)},[v.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const u=async C=>{const H=v.exitShortcut.toLowerCase().split("+"),_=H.includes("ctrl")===C.ctrlKey,M=H.includes("shift")===C.shiftKey,L=H.includes("alt")===C.altKey,X=H.some($=>$===C.key.toLowerCase());if(_&&M&&L&&X){C.preventDefault(),(E?await E("keyboard"):!0)&&(B.isLocked?c():j());return}if(v.disableShortcuts&&!B.isAdminMode){const $=["F5","F11","F12"],Z=[{ctrl:!0,key:"r"},{ctrl:!0,key:"w"},{ctrl:!0,key:"n"},{ctrl:!0,key:"t"},{ctrl:!0,shift:!0,key:"i"},{ctrl:!0,shift:!0,key:"j"},{alt:!0,key:"F4"}];if($.includes(C.key)){C.preventDefault();return}for(const J of Z)if(J.ctrl===C.ctrlKey&&(J.shift??!1)===C.shiftKey&&(J.alt??!1)===C.altKey&&J.key.toLowerCase()===C.key.toLowerCase()){C.preventDefault();return}}};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[v.disableShortcuts,v.exitShortcut,B.isAdminMode,B.isLocked,j,c,E]),e.useEffect(()=>{if(!v.disableCopyPaste)return;const u=x=>{B.isAdminMode||x.preventDefault()},C=x=>{B.isAdminMode||x.preventDefault()};return document.addEventListener("copy",u),document.addEventListener("paste",C),()=>{document.removeEventListener("copy",u),document.removeEventListener("paste",C)}},[v.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const u=["mousedown","mousemove","keydown","touchstart","scroll"],C=()=>{s()};for(const x of u)document.addEventListener(x,C);return s(),()=>{for(const x of u)document.removeEventListener(x,C);p.current&&clearTimeout(p.current)}},[s]),e.useEffect(()=>{if(v.autoFullscreen){const u=setTimeout(()=>{W()},100);return()=>clearTimeout(u)}},[v.autoFullscreen,W]),e.useImperativeHandle(f,()=>({getState:()=>B,enterFullscreen:W,exitFullscreen:j,toggleFullscreen:U,lock:D,unlock:P,enterAdminMode:T,exitAdminMode:O,resetIdleTimer:s,showScreensaver:r,hideScreensaver:a,openPinDialog:c,closePinDialog:o}),[B,W,j,U,D,P,T,O,s,r,a,c,o]);const m={...B,enterFullscreen:W,exitFullscreen:j,toggleFullscreen:U,lock:D,unlock:P,enterAdminMode:T,exitAdminMode:O,resetIdleTimer:s},w=["nice-kiosk-mode",`nice-kiosk-mode--${B.mode}`,B.isFullscreen&&"nice-kiosk-mode--fullscreen",!v.showCursor&&"nice-kiosk-mode--no-cursor",v.disableSelection&&"nice-kiosk-mode--no-select",!v.allowScrolling&&"nice-kiosk-mode--no-scroll",v.className].filter(Boolean).join(" ");return t.jsx(Pe.Provider,{value:m,children:t.jsxs("div",{ref:d,className:w,onClick:y,children:[t.jsx("div",{className:"nice-kiosk-mode__content",children:k}),B.isAdminMode&&N&&t.jsxs("div",{className:"nice-kiosk-mode__admin",children:[t.jsxs("div",{className:"nice-kiosk-mode__admin-header",children:[t.jsx("h2",{className:"nice-kiosk-mode__admin-title",children:"Admin Mode"}),t.jsx("button",{className:"nice-kiosk-mode__admin-close",onClick:O,"aria-label":"Close admin panel",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-kiosk-mode__admin-content",children:N})]}),B.isScreensaverActive&&t.jsx("div",{className:"nice-kiosk-mode__screensaver",onClick:a,onTouchStart:a,children:g||t.jsx("div",{className:"nice-kiosk-mode__screensaver-default",children:t.jsx("div",{className:"nice-kiosk-mode__screensaver-text",children:"Touch to continue"})})}),B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__pin-overlay",children:t.jsxs("div",{className:"nice-kiosk-mode__pin-dialog",children:[t.jsx("h3",{className:"nice-kiosk-mode__pin-title",children:"Enter PIN"}),t.jsx("input",{type:"password",className:`nice-kiosk-mode__pin-input ${K?"nice-kiosk-mode__pin-input--error":""}`,value:z,onChange:u=>Y(u.target.value),onKeyPress:A,maxLength:8,autoFocus:!0,placeholder:"••••"}),t.jsxs("div",{className:"nice-kiosk-mode__pin-buttons",children:[t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--cancel",onClick:o,children:"Cancel"}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:S,children:"Unlock"})]}),K&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:"Incorrect PIN"})]})}),B.isLocked&&!B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__lock-indicator",children:t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:"Kiosk Locked"})})]})})}),{displayName:"NiceKioskMode"}),Re=Le;process.env.NODE_ENV!=="production"&&(Re.displayName="NiceKioskModeProvider");const Oe=e.createContext(null),Et=()=>{const n=e.useContext(Oe);if(!n)throw new Error("useLowPowerMode must be used within NiceLowPowerModeProvider");return n},Dt={normal:{mode:"normal",brightness:1,wakeOnTouch:!0},dim:{mode:"dim",brightness:.6,disableAnimations:!1,wakeOnTouch:!0},low:{mode:"low",brightness:.3,frameRateCap:30,disableAnimations:!0,reduceImageQuality:!0,wakeOnTouch:!0},sleep:{mode:"sleep",brightness:0,frameRateCap:1,disableAnimations:!0,disableBackgroundProcesses:!0,reduceImageQuality:!0,wakeOnTouch:!0,wakeOnMotion:!0}},At={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},Te=Object.assign(e.forwardRef((n,f)=>{const{config:h,onModeChange:k,onBrightnessChange:g,onSleep:N,onWake:R,onLowBattery:G,children:i}=n,l={...At,...h},b={...Dt,...h==null?void 0:h.modes},E=e.useRef(null),v=e.useRef(null),d=e.useRef(Date.now()),p=e.useRef(null),[I,B]=e.useState({currentMode:l.initialMode,brightness:b[l.initialMode].brightness??1,isPowerSaving:l.initialMode!=="normal",isSleeping:l.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),q=e.useCallback(O=>{const y=b[O];document.documentElement.style.setProperty("--lpm-brightness",String(y.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${l.transitionDuration}ms`),y.disableAnimations?document.documentElement.classList.add("nice-lpm-no-animations"):document.documentElement.classList.remove("nice-lpm-no-animations"),y.reduceImageQuality?document.documentElement.classList.add("nice-lpm-reduced-quality"):document.documentElement.classList.remove("nice-lpm-reduced-quality")},[b,l.transitionDuration]),z=e.useCallback(O=>{B(y=>{if(y.currentMode===O)return y;const s=y.currentMode,r=b[O];return q(O),k==null||k(O,s),g==null||g(r.brightness??1),O==="sleep"&&s!=="sleep"?N==null||N():s==="sleep"&&O!=="sleep"&&(R==null||R()),{...y,currentMode:O,brightness:r.brightness??1,isPowerSaving:O!=="normal",isSleeping:O==="sleep",isDisplayOn:O!=="sleep"}})},[b,q,k,g,N,R]),Y=e.useCallback(O=>{const y=Math.max(0,Math.min(1,O));document.documentElement.style.setProperty("--lpm-brightness",String(y)),B(s=>({...s,brightness:y})),g==null||g(y)},[g]),K=e.useCallback(()=>{z("sleep")},[z]),F=e.useCallback(()=>{z("normal"),j()},[z]),W=e.useCallback(()=>{I.currentMode==="normal"?z("low"):z("normal")},[I.currentMode,z]),j=e.useCallback(()=>{if(d.current=Date.now(),E.current&&clearTimeout(E.current),v.current&&clearTimeout(v.current),I.isSleeping){F();return}I.currentMode!=="normal"&&I.currentMode!=="sleep"&&z("normal"),l.autoDimTimeout>0&&(E.current=setTimeout(()=>{I.currentMode==="normal"&&z("dim")},l.autoDimTimeout)),l.autoSleepTimeout>0&&(v.current=setTimeout(()=>{z("sleep")},l.autoSleepTimeout)),B(O=>({...O,idleTime:0}))},[I.isSleeping,I.currentMode,l.autoDimTimeout,l.autoSleepTimeout,z,F]),U=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const O=await navigator.getBattery();return{level:Math.round(O.level*100),charging:O.charging}}catch{return{}}return{}},[]),D=e.useCallback(async()=>{const O=await U();O.level!==void 0&&(B(y=>({...y,batteryLevel:O.level,isCharging:O.charging})),O.charging||(O.level<=l.criticalBatteryThreshold?(z("sleep"),G==null||G(O.level)):O.level<=l.lowBatteryThreshold&&(I.currentMode==="normal"&&z("low"),G==null||G(O.level))))},[U,l.lowBatteryThreshold,l.criticalBatteryThreshold,I.currentMode,z,G]),P=e.useCallback(()=>{if(!(h!=null&&h.schedule)||h.schedule.length===0)return;const y=new Date().getHours();for(const s of h.schedule){const{startHour:r,endHour:a,mode:c}=s;let o;if(r<=a?o=y>=r&&y<a:o=y>=r||y<a,o){B(S=>({...S,scheduledModeActive:c})),I.currentMode!==c&&z(c);return}}B(s=>({...s,scheduledModeActive:void 0}))},[h==null?void 0:h.schedule,I.currentMode,z]);e.useEffect(()=>{const O=["mousedown","mousemove","keydown","touchstart","scroll"],y=()=>{l.wakeOnTouch&&j()};for(const s of O)document.addEventListener(s,y);return j(),()=>{for(const s of O)document.removeEventListener(s,y);E.current&&clearTimeout(E.current),v.current&&clearTimeout(v.current)}},[l.wakeOnTouch,j]),e.useEffect(()=>{D(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const y=await navigator.getBattery();p.current=y,y.addEventListener("levelchange",D),y.addEventListener("chargingchange",D)}catch{}})()},[D]),e.useEffect(()=>{P();const O=setInterval(P,6e4);return()=>clearInterval(O)},[P]),e.useEffect(()=>{q(l.initialMode)},[l.initialMode,q]),e.useImperativeHandle(f,()=>({getState:()=>I,setMode:z,setBrightness:Y,sleep:K,wake:F,togglePowerSaving:W,resetIdleTimer:j,getBatteryInfo:U}),[I,z,Y,K,F,W,j,U]);const T={...I,setMode:z,setBrightness:Y,sleep:K,wake:F,resetIdleTimer:j};return t.jsx(Oe.Provider,{value:T,children:t.jsxs("div",{className:`nice-lpm nice-lpm--${I.currentMode}`,children:[t.jsx("div",{className:"nice-lpm__overlay",style:{opacity:1-I.brightness}}),t.jsx("div",{className:"nice-lpm__content",children:i}),I.isSleeping&&t.jsx("div",{className:"nice-lpm__sleep-screen",onClick:l.wakeOnTouch?F:void 0,onTouchStart:l.wakeOnTouch?F:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:"Touch to wake"})})]})})}),{displayName:"NiceLowPowerMode"}),Me=Te;process.env.NODE_ENV!=="production"&&(Me.displayName="NiceLowPowerModeProvider");const Fe=e.createContext(null),Pt=()=>{const n=e.useContext(Fe);if(!n)throw new Error("useOrientationLock must be used within NiceOrientationLockProvider");return n},Lt={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},Be=()=>{if(typeof window>"u")return"portrait";const n=window.screen;return n.orientation?n.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},Rt=()=>{if(typeof window>"u")return 0;const n=window.screen;return n.orientation?n.orientation.angle:window.orientation||0},he=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const n=Be(),f=Rt(),h=window.screen.width,k=window.screen.height,g=n.includes("portrait")||window.innerHeight>window.innerWidth,N=n.includes("landscape")||window.innerWidth>window.innerHeight;return{type:n,angle:f,isPortrait:g,isLandscape:N,width:h,height:k,aspectRatio:h/k}},Ot=()=>{if(typeof window>"u")return!1;const n=window.screen;return!!(n.orientation&&typeof n.orientation.lock=="function")},$e=Object.assign(e.forwardRef((n,f)=>{const{config:h,onOrientationChange:k,onLockChange:g,onUnsupportedOrientation:N,rotationPrompt:R,children:G,className:i}=n,l={...Lt,...h},b=e.useRef(!1),[E,v]=e.useState(Be),[d,p]=e.useState(null),[I,B]=e.useState(he),[q]=e.useState(Ot),z=e.useCallback(y=>!!(l.supportedOrientations.includes("any")||l.supportedOrientations.includes(y)||y.includes("portrait")&&l.supportedOrientations.includes("portrait")||y.includes("landscape")&&l.supportedOrientations.includes("landscape")),[l.supportedOrientations]),Y=e.useCallback(async y=>{if(!q)return console.warn("Screen Orientation API is not available"),p(y),g==null||g(!0,y),!1;try{return await window.screen.orientation.lock(y),p(y),g==null||g(!0,y),!0}catch(s){return console.warn("Failed to lock orientation:",s),p(y),g==null||g(!0,y),!1}},[q,g]),K=e.useCallback(async()=>{if(p(null),g==null||g(!1,null),!q)return!1;try{return window.screen.orientation.unlock(),!0}catch(y){return console.warn("Failed to unlock orientation:",y),!1}},[q,g]),F=e.useCallback(async()=>d?K():Y(E),[d,E,Y,K]),W=e.useCallback(()=>he(),[]),j=e.useCallback(()=>{const y=he(),s=y.type;v(s),B(y),k==null||k(y),z(s)||N==null||N(s,l.supportedOrientations)},[l.supportedOrientations,z,k,N]);e.useEffect(()=>{b.current||(b.current=!0,j(),l.lockOnMount&&l.preferredOrientation!=="any"&&Y(l.preferredOrientation))},[l.lockOnMount,l.preferredOrientation,j,Y]),e.useEffect(()=>{const y=window.screen.orientation;return y&&y.addEventListener("change",j),window.addEventListener("resize",j),window.addEventListener("orientationchange",j),()=>{y&&y.removeEventListener("change",j),window.removeEventListener("resize",j),window.removeEventListener("orientationchange",j)}},[j]);const U={current:E,locked:d,isLocked:d!==null,isSupported:z(E),info:I,isApiAvailable:q};e.useImperativeHandle(f,()=>({getState:()=>U,lock:Y,unlock:K,toggleLock:F,getOrientationInfo:W,isOrientationSupported:z}),[U,Y,K,F,W,z]);const D={...U,lock:Y,unlock:K,getOrientationInfo:W},P=e.useCallback(()=>{if(!l.autoRotateContent||!d||d==="any")return;const y=d.includes("portrait"),s=I.isPortrait;return y===s?void 0:{transform:`rotate(${y?90:-90}deg)`,transformOrigin:"center center",width:y?I.height:I.width,height:y?I.width:I.height}},[l.autoRotateContent,d,I]),T=l.showRotationPrompt&&d!==null&&d!=="any"&&!U.isSupported,O=["nice-orientation",`nice-orientation--${E}`,d&&`nice-orientation--locked-${d}`,!U.isSupported&&"nice-orientation--unsupported",i].filter(Boolean).join(" ");return t.jsx(Fe.Provider,{value:D,children:t.jsxs("div",{className:O,style:P(),"data-orientation":E,"data-locked":d||void 0,children:[G,T&&t.jsx("div",{className:"nice-orientation__prompt",children:R||t.jsxs("div",{className:"nice-orientation__prompt-content",children:[t.jsx("div",{className:"nice-orientation__prompt-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--device","aria-hidden":"true"})}),t.jsxs("p",{className:"nice-orientation__prompt-text",children:["Please rotate your device to"," ",d!=null&&d.includes("portrait")?"portrait":"landscape"," mode"]})]})})]})})}),{displayName:"NiceOrientationLock"}),qe=$e;process.env.NODE_ENV!=="production"&&(qe.displayName="NiceOrientationLockProvider");const Ue=e.createContext(null),Tt=()=>{const n=e.useContext(Ue);if(!n)throw new Error("useRemoteManagement must be used within NiceRemoteManagementProvider");return n},Mt={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},Ve=Object.assign(e.forwardRef((n,f)=>{const{config:h,onConnectionChange:k,onCommandReceived:g,onCustomCommand:N,onCaptureScreenshot:R,children:G}=n,i={...Mt,...h},l=e.useRef(null),b=e.useRef(null),E=e.useRef(null),v=e.useRef([]),d=e.useRef(Date.now()),p=e.useRef(0),[I,B]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),q=e.useCallback(()=>{const s=typeof navigator<"u"?navigator:null,r=typeof window<"u"?window:null;return{deviceId:i.deviceId,name:i.deviceName||i.deviceId,type:"embedded-display",os:s==null?void 0:s.platform,browser:s==null?void 0:s.userAgent,resolution:r?`${r.screen.width}x${r.screen.height}`:void 0,uptime:Math.floor((Date.now()-d.current)/1e3),metadata:{}}},[i.deviceId,i.deviceName]),z=e.useCallback(async()=>{const s={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const r=performance.memory;r&&(s.memory=Math.round(r.usedJSHeapSize/r.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const r=await navigator.getBattery();s.battery=Math.round(r.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const r=await navigator.storage.estimate();r.quota&&r.usage&&(s.storageFree=r.quota-r.usage)}catch{}return s},[]),Y=e.useRef({enabled:i.enableScreenshot,capture:R});e.useEffect(()=>{Y.current={enabled:i.enableScreenshot,capture:R}});const K=e.useCallback(async()=>{const{enabled:s,capture:r}=Y.current;if(!s)throw new Error("Screenshots are disabled on this device (enableScreenshot: false)");if(!r)throw new Error("This device cannot take screenshots: no onCaptureScreenshot handler");const a=await r();if(!a)throw new Error("The screenshot handler returned no image");return a},[]),F=e.useCallback(()=>K().catch(()=>{}),[K]),W=e.useRef({onConnectionChange:k,onCommandReceived:g,onCustomCommand:N});e.useEffect(()=>{W.current={onConnectionChange:k,onCommandReceived:g,onCustomCommand:N}});const j=e.useCallback(async()=>{var s,r,a,c,o;if(((s=l.current)==null?void 0:s.readyState)!==WebSocket.OPEN){B(S=>({...S,status:"connecting"})),(a=(r=W.current).onConnectionChange)==null||a.call(r,"connecting");try{const S=new URL(i.serverUrl);S.searchParams.set("deviceId",i.deviceId),i.apiKey&&S.searchParams.set("apiKey",i.apiKey);const A=new WebSocket(S.toString());l.current=A,A.onopen=()=>{var m,w;p.current=0,B(u=>({...u,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),(w=(m=W.current).onConnectionChange)==null||w.call(m,"connected"),A.send(JSON.stringify({type:"register",payload:q()}))},A.onmessage=async m=>{var w,u;try{const C=JSON.parse(m.data);if(C.type==="command"){const x={id:C.id,type:C.commandType,payload:C.payload,timestamp:new Date,acknowledged:!0,executed:!1};B(M=>({...M,pendingCommands:[...M.pendingCommands,x]})),(u=(w=W.current).onCommandReceived)==null||u.call(w,x);let H,_;try{switch(x.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":H=await K();break;case"logs":H=v.current;break;case"custom":W.current.onCustomCommand&&(H=await W.current.onCustomCommand(x));break}x.executed=!0,x.result=H}catch(M){_=M instanceof Error?M.message:String(M),x.error=_}A.send(JSON.stringify({type:"commandResult",commandId:x.id,result:H,error:_})),B(M=>({...M,pendingCommands:M.pendingCommands.filter(L=>L.id!==x.id),commandHistory:[...M.commandHistory.slice(-49),x]}))}}catch{}},A.onerror=()=>{l.current===A&&B(m=>({...m,status:"error",error:"WebSocket error"}))},A.onclose=()=>{var m,w;l.current===A&&(l.current=null,B(u=>({...u,status:"disconnected",isConnected:!1})),p.current<i.maxReconnectAttempts&&setTimeout(()=>{p.current>=i.maxReconnectAttempts||(p.current+=1,B(u=>({...u,reconnectAttempts:p.current})),j())},i.reconnectDelay),(w=(m=W.current).onConnectionChange)==null||w.call(m,"disconnected"))}}catch(S){B(A=>({...A,status:"error",error:S instanceof Error?S.message:"Connection failed"})),(o=(c=W.current).onConnectionChange)==null||o.call(c,"error")}}},[i.serverUrl,i.deviceId,i.apiKey,i.maxReconnectAttempts,i.reconnectDelay,q,K]),U=e.useCallback(()=>{p.current=i.maxReconnectAttempts,l.current&&(l.current.close(),l.current=null),B(s=>({...s,status:"disconnected",isConnected:!1,reconnectAttempts:i.maxReconnectAttempts}))},[i.maxReconnectAttempts]),D=e.useCallback(async()=>{var s;((s=l.current)==null?void 0:s.readyState)===WebSocket.OPEN&&(l.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:i.deviceId})),B(r=>({...r,lastHeartbeat:new Date})))},[i.deviceId]),P=e.useCallback(async s=>{var a;if(((a=l.current)==null?void 0:a.readyState)!==WebSocket.OPEN)return;const r=s||await z();l.current.send(JSON.stringify({type:"health",metrics:r,deviceId:i.deviceId})),B(c=>({...c,healthMetrics:r}))},[i.deviceId,z]),T=e.useCallback(async(s,r,a)=>{var c;((c=l.current)==null?void 0:c.readyState)===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"commandResult",commandId:s,result:r,error:a}))},[]),O=e.useCallback((s,r,a)=>{var o;const c={level:s,message:r,data:a,timestamp:new Date};v.current=[...v.current.slice(-(i.logBufferSize-1)),c],i.enableLogs&&((o=l.current)==null?void 0:o.readyState)===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"log",...c,deviceId:i.deviceId}))},[i.deviceId,i.enableLogs,i.logBufferSize]);e.useEffect(()=>(p.current=0,j(),()=>{U(),b.current&&clearInterval(b.current),E.current&&clearInterval(E.current)}),[]),e.useEffect(()=>{if(I.isConnected)return b.current=setInterval(D,i.heartbeatInterval),()=>{b.current&&clearInterval(b.current)}},[I.isConnected,i.heartbeatInterval,D]),e.useEffect(()=>{if(!(!I.isConnected||!i.enableHealthMonitoring))return E.current=setInterval(()=>{P()},i.healthReportInterval),P(),()=>{E.current&&clearInterval(E.current)}},[I.isConnected,i.enableHealthMonitoring,i.healthReportInterval,P]),e.useImperativeHandle(f,()=>({getState:()=>I,connect:j,disconnect:U,sendHeartbeat:D,sendHealthMetrics:P,reportCommandResult:T,sendLog:O,captureScreenshot:F,getDeviceInfo:q}),[I,j,U,D,P,T,O,F,q]);const y={...I,deviceInfo:q(),connect:j,disconnect:U,sendLog:O};return t.jsx(Ue.Provider,{value:y,children:G})}),{displayName:"NiceRemoteManagement"}),He=Ve;process.env.NODE_ENV!=="production"&&(He.displayName="NiceRemoteManagementProvider");const Ft={modes:["pixel-shift","dimming"],inactivityTimeout:300*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--nice-text-primary, #000000)","var(--nice-text, #111111)","var(--nice-bg, #0a0a0a)"],interval:3e4,transitionDuration:1e3},dimming:{level:.3,fadeDuration:2e3},screensaver:{type:"blank"},staticDetectionThreshold:3e4,autoDetectStatic:!1},Bt=Object.assign(e.forwardRef((n,f)=>{var S,A,m,w,u,C;const{config:h,enabled:k=!0,onActivate:g,onDeactivate:N,onModeChange:R,children:G}=n,i={...Ft,...h},l=e.useRef(null),b=e.useRef(null),E=e.useRef(null),v=e.useRef(null),[d,p]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[I,B]=e.useState(0),[q,z]=e.useState({x:50,y:50,dx:1,dy:1}),Y=e.useCallback(()=>{if(!i.pixelShift)return;const{maxShift:x}=i.pixelShift,H=Math.floor(Math.random()*(x*2+1))-x,_=Math.floor(Math.random()*(x*2+1))-x;p(M=>({...M,shiftX:H,shiftY:_}))},[i.pixelShift]),K=e.useCallback(()=>{!i.pixelShift||E.current||(Y(),E.current=setInterval(Y,i.pixelShift.interval))},[i.pixelShift,Y]),F=e.useCallback(()=>{E.current&&(clearInterval(E.current),E.current=null),p(x=>({...x,shiftX:0,shiftY:0}))},[]),W=e.useCallback(()=>{!i.colorCycle||v.current||(v.current=setInterval(()=>{B(x=>{var H;return(x+1)%(((H=i.colorCycle)==null?void 0:H.colors.length)||1)})},i.colorCycle.interval))},[i.colorCycle]),j=e.useCallback(()=>{v.current&&(clearInterval(v.current),v.current=null),B(0)},[]),U=e.useCallback(()=>{if(!k||d.isActive)return;const x=i.modes;p(H=>({...H,isActive:!0,activeModes:x})),x.includes("pixel-shift")&&K(),x.includes("color-cycling")&&W(),x.includes("dimming")&&p(H=>({...H,isDimmed:!0})),x.includes("screensaver")&&p(H=>({...H,isScreensaverActive:!0})),g==null||g(),R==null||R(x)},[k,d.isActive,i.modes,K,W,g,R]),D=e.useCallback(()=>{d.isActive&&(F(),j(),p(x=>({...x,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),N==null||N(),R==null||R([]))},[d.isActive,F,j,N,R]),P=e.useCallback(()=>{d.isActive?D():U()},[d.isActive,U,D]),T=e.useCallback(()=>{b.current&&clearTimeout(b.current),d.isActive&&D(),k&&i.inactivityTimeout>0&&(b.current=setTimeout(()=>{U()},i.inactivityTimeout))},[k,d.isActive,i.inactivityTimeout,U,D]),O=e.useCallback(()=>{p(x=>({...x,isScreensaverActive:!0}))},[]),y=e.useCallback(()=>{p(x=>({...x,isScreensaverActive:!1})),T()},[T]),s=e.useCallback(x=>{p(H=>({...H,isDimmed:x>0}))},[]);e.useEffect(()=>{var H;if(!d.isScreensaverActive||((H=i.screensaver)==null?void 0:H.type)!=="bounce")return;const x=setInterval(()=>{z(_=>{let{x:M,y:L,dx:X,dy:$}=_;return M+=X*.5,L+=$*.5,(M<=0||M>=90)&&(X=-X),(L<=0||L>=90)&&($=-$),{x:M,y:L,dx:X,dy:$}})},50);return()=>clearInterval(x)},[d.isScreensaverActive,(S=i.screensaver)==null?void 0:S.type]),e.useEffect(()=>{if(!k)return;const x=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],H=()=>{T()};for(const _ of x)document.addEventListener(_,H);return T(),()=>{for(const _ of x)document.removeEventListener(_,H);b.current&&clearTimeout(b.current),F(),j()}},[k,T,F,j]),e.useImperativeHandle(f,()=>({getState:()=>d,activate:U,deactivate:D,toggle:P,resetIdleTimer:T,forceShift:Y,showScreensaver:O,hideScreensaver:y,setDimLevel:s}),[d,U,D,P,T,Y,O,y,s]);const r=()=>{if(!d.isScreensaverActive)return null;const x=i.screensaver||{type:"blank"};switch(x.type){case"blank":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:y,onTouchStart:y});case"bounce":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:y,onTouchStart:y,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${q.x}%`,top:`${q.y}%`},children:t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"1em",height:"1em",background:"currentColor",clipPath:"polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0% 50%)"}})})});case"matrix":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--matrix",onClick:y,onTouchStart:y,children:Array.from({length:20}).map((H,_)=>t.jsx("div",{className:"nice-sbp__matrix-column",style:{left:`${_*5}%`,animationDelay:`${Math.random()*5}s`,animationDuration:`${5+Math.random()*5}s`},children:Array.from({length:20}).map((M,L)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},L))},_))});case"noise":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:y,onTouchStart:y});case"custom":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:y,onTouchStart:y,children:x.component});default:return null}},a={transform:d.isActive&&i.modes.includes("pixel-shift")?`translate(${d.shiftX}px, ${d.shiftY}px)`:void 0,transition:(A=i.pixelShift)!=null&&A.smooth?"transform 0.5s ease":void 0},c={"--dim-level":d.isDimmed?((m=i.dimming)==null?void 0:m.level)||.3:0,"--dim-duration":`${((w=i.dimming)==null?void 0:w.fadeDuration)||2e3}ms`},o=d.isActive&&i.modes.includes("color-cycling")?{backgroundColor:(u=i.colorCycle)==null?void 0:u.colors[I],transition:`background-color ${((C=i.colorCycle)==null?void 0:C.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:l,className:`nice-sbp ${d.isActive?"nice-sbp--active":""}`,style:{...o},children:[t.jsx("div",{className:"nice-sbp__content",style:a,children:G}),d.isDimmed&&t.jsx("div",{className:"nice-sbp__dim-overlay",style:c,onClick:T,onTouchStart:T}),r(),d.isActive&&i.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})}),{displayName:"NiceScreenBurnPrevention"}),$t={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},qt=n=>({4:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:90,targetY:90},{targetX:10,targetY:90}],5:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:50,targetY:50},{targetX:10,targetY:90},{targetX:90,targetY:90}],9:[{targetX:10,targetY:10},{targetX:50,targetY:10},{targetX:90,targetY:10},{targetX:10,targetY:50},{targetX:50,targetY:50},{targetX:90,targetY:50},{targetX:10,targetY:90},{targetX:50,targetY:90},{targetX:90,targetY:90}]})[n],Ut=Object.assign(e.forwardRef((n,f)=>{const{config:h,autoStart:k=!1,onStart:g,onPointCalibrated:N,onComplete:R,onCancel:G,children:i}=n,l={...$t,...h},b=e.useRef(null),E=e.useRef(null),[v,d]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:l.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),p=e.useCallback(P=>{const T=P.filter(L=>L.calibrated&&L.actualX!==void 0&&L.actualY!==void 0);if(T.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let O=0,y=0,s=0,r=0;const a=T.length;for(const L of T)O+=L.targetX,y+=L.targetY,s+=L.actualX,r+=L.actualY;const c=O/a,o=y/a,S=s/a,A=r/a;let m=0,w=0,u=0,C=0;for(const L of T){const X=L.targetX-c,$=L.targetY-o,Z=L.actualX-S,J=L.actualY-A;m+=X*X,w+=X*Z,u+=$*$,C+=$*J}const x=w!==0?m/w:1,H=C!==0?u/C:1,_=c-x*S,M=o-H*A;return{scaleX:x,scaleY:H,offsetX:_,offsetY:M,rotation:0}},[]),I=e.useCallback((P,T)=>{const O=P.filter(s=>s.calibrated);if(O.length===0)return 0;let y=0;for(const s of O){if(s.actualX===void 0||s.actualY===void 0)continue;const r=T.scaleX*s.actualX+T.offsetX,a=T.scaleY*s.actualY+T.offsetY,c=s.targetX-r,o=s.targetY-a;y+=Math.sqrt(c*c+o*o)}return y/O.length},[]),B=e.useCallback(()=>{const T=qt(l.pointCount).map(O=>({...O,calibrated:!1}));d({isActive:!0,currentPointIndex:0,totalPoints:l.pointCount,points:T,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),g==null||g()},[l.pointCount,g]),q=e.useCallback(()=>{E.current&&clearTimeout(E.current),d(P=>({...P,isActive:!1,isCompleted:!1})),G==null||G()},[G]),z=e.useCallback(()=>{d(P=>({...P,isCompleted:!1}))},[]),Y=e.useCallback(()=>{if(l.persistCalibration)try{localStorage.removeItem(l.storageKey)}catch{}d({isActive:!1,currentPointIndex:0,totalPoints:l.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[l.persistCalibration,l.storageKey,l.pointCount]),K=e.useCallback(P=>{const T=p(P),O=I(P,T),y=O<=l.accuracyThreshold;if(l.persistCalibration&&y)try{localStorage.setItem(l.storageKey,JSON.stringify({matrix:T,points:P}))}catch{}d(s=>({...s,points:P,isActive:!1,isCompleted:!0,isSuccessful:y,matrix:T,averageError:O})),R==null||R(T,y)},[l.accuracyThreshold,l.persistCalibration,l.storageKey,p,I,R]),F=e.useCallback(P=>{if(!v.isActive||!b.current)return;P.preventDefault();const T=b.current.getBoundingClientRect();let O,y;"touches"in P?(O=P.touches[0].clientX,y=P.touches[0].clientY):(O=P.clientX,y=P.clientY);const s=(O-T.left)/T.width*100,r=(y-T.top)/T.height*100,a=v.currentPointIndex,c=[...v.points];c[a]={...c[a],actualX:s,actualY:r,calibrated:!0};const o=a+1;N==null||N(c[a],a),o>=v.totalPoints?K(c):d(S=>({...S,currentPointIndex:o,points:c}))},[v.isActive,v.currentPointIndex,v.points,v.totalPoints,K,N]),W=e.useCallback((P,T)=>{const O=v.matrix;return O?{x:O.scaleX*P+O.offsetX,y:O.scaleY*T+O.offsetY}:{x:P,y:T}},[v.matrix]),j=e.useCallback(()=>{if(v.matrix)return!0;if(l.persistCalibration)try{return!!localStorage.getItem(l.storageKey)}catch{return!1}return!1},[v.matrix,l.persistCalibration,l.storageKey]),U=e.useCallback(()=>{if(l.persistCalibration)try{localStorage.removeItem(l.storageKey)}catch{}d(P=>({...P,matrix:null}))},[l.persistCalibration,l.storageKey]);if(e.useEffect(()=>{if(l.persistCalibration)try{const P=localStorage.getItem(l.storageKey);if(P){const T=JSON.parse(P);d(O=>({...O,matrix:T.matrix,points:T.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[l.persistCalibration,l.storageKey]),e.useEffect(()=>{if(!v.isActive)return;const P=b.current;if(P)return P.addEventListener("touchstart",F,{passive:!1}),P.addEventListener("mousedown",F),()=>{P.removeEventListener("touchstart",F),P.removeEventListener("mousedown",F)}},[v.isActive,F]),e.useEffect(()=>{if(!(!v.isActive||l.pointTimeout<=0))return E.current=setTimeout(()=>{v.currentPointIndex<v.totalPoints-1?d(P=>({...P,currentPointIndex:P.currentPointIndex+1})):K(v.points)},l.pointTimeout),()=>{E.current&&clearTimeout(E.current)}},[v.isActive,v.currentPointIndex,v.points,v.totalPoints,l.pointTimeout,K]),e.useEffect(()=>{k&&!j()&&B()},[k,j,B]),e.useImperativeHandle(f,()=>({getState:()=>v,start:B,cancel:q,reset:Y,getMatrix:()=>v.matrix,transformPoint:W,hasCalibration:j,clearCalibration:U}),[v,B,q,Y,W,j,U]),!v.isActive&&!v.isCompleted)return t.jsx(t.Fragment,{children:i});const D=v.isActive?v.points[v.currentPointIndex]:void 0;return t.jsxs("div",{ref:b,className:"nice-touch-calibration",children:[t.jsxs("div",{className:"nice-touch-calibration__overlay",children:[t.jsxs("div",{className:"nice-touch-calibration__instructions",children:[t.jsx("h2",{className:"nice-touch-calibration__title",children:"Touch Screen Calibration"}),t.jsx("p",{className:"nice-touch-calibration__text",children:"Touch the center of each target to calibrate your screen."}),t.jsxs("div",{className:"nice-touch-calibration__progress",children:["Point ",v.currentPointIndex+1," of ",v.totalPoints]})]}),D&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${D.targetX}%`,top:`${D.targetY}%`,width:l.targetSize,height:l.targetSize},children:(h==null?void 0:h.targetComponent)||t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"nice-touch-calibration__target-outer"}),t.jsx("div",{className:"nice-touch-calibration__target-inner"}),t.jsx("div",{className:"nice-touch-calibration__target-center"})]})}),v.points.map((P,T)=>P.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${P.actualX}%`,top:`${P.actualY}%`}},T)),v.isActive&&t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:q,children:"Cancel"})]}),v.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${v.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:t.jsx("span",{className:`nice-platform-mark nice-platform-mark--${v.isSuccessful?"check":"alert"}`,"aria-hidden":"true"})}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:v.isSuccessful?"Calibration Complete":"Calibration Failed"}),l.showAccuracy&&t.jsxs("p",{className:"nice-touch-calibration__result-accuracy",children:["Average error: ",v.averageError.toFixed(1),"px"]}),!v.isSuccessful&&l.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:B,children:"Retry Calibration"}),t.jsx("button",{className:"nice-touch-calibration__retry nice-touch-calibration__done",onClick:z,children:"Done"})]})]})}),{displayName:"NiceTouchCalibration"}),Vt={format:"code128",width:2,height:100,displayValue:!0,font:"monospace",fontSize:14,textAlign:"center",textPosition:"bottom",textMargin:2,background:"#ffffff",lineColor:"#000000",margin:10,flat:!1},ve=104,Ht=106,Wt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",le=["11011001100","11001101100","11001100110","10010011000","10010001100","10001001100","10011001000","10011000100","10001100100","11001001000","11001000100","11000100100","10110011100","10011011100","10011001110","10111001100","10011101100","10011100110","11001110010","11001011100","11001001110","11011100100","11001110100","11101101110","11101001100","11100101100","11100100110","11101100100","11100110100","11100110010","11011011000","11011000110","11000110110","10100011000","10001011000","10001000110","10110001000","10001101000","10001100010","11010001000","11000101000","11000100010","10110111000","10110001110","10001101110","10111011000","10111000110","10001110110","11101110110","11010001110","11000101110","11011101000","11011100010","11011101110","11101011000","11101000110","11100010110","11101101000","11101100010","11100011010","11101111010","11001000010","11110001010","10100110000","10100001100","10010110000","10010000110","10000101100","10000100110","10110010000","10110000100","10011010000","10011000010","10000110100","10000110010","11000010010","11001010000","11110111010","11000010100","10001111010","10100111100","10010111100","10010011110","10111100100","10011110100","10011110010","11110100100","11110010100","11110010010","11011011110","11011110110","11110110110","10101111000","10100011110","10001011110","10111101000","10111100010","11110101000","11110100010","10111011110","10111101110","11101011110","11110101110","11010000100","11010010000","11010011100","1100011101011"],xe=n=>{let f=le[ve],h=ve;for(let k=0;k<n.length;k++){const g=n[k],N=Wt.indexOf(g);N!==-1&&(f+=le[N],h+=N*(k+1))}return h=h%103,f+=le[h],f+=le[Ht],f},We=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],zt=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],ze=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],Gt=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],Yt=n=>{let f=0;for(let h=0;h<12;h++)f+=parseInt(n[h])*(h%2===0?1:3);return(10-f%10)%10},Xt=n=>{let f=n.replace(/\D/g,"").slice(0,12).padStart(12,"0");const h=Yt(f);f+=h;const k=parseInt(f[0]),g=Gt[k];let N="101";for(let R=1;R<=6;R++){const G=parseInt(f[R]);N+=g[R-1]==="L"?We[G]:zt[G]}N+="01010";for(let R=7;R<=12;R++){const G=parseInt(f[R]);N+=ze[G]}return N+="101",N},Kt=n=>{let f=n.replace(/\D/g,"").slice(0,7).padStart(7,"0"),h=0;for(let N=0;N<7;N++)h+=parseInt(f[N])*(N%2===0?3:1);const k=(10-h%10)%10;f+=k;let g="101";for(let N=0;N<4;N++)g+=We[parseInt(f[N])];g+="01010";for(let N=4;N<8;N++)g+=ze[parseInt(f[N])];return g+="101",g},Qt={0:"101001101101",1:"110100101011",2:"101100101011",3:"110110010101",4:"101001101011",5:"110100110101",6:"101100110101",7:"101001011011",8:"110100101101",9:"101100101101",A:"110101001011",B:"101101001011",C:"110110100101",D:"101011001011",E:"110101100101",F:"101101100101",G:"101010011011",H:"110101001101",I:"101101001101",J:"101011001101",K:"110101010011",L:"101101010011",M:"110110101001",N:"101011010011",O:"110101101001",P:"101101101001",Q:"101010110011",R:"110101011001",S:"101101011001",T:"101011011001",U:"110010101011",V:"100110101011",W:"110011010101",X:"100101101011",Y:"110010110101",Z:"100110110101","-":"100101011011",".":"110010101101"," ":"100110101101",$:"100100100101","/":"100100101001","+":"100101001001","%":"101001001001","*":"100101101101"},Jt=n=>{const f=("*"+n.toUpperCase()+"*").split("");let h="";for(const k of f){const g=Qt[k];g&&(h+=g+"0")}return h.slice(0,-1)},Ce=n=>{switch(n){case"code128":return xe;case"code39":case"code93":return Jt;case"ean13":return Xt;case"ean8":return Kt;default:return xe}},Zt=Object.assign(e.forwardRef((n,f)=>{const{value:h,options:k,onGenerate:g,onError:N,showBorder:R=!1,className:G}=n,i={...Vt,...k},l=e.useRef(null),b=e.useRef(null),[E,v]=e.useState(null),[d,p]=e.useState(null),I=e.useCallback(()=>{if(!l.current||!h)return;const W=l.current,j=W.getContext("2d");if(j)try{const D=Ce(i.format)(h),P=i.width,T=D.length*P,O=i.marginTop??i.margin,y=i.marginBottom??i.margin,s=i.marginLeft??i.margin,r=i.marginRight??i.margin,a=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,c=T+s+r,o=i.height+O+y+a;W.width=c,W.height=o,j.fillStyle=i.background,j.fillRect(0,0,c,o),j.fillStyle=i.lineColor;let S=s;const A=i.textPosition==="top"&&i.displayValue?O+a:O;for(let w=0;w<D.length;w++)D[w]==="1"&&j.fillRect(S,A,P,i.height),S+=P;if(i.displayValue&&!i.flat){j.fillStyle=i.lineColor,j.font=`${i.fontSize}px ${i.font}`,j.textBaseline=i.textPosition==="top"?"top":"bottom";let w=s;i.textAlign==="center"?(w=s+T/2,j.textAlign="center"):i.textAlign==="right"?(w=s+T,j.textAlign="right"):j.textAlign="left";const u=i.textPosition==="top"?O+i.textMargin:o-y-i.textMargin;j.fillText(h,w,u)}const m=W.toDataURL("image/png");p(m),v(null),g==null||g(m)}catch(U){const D=U instanceof Error?U.message:"Failed to generate barcode";v(D),N==null||N(new Error(D))}},[h,i,g,N]);e.useEffect(()=>{I()},[I]);const B=e.useCallback((W="image/png",j=1)=>{var U;return((U=l.current)==null?void 0:U.toDataURL(W,j))||null},[]),q=e.useCallback(()=>{if(!l.current||!h)return null;try{const j=Ce(i.format)(h),U=i.width,D=i.marginTop??i.margin,P=i.marginBottom??i.margin,T=i.marginLeft??i.margin,O=i.marginRight??i.margin,y=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,s=j.length*U,r=s+T+O,a=i.height+D+P+y,c=[];let o=T;const S=i.textPosition==="top"&&i.displayValue?D+y:D;for(let m=0;m<j.length;m++)j[m]==="1"&&c.push(`<rect x="${o}" y="${S}" width="${U}" height="${i.height}" fill="${i.lineColor}"/>`),o+=U;let A="";if(i.displayValue&&!i.flat){const m=i.textAlign==="center"?"middle":i.textAlign==="right"?"end":"start";let w=T;i.textAlign==="center"?w=T+s/2:i.textAlign==="right"&&(w=T+s);const u=i.textPosition==="top"?D+i.fontSize:a-P-i.textMargin;A=`<text x="${w}" y="${u}" font-family="${i.font}" font-size="${i.fontSize}" text-anchor="${m}" fill="${i.lineColor}">${h}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${a}" viewBox="0 0 ${r} ${a}">
|
|
2
|
-
<rect width="100%" height="100%" fill="${
|
|
3
|
-
${
|
|
1
|
+
"use strict";var Ct=Object.defineProperty;var kt=(s,g,c)=>g in s?Ct(s,g,{enumerable:!0,configurable:!0,writable:!0,value:c}):s[g]=c;var ue=(s,g,c)=>kt(s,typeof g!="symbol"?g+"":g,c);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),ae=require("@nice2dev/ui-core"),e=require("react"),fe=e.createContext(null),St=()=>{const s=e.useContext(fe);if(!s)throw new Error("useAutoStart must be used within NiceAutoStartProvider");return s},Nt={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},De=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{tasks:w=[],config:N,splash:x,errorScreen:A,onComplete:G,onTaskComplete:C,onError:D,onRecovery:a,children:y}=s,E={...Nt,...N},f=e.useRef(0),m=e.useRef(w),I=e.useRef(null),[F,B]=e.useState(E.showSplash),[$,Y]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:w.length,results:[],recoveryAttempt:0,totalDuration:0}),H=e.useCallback(async r=>{const d=Date.now();let n=0;const l=async()=>{try{const o=r.timeout||E.globalTimeout,h=new Promise((v,b)=>{setTimeout(()=>b(new Error("Task timeout")),o)});return await Promise.race([r.execute(),h]),{taskId:r.id,success:!0,duration:Date.now()-d,retriesUsed:n}}catch(o){const h=r.retries??0;return n<h?(n++,await new Promise(v=>setTimeout(v,500)),l()):{taskId:r.id,success:!1,error:o instanceof Error?o:new Error(String(o)),duration:Date.now()-d,retriesUsed:n}}};return l()},[E.globalTimeout]),X=e.useCallback(r=>{const d=[],n=[...r],l=new Set;for(;n.length>0;){const o=n.filter(v=>v.dependencies?v.dependencies.every(b=>l.has(b)):!0);if(o.length===0){d.push(...n);break}o.sort((v,b)=>(b.priority??0)-(v.priority??0));const h=o[0];d.push(h),l.add(h.id),n.splice(n.indexOf(h),1)}return d},[]),O=e.useCallback(async()=>{f.current=Date.now();const r=new AbortController;I.current=r;const d=X(m.current),n=[];Y(o=>({...o,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:d.length,results:[]}));for(let o=0;o<d.length;o++){if(r.signal.aborted)return;const h=d[o];Y(b=>({...b,currentTask:h.name,progress:Math.round(o/d.length*100)}));const v=await H(h);if(r.signal.aborted)return;if(n.push(v),Y(b=>({...b,completedTasks:o+1,results:[...b.results,v]})),C==null||C(v),!v.success&&h.critical){const b=v.error||new Error("Critical task failed");D==null||D(b,h.id),Y(k=>({...k,phase:"error",isLoading:!1,hasError:!0,errorMessage:b.message}));return}}const l=Date.now()-f.current;if(Y(o=>({...o,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:l})),G==null||G(n),E.autoHideSplash){const o=Date.now()-f.current,h=Math.max(0,E.splashDuration-o);setTimeout(()=>{B(!1)},h)}},[X,H,E.autoHideSplash,E.splashDuration,C,D,G]),z=e.useCallback(async()=>{I.current&&I.current.abort(),Y(r=>({...r,recoveryAttempt:0})),B(E.showSplash),await O()},[E.showSplash,O]),T=e.useCallback(()=>{I.current&&I.current.abort(),Y(r=>({...r,phase:"ready",isLoading:!1,isReady:!0,progress:100})),B(!1)},[]),M=e.useCallback(()=>{B(!1)},[]),j=e.useCallback(async()=>{const r=$.recoveryAttempt+1;r>E.recoveryAttempts||(Y(d=>({...d,phase:"recovery",recoveryAttempt:r})),a==null||a(r),await new Promise(d=>setTimeout(d,E.recoveryDelay)),await O())},[$.recoveryAttempt,E.recoveryAttempts,E.recoveryDelay,a,O]),S=e.useCallback(r=>{m.current=[...m.current,r]},[]),P=e.useCallback(r=>{m.current=m.current.filter(d=>d.id!==r)},[]),W=e.useCallback(r=>$.results.find(d=>d.taskId===r),[$.results]);e.useEffect(()=>{$.hasError&&E.autoRecovery&&$.recoveryAttempt<E.recoveryAttempts&&j()},[$.hasError,E.autoRecovery,E.recoveryAttempts,$.recoveryAttempt,j]),e.useEffect(()=>(O(),()=>{I.current&&I.current.abort()}),[]),e.useImperativeHandle(g,()=>({getState:()=>$,restart:z,skip:T,addTask:S,removeTask:P,getTaskResult:W,hideSplash:M,recover:j}),[$,z,T,S,P,W,M,j]);const i={...$,restart:z,skip:T,hideSplash:M};return $.hasError&&$.recoveryAttempt>=E.recoveryAttempts?t.jsx(fe.Provider,{value:i,children:A||t.jsxs("div",{className:"nice-auto-start__error",children:[t.jsx("div",{className:"nice-auto-start__error-icon","aria-hidden":"true",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert"})}),t.jsx("h2",{className:"nice-auto-start__error-title",children:c("autoStart.startupFailed","Startup Failed")}),t.jsx("p",{className:"nice-auto-start__error-message",children:$.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:z,children:c("autoStart.retry","Retry")})]})}):F&&!$.isReady?t.jsx(fe.Provider,{value:i,children:x||t.jsx("div",{className:"nice-auto-start__splash",children:t.jsxs("div",{className:"nice-auto-start__splash-content",children:[t.jsx("div",{className:"nice-auto-start__splash-logo","aria-hidden":"true"}),t.jsx("h1",{className:"nice-auto-start__splash-title",children:c("autoStart.loading","Loading...")}),E.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${$.progress}%`}})}),E.showTaskNames&&$.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:$.currentTask}),$.phase==="recovery"&&t.jsx("div",{className:"nice-auto-start__splash-recovery",children:c("autoStart.recoveryAttemptOf","Recovery attempt {recoveryAttempt} of {recoveryAttempts}").replace("{recoveryAttempt}",String($.recoveryAttempt)).replace("{recoveryAttempts}",String(E.recoveryAttempts))})]})})}):t.jsx(fe.Provider,{value:i,children:y})}),{displayName:"NiceAutoStart"}),Ae=De;process.env.NODE_ENV!=="production"&&(Ae.displayName="NiceAutoStartProvider");const Ee=e.createContext(null),Le=()=>{const s=e.useContext(Ee);if(!s)throw new Error("useExternalDisplay must be used within NiceExternalDisplayProvider");return s},_t={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},It=()=>typeof window>"u"?!1:"getScreenDetails"in window,jt=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Dt=s=>{const g=[];return s.width!==void 0&&g.push(`width=${s.width}`),s.height!==void 0&&g.push(`height=${s.height}`),s.left!==void 0&&g.push(`left=${s.left}`),s.top!==void 0&&g.push(`top=${s.top}`),s.menubar!==void 0&&g.push(`menubar=${s.menubar?"yes":"no"}`),s.toolbar!==void 0&&g.push(`toolbar=${s.toolbar?"yes":"no"}`),s.location!==void 0&&g.push(`location=${s.location?"yes":"no"}`),s.status!==void 0&&g.push(`status=${s.status?"yes":"no"}`),s.resizable!==void 0&&g.push(`resizable=${s.resizable?"yes":"no"}`),s.scrollbars!==void 0&&g.push(`scrollbars=${s.scrollbars?"yes":"no"}`),g.join(",")},he="Primary Display";function we(s,g){if(s.id==="primary"&&s.label===he)return g("externalDisplay.primaryDisplay",he);const c=/^Display (\d+)$/.exec(s.label);return c?g("externalDisplay.displayN","Display {n}").replace("{n}",c[1]):s.label}const xe=()=>{var g;if(typeof window>"u")return{id:"primary",label:he,width:0,height:0,availWidth:0,availHeight:0,left:0,top:0,devicePixelRatio:1,isPrimary:!0,orientation:"landscape-primary",colorDepth:24};const s=window.screen;return{id:"primary",label:he,width:s.width,height:s.height,availWidth:s.availWidth,availHeight:s.availHeight,left:s.availLeft||0,top:s.availTop||0,devicePixelRatio:window.devicePixelRatio,isPrimary:!0,orientation:((g=s.orientation)==null?void 0:g.type)||"landscape-primary",colorDepth:s.colorDepth}},At=async()=>{try{return(await navigator.permissions.query({name:"window-management"})).state}catch{return"unknown"}},Ce=async()=>(await window.getScreenDetails()).screens.map((g,c)=>{var w;return{id:`screen-${c}`,label:g.label||`Display ${c+1}`,width:g.width,height:g.height,availWidth:g.availWidth,availHeight:g.availHeight,left:g.left,top:g.top,devicePixelRatio:g.devicePixelRatio,isPrimary:g.isPrimary,isInternal:g.isInternal,orientation:((w=g.orientation)==null?void 0:w.type)||"landscape-primary",colorDepth:g.colorDepth}}),ke=(s,g)=>JSON.stringify(s)===JSON.stringify(g),Pe=Object.assign(e.forwardRef((s,g)=>{const{config:c,onScreensChange:w,onWindowOpen:N,onWindowClose:x,onPermissionChange:A,children:G}=s,C={..._t,...c},D=e.useRef(new Map),a=e.useRef(null),[y,E]=e.useState([xe()]),[f,m]=e.useState([]),[I,F]=e.useState("unknown"),[B]=e.useState(It),$=e.useRef(w),Y=e.useRef(A);e.useEffect(()=>{$.current=w,Y.current=A});const H=e.useRef([]),X=e.useCallback(o=>{var h;E(v=>ke(v,o)?v:o),ke(H.current,o)||(H.current=o,(h=$.current)==null||h.call($,o))},[]),O=e.useRef("unknown"),z=e.useCallback(o=>{var h;O.current!==o&&(O.current=o,F(o),(h=Y.current)==null||h.call(Y,o))},[]),T=e.useCallback(async()=>{if(B){const h=await At();if(z(h),h==="granted")try{const v=await Ce();return X(v),v}catch{}}const o=[xe()];return X(o),o},[B,z,X]),M=e.useCallback(async()=>{if(!B)return z("denied"),!1;try{return X(await Ce()),z("granted"),!0}catch(o){return z(o instanceof DOMException&&o.name==="NotAllowedError"?"denied":"unknown"),!1}},[B,z,X]),j=e.useCallback(async(o,h="about:blank",v={})=>{if(!C.allowMultiWindow&&f.length>0)return console.warn("Multi-window mode is disabled"),null;const b=jt(),k={...C.defaultFeatures,...v,width:v.width??o.availWidth,height:v.height??o.availHeight,left:v.left??o.left,top:v.top??o.top},u=Dt(k),p={window:null,screen:o,id:b,state:"opening",isFullscreen:!1,features:k};m(R=>[...R,p]);try{const R=window.open(h,b,u);if(!R)return m(L=>L.map(q=>q.id===b?{...q,state:"error"}:q)),null;D.current.set(b,R);const K={...p,window:R,state:"open"};m(L=>L.map(q=>q.id===b?K:q));const _=setInterval(()=>{R.closed&&(clearInterval(_),D.current.delete(b),m(L=>L.filter(q=>q.id!==b)),x==null||x(K))},500);return k.fullscreen&&R.addEventListener("load",()=>{var L,q;(q=(L=R.document.documentElement).requestFullscreen)==null||q.call(L)}),N==null||N(K),K}catch(R){return console.error("Failed to open window:",R),m(K=>K.map(_=>_.id===b?{..._,state:"error"}:_)),null}},[C.allowMultiWindow,C.defaultFeatures,f.length,N,x]),S=e.useCallback(o=>{const h=D.current.get(o);h&&!h.closed&&h.close(),D.current.delete(o),m(v=>v.filter(b=>b.id!==o))},[]),P=e.useCallback(()=>{for(const[o,h]of D.current)h.closed||h.close(),D.current.delete(o);m([])},[]),W=e.useCallback((o,h)=>{const v=D.current.get(o);v&&!v.closed&&(v.moveTo(h.left,h.top),v.resizeTo(h.availWidth,h.availHeight),m(b=>b.map(k=>k.id===o?{...k,screen:h}:k)))},[]),i=e.useCallback(async o=>{const h=D.current.get(o);if(!h||h.closed)return!1;try{const v=!!h.document.fullscreenElement;return v?await h.document.exitFullscreen():await h.document.documentElement.requestFullscreen(),m(b=>b.map(k=>k.id===o?{...k,isFullscreen:!v}:k)),!0}catch{return!1}},[]),r=e.useCallback((o,h)=>{const v=D.current.get(o);v&&!v.closed&&v.postMessage(h,"*")},[]),d=e.useCallback(o=>{for(const h of D.current.values())h.closed||h.postMessage(o,"*")},[]);e.useEffect(()=>{C.autoDetect&&T()},[C.autoDetect,T]),e.useEffect(()=>(C.autoDetect&&C.pollInterval>0&&(a.current=setInterval(T,C.pollInterval)),()=>{a.current&&clearInterval(a.current)}),[C.autoDetect,C.pollInterval,T]),e.useEffect(()=>{if(!B)return;const o=()=>{T()};return window.addEventListener("screenschange",o),()=>{window.removeEventListener("screenschange",o)}},[B,T]),e.useEffect(()=>()=>{P()},[P]);const n=e.useMemo(()=>({screens:y,primaryScreen:y.find(o=>o.isPrimary)||null,externalScreens:y.filter(o=>!o.isPrimary),windows:f,isApiAvailable:B,permissionState:I}),[y,f,B,I]);e.useImperativeHandle(g,()=>({getState:()=>n,requestPermission:M,getScreens:T,openWindow:j,closeWindow:S,closeAllWindows:P,moveWindowToScreen:W,toggleFullscreen:i,sendMessage:r,broadcast:d}),[n,M,T,j,S,P,W,i,r,d]);const l={...n,requestPermission:M,openWindow:j,closeWindow:S,moveWindowToScreen:W};return t.jsx(Ee.Provider,{value:l,children:t.jsx("div",{className:"nice-external-display",children:G})})}),{displayName:"NiceExternalDisplay"}),Re=Pe;process.env.NODE_ENV!=="production"&&(Re.displayName="NiceExternalDisplayProvider");const Oe=({onSelect:s,selectedId:g,showPreview:c=!0,className:w})=>{const{t:N}=ae.useNiceTranslation(),{screens:x,primaryScreen:A}=Le(),G=y=>{s==null||s(y)},D=(()=>{let y=0,E=0,f=0,m=0;for(const I of x)y=Math.min(y,I.left),E=Math.min(E,I.top),f=Math.max(f,I.left+I.width),m=Math.max(m,I.top+I.height);return{minX:y,minY:E,maxX:f,maxY:m,width:f-y,height:m-E}})(),a=Math.min(280/D.width,160/D.height,1);return t.jsxs("div",{className:`nice-screen-selector ${w||""}`,children:[c&&t.jsx("div",{className:"nice-screen-selector__preview",style:{width:D.width*a,height:D.height*a},children:x.map(y=>t.jsx("button",{className:`nice-screen-selector__screen ${g===y.id?"nice-screen-selector__screen--selected":""} ${y.isPrimary?"nice-screen-selector__screen--primary":""}`,style:{left:(y.left-D.minX)*a,top:(y.top-D.minY)*a,width:y.width*a,height:y.height*a},onClick:()=>G(y),title:we(y,N),children:t.jsx("span",{className:"nice-screen-selector__screen-label",children:y.isPrimary?"P":x.indexOf(y)+1})},y.id))}),t.jsx("div",{className:"nice-screen-selector__list",children:x.map(y=>t.jsxs("button",{className:`nice-screen-selector__item ${g===y.id?"nice-screen-selector__item--selected":""}`,onClick:()=>G(y),children:[t.jsx("span",{className:"nice-screen-selector__item-name",children:we(y,N)}),t.jsxs("span",{className:"nice-screen-selector__item-resolution",children:[y.width," × ",y.height]}),y.isPrimary&&t.jsx("span",{className:"nice-screen-selector__item-badge",children:N("externalDisplay.primary","Primary")})]},y.id))})]})};process.env.NODE_ENV!=="production"&&(Oe.displayName="NiceScreenSelector");const Te=e.createContext(null),Et=()=>{const s=e.useContext(Te);if(!s)throw new Error("useKioskMode must be used within NiceKioskModeProvider");return s},Lt={autoFullscreen:!0,lockNavigation:!0,disableContextMenu:!0,disableShortcuts:!0,disableSelection:!0,disableCopyPaste:!0,exitPin:"1234",exitShortcut:"ctrl+shift+k",adminTapCount:5,adminTapTimeout:2e3,inactivityTimeout:300*1e3,showCursor:!0,allowScrolling:!0,className:""},Me=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,children:N,screensaver:x,adminPanel:A,onModeChange:G,onFullscreenChange:C,onAdminAccess:D,onInactivity:a,onActivity:y,onExitRequest:E}=s,f={...Lt,...w},m=e.useRef(null),I=e.useRef(null),F=e.useRef({count:0,timer:null}),[B,$]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[Y,H]=e.useState(""),[X,O]=e.useState(!1),z=e.useCallback(async()=>{const u=m.current;if(u)try{u.requestFullscreen?await u.requestFullscreen():u.webkitRequestFullscreen?await u.webkitRequestFullscreen():u.msRequestFullscreen&&await u.msRequestFullscreen()}catch(p){console.warn("Failed to enter fullscreen:",p)}},[]),T=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(u){console.warn("Failed to exit fullscreen:",u)}},[]),M=e.useCallback(async()=>{B.isFullscreen?await T():await z()},[B.isFullscreen,z,T]),j=e.useCallback(()=>{$(u=>({...u,mode:"locked",isLocked:!0,isAdminMode:!1})),G==null||G("locked")},[G]),S=e.useCallback(u=>f.exitPin&&u!==f.exitPin?(O(!0),setTimeout(()=>O(!1),1e3),!1):($(p=>({...p,mode:p.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),H(""),!0),[f.exitPin]),P=e.useCallback(()=>{$(u=>({...u,isAdminMode:!0})),D==null||D()},[D]),W=e.useCallback(()=>{$(u=>({...u,isAdminMode:!1}))},[]),i=e.useCallback(()=>{F.current.timer&&clearTimeout(F.current.timer),F.current.count++,F.current.count>=f.adminTapCount?(F.current.count=0,P()):F.current.timer=setTimeout(()=>{F.current.count=0},f.adminTapTimeout)},[f.adminTapCount,f.adminTapTimeout,P]),r=e.useCallback(()=>{I.current&&clearTimeout(I.current),B.isScreensaverActive&&($(u=>({...u,isScreensaverActive:!1})),y==null||y()),f.inactivityTimeout>0&&(I.current=setTimeout(()=>{$(u=>({...u,isScreensaverActive:!0})),a==null||a()},f.inactivityTimeout))},[f.inactivityTimeout,B.isScreensaverActive,y,a]),d=e.useCallback(()=>{$(u=>({...u,isScreensaverActive:!0}))},[]),n=e.useCallback(()=>{$(u=>({...u,isScreensaverActive:!1})),r()},[r]),l=e.useCallback(()=>{$(u=>({...u,isPinDialogOpen:!0})),H(""),O(!1)},[]),o=e.useCallback(()=>{$(u=>({...u,isPinDialogOpen:!1})),H(""),O(!1)},[]),h=e.useCallback(()=>{S(Y)},[Y,S]),v=e.useCallback(u=>{u.key==="Enter"&&h()},[h]);e.useEffect(()=>{const u=()=>{const p=!!document.fullscreenElement;$(R=>({...R,mode:R.isLocked?"locked":p?"fullscreen":"windowed",isFullscreen:p})),C==null||C(p)};return document.addEventListener("fullscreenchange",u),document.addEventListener("webkitfullscreenchange",u),()=>{document.removeEventListener("fullscreenchange",u),document.removeEventListener("webkitfullscreenchange",u)}},[C]),e.useEffect(()=>{if(!f.disableContextMenu)return;const u=p=>{B.isAdminMode||p.preventDefault()};return document.addEventListener("contextmenu",u),()=>document.removeEventListener("contextmenu",u)},[f.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const u=async p=>{const K=f.exitShortcut.toLowerCase().split("+"),_=K.includes("ctrl")===p.ctrlKey,L=K.includes("shift")===p.shiftKey,q=K.includes("alt")===p.altKey,V=K.some(Q=>Q===p.key.toLowerCase());if(_&&L&&q&&V){p.preventDefault(),(E?await E("keyboard"):!0)&&(B.isLocked?l():T());return}if(f.disableShortcuts&&!B.isAdminMode){const Q=["F5","F11","F12"],te=[{ctrl:!0,key:"r"},{ctrl:!0,key:"w"},{ctrl:!0,key:"n"},{ctrl:!0,key:"t"},{ctrl:!0,shift:!0,key:"i"},{ctrl:!0,shift:!0,key:"j"},{alt:!0,key:"F4"}];if(Q.includes(p.key)){p.preventDefault();return}for(const Z of te)if(Z.ctrl===p.ctrlKey&&(Z.shift??!1)===p.shiftKey&&(Z.alt??!1)===p.altKey&&Z.key.toLowerCase()===p.key.toLowerCase()){p.preventDefault();return}}};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[f.disableShortcuts,f.exitShortcut,B.isAdminMode,B.isLocked,T,l,E]),e.useEffect(()=>{if(!f.disableCopyPaste)return;const u=R=>{B.isAdminMode||R.preventDefault()},p=R=>{B.isAdminMode||R.preventDefault()};return document.addEventListener("copy",u),document.addEventListener("paste",p),()=>{document.removeEventListener("copy",u),document.removeEventListener("paste",p)}},[f.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const u=["mousedown","mousemove","keydown","touchstart","scroll"],p=()=>{r()};for(const R of u)document.addEventListener(R,p);return r(),()=>{for(const R of u)document.removeEventListener(R,p);I.current&&clearTimeout(I.current)}},[r]),e.useEffect(()=>{if(f.autoFullscreen){const u=setTimeout(()=>{z()},100);return()=>clearTimeout(u)}},[f.autoFullscreen,z]),e.useImperativeHandle(g,()=>({getState:()=>B,enterFullscreen:z,exitFullscreen:T,toggleFullscreen:M,lock:j,unlock:S,enterAdminMode:P,exitAdminMode:W,resetIdleTimer:r,showScreensaver:d,hideScreensaver:n,openPinDialog:l,closePinDialog:o}),[B,z,T,M,j,S,P,W,r,d,n,l,o]);const b={...B,enterFullscreen:z,exitFullscreen:T,toggleFullscreen:M,lock:j,unlock:S,enterAdminMode:P,exitAdminMode:W,resetIdleTimer:r},k=["nice-kiosk-mode",`nice-kiosk-mode--${B.mode}`,B.isFullscreen&&"nice-kiosk-mode--fullscreen",!f.showCursor&&"nice-kiosk-mode--no-cursor",f.disableSelection&&"nice-kiosk-mode--no-select",!f.allowScrolling&&"nice-kiosk-mode--no-scroll",f.className].filter(Boolean).join(" ");return t.jsx(Te.Provider,{value:b,children:t.jsxs("div",{role:"presentation",ref:m,className:k,onClick:i,children:[t.jsx("div",{className:"nice-kiosk-mode__content",children:N}),B.isAdminMode&&A&&t.jsxs("div",{className:"nice-kiosk-mode__admin",children:[t.jsxs("div",{className:"nice-kiosk-mode__admin-header",children:[t.jsx("h2",{className:"nice-kiosk-mode__admin-title",children:c("kioskMode.adminMode","Admin Mode")}),t.jsx("button",{className:"nice-kiosk-mode__admin-close",onClick:W,"aria-label":c("kioskMode.closeAdminPanel","Close admin panel"),children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-kiosk-mode__admin-content",children:A})]}),B.isScreensaverActive&&t.jsx("div",{role:"presentation",className:"nice-kiosk-mode__screensaver",onClick:n,onTouchStart:n,children:x||t.jsx("div",{className:"nice-kiosk-mode__screensaver-default",children:t.jsx("div",{className:"nice-kiosk-mode__screensaver-text",children:c("kioskMode.touchToContinue","Touch to continue")})})}),B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__pin-overlay",children:t.jsxs("div",{className:"nice-kiosk-mode__pin-dialog",children:[t.jsx("h3",{className:"nice-kiosk-mode__pin-title",children:c("kioskMode.enterPin","Enter PIN")}),t.jsx("input",{type:"password",className:`nice-kiosk-mode__pin-input ${X?"nice-kiosk-mode__pin-input--error":""}`,value:Y,onChange:u=>H(u.target.value),onKeyPress:v,maxLength:8,autoFocus:!0,placeholder:"••••"}),t.jsxs("div",{className:"nice-kiosk-mode__pin-buttons",children:[t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--cancel",onClick:o,children:c("kioskMode.cancel","Cancel")}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:h,children:c("kioskMode.unlock","Unlock")})]}),X&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:c("kioskMode.incorrectPin","Incorrect PIN")})]})}),B.isLocked&&!B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__lock-indicator",children:t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:c("kioskMode.kioskLocked","Kiosk Locked")})})]})})}),{displayName:"NiceKioskMode"}),Fe=Me;process.env.NODE_ENV!=="production"&&(Fe.displayName="NiceKioskModeProvider");const Be=e.createContext(null),Pt=()=>{const s=e.useContext(Be);if(!s)throw new Error("useLowPowerMode must be used within NiceLowPowerModeProvider");return s},Rt={normal:{mode:"normal",brightness:1,wakeOnTouch:!0},dim:{mode:"dim",brightness:.6,disableAnimations:!1,wakeOnTouch:!0},low:{mode:"low",brightness:.3,frameRateCap:30,disableAnimations:!0,reduceImageQuality:!0,wakeOnTouch:!0},sleep:{mode:"sleep",brightness:0,frameRateCap:1,disableAnimations:!0,disableBackgroundProcesses:!0,reduceImageQuality:!0,wakeOnTouch:!0,wakeOnMotion:!0}},Ot={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},$e=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,onModeChange:N,onBrightnessChange:x,onSleep:A,onWake:G,onLowBattery:C,children:D}=s,a={...Ot,...w},y=JSON.stringify((w==null?void 0:w.modes)??null),E=e.useMemo(()=>({...Rt,...JSON.parse(y)}),[y]),f=e.useRef(null),m=e.useRef(null),I=e.useRef(Date.now()),F=e.useRef(null),[B,$]=e.useState({currentMode:a.initialMode,brightness:E[a.initialMode].brightness??1,isPowerSaving:a.initialMode!=="normal",isSleeping:a.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),Y=e.useRef(B);Y.current=B;const H=e.useRef({onModeChange:N,onBrightnessChange:x,onSleep:A,onWake:G});H.current={onModeChange:N,onBrightnessChange:x,onSleep:A,onWake:G};const X=e.useCallback(n=>{const l=E[n];document.documentElement.style.setProperty("--lpm-brightness",String(l.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${a.transitionDuration}ms`),l.disableAnimations?document.documentElement.classList.add("nice-lpm-no-animations"):document.documentElement.classList.remove("nice-lpm-no-animations"),l.reduceImageQuality?document.documentElement.classList.add("nice-lpm-reduced-quality"):document.documentElement.classList.remove("nice-lpm-reduced-quality")},[E,a.transitionDuration]),O=e.useCallback(n=>{$(l=>{var b,k,u,p;if(l.currentMode===n)return l;const o=l.currentMode,h=E[n];X(n);const v=H.current;return(b=v.onModeChange)==null||b.call(v,n,o),(k=v.onBrightnessChange)==null||k.call(v,h.brightness??1),n==="sleep"&&o!=="sleep"?(u=v.onSleep)==null||u.call(v):o==="sleep"&&n!=="sleep"&&((p=v.onWake)==null||p.call(v)),{...l,currentMode:n,brightness:h.brightness??1,isPowerSaving:n!=="normal",isSleeping:n==="sleep",isDisplayOn:n!=="sleep"}})},[E,X]),z=e.useCallback(n=>{const l=Math.max(0,Math.min(1,n));document.documentElement.style.setProperty("--lpm-brightness",String(l)),$(o=>({...o,brightness:l})),x==null||x(l)},[x]),T=e.useCallback(()=>{O("sleep")},[O]),M=e.useCallback(()=>{I.current=Date.now(),f.current&&clearTimeout(f.current),m.current&&clearTimeout(m.current),a.autoDimTimeout>0&&(f.current=setTimeout(()=>{Y.current.currentMode==="normal"&&O("dim")},a.autoDimTimeout)),a.autoSleepTimeout>0&&(m.current=setTimeout(()=>{O("sleep")},a.autoSleepTimeout)),$(n=>n.idleTime===0?n:{...n,idleTime:0})},[a.autoDimTimeout,a.autoSleepTimeout,O]),j=e.useCallback(()=>{Y.current.currentMode!=="normal"&&O("normal"),M()},[O,M]),S=e.useCallback(()=>{O("normal"),j()},[O,j]),P=e.useCallback(()=>{B.currentMode==="normal"?O("low"):O("normal")},[B.currentMode,O]),W=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const n=await navigator.getBattery();return{level:Math.round(n.level*100),charging:n.charging}}catch{return{}}return{}},[]),i=e.useCallback(async()=>{const n=await W();n.level!==void 0&&($(l=>({...l,batteryLevel:n.level,isCharging:n.charging})),n.charging||(n.level<=a.criticalBatteryThreshold?(O("sleep"),C==null||C(n.level)):n.level<=a.lowBatteryThreshold&&(B.currentMode==="normal"&&O("low"),C==null||C(n.level))))},[W,a.lowBatteryThreshold,a.criticalBatteryThreshold,B.currentMode,O,C]),r=e.useCallback(()=>{if(!(w!=null&&w.schedule)||w.schedule.length===0)return;const l=new Date().getHours();for(const o of w.schedule){const{startHour:h,endHour:v,mode:b}=o;let k;if(h<=v?k=l>=h&&l<v:k=l>=h||l<v,k){$(u=>({...u,scheduledModeActive:b})),B.currentMode!==b&&O(b);return}}$(o=>({...o,scheduledModeActive:void 0}))},[w==null?void 0:w.schedule,B.currentMode,O]);e.useEffect(()=>{const n=["mousedown","mousemove","keydown","touchstart","scroll"],l=()=>{a.wakeOnTouch&&j()};for(const o of n)document.addEventListener(o,l);return M(),()=>{for(const o of n)document.removeEventListener(o,l);f.current&&clearTimeout(f.current),m.current&&clearTimeout(m.current)}},[a.wakeOnTouch,j,M]),e.useEffect(()=>{i(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const l=await navigator.getBattery();F.current=l,l.addEventListener("levelchange",i),l.addEventListener("chargingchange",i)}catch{}})()},[i]),e.useEffect(()=>{r();const n=setInterval(r,6e4);return()=>clearInterval(n)},[r]),e.useEffect(()=>{X(a.initialMode)},[a.initialMode,X]),e.useImperativeHandle(g,()=>({getState:()=>B,setMode:O,setBrightness:z,sleep:T,wake:S,togglePowerSaving:P,resetIdleTimer:j,getBatteryInfo:W}),[B,O,z,T,S,P,j,W]);const d={...B,setMode:O,setBrightness:z,sleep:T,wake:S,resetIdleTimer:j};return t.jsx(Be.Provider,{value:d,children:t.jsxs("div",{className:`nice-lpm nice-lpm--${B.currentMode}`,children:[t.jsx("div",{className:"nice-lpm__overlay",style:{opacity:1-B.brightness}}),t.jsx("div",{className:"nice-lpm__content",children:D}),B.isSleeping&&t.jsx("div",{role:"presentation",className:"nice-lpm__sleep-screen",onClick:a.wakeOnTouch?S:void 0,onTouchStart:a.wakeOnTouch?S:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:c("lowPowerMode.touchToWake","Touch to wake")})})]})})}),{displayName:"NiceLowPowerMode"}),qe=$e;process.env.NODE_ENV!=="production"&&(qe.displayName="NiceLowPowerModeProvider");const Ue=e.createContext(null),Tt=()=>{const s=e.useContext(Ue);if(!s)throw new Error("useOrientationLock must be used within NiceOrientationLockProvider");return s},Mt={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},Ve=()=>{if(typeof window>"u")return"portrait";const s=window.screen;return s.orientation?s.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},Ft=()=>{if(typeof window>"u")return 0;const s=window.screen;return s.orientation?s.orientation.angle:window.orientation||0},ye=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const s=Ve(),g=Ft(),c=window.screen.width,w=window.screen.height,N=s.includes("portrait")||window.innerHeight>window.innerWidth,x=s.includes("landscape")||window.innerWidth>window.innerHeight;return{type:s,angle:g,isPortrait:N,isLandscape:x,width:c,height:w,aspectRatio:c/w}},Bt=()=>{if(typeof window>"u")return!1;const s=window.screen;return!!(s.orientation&&typeof s.orientation.lock=="function")},We=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,onOrientationChange:N,onLockChange:x,onUnsupportedOrientation:A,rotationPrompt:G,children:C,className:D}=s,a={...Mt,...w},y=e.useRef(!1),[E,f]=e.useState(Ve),[m,I]=e.useState(null),[F,B]=e.useState(ye),[$]=e.useState(Bt),Y=e.useCallback(i=>!!(a.supportedOrientations.includes("any")||a.supportedOrientations.includes(i)||i.includes("portrait")&&a.supportedOrientations.includes("portrait")||i.includes("landscape")&&a.supportedOrientations.includes("landscape")),[a.supportedOrientations]),H=e.useCallback(async i=>{if(!$)return console.warn("Screen Orientation API is not available"),I(i),x==null||x(!0,i),!1;try{return await window.screen.orientation.lock(i),I(i),x==null||x(!0,i),!0}catch(r){return console.warn("Failed to lock orientation:",r),I(i),x==null||x(!0,i),!1}},[$,x]),X=e.useCallback(async()=>{if(I(null),x==null||x(!1,null),!$)return!1;try{return window.screen.orientation.unlock(),!0}catch(i){return console.warn("Failed to unlock orientation:",i),!1}},[$,x]),O=e.useCallback(async()=>m?X():H(E),[m,E,H,X]),z=e.useCallback(()=>ye(),[]),T=e.useCallback(()=>{const i=ye(),r=i.type;f(r),B(i),N==null||N(i),Y(r)||A==null||A(r,a.supportedOrientations)},[a.supportedOrientations,Y,N,A]);e.useEffect(()=>{y.current||(y.current=!0,T(),a.lockOnMount&&a.preferredOrientation!=="any"&&H(a.preferredOrientation))},[a.lockOnMount,a.preferredOrientation,T,H]),e.useEffect(()=>{const i=window.screen.orientation;return i&&i.addEventListener("change",T),window.addEventListener("resize",T),window.addEventListener("orientationchange",T),()=>{i&&i.removeEventListener("change",T),window.removeEventListener("resize",T),window.removeEventListener("orientationchange",T)}},[T]);const M=e.useMemo(()=>({current:E,locked:m,isLocked:m!==null,isSupported:Y(E),info:F,isApiAvailable:$}),[E,m,F,$,Y]);e.useImperativeHandle(g,()=>({getState:()=>M,lock:H,unlock:X,toggleLock:O,getOrientationInfo:z,isOrientationSupported:Y}),[M,H,X,O,z,Y]);const j={...M,lock:H,unlock:X,getOrientationInfo:z},S=e.useCallback(()=>{if(!a.autoRotateContent||!m||m==="any")return;const i=m.includes("portrait"),r=F.isPortrait;return i===r?void 0:{transform:`rotate(${i?90:-90}deg)`,transformOrigin:"center center",width:i?F.height:F.width,height:i?F.width:F.height}},[a.autoRotateContent,m,F]),P=a.showRotationPrompt&&m!==null&&m!=="any"&&!M.isSupported,W=["nice-orientation",`nice-orientation--${E}`,m&&`nice-orientation--locked-${m}`,!M.isSupported&&"nice-orientation--unsupported",D].filter(Boolean).join(" ");return t.jsx(Ue.Provider,{value:j,children:t.jsxs("div",{className:W,style:S(),"data-orientation":E,"data-locked":m||void 0,children:[C,P&&t.jsx("div",{className:"nice-orientation__prompt",children:G||t.jsxs("div",{className:"nice-orientation__prompt-content",children:[t.jsx("div",{className:"nice-orientation__prompt-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--device","aria-hidden":"true"})}),t.jsx("p",{className:"nice-orientation__prompt-text",children:m!=null&&m.includes("portrait")?c("orientationLock.rotateToPortrait","Please rotate your device to portrait mode"):c("orientationLock.rotateToLandscape","Please rotate your device to landscape mode")})]})})]})})}),{displayName:"NiceOrientationLock"}),He=We;process.env.NODE_ENV!=="production"&&(He.displayName="NiceOrientationLockProvider");const ze=e.createContext(null),$t=()=>{const s=e.useContext(ze);if(!s)throw new Error("useRemoteManagement must be used within NiceRemoteManagementProvider");return s},qt={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},Ge=Object.assign(e.forwardRef((s,g)=>{const{config:c,onConnectionChange:w,onCommandReceived:N,onCustomCommand:x,onCaptureScreenshot:A,children:G}=s,C={...qt,...c},D=e.useRef(null),a=e.useRef(null),y=e.useRef(null),E=e.useRef([]),f=e.useRef(Date.now()),m=e.useRef(0),[I,F]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),B=e.useCallback(()=>{const i=typeof navigator<"u"?navigator:null,r=typeof window<"u"?window:null;return{deviceId:C.deviceId,name:C.deviceName||C.deviceId,type:"embedded-display",os:i==null?void 0:i.platform,browser:i==null?void 0:i.userAgent,resolution:r?`${r.screen.width}x${r.screen.height}`:void 0,uptime:Math.floor((Date.now()-f.current)/1e3),metadata:{}}},[C.deviceId,C.deviceName]),$=e.useCallback(async()=>{const i={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const r=performance.memory;r&&(i.memory=Math.round(r.usedJSHeapSize/r.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const r=await navigator.getBattery();i.battery=Math.round(r.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const r=await navigator.storage.estimate();r.quota&&r.usage&&(i.storageFree=r.quota-r.usage)}catch{}return i},[]),Y=e.useRef({enabled:C.enableScreenshot,capture:A});e.useEffect(()=>{Y.current={enabled:C.enableScreenshot,capture:A}});const H=e.useCallback(async()=>{const{enabled:i,capture:r}=Y.current;if(!i)throw new Error("Screenshots are disabled on this device (enableScreenshot: false)");if(!r)throw new Error("This device cannot take screenshots: no onCaptureScreenshot handler");const d=await r();if(!d)throw new Error("The screenshot handler returned no image");return d},[]),X=e.useCallback(()=>H().catch(()=>{}),[H]),O=e.useRef({onConnectionChange:w,onCommandReceived:N,onCustomCommand:x});e.useEffect(()=>{O.current={onConnectionChange:w,onCommandReceived:N,onCustomCommand:x}});const z=e.useCallback(async()=>{var i,r,d,n,l;if(((i=D.current)==null?void 0:i.readyState)!==WebSocket.OPEN){F(o=>({...o,status:"connecting"})),(d=(r=O.current).onConnectionChange)==null||d.call(r,"connecting");try{const o=new URL(C.serverUrl);o.searchParams.set("deviceId",C.deviceId),C.apiKey&&o.searchParams.set("apiKey",C.apiKey);const h=new WebSocket(o.toString());D.current=h,h.onopen=()=>{var v,b;m.current=0,F(k=>({...k,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),(b=(v=O.current).onConnectionChange)==null||b.call(v,"connected"),h.send(JSON.stringify({type:"register",payload:B()}))},h.onmessage=async v=>{var b,k;try{const u=JSON.parse(v.data);if(u.type==="command"){const p={id:u.id,type:u.commandType,payload:u.payload,timestamp:new Date,acknowledged:!0,executed:!1};F(_=>({..._,pendingCommands:[..._.pendingCommands,p]})),(k=(b=O.current).onCommandReceived)==null||k.call(b,p);let R,K;try{switch(p.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":R=await H();break;case"logs":R=E.current;break;case"custom":O.current.onCustomCommand&&(R=await O.current.onCustomCommand(p));break}p.executed=!0,p.result=R}catch(_){K=_ instanceof Error?_.message:String(_),p.error=K}h.send(JSON.stringify({type:"commandResult",commandId:p.id,result:R,error:K})),F(_=>({..._,pendingCommands:_.pendingCommands.filter(L=>L.id!==p.id),commandHistory:[..._.commandHistory.slice(-49),p]}))}}catch{}},h.onerror=()=>{D.current===h&&F(v=>({...v,status:"error",error:"WebSocket error"}))},h.onclose=()=>{var v,b;D.current===h&&(D.current=null,F(k=>({...k,status:"disconnected",isConnected:!1})),m.current<C.maxReconnectAttempts&&setTimeout(()=>{m.current>=C.maxReconnectAttempts||(m.current+=1,F(k=>({...k,reconnectAttempts:m.current})),z())},C.reconnectDelay),(b=(v=O.current).onConnectionChange)==null||b.call(v,"disconnected"))}}catch(o){F(h=>({...h,status:"error",error:o instanceof Error?o.message:"Connection failed"})),(l=(n=O.current).onConnectionChange)==null||l.call(n,"error")}}},[C.serverUrl,C.deviceId,C.apiKey,C.maxReconnectAttempts,C.reconnectDelay,B,H]),T=e.useCallback(()=>{m.current=C.maxReconnectAttempts,D.current&&(D.current.close(),D.current=null),F(i=>({...i,status:"disconnected",isConnected:!1,reconnectAttempts:C.maxReconnectAttempts}))},[C.maxReconnectAttempts]),M=e.useCallback(async()=>{var i;((i=D.current)==null?void 0:i.readyState)===WebSocket.OPEN&&(D.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:C.deviceId})),F(r=>({...r,lastHeartbeat:new Date})))},[C.deviceId]),j=e.useCallback(async i=>{var d;if(((d=D.current)==null?void 0:d.readyState)!==WebSocket.OPEN)return;const r=i||await $();D.current.send(JSON.stringify({type:"health",metrics:r,deviceId:C.deviceId})),F(n=>({...n,healthMetrics:r}))},[C.deviceId,$]),S=e.useCallback(async(i,r,d)=>{var n;((n=D.current)==null?void 0:n.readyState)===WebSocket.OPEN&&D.current.send(JSON.stringify({type:"commandResult",commandId:i,result:r,error:d}))},[]),P=e.useCallback((i,r,d)=>{var l;const n={level:i,message:r,data:d,timestamp:new Date};E.current=[...E.current.slice(-(C.logBufferSize-1)),n],C.enableLogs&&((l=D.current)==null?void 0:l.readyState)===WebSocket.OPEN&&D.current.send(JSON.stringify({type:"log",...n,deviceId:C.deviceId}))},[C.deviceId,C.enableLogs,C.logBufferSize]);e.useEffect(()=>(m.current=0,z(),()=>{T(),a.current&&clearInterval(a.current),y.current&&clearInterval(y.current)}),[]),e.useEffect(()=>{if(I.isConnected)return a.current=setInterval(M,C.heartbeatInterval),()=>{a.current&&clearInterval(a.current)}},[I.isConnected,C.heartbeatInterval,M]),e.useEffect(()=>{if(!(!I.isConnected||!C.enableHealthMonitoring))return y.current=setInterval(()=>{j()},C.healthReportInterval),j(),()=>{y.current&&clearInterval(y.current)}},[I.isConnected,C.enableHealthMonitoring,C.healthReportInterval,j]),e.useImperativeHandle(g,()=>({getState:()=>I,connect:z,disconnect:T,sendHeartbeat:M,sendHealthMetrics:j,reportCommandResult:S,sendLog:P,captureScreenshot:X,getDeviceInfo:B}),[I,z,T,M,j,S,P,X,B]);const W={...I,deviceInfo:B(),connect:z,disconnect:T,sendLog:P};return t.jsx(ze.Provider,{value:W,children:G})}),{displayName:"NiceRemoteManagement"}),Ye=Ge;process.env.NODE_ENV!=="production"&&(Ye.displayName="NiceRemoteManagementProvider");const Ut={modes:["pixel-shift","dimming"],inactivityTimeout:300*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--nice-text-primary, #000000)","var(--nice-text, #111111)","var(--nice-bg, #0a0a0a)"],interval:3e4,transitionDuration:1e3},dimming:{level:.3,fadeDuration:2e3},screensaver:{type:"blank"},staticDetectionThreshold:3e4,autoDetectStatic:!1},Vt=Object.assign(e.forwardRef((s,g)=>{var o,h,v,b,k,u;const{config:c,enabled:w=!0,onActivate:N,onDeactivate:x,onModeChange:A,children:G}=s,C={...Ut,...c},D=e.useRef(null),a=e.useRef(null),y=e.useRef(null),E=e.useRef(null),[f,m]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[I,F]=e.useState(0),[B,$]=e.useState({x:50,y:50,dx:1,dy:1}),Y=e.useCallback(()=>{if(!C.pixelShift)return;const{maxShift:p}=C.pixelShift,R=Math.floor(Math.random()*(p*2+1))-p,K=Math.floor(Math.random()*(p*2+1))-p;m(_=>({..._,shiftX:R,shiftY:K}))},[C.pixelShift]),H=e.useCallback(()=>{!C.pixelShift||y.current||(Y(),y.current=setInterval(Y,C.pixelShift.interval))},[C.pixelShift,Y]),X=e.useCallback(()=>{y.current&&(clearInterval(y.current),y.current=null),m(p=>({...p,shiftX:0,shiftY:0}))},[]),O=e.useCallback(()=>{!C.colorCycle||E.current||(E.current=setInterval(()=>{F(p=>{var R;return(p+1)%(((R=C.colorCycle)==null?void 0:R.colors.length)||1)})},C.colorCycle.interval))},[C.colorCycle]),z=e.useCallback(()=>{E.current&&(clearInterval(E.current),E.current=null),F(0)},[]),T=e.useCallback(()=>{if(!w||f.isActive)return;const p=C.modes;m(R=>({...R,isActive:!0,activeModes:p})),p.includes("pixel-shift")&&H(),p.includes("color-cycling")&&O(),p.includes("dimming")&&m(R=>({...R,isDimmed:!0})),p.includes("screensaver")&&m(R=>({...R,isScreensaverActive:!0})),N==null||N(),A==null||A(p)},[w,f.isActive,C.modes,H,O,N,A]),M=e.useCallback(()=>{f.isActive&&(X(),z(),m(p=>({...p,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),x==null||x(),A==null||A([]))},[f.isActive,X,z,x,A]),j=e.useCallback(()=>{f.isActive?M():T()},[f.isActive,T,M]),S=e.useCallback(()=>{a.current&&clearTimeout(a.current),f.isActive&&M(),w&&C.inactivityTimeout>0&&(a.current=setTimeout(()=>{T()},C.inactivityTimeout))},[w,f.isActive,C.inactivityTimeout,T,M]),P=e.useCallback(()=>{m(p=>({...p,isScreensaverActive:!0}))},[]),W=e.useCallback(()=>{m(p=>({...p,isScreensaverActive:!1})),S()},[S]),i=e.useCallback(p=>{m(R=>({...R,isDimmed:p>0}))},[]);e.useEffect(()=>{var R;if(!f.isScreensaverActive||((R=C.screensaver)==null?void 0:R.type)!=="bounce")return;const p=setInterval(()=>{$(K=>{let{x:_,y:L,dx:q,dy:V}=K;return _+=q*.5,L+=V*.5,(_<=0||_>=90)&&(q=-q),(L<=0||L>=90)&&(V=-V),{x:_,y:L,dx:q,dy:V}})},50);return()=>clearInterval(p)},[f.isScreensaverActive,(o=C.screensaver)==null?void 0:o.type]),e.useEffect(()=>{if(!w)return;const p=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],R=()=>{S()};for(const K of p)document.addEventListener(K,R);return S(),()=>{for(const K of p)document.removeEventListener(K,R);a.current&&clearTimeout(a.current),X(),z()}},[w,S,X,z]),e.useImperativeHandle(g,()=>({getState:()=>f,activate:T,deactivate:M,toggle:j,resetIdleTimer:S,forceShift:Y,showScreensaver:P,hideScreensaver:W,setDimLevel:i}),[f,T,M,j,S,Y,P,W,i]);const r=()=>{if(!f.isScreensaverActive)return null;const p=C.screensaver||{type:"blank"};switch(p.type){case"blank":return t.jsx("div",{role:"presentation",className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:W,onTouchStart:W});case"bounce":return t.jsx("div",{role:"presentation",className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:W,onTouchStart:W,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${B.x}%`,top:`${B.y}%`},children:t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"1em",height:"1em",background:"currentColor",clipPath:"polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0% 50%)"}})})});case"matrix":return t.jsx("div",{role:"presentation",className:"nice-sbp__screensaver nice-sbp__screensaver--matrix",onClick:W,onTouchStart:W,children:Array.from({length:20}).map((R,K)=>t.jsx("div",{className:"nice-sbp__matrix-column",style:{left:`${K*5}%`,animationDelay:`${Math.random()*5}s`,animationDuration:`${5+Math.random()*5}s`},children:Array.from({length:20}).map((_,L)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},L))},K))});case"noise":return t.jsx("div",{role:"presentation",className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:W,onTouchStart:W});case"custom":return t.jsx("div",{role:"presentation",className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:W,onTouchStart:W,children:p.component});default:return null}},d={transform:f.isActive&&C.modes.includes("pixel-shift")?`translate(${f.shiftX}px, ${f.shiftY}px)`:void 0,transition:(h=C.pixelShift)!=null&&h.smooth?"transform 0.5s ease":void 0},n={"--dim-level":f.isDimmed?((v=C.dimming)==null?void 0:v.level)||.3:0,"--dim-duration":`${((b=C.dimming)==null?void 0:b.fadeDuration)||2e3}ms`},l=f.isActive&&C.modes.includes("color-cycling")?{backgroundColor:(k=C.colorCycle)==null?void 0:k.colors[I],transition:`background-color ${((u=C.colorCycle)==null?void 0:u.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:D,className:`nice-sbp ${f.isActive?"nice-sbp--active":""}`,style:{...l},children:[t.jsx("div",{className:"nice-sbp__content",style:d,children:G}),f.isDimmed&&t.jsx("div",{role:"presentation",className:"nice-sbp__dim-overlay",style:n,onClick:S,onTouchStart:S}),r(),f.isActive&&C.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})}),{displayName:"NiceScreenBurnPrevention"}),Wt={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},Ht=s=>({4:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:90,targetY:90},{targetX:10,targetY:90}],5:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:50,targetY:50},{targetX:10,targetY:90},{targetX:90,targetY:90}],9:[{targetX:10,targetY:10},{targetX:50,targetY:10},{targetX:90,targetY:10},{targetX:10,targetY:50},{targetX:50,targetY:50},{targetX:90,targetY:50},{targetX:10,targetY:90},{targetX:50,targetY:90},{targetX:90,targetY:90}]})[s],zt=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,autoStart:N=!1,onStart:x,onPointCalibrated:A,onComplete:G,onCancel:C,children:D}=s,a={...Wt,...w},y=e.useRef(null),E=e.useRef(null),[f,m]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:a.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),I=e.useCallback(S=>{const P=S.filter(q=>q.calibrated&&q.actualX!==void 0&&q.actualY!==void 0);if(P.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let W=0,i=0,r=0,d=0;const n=P.length;for(const q of P)W+=q.targetX,i+=q.targetY,r+=q.actualX,d+=q.actualY;const l=W/n,o=i/n,h=r/n,v=d/n;let b=0,k=0,u=0,p=0;for(const q of P){const V=q.targetX-l,Q=q.targetY-o,te=q.actualX-h,Z=q.actualY-v;b+=V*V,k+=V*te,u+=Q*Q,p+=Q*Z}const R=k!==0?b/k:1,K=p!==0?u/p:1,_=l-R*h,L=o-K*v;return{scaleX:R,scaleY:K,offsetX:_,offsetY:L,rotation:0}},[]),F=e.useCallback((S,P)=>{const W=S.filter(r=>r.calibrated);if(W.length===0)return 0;let i=0;for(const r of W){if(r.actualX===void 0||r.actualY===void 0)continue;const d=P.scaleX*r.actualX+P.offsetX,n=P.scaleY*r.actualY+P.offsetY,l=r.targetX-d,o=r.targetY-n;i+=Math.sqrt(l*l+o*o)}return i/W.length},[]),B=e.useCallback(()=>{const P=Ht(a.pointCount).map(W=>({...W,calibrated:!1}));m({isActive:!0,currentPointIndex:0,totalPoints:a.pointCount,points:P,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),x==null||x()},[a.pointCount,x]),$=e.useCallback(()=>{E.current&&clearTimeout(E.current),m(S=>({...S,isActive:!1,isCompleted:!1})),C==null||C()},[C]),Y=e.useCallback(()=>{m(S=>({...S,isCompleted:!1}))},[]),H=e.useCallback(()=>{if(a.persistCalibration)try{localStorage.removeItem(a.storageKey)}catch{}m({isActive:!1,currentPointIndex:0,totalPoints:a.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[a.persistCalibration,a.storageKey,a.pointCount]),X=e.useCallback(S=>{const P=I(S),W=F(S,P),i=W<=a.accuracyThreshold;if(a.persistCalibration&&i)try{localStorage.setItem(a.storageKey,JSON.stringify({matrix:P,points:S}))}catch{}m(r=>({...r,points:S,isActive:!1,isCompleted:!0,isSuccessful:i,matrix:P,averageError:W})),G==null||G(P,i)},[a.accuracyThreshold,a.persistCalibration,a.storageKey,I,F,G]),O=e.useCallback(S=>{if(!f.isActive||!y.current)return;S.preventDefault();const P=y.current.getBoundingClientRect();let W,i;"touches"in S?(W=S.touches[0].clientX,i=S.touches[0].clientY):(W=S.clientX,i=S.clientY);const r=(W-P.left)/P.width*100,d=(i-P.top)/P.height*100,n=f.currentPointIndex,l=[...f.points];l[n]={...l[n],actualX:r,actualY:d,calibrated:!0};const o=n+1;A==null||A(l[n],n),o>=f.totalPoints?X(l):m(h=>({...h,currentPointIndex:o,points:l}))},[f.isActive,f.currentPointIndex,f.points,f.totalPoints,X,A]),z=e.useCallback((S,P)=>{const W=f.matrix;return W?{x:W.scaleX*S+W.offsetX,y:W.scaleY*P+W.offsetY}:{x:S,y:P}},[f.matrix]),T=e.useCallback(()=>{if(f.matrix)return!0;if(a.persistCalibration)try{return!!localStorage.getItem(a.storageKey)}catch{return!1}return!1},[f.matrix,a.persistCalibration,a.storageKey]),M=e.useCallback(()=>{if(a.persistCalibration)try{localStorage.removeItem(a.storageKey)}catch{}m(S=>({...S,matrix:null}))},[a.persistCalibration,a.storageKey]);if(e.useEffect(()=>{if(a.persistCalibration)try{const S=localStorage.getItem(a.storageKey);if(S){const P=JSON.parse(S);m(W=>({...W,matrix:P.matrix,points:P.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[a.persistCalibration,a.storageKey]),e.useEffect(()=>{if(!f.isActive)return;const S=y.current;if(S)return S.addEventListener("touchstart",O,{passive:!1}),S.addEventListener("mousedown",O),()=>{S.removeEventListener("touchstart",O),S.removeEventListener("mousedown",O)}},[f.isActive,O]),e.useEffect(()=>{if(!(!f.isActive||a.pointTimeout<=0))return E.current=setTimeout(()=>{f.currentPointIndex<f.totalPoints-1?m(S=>({...S,currentPointIndex:S.currentPointIndex+1})):X(f.points)},a.pointTimeout),()=>{E.current&&clearTimeout(E.current)}},[f.isActive,f.currentPointIndex,f.points,f.totalPoints,a.pointTimeout,X]),e.useEffect(()=>{N&&!T()&&B()},[N,T,B]),e.useImperativeHandle(g,()=>({getState:()=>f,start:B,cancel:$,reset:H,getMatrix:()=>f.matrix,transformPoint:z,hasCalibration:T,clearCalibration:M}),[f,B,$,H,z,T,M]),!f.isActive&&!f.isCompleted)return t.jsx(t.Fragment,{children:D});const j=f.isActive?f.points[f.currentPointIndex]:void 0;return t.jsxs("div",{ref:y,className:"nice-touch-calibration",children:[t.jsxs("div",{className:"nice-touch-calibration__overlay",children:[t.jsxs("div",{className:"nice-touch-calibration__instructions",children:[t.jsx("h2",{className:"nice-touch-calibration__title",children:c("touchCalibration.touchScreenCalibration","Touch Screen Calibration")}),t.jsx("p",{className:"nice-touch-calibration__text",children:c("touchCalibration.touchTheCenterOfEach","Touch the center of each target to calibrate your screen.")}),t.jsx("div",{className:"nice-touch-calibration__progress",children:c("touchCalibration.pointOf","Point {currentPointIndex} of {totalPoints}").replace("{currentPointIndex}",String(f.currentPointIndex+1)).replace("{totalPoints}",String(f.totalPoints))})]}),j&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${j.targetX}%`,top:`${j.targetY}%`,width:a.targetSize,height:a.targetSize},children:(w==null?void 0:w.targetComponent)||t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"nice-touch-calibration__target-outer"}),t.jsx("div",{className:"nice-touch-calibration__target-inner"}),t.jsx("div",{className:"nice-touch-calibration__target-center"})]})}),f.points.map((S,P)=>S.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${S.actualX}%`,top:`${S.actualY}%`}},P)),f.isActive&&t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:$,children:c("touchCalibration.cancel","Cancel")})]}),f.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${f.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:t.jsx("span",{className:`nice-platform-mark nice-platform-mark--${f.isSuccessful?"check":"alert"}`,"aria-hidden":"true"})}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:f.isSuccessful?c("touchCalibration.calibrationComplete","Calibration Complete"):c("touchCalibration.calibrationFailed","Calibration Failed")}),a.showAccuracy&&t.jsx("p",{className:"nice-touch-calibration__result-accuracy",children:c("touchCalibration.averageErrorPx","Average error: {averageError}px").replace("{averageError}",String(f.averageError.toFixed(1)))}),!f.isSuccessful&&a.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:B,children:c("touchCalibration.retryCalibration","Retry Calibration")}),t.jsx("button",{className:"nice-touch-calibration__retry nice-touch-calibration__done",onClick:Y,children:c("touchCalibration.done","Done")})]})]})}),{displayName:"NiceTouchCalibration"}),Gt={format:"code128",width:2,height:100,displayValue:!0,font:"monospace",fontSize:14,textAlign:"center",textPosition:"bottom",textMargin:2,background:"#ffffff",lineColor:"#000000",margin:10,flat:!1},Se=104,Yt=106,Xt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",de=["11011001100","11001101100","11001100110","10010011000","10010001100","10001001100","10011001000","10011000100","10001100100","11001001000","11001000100","11000100100","10110011100","10011011100","10011001110","10111001100","10011101100","10011100110","11001110010","11001011100","11001001110","11011100100","11001110100","11101101110","11101001100","11100101100","11100100110","11101100100","11100110100","11100110010","11011011000","11011000110","11000110110","10100011000","10001011000","10001000110","10110001000","10001101000","10001100010","11010001000","11000101000","11000100010","10110111000","10110001110","10001101110","10111011000","10111000110","10001110110","11101110110","11010001110","11000101110","11011101000","11011100010","11011101110","11101011000","11101000110","11100010110","11101101000","11101100010","11100011010","11101111010","11001000010","11110001010","10100110000","10100001100","10010110000","10010000110","10000101100","10000100110","10110010000","10110000100","10011010000","10011000010","10000110100","10000110010","11000010010","11001010000","11110111010","11000010100","10001111010","10100111100","10010111100","10010011110","10111100100","10011110100","10011110010","11110100100","11110010100","11110010010","11011011110","11011110110","11110110110","10101111000","10100011110","10001011110","10111101000","10111100010","11110101000","11110100010","10111011110","10111101110","11101011110","11110101110","11010000100","11010010000","11010011100","1100011101011"],Ne=s=>{let g=de[Se],c=Se;for(let w=0;w<s.length;w++){const N=s[w],x=Xt.indexOf(N);x!==-1&&(g+=de[x],c+=x*(w+1))}return c=c%103,g+=de[c],g+=de[Yt],g},Xe=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],Kt=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],Ke=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],Qt=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],Jt=s=>{let g=0;for(let c=0;c<12;c++)g+=parseInt(s[c])*(c%2===0?1:3);return(10-g%10)%10},Zt=s=>{let g=s.replace(/\D/g,"").slice(0,12).padStart(12,"0");const c=Jt(g);g+=c;const w=parseInt(g[0]),N=Qt[w];let x="101";for(let A=1;A<=6;A++){const G=parseInt(g[A]);x+=N[A-1]==="L"?Xe[G]:Kt[G]}x+="01010";for(let A=7;A<=12;A++){const G=parseInt(g[A]);x+=Ke[G]}return x+="101",x},en=s=>{let g=s.replace(/\D/g,"").slice(0,7).padStart(7,"0"),c=0;for(let x=0;x<7;x++)c+=parseInt(g[x])*(x%2===0?3:1);const w=(10-c%10)%10;g+=w;let N="101";for(let x=0;x<4;x++)N+=Xe[parseInt(g[x])];N+="01010";for(let x=4;x<8;x++)N+=Ke[parseInt(g[x])];return N+="101",N},tn={0:"101001101101",1:"110100101011",2:"101100101011",3:"110110010101",4:"101001101011",5:"110100110101",6:"101100110101",7:"101001011011",8:"110100101101",9:"101100101101",A:"110101001011",B:"101101001011",C:"110110100101",D:"101011001011",E:"110101100101",F:"101101100101",G:"101010011011",H:"110101001101",I:"101101001101",J:"101011001101",K:"110101010011",L:"101101010011",M:"110110101001",N:"101011010011",O:"110101101001",P:"101101101001",Q:"101010110011",R:"110101011001",S:"101101011001",T:"101011011001",U:"110010101011",V:"100110101011",W:"110011010101",X:"100101101011",Y:"110010110101",Z:"100110110101","-":"100101011011",".":"110010101101"," ":"100110101101",$:"100100100101","/":"100100101001","+":"100101001001","%":"101001001001","*":"100101101101"},nn=s=>{const g=("*"+s.toUpperCase()+"*").split("");let c="";for(const w of g){const N=tn[w];N&&(c+=N+"0")}return c.slice(0,-1)},_e=s=>{switch(s){case"code128":return Ne;case"code39":case"code93":return nn;case"ean13":return Zt;case"ean8":return en;default:return Ne}},sn=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{value:w,options:N,onGenerate:x,onError:A,showBorder:G=!1,className:C}=s,D=JSON.stringify(N??null),a=e.useMemo(()=>({...Gt,...JSON.parse(D)}),[D]),y=e.useRef(null),E=e.useRef(null),[f,m]=e.useState(null),[I,F]=e.useState(null),B=e.useCallback(()=>{if(!y.current||!w)return;const T=y.current,M=T.getContext("2d");if(M)try{const S=_e(a.format)(w),P=a.width,W=S.length*P,i=a.marginTop??a.margin,r=a.marginBottom??a.margin,d=a.marginLeft??a.margin,n=a.marginRight??a.margin,l=a.displayValue&&!a.flat?a.fontSize+a.textMargin*2:0,o=W+d+n,h=a.height+i+r+l;T.width=o,T.height=h,M.fillStyle=a.background,M.fillRect(0,0,o,h),M.fillStyle=a.lineColor;let v=d;const b=a.textPosition==="top"&&a.displayValue?i+l:i;for(let u=0;u<S.length;u++)S[u]==="1"&&M.fillRect(v,b,P,a.height),v+=P;if(a.displayValue&&!a.flat){M.fillStyle=a.lineColor,M.font=`${a.fontSize}px ${a.font}`,M.textBaseline=a.textPosition==="top"?"top":"bottom";let u=d;a.textAlign==="center"?(u=d+W/2,M.textAlign="center"):a.textAlign==="right"?(u=d+W,M.textAlign="right"):M.textAlign="left";const p=a.textPosition==="top"?i+a.textMargin:h-r-a.textMargin;M.fillText(w,u,p)}const k=T.toDataURL("image/png");F(k),m(null),x==null||x(k)}catch(j){const S=j instanceof Error?j.message:c("barcodeGenerator.failedToGenerateBarcode","Failed to generate barcode");m(S),A==null||A(new Error(S))}},[w,a,x,A,c]);e.useEffect(()=>{B()},[B]);const $=e.useCallback((T="image/png",M=1)=>{var j;return((j=y.current)==null?void 0:j.toDataURL(T,M))||null},[]),Y=e.useCallback(()=>{if(!y.current||!w)return null;try{const M=_e(a.format)(w),j=a.width,S=a.marginTop??a.margin,P=a.marginBottom??a.margin,W=a.marginLeft??a.margin,i=a.marginRight??a.margin,r=a.displayValue&&!a.flat?a.fontSize+a.textMargin*2:0,d=M.length*j,n=d+W+i,l=a.height+S+P+r,o=[];let h=W;const v=a.textPosition==="top"&&a.displayValue?S+r:S;for(let k=0;k<M.length;k++)M[k]==="1"&&o.push(`<rect x="${h}" y="${v}" width="${j}" height="${a.height}" fill="${a.lineColor}"/>`),h+=j;let b="";if(a.displayValue&&!a.flat){const k=a.textAlign==="center"?"middle":a.textAlign==="right"?"end":"start";let u=W;a.textAlign==="center"?u=W+d/2:a.textAlign==="right"&&(u=W+d);const p=a.textPosition==="top"?S+a.fontSize:l-P-a.textMargin;b=`<text x="${u}" y="${p}" font-family="${a.font}" font-size="${a.fontSize}" text-anchor="${k}" fill="${a.lineColor}">${w}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${l}" viewBox="0 0 ${n} ${l}">
|
|
2
|
+
<rect width="100%" height="100%" fill="${a.background}"/>
|
|
3
|
+
${o.join(`
|
|
4
4
|
`)}
|
|
5
|
-
${
|
|
6
|
-
</svg>`}catch{return null}},[h,i]),z=e.useCallback(()=>l.current,[]),Y=e.useCallback((W="barcode",j="png")=>{const U=document.createElement("a");if(j==="svg"){const D=q();if(!D)return;const P=new Blob([D],{type:"image/svg+xml"});U.href=URL.createObjectURL(P),U.download=`${W}.svg`}else{const D=B();if(!D)return;U.href=D,U.download=`${W}.png`}U.click()},[B,q]),K=e.useCallback(()=>{I()},[I]);e.useImperativeHandle(f,()=>({toDataURL:B,toSVG:q,getCanvas:z,download:Y,regenerate:K}),[B,q,z,Y,K]);const F=["nice-barcode-generator",R&&"nice-barcode-generator--bordered",E&&"nice-barcode-generator--error",G].filter(Boolean).join(" ");return t.jsxs("div",{className:F,children:[t.jsx("canvas",{ref:l,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:b,style:{display:"none"}}),E&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:E})})]})}),{displayName:"NiceBarcodeGenerator"}),en={formats:["qr_code","ean_13","ean_8","code_128","code_39","upc_a","upc_e"],continuous:!0,scanInterval:100,showBoundingBox:!0,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd"},tn=n=>({aztec:"aztec",code_128:"code_128",code_39:"code_39",code_93:"code_93",codabar:"codabar",data_matrix:"data_matrix",ean_13:"ean_13",ean_8:"ean_8",itf:"itf",pdf417:"pdf417",qr_code:"qr_code",upc_a:"upc_a",upc_e:"upc_e"})[n.toLowerCase().replace("-","_")]||"unknown",nn=()=>typeof window<"u"&&"BarcodeDetector"in window,sn=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],rn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.type="sine",f.frequency.value=1e3,h.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},100)}catch{}},an=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},cn=Object.assign(e.forwardRef((n,f)=>{const{config:h,onScan:k,onBatchScan:g,onError:N,onCameraReady:R,customScanFrame:G,showScanFrame:i=!0,autoStart:l=!1,children:b,className:E}=n,v={...en,...h},d=e.useRef(null),p=e.useRef(null),I=e.useRef(null),B=e.useRef(null),q=e.useRef(null),z=e.useRef(null),[Y,K]=e.useState(!1),[F,W]=e.useState(!1),[j,U]=e.useState(null),[D,P]=e.useState(null),[T,O]=e.useState(null),[y,s]=e.useState(v.facingMode),[r,a]=e.useState(null),c=nn(),o=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(X=>X.stop()),O(!0),!0}catch{return O(!1),!1}},[]),S=e.useCallback(async()=>{if(!d.current)return;const L=sn(v.resolution),X={video:{facingMode:y,width:{ideal:L.width},height:{ideal:L.height}},audio:!1};try{const $=await navigator.mediaDevices.getUserMedia(X);I.current=$,d.current.srcObject=$,await d.current.play(),W(!0),O(!0),P(null),R==null||R()}catch($){const Z=$ instanceof Error?$.message:"Failed to access camera";P(Z),O(!1),N==null||N(new Error(Z))}},[v.resolution,y,R,N]),A=e.useCallback(()=>{I.current&&(I.current.getTracks().forEach(L=>L.stop()),I.current=null),d.current&&(d.current.srcObject=null),W(!1)},[]),m=e.useCallback(async()=>{s(y==="user"?"environment":"user"),Y&&A()},[y,Y,A]),w=e.useCallback(async()=>{if(c)try{const L=window.BarcodeDetector,X=v.formats.map($=>$.replace("_","-"));B.current=new L({formats:X})}catch(L){const X=L instanceof Error?L.message:"Failed to initialize barcode detector";P(X),N==null||N(new Error(X))}},[c,v.formats,N]),u=e.useCallback(async()=>{if(!(!d.current||!B.current||!F))try{const X=await B.current.detect(d.current);if(X.length>0){const $=X.map(J=>({rawValue:J.rawValue,format:tn(J.format),boundingBox:J.boundingBox?{x:J.boundingBox.x,y:J.boundingBox.y,width:J.boundingBox.width,height:J.boundingBox.height}:void 0,cornerPoints:J.cornerPoints,timestamp:new Date})),Z=$[0];if(v.continuous&&Z.rawValue===z.current)return;z.current=Z.rawValue,v.showBoundingBox&&Z.boundingBox&&(a(Z.boundingBox),setTimeout(()=>a(null),500)),v.beepOnScan&&rn(),v.vibrateOnScan&&an(),U(Z),k==null||k(Z),$.length>1&&(g==null||g($)),setTimeout(()=>{z.current=null},1e3)}}catch{}},[F,v.continuous,v.showBoundingBox,v.beepOnScan,v.vibrateOnScan,k,g]),C=e.useCallback(async()=>{K(!0),P(null),await w(),await S()},[w,S]),x=e.useCallback(()=>{K(!1),q.current&&(clearInterval(q.current),q.current=null),A()},[A]),H=e.useCallback(async()=>{Y?x():await C()},[Y,C,x]),_=e.useCallback(()=>{if(!d.current||!p.current)return null;const L=p.current,X=d.current;L.width=X.videoWidth,L.height=X.videoHeight;const $=L.getContext("2d");return $?($.drawImage(X,0,0),L.toDataURL("image/png")):null},[]);e.useEffect(()=>(Y&&F&&v.continuous&&(q.current=setInterval(u,v.scanInterval)),()=>{q.current&&(clearInterval(q.current),q.current=null)}),[Y,F,v.continuous,v.scanInterval,u]),e.useEffect(()=>(l&&C(),()=>{x()}),[]),e.useEffect(()=>{Y&&!F&&S()},[y,Y,F,S]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:Y,isCameraReady:F,lastResult:j,error:D,isSupported:c,hasPermission:T}),start:C,stop:x,toggle:H,takeSnapshot:_,switchCamera:m,requestPermission:o}),[Y,F,j,D,c,T,C,x,H,_,m,o]);const M=["nice-barcode-scanner",Y&&"nice-barcode-scanner--scanning",F&&"nice-barcode-scanner--ready",D&&"nice-barcode-scanner--error",E].filter(Boolean).join(" ");return t.jsxs("div",{className:M,children:[t.jsx("video",{ref:d,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:p,className:"nice-barcode-scanner__canvas"}),i&&Y&&t.jsxs("div",{className:"nice-barcode-scanner__frame",children:[t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--br"}),t.jsx("div",{className:"nice-barcode-scanner__scan-line"})]}),r&&d.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${r.x/d.current.videoWidth*100}%`,top:`${r.y/d.current.videoHeight*100}%`,width:`${r.width/d.current.videoWidth*100}%`,height:`${r.height/d.current.videoHeight*100}%`}}),D&&t.jsxs("div",{className:"nice-barcode-scanner__error",children:[t.jsx("div",{className:"nice-barcode-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-barcode-scanner__error-text",children:D}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>C(),children:"Try Again"})]}),!c&&t.jsx("div",{className:"nice-barcode-scanner__unsupported",children:t.jsx("p",{children:"Barcode scanning is not supported in this browser."})}),b&&t.jsx("div",{className:"nice-barcode-scanner__overlay",children:b})]})}),{displayName:"NiceBarcodeScanner"}),ge=e.createContext(null),Ge=e.createContext(null),ce=n=>()=>{process.env.NODE_ENV!=="production"&&console.warn(`[NiceBatchScannerProvider] ${n}: no NiceBatchScanner is mounted below it.`)},on={items:[],isScanning:!1,addItem:ce("addItem"),removeItem:ce("removeItem"),updateQuantity:ce("updateQuantity"),clearAll:ce("clearAll"),startScanning:async()=>ce("startScanning")(),stopScanning:ce("stopScanning")},ln=()=>{const n=e.useContext(ge);if(!n)throw new Error("useBatchScanner must be used inside NiceBatchScanner or below NiceBatchScannerProvider");return n},un={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},dn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.frequency.value=1200,f.type="sine",h.gain.setValueAtTime(.3,n.currentTime),h.gain.exponentialRampToValueAtTime(.01,n.currentTime+.1),f.start(),f.stop(n.currentTime+.1)}catch{}},fn=(n=50)=>{"vibrate"in navigator&&navigator.vibrate(n)},mn=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,hn=Object.assign(e.forwardRef((n,f)=>{const{options:h,initialItems:k=[],onScan:g,onRemove:N,onBatchComplete:R,onQuantityChange:G,onError:i,validateScan:l,transformValue:b,className:E,children:v}=n,d=e.useMemo(()=>({...un,...h}),[h]),p=e.useRef(null),I=e.useRef(null),B=e.useRef(null),q=e.useRef(null),z=e.useRef(0),Y=e.useRef(""),K=e.useRef(0),[F,W]=e.useState(k),[j,U]=e.useState(!1),[D,P]=e.useState(!1),[T,O]=e.useState(""),[y,s]=e.useState([]),[r,a]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const Q=await BarcodeDetector.getSupportedFormats();Q.length>0&&(q.current=new BarcodeDetector({formats:(h==null?void 0:h.formats)||Q}),P(!0))}catch{P(!1)}})()},[h==null?void 0:h.formats]);const c=e.useCallback(async(V,Q="unknown",ee)=>{const te=b?b(V,Q):V;if(l&&!await l(te,Q))return;const ne=F.findIndex(se=>se.value===te);if(ne!==-1&&d.autoIncrementDuplicates){const se=[...F];se[ne]={...se[ne],quantity:se[ne].quantity+1,timestamp:Date.now()},W(se),G==null||G(se[ne],se[ne].quantity)}else if(F.length<d.maxItems){const se={id:mn(),value:te,format:Q,timestamp:Date.now(),rawValue:V,quantity:1,boundingBox:ee};W(re=>[se,...re]),g==null||g(se)}d.beepOnScan&&dn(),d.vibrateOnScan&&fn()},[F,d,l,b,g,G]),o=e.useCallback(V=>{const Q=F.find(ee=>ee.id===V);Q&&(W(ee=>ee.filter(te=>te.id!==V)),N==null||N(Q))},[F,N]),S=e.useCallback((V,Q)=>{if(Q<1){o(V);return}W(te=>te.map(ne=>ne.id===V?{...ne,quantity:Q}:ne));const ee=F.find(te=>te.id===V);ee&&(G==null||G(ee,Q))},[F,o,G]),A=e.useCallback(()=>{W([])},[]),m=e.useCallback(async()=>{if(!p.current||!q.current||!I.current)return;const V=p.current,Q=I.current,ee=Q.getContext("2d");if(!ee||V.readyState!==V.HAVE_ENOUGH_DATA){z.current=requestAnimationFrame(m);return}Q.width=V.videoWidth,Q.height=V.videoHeight,ee.drawImage(V,0,0);try{const te=await q.current.detect(Q);if(te.length>0){const ne=Date.now(),se=[];for(const re of te)se.push(re.boundingBox),(re.rawValue!==Y.current||ne-K.current>2e3)&&(Y.current=re.rawValue,K.current=ne,c(re.rawValue,re.format,re.boundingBox));d.showBoundingBox&&(s(se),setTimeout(()=>s([]),500))}}catch(te){console.warn("Scan error:",te)}z.current=requestAnimationFrame(m)},[c,d.showBoundingBox]),w=e.useCallback(async()=>{if(!D||!q.current){a("Camera or BarcodeDetector not available"),i==null||i(new Error("Camera or BarcodeDetector not available"));return}try{const V=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}}});B.current=V,p.current&&(p.current.srcObject=V,await p.current.play()),U(!0),a(null),z.current=requestAnimationFrame(m)}catch(V){const Q=V instanceof Error?V.message:"Failed to start camera";a(Q),i==null||i(new Error(Q))}},[D,m,i]),u=e.useCallback(()=>{z.current&&cancelAnimationFrame(z.current),B.current&&(B.current.getTracks().forEach(V=>V.stop()),B.current=null),p.current&&(p.current.srcObject=null),U(!1),s([])},[]);e.useEffect(()=>()=>{u()},[u]);const C=e.useCallback(()=>{T.trim()&&(c(T.trim()),O(""))},[T,c]),x=e.useCallback(()=>{const V=["Value","Format","Quantity","Timestamp"],Q=F.map(ee=>[`"${ee.value.replace(/"/g,'""')}"`,ee.format,ee.quantity.toString(),new Date(ee.timestamp).toISOString()]);return[V.join(","),...Q.map(ee=>ee.join(","))].join(`
|
|
7
|
-
`)},[
|
|
8
|
-
<rect width="100%" height="100%" fill="${
|
|
5
|
+
${b}
|
|
6
|
+
</svg>`}catch{return null}},[w,a]),H=e.useCallback(()=>y.current,[]),X=e.useCallback((T="barcode",M="png")=>{const j=document.createElement("a");if(M==="svg"){const S=Y();if(!S)return;const P=new Blob([S],{type:"image/svg+xml"});j.href=URL.createObjectURL(P),j.download=`${T}.svg`}else{const S=$();if(!S)return;j.href=S,j.download=`${T}.png`}j.click()},[$,Y]),O=e.useCallback(()=>{B()},[B]);e.useImperativeHandle(g,()=>({toDataURL:$,toSVG:Y,getCanvas:H,download:X,regenerate:O}),[$,Y,H,X,O]);const z=["nice-barcode-generator",G&&"nice-barcode-generator--bordered",f&&"nice-barcode-generator--error",C].filter(Boolean).join(" ");return t.jsxs("div",{className:z,children:[t.jsx("canvas",{ref:y,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:E,style:{display:"none"}}),f&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:f})})]})}),{displayName:"NiceBarcodeGenerator"}),rn={formats:["qr_code","ean_13","ean_8","code_128","code_39","upc_a","upc_e"],continuous:!0,scanInterval:100,showBoundingBox:!0,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd"},an=s=>({aztec:"aztec",code_128:"code_128",code_39:"code_39",code_93:"code_93",codabar:"codabar",data_matrix:"data_matrix",ean_13:"ean_13",ean_8:"ean_8",itf:"itf",pdf417:"pdf417",qr_code:"qr_code",upc_a:"upc_a",upc_e:"upc_e"})[s.toLowerCase().replace("-","_")]||"unknown",on=()=>typeof window<"u"&&"BarcodeDetector"in window,cn=s=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[s],ln=()=>{try{const s=new(window.AudioContext||window.webkitAudioContext),g=s.createOscillator(),c=s.createGain();g.connect(c),c.connect(s.destination),g.type="sine",g.frequency.value=1e3,c.gain.value=.1,g.start(),setTimeout(()=>{g.stop(),s.close()},100)}catch{}},un=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},dn=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,onScan:N,onBatchScan:x,onError:A,onCameraReady:G,customScanFrame:C,showScanFrame:D=!0,autoStart:a=!1,children:y,className:E}=s,f={...rn,...w},m=e.useRef(null),I=e.useRef(null),F=e.useRef(null),B=e.useRef(null),$=e.useRef(null),Y=e.useRef(null),[H,X]=e.useState(!1),[O,z]=e.useState(!1),[T,M]=e.useState(null),[j,S]=e.useState(null),[P,W]=e.useState(null),[i,r]=e.useState(f.facingMode),[d,n]=e.useState(null),l=on(),o=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(V=>V.stop()),W(!0),!0}catch{return W(!1),!1}},[]),h=e.useCallback(async()=>{if(!m.current)return;const q=cn(f.resolution),V={video:{facingMode:i,width:{ideal:q.width},height:{ideal:q.height}},audio:!1};try{const Q=await navigator.mediaDevices.getUserMedia(V);F.current=Q,m.current.srcObject=Q,await m.current.play(),z(!0),W(!0),S(null),G==null||G()}catch(Q){const te=Q instanceof Error?Q.message:c("barcodeScanner.failedToAccessCamera","Failed to access camera");S(te),W(!1),A==null||A(new Error(te))}},[f.resolution,i,G,A,c]),v=e.useCallback(()=>{F.current&&(F.current.getTracks().forEach(q=>q.stop()),F.current=null),m.current&&(m.current.srcObject=null),z(!1)},[]),b=e.useCallback(async()=>{r(i==="user"?"environment":"user"),H&&v()},[i,H,v]),k=e.useCallback(async()=>{if(l)try{const q=window.BarcodeDetector,V=f.formats.map(Q=>Q.replace("_","-"));B.current=new q({formats:V})}catch(q){const V=q instanceof Error?q.message:c("barcodeScanner.failedToInitializeBarcodeDetector","Failed to initialize barcode detector");S(V),A==null||A(new Error(V))}},[l,f.formats,A,c]),u=e.useCallback(async()=>{if(!(!m.current||!B.current||!O))try{const V=await B.current.detect(m.current);if(V.length>0){const Q=V.map(Z=>({rawValue:Z.rawValue,format:an(Z.format),boundingBox:Z.boundingBox?{x:Z.boundingBox.x,y:Z.boundingBox.y,width:Z.boundingBox.width,height:Z.boundingBox.height}:void 0,cornerPoints:Z.cornerPoints,timestamp:new Date})),te=Q[0];if(f.continuous&&te.rawValue===Y.current)return;Y.current=te.rawValue,f.showBoundingBox&&te.boundingBox&&(n(te.boundingBox),setTimeout(()=>n(null),500)),f.beepOnScan&&ln(),f.vibrateOnScan&&un(),M(te),N==null||N(te),Q.length>1&&(x==null||x(Q)),setTimeout(()=>{Y.current=null},1e3)}}catch{}},[O,f.continuous,f.showBoundingBox,f.beepOnScan,f.vibrateOnScan,N,x]),p=e.useCallback(async()=>{X(!0),S(null),await k(),await h()},[k,h]),R=e.useCallback(()=>{X(!1),$.current&&(clearInterval($.current),$.current=null),v()},[v]),K=e.useCallback(async()=>{H?R():await p()},[H,p,R]),_=e.useCallback(()=>{if(!m.current||!I.current)return null;const q=I.current,V=m.current;q.width=V.videoWidth,q.height=V.videoHeight;const Q=q.getContext("2d");return Q?(Q.drawImage(V,0,0),q.toDataURL("image/png")):null},[]);e.useEffect(()=>(H&&O&&f.continuous&&($.current=setInterval(u,f.scanInterval)),()=>{$.current&&(clearInterval($.current),$.current=null)}),[H,O,f.continuous,f.scanInterval,u]),e.useEffect(()=>(a&&p(),()=>{R()}),[]),e.useEffect(()=>{H&&!O&&h()},[i,H,O,h]),e.useImperativeHandle(g,()=>({getState:()=>({isScanning:H,isCameraReady:O,lastResult:T,error:j,isSupported:l,hasPermission:P}),start:p,stop:R,toggle:K,takeSnapshot:_,switchCamera:b,requestPermission:o}),[H,O,T,j,l,P,p,R,K,_,b,o]);const L=["nice-barcode-scanner",H&&"nice-barcode-scanner--scanning",O&&"nice-barcode-scanner--ready",j&&"nice-barcode-scanner--error",E].filter(Boolean).join(" ");return t.jsxs("div",{className:L,children:[t.jsx("video",{ref:m,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:I,className:"nice-barcode-scanner__canvas"}),D&&H&&t.jsxs("div",{className:"nice-barcode-scanner__frame",children:[t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--br"}),t.jsx("div",{className:"nice-barcode-scanner__scan-line"})]}),d&&m.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${d.x/m.current.videoWidth*100}%`,top:`${d.y/m.current.videoHeight*100}%`,width:`${d.width/m.current.videoWidth*100}%`,height:`${d.height/m.current.videoHeight*100}%`}}),j&&t.jsxs("div",{className:"nice-barcode-scanner__error",children:[t.jsx("div",{className:"nice-barcode-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-barcode-scanner__error-text",children:j}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>p(),children:c("barcodeScanner.tryAgain","Try Again")})]}),!l&&t.jsx("div",{className:"nice-barcode-scanner__unsupported",children:t.jsx("p",{children:c("barcodeScanner.barcodeScanningIsNotSupported","Barcode scanning is not supported in this browser.")})}),y&&t.jsx("div",{className:"nice-barcode-scanner__overlay",children:y})]})}),{displayName:"NiceBarcodeScanner"}),be=e.createContext(null),Qe=e.createContext(null),le=s=>()=>{process.env.NODE_ENV!=="production"&&console.warn(`[NiceBatchScannerProvider] ${s}: no NiceBatchScanner is mounted below it.`)},fn={items:[],isScanning:!1,addItem:le("addItem"),removeItem:le("removeItem"),updateQuantity:le("updateQuantity"),clearAll:le("clearAll"),startScanning:async()=>le("startScanning")(),stopScanning:le("stopScanning")},mn=()=>{const s=e.useContext(be);if(!s)throw new Error("useBatchScanner must be used inside NiceBatchScanner or below NiceBatchScannerProvider");return s},hn={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},gn=()=>{try{const s=new(window.AudioContext||window.webkitAudioContext),g=s.createOscillator(),c=s.createGain();g.connect(c),c.connect(s.destination),g.frequency.value=1200,g.type="sine",c.gain.setValueAtTime(.3,s.currentTime),c.gain.exponentialRampToValueAtTime(.01,s.currentTime+.1),g.start(),g.stop(s.currentTime+.1)}catch{}},pn=(s=50)=>{"vibrate"in navigator&&navigator.vibrate(s)},yn=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,bn=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{options:w,initialItems:N=[],onScan:x,onRemove:A,onBatchComplete:G,onQuantityChange:C,onError:D,validateScan:a,transformValue:y,className:E,children:f}=s,m=e.useMemo(()=>({...hn,...w}),[w]),I=e.useRef(null),F=e.useRef(null),B=e.useRef(null),$=e.useRef(null),Y=e.useRef(0),H=e.useRef(""),X=e.useRef(0),[O,z]=e.useState(N),[T,M]=e.useState(!1),[j,S]=e.useState(!1),[P,W]=e.useState(""),[i,r]=e.useState([]),[d,n]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const J=await BarcodeDetector.getSupportedFormats();J.length>0&&($.current=new BarcodeDetector({formats:(w==null?void 0:w.formats)||J}),S(!0))}catch{S(!1)}})()},[w==null?void 0:w.formats]);const l=e.useCallback(async(U,J="unknown",ee)=>{const ne=y?y(U,J):U;if(a&&!await a(ne,J))return;const se=O.findIndex(re=>re.value===ne);if(se!==-1&&m.autoIncrementDuplicates){const re=[...O];re[se]={...re[se],quantity:re[se].quantity+1,timestamp:Date.now()},z(re),C==null||C(re[se],re[se].quantity)}else if(O.length<m.maxItems){const re={id:yn(),value:ne,format:J,timestamp:Date.now(),rawValue:U,quantity:1,boundingBox:ee};z(oe=>[re,...oe]),x==null||x(re)}m.beepOnScan&&gn(),m.vibrateOnScan&&pn()},[O,m,a,y,x,C]),o=e.useCallback(U=>{const J=O.find(ee=>ee.id===U);J&&(z(ee=>ee.filter(ne=>ne.id!==U)),A==null||A(J))},[O,A]),h=e.useCallback((U,J)=>{if(J<1){o(U);return}z(ne=>ne.map(se=>se.id===U?{...se,quantity:J}:se));const ee=O.find(ne=>ne.id===U);ee&&(C==null||C(ee,J))},[O,o,C]),v=e.useCallback(()=>{z([])},[]),b=e.useCallback(async()=>{if(!I.current||!$.current||!F.current)return;const U=I.current,J=F.current,ee=J.getContext("2d");if(!ee||U.readyState!==U.HAVE_ENOUGH_DATA){Y.current=requestAnimationFrame(b);return}J.width=U.videoWidth,J.height=U.videoHeight,ee.drawImage(U,0,0);try{const ne=await $.current.detect(J);if(ne.length>0){const se=Date.now(),re=[];for(const oe of ne)re.push(oe.boundingBox),(oe.rawValue!==H.current||se-X.current>2e3)&&(H.current=oe.rawValue,X.current=se,l(oe.rawValue,oe.format,oe.boundingBox));m.showBoundingBox&&(r(re),setTimeout(()=>r([]),500))}}catch(ne){console.warn("Scan error:",ne)}Y.current=requestAnimationFrame(b)},[l,m.showBoundingBox]),k=e.useCallback(async()=>{if(!j||!$.current){n(c("batchScanner.cameraOrBarcodedetectorNotAvailable","Camera or BarcodeDetector not available")),D==null||D(new Error("Camera or BarcodeDetector not available"));return}try{const U=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}}});B.current=U,I.current&&(I.current.srcObject=U,await I.current.play()),M(!0),n(null),Y.current=requestAnimationFrame(b)}catch(U){const J=U instanceof Error?U.message:c("batchScanner.failedToStartCamera","Failed to start camera");n(J),D==null||D(new Error(J))}},[j,b,D,c]),u=e.useCallback(()=>{Y.current&&cancelAnimationFrame(Y.current),B.current&&(B.current.getTracks().forEach(U=>U.stop()),B.current=null),I.current&&(I.current.srcObject=null),M(!1),r([])},[]);e.useEffect(()=>()=>{u()},[u]);const p=e.useCallback(()=>{P.trim()&&(l(P.trim()),W(""))},[P,l]),R=e.useCallback(()=>{const U=["Value","Format","Quantity","Timestamp"],J=O.map(ee=>[`"${ee.value.replace(/"/g,'""')}"`,ee.format,ee.quantity.toString(),new Date(ee.timestamp).toISOString()]);return[U.join(","),...J.map(ee=>ee.join(","))].join(`
|
|
7
|
+
`)},[O]),K=e.useCallback(()=>JSON.stringify(O,null,2),[O]),_=e.useCallback(()=>{u(),G==null||G(O)},[O,u,G]);e.useImperativeHandle(g,()=>({startScanning:k,stopScanning:u,getItems:()=>O,addItem:(U,J)=>l(U,J),removeItem:o,updateQuantity:h,clearAll:v,exportCSV:R,exportJSON:K,isScanning:()=>T}),[k,u,O,l,o,h,v,R,K,T]);const L={items:O,isScanning:T,addItem:(U,J)=>l(U,J),removeItem:o,updateQuantity:h,clearAll:v,startScanning:k,stopScanning:u},q=e.useContext(Qe),V=e.useRef(L);e.useEffect(()=>{V.current=L});const Q=e.useMemo(()=>({items:O,isScanning:T,addItem:(U,J)=>V.current.addItem(U,J),removeItem:U=>V.current.removeItem(U),updateQuantity:(U,J)=>V.current.updateQuantity(U,J),clearAll:()=>V.current.clearAll(),startScanning:()=>V.current.startScanning(),stopScanning:()=>V.current.stopScanning()}),[O,T]);e.useEffect(()=>{q==null||q(Q)},[q,Q]),e.useEffect(()=>{if(q)return()=>q(null)},[q]);const te=O.reduce((U,J)=>U+J.quantity,0),Z=["nice-batch-scanner",T&&"nice-batch-scanner--scanning",E].filter(Boolean).join(" ");return t.jsx(be.Provider,{value:L,children:t.jsxs("div",{className:Z,children:[t.jsxs("div",{className:"nice-batch-scanner__scanner",children:[t.jsx("video",{ref:I,className:"nice-batch-scanner__video",playsInline:!0,muted:!0,autoPlay:!0}),t.jsx("canvas",{ref:F,className:"nice-batch-scanner__canvas"}),I.current&&i.map((U,J)=>{const ee=I.current,ne=ee.clientWidth/ee.videoWidth,se=ee.clientHeight/ee.videoHeight;return t.jsx("div",{className:"nice-batch-scanner__bounding-box",style:{left:U.x*ne,top:U.y*se,width:U.width*ne,height:U.height*se}},J)}),T&&t.jsxs("div",{className:"nice-batch-scanner__frame",children:[t.jsx("div",{className:"nice-batch-scanner__frame-corner nice-batch-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-batch-scanner__frame-corner nice-batch-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-batch-scanner__frame-corner nice-batch-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-batch-scanner__frame-corner nice-batch-scanner__frame-corner--br"}),t.jsx("div",{className:"nice-batch-scanner__scan-line"})]}),d&&t.jsx("div",{className:"nice-batch-scanner__error",children:t.jsx("span",{children:d})}),!T&&!d&&t.jsxs("div",{className:"nice-batch-scanner__placeholder",children:[t.jsx("span",{className:"nice-platform-mark nice-platform-mark--viewfinder","aria-hidden":"true"}),t.jsx("p",{children:c("batchScanner.tapToStartScanning","Tap to start scanning")})]})]}),t.jsxs("div",{className:"nice-batch-scanner__controls",children:[t.jsx("button",{className:`nice-batch-scanner__btn nice-batch-scanner__btn--${T?"stop":"start"}`,onClick:T?u:k,children:T?c("batchScanner.stopScanning","Stop Scanning"):c("batchScanner.startScanning","Start Scanning")}),m.allowManualEntry&&t.jsxs("div",{className:"nice-batch-scanner__manual",children:[t.jsx("input",{type:"text",value:P,onChange:U=>W(U.target.value),onKeyDown:U=>U.key==="Enter"&&p(),placeholder:c("batchScanner.enterCodeManually","Enter code manually..."),className:"nice-batch-scanner__manual-input"}),t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--add",onClick:p,disabled:!P.trim(),children:c("batchScanner.add","Add")})]})]}),t.jsxs("div",{className:"nice-batch-scanner__summary",children:[t.jsxs("span",{className:"nice-batch-scanner__count",children:[t.jsx("strong",{children:O.length})," ",c("batchScanner.uniqueItems","unique items")]}),t.jsxs("span",{className:"nice-batch-scanner__total",children:[t.jsx("strong",{children:te})," ",c("batchScanner.totalQuantity","total quantity")]})]}),t.jsxs("div",{className:"nice-batch-scanner__items",children:[O.map(U=>t.jsxs("div",{className:"nice-batch-scanner__item",children:[t.jsxs("div",{className:"nice-batch-scanner__item-info",children:[t.jsx("span",{className:"nice-batch-scanner__item-value",children:U.value}),t.jsx("span",{className:"nice-batch-scanner__item-format",children:U.format})]}),t.jsxs("div",{className:"nice-batch-scanner__item-quantity",children:[t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>h(U.id,U.quantity-1),"aria-label":c("batchScanner.decreaseQuantity","Decrease quantity"),children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--minus","aria-hidden":"true"})}),t.jsx("span",{className:"nice-batch-scanner__qty-value",children:U.quantity}),t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>h(U.id,U.quantity+1),"aria-label":c("batchScanner.increaseQuantity","Increase quantity"),children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--plus","aria-hidden":"true"})})]}),t.jsx("button",{className:"nice-batch-scanner__item-remove",onClick:()=>o(U.id),"aria-label":c("batchScanner.removeItem","Remove item"),children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]},U.id)),O.length===0&&t.jsx("div",{className:"nice-batch-scanner__empty",children:c("batchScanner.noItemsScannedYet","No items scanned yet")})]}),O.length>0&&t.jsxs("div",{className:"nice-batch-scanner__actions",children:[t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--secondary",onClick:v,children:c("batchScanner.clearAll","Clear All")}),t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--primary",onClick:_,children:c("batchScanner.completeBatch","Complete Batch ({totalQuantity})").replace("{totalQuantity}",String(te))})]}),f]})})}),{displayName:"NiceBatchScanner"}),vn=({children:s})=>{const[g,c]=e.useState(null);return t.jsx(Qe.Provider,{value:c,children:t.jsx(be.Provider,{value:g??fn,children:s})})},wn={errorCorrection:"M",size:200,margin:2,darkColor:"#000000",lightColor:"#ffffff",logoSize:.2,logoMargin:1,cornerRadius:0},xn={L:[41,77,127,187,255,322,370,461,552,652],M:[34,63,101,149,202,255,293,365,432,513],Q:[27,48,77,111,144,178,207,259,312,364],H:[17,34,58,82,106,139,154,202,235,288]},Cn=(s,g)=>{const c=s.length,w=xn[g];for(let N=0;N<w.length;N++)if(w[N]>=c)return N+1;return 10},Ie=(s,g)=>{const c=Cn(s,g),w=c*4+17,N=Array(w).fill(null).map(()=>Array(w).fill(!1)),x=Array(w).fill(null).map(()=>Array(w).fill(!1)),A=(D,a)=>{for(let y=-1;y<=7;y++)for(let E=-1;E<=7;E++){const f=D+y,m=a+E;f<0||f>=w||m<0||m>=w||(x[f][m]=!0,y===-1||y===7||E===-1||E===7?N[f][m]=!1:y===0||y===6||E===0||E===6||y>=2&&y<=4&&E>=2&&E<=4?N[f][m]=!0:N[f][m]=!1)}};A(0,0),A(0,w-7),A(w-7,0);for(let D=8;D<w-8;D++)N[6][D]=D%2===0,N[D][6]=D%2===0,x[6][D]=!0,x[D][6]=!0;if(c>=2){const D=[6,w-7];c>=7&&D.splice(1,0,Math.floor(w/2));for(const a of D)for(const y of D)if(!(a<9&&y<9||a<9&&y>w-10||a>w-10&&y<9))for(let E=-2;E<=2;E++)for(let f=-2;f<=2;f++){const m=a+E,I=y+f;m<0||m>=w||I<0||I>=w||(x[m][I]=!0,N[m][I]=E===-2||E===2||f===-2||f===2||E===0&&f===0)}}const G=s.split("").reduce((D,a)=>(D<<5)-D+a.charCodeAt(0),0);let C=0;for(let D=w-1;D>=0;D-=2){D===6&&(D=5);for(let a=0;a<w;a++)for(let y=0;y<=1;y++){const E=D-y;if(x[a][E])continue;const f=C%s.length,m=s.charCodeAt(f)&1<<C%8,I=(G+a*w+E)%256>127;N[a][E]=m!==0!==I,C++}}return N},kn=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{value:w,options:N,onGenerate:x,onError:A,showBorder:G=!1,className:C}=s,D=JSON.stringify(N??null),a=e.useMemo(()=>({...wn,...JSON.parse(D)}),[D]),y=e.useRef(null),E=e.useRef(null),[f,m]=e.useState(null),[I,F]=e.useState(!(N!=null&&N.logo));e.useEffect(()=>{if(N!=null&&N.logo){const z=new Image;z.crossOrigin="anonymous",z.onload=()=>{E.current=z,F(!0)},z.onerror=()=>{E.current=null,F(!0)},z.src=N.logo}else E.current=null,F(!0)},[N==null?void 0:N.logo]);const B=e.useCallback(()=>{if(!y.current||!w||!I)return;const z=y.current,T=z.getContext("2d");if(T)try{const M=Ie(w,a.errorCorrection),j=M.length,S=Math.floor((a.size-a.margin*2)/j),P=j*S+a.margin*2*S;z.width=P,z.height=P,T.fillStyle=a.lightColor,T.fillRect(0,0,P,P),T.fillStyle=a.darkColor;const W=a.margin*S;for(let r=0;r<j;r++)for(let d=0;d<j;d++)if(M[r][d]){const n=W+d*S,l=W+r*S;if(a.cornerRadius>0){const o=Math.min(a.cornerRadius,S/2);T.beginPath(),T.roundRect(n,l,S,S,o),T.fill()}else T.fillRect(n,l,S,S)}if(E.current){const r=P*a.logoSize,d=(P-r)/2,n=(P-r)/2,l=a.logoMargin*S;T.fillStyle=a.lightColor,T.fillRect(d-l,n-l,r+l*2,r+l*2),T.drawImage(E.current,d,n,r,r)}const i=z.toDataURL("image/png");m(null),x==null||x(i)}catch(M){const j=M instanceof Error?M.message:c("qrGenerator.failedToGenerateQrCode","Failed to generate QR code");m(j),A==null||A(new Error(j))}},[w,a,I,x,A,c]);e.useEffect(()=>{B()},[B]);const $=e.useCallback((z="image/png",T=1)=>{var M;return((M=y.current)==null?void 0:M.toDataURL(z,T))||null},[]),Y=e.useCallback(()=>{if(!y.current||!w)return null;try{const z=Ie(w,a.errorCorrection),T=z.length,M=Math.floor((a.size-a.margin*2)/T),j=T*M+a.margin*2*M,S=a.margin*M,P=[];for(let W=0;W<T;W++)for(let i=0;i<T;i++)if(z[W][i]){const r=S+i*M,d=S+W*M;if(a.cornerRadius>0){const n=Math.min(a.cornerRadius,M/2);P.push(`<rect x="${r}" y="${d}" width="${M}" height="${M}" rx="${n}" fill="${a.darkColor}"/>`)}else P.push(`<rect x="${r}" y="${d}" width="${M}" height="${M}" fill="${a.darkColor}"/>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${j}" height="${j}" viewBox="0 0 ${j} ${j}">
|
|
8
|
+
<rect width="100%" height="100%" fill="${a.lightColor}"/>
|
|
9
9
|
${P.join(`
|
|
10
10
|
`)}
|
|
11
|
-
</svg>`}catch{return null}},[h,i]),z=e.useCallback((F="qrcode",W="png")=>{const j=document.createElement("a");if(W==="svg"){const U=q();if(!U)return;const D=new Blob([U],{type:"image/svg+xml"});j.href=URL.createObjectURL(D),j.download=`${F}.svg`}else{const U=B();if(!U)return;j.href=U,j.download=`${F}.png`}j.click()},[B,q]),Y=e.useCallback(()=>{I()},[I]);e.useImperativeHandle(f,()=>({toDataURL:B,toSVG:q,download:z,regenerate:Y}),[B,q,z,Y]);const K=["nice-qr-generator",R&&"nice-qr-generator--bordered",E&&"nice-qr-generator--error",G].filter(Boolean).join(" ");return t.jsxs("div",{className:K,children:[t.jsx("canvas",{ref:l,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),E&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:E})})]})}),{displayName:"NiceQRGenerator"}),vn={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},xn=n=>{var f,h,k;if(/^https?:\/\//i.test(n))return{type:"url",data:{url:n}};if(/^mailto:/i.test(n)){const g=n.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:g==null?void 0:g[1],params:g==null?void 0:g[2]}}}if(/^tel:/i.test(n))return{type:"tel",data:{phone:n.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(n)){const g=n.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:g==null?void 0:g[1],message:g==null?void 0:g[2]}}}if(/^geo:/i.test(n)){const g=n.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((g==null?void 0:g[1])||"0"),longitude:parseFloat((g==null?void 0:g[2])||"0"),altitude:g!=null&&g[3]?parseFloat(g[3]):void 0}}}if(/^BEGIN:VCARD/i.test(n))return{type:"vcard",data:{raw:n}};if(/^BEGIN:VEVENT/i.test(n))return{type:"vevent",data:{raw:n}};if(/^WIFI:/i.test(n)){const g=(f=n.match(/S:([^;]+)/))==null?void 0:f[1],N=(h=n.match(/P:([^;]+)/))==null?void 0:h[1],R=(k=n.match(/T:([^;]+)/))==null?void 0:k[1],G=n.includes("H:true");return{type:"wifi",data:{ssid:g,password:N,type:R,hidden:G}}}return{type:"text"}},Cn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.type="square",f.frequency.value=1200,h.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},80)}catch{}},kn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},Sn=()=>typeof window<"u"&&"BarcodeDetector"in window,_n=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],Nn=Object.assign(e.forwardRef((n,f)=>{const{config:h,onScan:k,onError:g,onCameraReady:N,autoStart:R=!1,showScanFrame:G=!0,children:i,className:l}=n,b={...vn,...h},E=e.useRef(null),v=e.useRef(null),d=e.useRef(null),p=e.useRef(null),I=e.useRef(null),B=e.useRef(null),[q,z]=e.useState(!1),[Y,K]=e.useState(!1),[F,W]=e.useState(null),[j,U]=e.useState(null),[D,P]=e.useState(null),[T,O]=e.useState(b.facingMode),[y,s]=e.useState(!1),[r,a]=e.useState(!1),[c,o]=e.useState(null),S=Sn(),A=e.useCallback(async()=>{var Q;if(!E.current)return;const J=_n(b.resolution),V={video:{facingMode:T,width:{ideal:J.width},height:{ideal:J.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(V);d.current=ee,E.current.srcObject=ee,await E.current.play();const te=ee.getVideoTracks()[0],ne=(Q=te.getCapabilities)==null?void 0:Q.call(te);s(!!(ne!=null&&ne.torch)),K(!0),P(!0),U(null),N==null||N()}catch(ee){const te=ee instanceof Error?ee.message:"Failed to access camera";U(te),P(!1),g==null||g(new Error(te))}},[b.resolution,T,N,g]),m=e.useCallback(()=>{d.current&&(d.current.getTracks().forEach(J=>J.stop()),d.current=null),E.current&&(E.current.srcObject=null),K(!1),a(!1)},[]),w=e.useCallback(async()=>{O(T==="user"?"environment":"user"),q&&m()},[T,q,m]),u=e.useCallback(async()=>{if(!d.current||!y)return;const J=d.current.getVideoTracks()[0],V=!r;try{await J.applyConstraints({advanced:[{torch:V}]}),a(V)}catch{}},[y,r]),C=e.useCallback(async()=>{if(S)try{const J=window.BarcodeDetector;p.current=new J({formats:["qr_code"]})}catch(J){const V=J instanceof Error?J.message:"Failed to initialize QR detector";U(V),g==null||g(new Error(V))}},[S,g]),x=e.useCallback((J,V)=>{const Q={text:J,boundingBox:V.boundingBox?{x:V.boundingBox.x,y:V.boundingBox.y,width:V.boundingBox.width,height:V.boundingBox.height}:void 0,cornerPoints:V.cornerPoints,timestamp:new Date};if(b.parseDataType){const ee=xn(J);Q.dataType=ee.type,Q.parsedData=ee.data}return Q},[b.parseDataType]),H=e.useCallback(async()=>{if(!(!E.current||!p.current||!Y))try{const V=await p.current.detect(E.current);if(V.length>0){const Q=V[0];if(b.continuous&&Q.rawValue===B.current)return;B.current=Q.rawValue;const ee=x(Q.rawValue,Q);b.highlightDetected&&ee.boundingBox&&(o(ee.boundingBox),setTimeout(()=>o(null),500)),b.beepOnScan&&Cn(),b.vibrateOnScan&&kn(),W(ee),k==null||k(ee),setTimeout(()=>{B.current=null},1e3)}}catch{}},[Y,b.continuous,b.highlightDetected,b.beepOnScan,b.vibrateOnScan,x,k]),_=e.useCallback(async()=>{z(!0),U(null),await C(),await A()},[C,A]),M=e.useCallback(()=>{z(!1),I.current&&(clearInterval(I.current),I.current=null),m()},[m]),L=e.useCallback(async()=>{q?M():await _()},[q,_,M]),X=e.useCallback(()=>{if(!E.current||!v.current)return null;const J=v.current,V=E.current;J.width=V.videoWidth,J.height=V.videoHeight;const Q=J.getContext("2d");return Q?(Q.drawImage(V,0,0),J.toDataURL("image/png")):null},[]),$=e.useCallback(async J=>!S||!p.current?null:new Promise(V=>{const Q=new Image;Q.onload=async()=>{try{const te=await p.current.detect(Q);if(te.length>0){const ne=x(te[0].rawValue,te[0]);V(ne)}else V(null)}catch{V(null)}},Q.onerror=()=>V(null),Q.src=URL.createObjectURL(J)}),[S,x]);e.useEffect(()=>(q&&Y&&b.continuous&&(I.current=setInterval(H,b.scanInterval)),()=>{I.current&&(clearInterval(I.current),I.current=null)}),[q,Y,b.continuous,b.scanInterval,H]),e.useEffect(()=>(R&&_(),()=>{M()}),[]),e.useEffect(()=>{q&&!Y&&A()},[T,q,Y,A]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:q,isCameraReady:Y,lastResult:F,error:j,isSupported:S,hasPermission:D,torchAvailable:y,torchOn:r}),start:_,stop:M,toggle:L,switchCamera:w,toggleTorch:u,takeSnapshot:X,scanImage:$}),[q,Y,F,j,S,D,y,r,_,M,L,w,u,X,$]);const Z=["nice-qr-scanner",q&&"nice-qr-scanner--scanning",Y&&"nice-qr-scanner--ready",j&&"nice-qr-scanner--error",l].filter(Boolean).join(" ");return t.jsxs("div",{className:Z,children:[t.jsx("video",{ref:E,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:v,className:"nice-qr-scanner__canvas"}),G&&q&&t.jsxs("div",{className:"nice-qr-scanner__frame",children:[t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--br"})]}),c&&E.current&&t.jsx("div",{className:"nice-qr-scanner__bounding-box",style:{left:`${c.x/E.current.videoWidth*100}%`,top:`${c.y/E.current.videoHeight*100}%`,width:`${c.width/E.current.videoWidth*100}%`,height:`${c.height/E.current.videoHeight*100}%`}}),j&&t.jsxs("div",{className:"nice-qr-scanner__error",children:[t.jsx("div",{className:"nice-qr-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-qr-scanner__error-text",children:j}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>_(),children:"Try Again"})]}),!S&&t.jsx("div",{className:"nice-qr-scanner__unsupported",children:t.jsx("p",{children:"QR scanning is not supported in this browser."})}),i&&t.jsx("div",{className:"nice-qr-scanner__overlay",children:i})]})}),{displayName:"NiceQRScanner"}),pe=e.createContext(null),jn=()=>{const n=e.useContext(pe);if(!n)throw new Error("useSymbology must be used within NiceSymbologyConfigProvider");return n},ie=[{id:"code128",name:"Code 128",category:"linear",description:"High-density barcode for alphanumeric data. Auto-switches between subsets A/B/C.",charset:"ASCII 0-127",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Shipping labels","Inventory","General purpose"],standard:"ISO/IEC 15417",detectorFormat:"code_128"},{id:"code128a",name:"Code 128A",category:"linear",description:"Code 128 subset A: uppercase + control characters.",charset:"ASCII 0-95 (uppercase, digits, control chars)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Systems with control characters","Legacy integration"],standard:"ISO/IEC 15417"},{id:"code128b",name:"Code 128B",category:"linear",description:"Code 128 subset B: uppercase + lowercase.",charset:"ASCII 32-127 (upper/lowercase, digits, symbols)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Alphanumeric data","Mixed case text"],standard:"ISO/IEC 15417"},{id:"code128c",name:"Code 128C",category:"linear",description:"Code 128 subset C: double-density numeric only.",charset:"0-9 (pairs only)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Long numeric values","Compact encoding"],standard:"ISO/IEC 15417"},{id:"code39",name:"Code 39",category:"linear",description:"Self-checking barcode supporting uppercase and digits.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Military (LOGMARS)","Automotive (AIAG)","Healthcare"],standard:"ISO/IEC 16388",detectorFormat:"code_39"},{id:"code93",name:"Code 93",category:"linear",description:"Compact barcode, denser than Code 39.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Canadian postal","General logistics"],standard:"ANSI/AIM BC5",detectorFormat:"code_93"},{id:"codabar",name:"Codabar",category:"linear",description:"Numeric barcode used in libraries and blood banks.",charset:"0-9, -, $, :, /, ., +, A-D (start/stop)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Blood banks","Libraries","FedEx"],standard:"ANSI/AIM BC3",detectorFormat:"codabar"},{id:"ean13",name:"EAN-13",category:"linear",description:"European Article Numbering — worldwide retail standard.",charset:"0-9",minLength:12,maxLength:12,fixedLength:13,hasCheckDigit:!0,useCases:["Retail worldwide","ISBN","ISSN"],standard:"ISO/IEC 15420",detectorFormat:"ean_13"},{id:"ean8",name:"EAN-8",category:"linear",description:"Compact version of EAN-13 for small products.",charset:"0-9",minLength:7,maxLength:7,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Space-constrained packaging"],standard:"ISO/IEC 15420",detectorFormat:"ean_8"},{id:"ean5",name:"EAN-5 Supplement",category:"linear",description:"5-digit addon for periodicals and books.",charset:"0-9",minLength:5,maxLength:5,fixedLength:5,hasCheckDigit:!0,useCases:["Book pricing","Magazine issues"],standard:"ISO/IEC 15420"},{id:"ean2",name:"EAN-2 Supplement",category:"linear",description:"2-digit addon for periodicals.",charset:"0-9",minLength:2,maxLength:2,fixedLength:2,hasCheckDigit:!1,useCases:["Magazine issue numbers"],standard:"ISO/IEC 15420"},{id:"upc_a",name:"UPC-A",category:"linear",description:"Universal Product Code — North American retail standard.",charset:"0-9",minLength:11,maxLength:11,fixedLength:12,hasCheckDigit:!0,useCases:["US/Canada retail","Point of Sale"],standard:"ISO/IEC 15420",detectorFormat:"upc_a"},{id:"upc_e",name:"UPC-E",category:"linear",description:"Compressed UPC for small packages.",charset:"0-9",minLength:6,maxLength:6,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Compact packaging"],standard:"ISO/IEC 15420",detectorFormat:"upc_e"},{id:"itf",name:"Interleaved 2 of 5",category:"linear",description:"Numeric pairs encoded in interleaved format.",charset:"0-9 (even length)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Warehouse distribution","Packaging"],standard:"ISO/IEC 16390",detectorFormat:"itf"},{id:"itf14",name:"ITF-14",category:"linear",description:"GTIN-14 barcode for shipping containers.",charset:"0-9",minLength:13,maxLength:13,fixedLength:14,hasCheckDigit:!0,useCases:["Shipping containers","Outer packaging"],standard:"ISO/IEC 16390"},{id:"msi",name:"MSI (Modified Plessey)",category:"linear",description:"Numeric barcode used in inventory management.",charset:"0-9",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Retail shelves","Inventory"],standard:"Proprietary"},{id:"pharmacode",name:"Pharmacode",category:"linear",description:"Pharmaceutical packaging identification.",charset:"3-131070 (numeric value)",minLength:1,maxLength:6,fixedLength:null,hasCheckDigit:!1,useCases:["Pharmaceutical packaging","Drug identification"],standard:"Laetus"},{id:"plessey",name:"Plessey",category:"linear",description:"Legacy barcode used in UK libraries.",charset:"0-9, A-F",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Legacy systems"],standard:"Proprietary"},{id:"telepen",name:"Telepen",category:"linear",description:"Full ASCII barcode used in UK libraries.",charset:"Full ASCII",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Inventory"],standard:"AIM"},{id:"qr_code",name:"QR Code",category:"2d",description:"Quick Response code — high capacity 2D barcode.",charset:"Full Unicode",minLength:1,maxLength:7089,fixedLength:null,hasCheckDigit:!0,useCases:["Mobile scanning","URLs","vCards","Payments"],standard:"ISO/IEC 18004",detectorFormat:"qr_code"},{id:"data_matrix",name:"Data Matrix",category:"2d",description:"High-density 2D code for small items.",charset:"Full ASCII",minLength:1,maxLength:2335,fixedLength:null,hasCheckDigit:!0,useCases:["Electronics","PCB marking","Medical devices","Aerospace"],standard:"ISO/IEC 16022",detectorFormat:"data_matrix"},{id:"aztec",name:"Aztec Code",category:"2d",description:"Compact 2D code, no quiet zone required.",charset:"Full ASCII",minLength:1,maxLength:3832,fixedLength:null,hasCheckDigit:!0,useCases:["Transport tickets","Boarding passes","Government IDs"],standard:"ISO/IEC 24778",detectorFormat:"aztec"},{id:"pdf417",name:"PDF417",category:"2d",description:"Stacked linear barcode with high capacity.",charset:"Full ASCII",minLength:1,maxLength:1850,fixedLength:null,hasCheckDigit:!0,useCases:["ID cards","Driver's licenses","Airline boarding","Postage"],standard:"ISO/IEC 15438",detectorFormat:"pdf417"},{id:"maxicode",name:"MaxiCode",category:"2d",description:"Fixed-size 2D code used by UPS.",charset:"Full ASCII",minLength:1,maxLength:93,fixedLength:null,hasCheckDigit:!0,useCases:["UPS shipping","High-speed sorting"],standard:"ISO/IEC 16023"},{id:"gs1_128",name:"GS1-128",category:"gs1",description:"Application Identifier-based supply chain barcode.",charset:"Full ASCII (with AI prefixes)",minLength:1,maxLength:48,fixedLength:null,hasCheckDigit:!0,useCases:["Supply chain","Healthcare","Food traceability"],standard:"ISO/IEC 15417 + GS1 General Specifications"},{id:"gs1_databar",name:"GS1 DataBar",category:"gs1",description:"Compact GS1 barcode for fresh food and coupons.",charset:"0-9 (GTIN-based)",minLength:14,maxLength:74,fixedLength:null,hasCheckDigit:!0,useCases:["Fresh food","Pharmacy","Coupons","Variable weight"],standard:"ISO/IEC 24724"}],de=(n,f)=>{const h=ie.find(i=>i.id===f);if(!h)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const k=[],g=[],N=h.fixedLength&&h.hasCheckDigit?h.fixedLength-1:h.fixedLength,R=!!h.fixedLength&&h.hasCheckDigit&&n.length===h.fixedLength;switch(h.fixedLength?n.length!==N&&!R&&k.push(h.hasCheckDigit?`Expected ${N} digits, or ${h.fixedLength} with the check digit; got ${n.length}`:`Expected ${h.fixedLength} characters, got ${n.length}`):(n.length<h.minLength&&k.push(`Minimum ${h.minLength} characters required`),n.length>h.maxLength&&k.push(`Maximum ${h.maxLength} characters allowed`)),f){case"ean13":case"ean8":case"ean5":case"ean2":case"upc_a":case"upc_e":case"itf":case"itf14":case"msi":case"pharmacode":/^\d+$/.test(n)||k.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(n)||k.push("Only numeric digits allowed"),n.length%2!==0&&g.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(n.toUpperCase())||k.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(n.toUpperCase())||k.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(n)||k.push("Only hex characters (0-9, A-F) allowed");break}let G;if(h.hasCheckDigit&&k.length===0)switch(f){case"ean13":case"ean8":case"upc_a":case"itf14":{const i=(R?n.slice(0,-1):n).split("").map(Number);let l=0;for(let b=0;b<i.length;b++)l+=i[b]*((i.length-1-b)%2===0?3:1);G=String((10-l%10)%10),R&&n[n.length-1]!==G&&k.push(`Check digit should be ${G}, not ${n[n.length-1]}`);break}}return f==="itf"&&n.length%2!==0&&k.push("ITF requires even number of digits"),{valid:k.length===0,errors:k,warnings:g,checkDigit:G,formattedValue:G&&!R?n+G:n}},Se={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},In=Object.assign(e.forwardRef((n,f)=>{const{selected:h,onChange:k,category:g="all",multiSelect:N=!0,showDetails:R=!0,showValidation:G=!1,testValue:i="",readOnly:l=!1,className:b}=n,[E,v]=e.useState([]),[d,p]=e.useState(null),I=h??E,B=e.useMemo(()=>g==="all"?ie:ie.filter(y=>y.category===g),[g]),q=e.useMemo(()=>{const y={};for(const s of B)y[s.category]||(y[s.category]=[]),y[s.category].push(s);return y},[B]),z=e.useCallback(y=>{h||v(y),k==null||k(y)},[h,k]),Y=e.useCallback(y=>{N?I.includes(y)||z([...I,y]):z([y])},[I,N,z]),K=e.useCallback(y=>{z(I.filter(s=>s!==y))},[I,z]),F=e.useCallback(y=>{l||(I.includes(y)?K(y):Y(y))},[I,l,Y,K]),W=e.useCallback(()=>{z(B.map(y=>y.id))},[B,z]),j=e.useCallback(()=>{z([])},[z]),U=e.useCallback(y=>ie.find(s=>s.id===y),[]),D=e.useMemo(()=>!G||!i||!d?null:de(i,d),[G,i,d]);e.useImperativeHandle(f,()=>({getSelected:()=>I,select:Y,deselect:K,selectAll:W,clearSelection:j,validate:de,getInfo:U,getAll:()=>ie}),[I,Y,K,W,j,U]);const P=e.useMemo(()=>({symbologies:ie,selected:I,validate:de,getInfo:U}),[I,U]),T=d?U(d):null,O=["nice-symbology-config",l&&"nice-symbology-config--readonly",b].filter(Boolean).join(" ");return t.jsx(pe.Provider,{value:P,children:t.jsxs("div",{className:O,children:[N&&!l&&t.jsxs("div",{className:"nice-symbology-config__toolbar",children:[t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:W,children:"Select All"}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:j,children:"Clear"}),t.jsxs("span",{className:"nice-symbology-config__count",children:[I.length," / ",B.length," selected"]})]}),t.jsxs("div",{className:"nice-symbology-config__content",children:[t.jsx("div",{className:"nice-symbology-config__list",children:Object.entries(q).map(([y,s])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:Se[y]||y}),t.jsx("div",{className:"nice-symbology-config__grid",children:s.map(r=>{const a=I.includes(r.id),c=d===r.id;return t.jsxs("div",{className:["nice-symbology-config__item",a&&"nice-symbology-config__item--selected",c&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{F(r.id),p(r.id)},role:"option","aria-selected":a,tabIndex:0,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),F(r.id),p(r.id))},children:[N&&t.jsx("span",{className:`nice-symbology-config__checkbox ${a?"nice-symbology-config__checkbox--checked":""}`,children:a&&t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}})}),t.jsxs("div",{className:"nice-symbology-config__item-info",children:[t.jsx("span",{className:"nice-symbology-config__item-name",children:r.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:r.fixedLength?`${r.fixedLength} digits`:`${r.minLength}-${r.maxLength} chars`})]})]},r.id)})})]},y))}),R&&T&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:T.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:T.description}),t.jsxs("div",{className:"nice-symbology-config__details-props",children:[t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Category"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:Se[T.category]})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Character Set"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.charset})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Length"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.fixedLength?`Fixed: ${T.fixedLength}`:`${T.minLength} – ${T.maxLength}`})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Check Digit"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.hasCheckDigit?"Yes":"No"})]}),T.standard&&t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Standard"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.standard})]})]}),t.jsxs("div",{className:"nice-symbology-config__use-cases",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Use Cases"}),t.jsx("div",{className:"nice-symbology-config__tags",children:T.useCases.map(y=>t.jsx("span",{className:"nice-symbology-config__tag",children:y},y))})]}),G&&D&&t.jsxs("div",{className:"nice-symbology-config__validation",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Validation"}),t.jsxs("div",{className:`nice-symbology-config__validation-result ${D.valid?"nice-symbology-config__validation-result--valid":"nice-symbology-config__validation-result--invalid"}`,children:[t.jsx("span",{children:D.valid?"Valid":"Invalid"}),D.checkDigit&&t.jsxs("span",{children:["Check digit: ",D.checkDigit]})]}),D.errors.map((y,s)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:y},s)),D.warnings.map((y,s)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:y},s))]})]})]})]})})}),{displayName:"NiceSymbologyConfig"}),En=({children:n})=>{const f=e.useCallback(k=>ie.find(g=>g.id===k),[]),h={symbologies:ie,selected:[],validate:de,getInfo:f};return t.jsx(pe.Provider,{value:h,children:n})},Ye=e.createContext(null),Dn=()=>{const n=e.useContext(Ye);if(!n)throw new Error("useBackgroundSync must be used within NiceBackgroundSyncProvider");return n},An={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},Pn=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Ln=n=>new Promise(f=>setTimeout(f,n)),Xe=Object.assign(e.forwardRef((n,f)=>{const{config:h,handlers:k,onSyncStart:g,onSyncComplete:N,onTaskSuccess:R,onTaskFailed:G,onOnlineChange:i,children:l}=n,b={...An,...h},E=e.useRef(null),v=e.useRef(!1),[d,p]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),I=e.useCallback(async()=>E.current?E.current:new Promise((a,c)=>{const o=indexedDB.open(b.dbName,1);o.onerror=()=>c(o.error),o.onupgradeneeded=()=>{const S=o.result;if(!S.objectStoreNames.contains(b.storeName)){const A=S.createObjectStore(b.storeName,{keyPath:"id"});A.createIndex("tag","tag",{unique:!1}),A.createIndex("status","status",{unique:!1}),A.createIndex("priority","priority",{unique:!1})}},o.onsuccess=()=>{E.current=o.result,a(o.result)}}),[b.dbName,b.storeName]),B=e.useCallback(async(a,c,o)=>{const S=await I(),A={id:Pn(),tag:a,data:c,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(o==null?void 0:o.maxAttempts)??b.defaultMaxAttempts,priority:(o==null?void 0:o.priority)??0};return new Promise((m,w)=>{const x=S.transaction(b.storeName,"readwrite").objectStore(b.storeName).add(A);x.onerror=()=>w(x.error),x.onsuccess=()=>{p(H=>({...H,pendingCount:H.pendingCount+1})),m(A.id)}})},[I,b.storeName,b.defaultMaxAttempts]),q=e.useCallback(async a=>{const c=await I();return new Promise((o,S)=>{const w=c.transaction(b.storeName,"readwrite").objectStore(b.storeName).delete(a);w.onerror=()=>S(w.error),w.onsuccess=()=>o(!0)})},[I,b.storeName]),z=e.useCallback(async a=>{const c=await I();return new Promise((o,S)=>{const m=c.transaction(b.storeName,"readonly").objectStore(b.storeName),w=a?m.index("tag").getAll(a):m.getAll();w.onerror=()=>S(w.error),w.onsuccess=()=>o(w.result)})},[I,b.storeName]),Y=e.useCallback(async a=>(await z(a)).filter(o=>o.status==="pending"),[z]),K=e.useCallback(async a=>(await z(a)).filter(o=>o.status==="failed"),[z]),F=e.useCallback(async a=>{const c=await I();return new Promise((o,S)=>{const w=c.transaction(b.storeName,"readwrite").objectStore(b.storeName).put(a);w.onerror=()=>S(w.error),w.onsuccess=()=>o()})},[I,b.storeName]),W=e.useCallback(async()=>{const a=await z(),c=a.filter(S=>S.status==="pending").length,o=a.filter(S=>S.status==="failed").length;p(S=>({...S,pendingCount:c,failedCount:o}))},[z]),j=e.useCallback(async a=>{const c=k[a.tag];if(!c)return console.warn(`No handler registered for tag: ${a.tag}`),!1;a.status="syncing",a.lastAttemptAt=new Date,a.attempts++,await F(a);try{return await c.handler(a),a.status="success",await F(a),R==null||R(a),await q(a.id),!0}catch(o){const S=o instanceof Error?o.message:"Unknown error";return a.error=S,a.attempts>=a.maxAttempts?(a.status="failed",G==null||G(a,o instanceof Error?o:new Error(S))):a.status="pending",await F(a),!1}},[k,F,q,R,G]),U=e.useCallback(async a=>{if(d.isSyncing)return{success:0,failed:0};v.current=!1,p(o=>({...o,isSyncing:!0,syncProgress:0,error:void 0})),g==null||g();const c={success:0,failed:0};try{const o=await Y(a);o.sort((A,m)=>m.priority-A.priority);const S=o.length;for(let A=0;A<o.length&&!v.current;A++){const m=o[A],w=await j(m);if(w?c.success++:m.attempts>=m.maxAttempts&&c.failed++,!w&&m.attempts<m.maxAttempts){const u=Math.min(b.retryDelay*Math.pow(b.backoffFactor,m.attempts-1),b.maxRetryDelay);await Ln(u)}p(u=>({...u,syncProgress:Math.round((A+1)/S*100)}))}}catch(o){const S=o instanceof Error?o.message:"Sync failed";p(A=>({...A,error:S}))}return await W(),p(o=>({...o,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),N==null||N(c),c},[d.isSyncing,Y,j,b.retryDelay,b.backoffFactor,b.maxRetryDelay,W,g,N]),D=e.useCallback(()=>{v.current=!0},[]),P=e.useCallback(async a=>{const o=(await z()).find(S=>S.id===a);o&&o.status==="failed"&&(o.status="pending",o.attempts=0,o.error=void 0,await F(o),await W())},[z,F,W]),T=e.useCallback(async a=>{const c=await K(a);for(const o of c)o.status="pending",o.attempts=0,o.error=void 0,await F(o);await W()},[K,F,W]),O=e.useCallback(async a=>{const c=await I(),o=await z(a);return new Promise((S,A)=>{const m=c.transaction(b.storeName,"readwrite"),w=m.objectStore(b.storeName);m.onerror=()=>A(m.error),m.oncomplete=async()=>{await W(),S()};for(const u of o)w.delete(u.id)})},[I,z,b.storeName,W]),y=e.useCallback(async a=>{const c=await I(),o=await K(a);return new Promise((S,A)=>{const m=c.transaction(b.storeName,"readwrite"),w=m.objectStore(b.storeName);m.onerror=()=>A(m.error),m.oncomplete=async()=>{await W(),S()};for(const u of o)w.delete(u.id)})},[I,K,b.storeName,W]),s=e.useCallback(async a=>{if(!("serviceWorker"in navigator))return!1;try{const c=await navigator.serviceWorker.ready;if("sync"in c)return await c.sync.register(a),!0}catch(c){console.warn("Background Sync registration failed:",c)}return!1},[]);e.useEffect(()=>{const a=()=>{p(o=>({...o,isOnline:!0})),i==null||i(!0),b.autoSyncOnConnect&&U()},c=()=>{p(o=>({...o,isOnline:!1})),i==null||i(!1)};return window.addEventListener("online",a),window.addEventListener("offline",c),()=>{window.removeEventListener("online",a),window.removeEventListener("offline",c)}},[b.autoSyncOnConnect,U,i]),e.useEffect(()=>{if(b.periodicSyncInterval<=0)return;const a=setInterval(()=>{d.isOnline&&!d.isSyncing&&U()},b.periodicSyncInterval);return()=>clearInterval(a)},[b.periodicSyncInterval,d.isOnline,d.isSyncing,U]),e.useEffect(()=>{W()},[W]),e.useImperativeHandle(f,()=>({getState:()=>d,addTask:B,removeTask:q,getTasks:z,getPendingTasks:Y,getFailedTasks:K,retryTask:P,retryAllFailed:T,clearTasks:O,clearFailed:y,syncNow:U,cancelSync:D,registerBackgroundSync:s}),[d,B,q,z,Y,K,P,T,O,y,U,D,s]);const r={...d,addTask:B,removeTask:q,getTasks:z,getPendingTasks:Y,getFailedTasks:K,retryTask:P,retryAllFailed:T,clearTasks:O,clearFailed:y,syncNow:U,cancelSync:D};return t.jsx(Ye.Provider,{value:r,children:l})}),{displayName:"NiceBackgroundSync"}),Ke=Xe;process.env.NODE_ENV!=="production"&&(Ke.displayName="NiceBackgroundSyncProvider");const Qe=e.createContext(null),Je=()=>{const n=e.useContext(Qe);if(!n)throw new Error("useCacheStrategies must be used within NiceCacheStrategiesProvider");return n},Rn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class On{constructor(){oe(this,"dbName","nice-cache-db");oe(this,"storeName","cache-entries");oe(this,"db",null)}async init(){if(!this.db)return new Promise((f,h)=>{const k=indexedDB.open(this.dbName,1);k.onerror=()=>h(k.error),k.onupgradeneeded=()=>{const g=k.result;g.objectStoreNames.contains(this.storeName)||g.createObjectStore(this.storeName,{keyPath:"key"})},k.onsuccess=()=>{this.db=k.result,f()}})}async get(f){if(await this.init(),!!this.db)return new Promise((h,k)=>{const R=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(f);R.onerror=()=>k(R.error),R.onsuccess=()=>{const G=R.result;h(G?G.value:void 0)}})}async set(f,h){if(await this.init(),!!this.db)return new Promise((k,g)=>{const G=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:f,value:h});G.onerror=()=>g(G.error),G.onsuccess=()=>k()})}async delete(f){return await this.init(),this.db?new Promise((h,k)=>{const R=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(f);R.onerror=()=>k(R.error),R.onsuccess=()=>h(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();N.onerror=()=>h(N.error),N.onsuccess=()=>f(N.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();N.onerror=()=>h(N.error),N.onsuccess=()=>f()})}async getAll(){return await this.init(),this.db?new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();N.onerror=()=>h(N.error),N.onsuccess=()=>f(N.result)}):[]}}const Ze=Object.assign(e.forwardRef((n,f)=>{const{config:h,routeStrategies:k={},precacheUrls:g=[],onFetch:N,onCacheHit:R,onCacheMiss:G,onNetworkError:i,children:l}=n,b={...Rn,...h},E=e.useRef(new On),[v,d]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:b.defaultStrategy}),p=e.useCallback(s=>{for(const[r,a]of Object.entries(k))if(new RegExp(r).test(s))return a;return v.strategy},[k,v.strategy]),I=e.useCallback(s=>{d(r=>({...r,strategy:s}))},[]),B=e.useCallback(async s=>{const r=await E.current.get(s);if(!r)return;const a=Date.now(),c=r.expiresAt&&r.expiresAt<a,o=r.timestamp+b.staleThreshold<a;if(c&&!b.serveStale){await E.current.delete(s);return}return{data:r.data,timestamp:new Date(r.timestamp),expiresAt:r.expiresAt?new Date(r.expiresAt):void 0,etag:r.etag,key:s,isStale:o||!!c,source:"cache",url:r.url}},[b.staleThreshold,b.serveStale]),q=e.useCallback(async()=>{const s=await E.current.getAll();let r=0,a,c;for(const o of s){const S=JSON.stringify(o.value.data).length;r+=S,(!a||o.value.timestamp<a)&&(a=o.value.timestamp),(!c||o.value.timestamp>c)&&(c=o.value.timestamp)}return{size:r,entryCount:s.length,oldestEntry:a?new Date(a):void 0,newestEntry:c?new Date(c):void 0}},[]),z=e.useCallback(async()=>{const s=await q();d(r=>({...r,entryCount:s.entryCount,totalSize:s.size}))},[q]),Y=e.useCallback(async(s,r,a)=>{const c=Date.now(),o={data:r,timestamp:c,expiresAt:a?c+a:c+b.defaultTTL};if(await E.current.set(s,o),(await E.current.keys()).length>b.maxEntries){const A=await E.current.getAll();A.sort((w,u)=>w.value.timestamp-u.value.timestamp);const m=A.slice(0,A.length-b.maxEntries);for(const w of m)await E.current.delete(w.key)}await z()},[b.defaultTTL,b.maxEntries,z]),K=e.useCallback(async s=>{const r=await E.current.delete(s);return await z(),r},[z]),F=e.useCallback(async()=>{await E.current.clear(),d(s=>({...s,entryCount:0,totalSize:0}))},[]),W=e.useCallback(async()=>E.current.keys(),[]),j=e.useCallback(async s=>await B(s)!==void 0,[B]),U=e.useCallback(async s=>{const r=await E.current.keys();let a=0;for(const c of r)s.test(c)&&(await E.current.delete(c),a++);return await z(),a},[z]),D=e.useCallback(async(s,r,a)=>{const c=new AbortController,o=setTimeout(()=>c.abort(),a);try{const S=await fetch(s,{...r,signal:c.signal});return clearTimeout(o),S}catch(S){throw clearTimeout(o),S}},[]),P=e.useCallback(async(s,r={})=>{const{strategy:a=p(s),ttl:c,cacheKey:o=s,forceRefresh:S=!1,timeout:A=b.networkTimeout,...m}=r;d(u=>({...u,isFetching:!0}));const w=async()=>{try{const u=await D(s,m,A);if(!u.ok)throw new Error(`HTTP ${u.status}`);const C=await u.json(),x=u.headers.get("etag")||void 0;await Y(o,C,c);const H={data:C,timestamp:new Date,etag:x,key:o,isStale:!1,source:"network",url:s};return d(_=>({..._,isFetching:!1})),N==null||N(H),H}catch(u){throw i==null||i(u instanceof Error?u:new Error(String(u)),s),u}};try{switch(a){case"cache-only":{const u=await B(o);if(u)return d(C=>({...C,isFetching:!1,hits:C.hits+1})),R==null||R(u),u;throw d(C=>({...C,isFetching:!1,misses:C.misses+1})),G==null||G(s),new Error("No cache entry found")}case"network-only":return d(u=>({...u,misses:u.misses+1})),await w();case"cache-first":{if(!S){const u=await B(o);if(u&&!u.isStale)return d(C=>({...C,isFetching:!1,hits:C.hits+1})),R==null||R(u),u}return d(u=>({...u,misses:u.misses+1})),await w()}case"network-first":try{return d(u=>({...u,misses:u.misses+1})),await w()}catch(u){const C=await B(o);if(C)return d(x=>({...x,isFetching:!1,hits:x.hits+1})),R==null||R(C),C;throw u}case"stale-while-revalidate":default:{const u=await B(o);return u&&!S?(d(C=>({...C,hits:C.hits+1})),R==null||R(u),u.isStale&&w().catch(()=>{}),d(C=>({...C,isFetching:!1})),u):(d(C=>({...C,misses:C.misses+1})),await w())}}}catch(u){throw d(C=>({...C,isFetching:!1})),u}},[p,b.networkTimeout,D,B,Y,N,R,G,i]),T=e.useCallback(async(s,r)=>(await P(s,r)).data,[P]),O=e.useCallback(async(s,r)=>{await Promise.all(s.map(a=>P(a,{...r,strategy:"network-first"}).catch(()=>{})))},[P]);e.useEffect(()=>{g.length>0&&O(g)},[g,O]),e.useEffect(()=>{(async()=>{await E.current.init();const r=await q();d(a=>({...a,totalSize:r.size,entryCount:r.entryCount}))})()},[q]),e.useImperativeHandle(f,()=>({getState:()=>v,fetch:P,fetchJSON:T,getFromCache:B,addToCache:Y,removeFromCache:K,clearCache:F,getCacheKeys:W,getCacheStats:q,prefetch:O,isCached:j,invalidateByPattern:U,setStrategy:I,getStrategyForUrl:p}),[v,P,T,B,Y,K,F,W,q,O,j,U,I,p]);const y={...v,fetch:P,fetchJSON:T,getFromCache:B,addToCache:Y,removeFromCache:K,clearCache:F,getCacheKeys:W,prefetch:O,isCached:j,setStrategy:I,getStrategyForUrl:p};return t.jsx(Qe.Provider,{value:y,children:l})}),{displayName:"NiceCacheStrategies"}),et=Ze;process.env.NODE_ENV!=="production"&&(et.displayName="NiceCacheStrategiesProvider");function Tn(n,f){const h=Je(),[k,g]=e.useState(void 0),[N,R]=e.useState(!1),[G,i]=e.useState(void 0),l=e.useCallback(async()=>{if(n){R(!0),i(void 0);try{const b=await h.fetchJSON(n,f);g(b)}catch(b){i(b instanceof Error?b:new Error(String(b)))}finally{R(!1)}}},[n,f,h]);return e.useEffect(()=>{l()},[l]),{data:k,isLoading:N,error:G,refetch:l}}const tt=e.createContext(null),Mn=()=>{const n=e.useContext(tt);if(!n)throw new Error("useConflictResolution must be used within NiceConflictResolutionProvider");return n},Fn={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},Bn=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,$n=n=>JSON.stringify(n),qn=(n,f)=>JSON.stringify(n)===JSON.stringify(f),Un=(n,f,h)=>({...n,...f}),nt=Object.assign(e.forwardRef((n,f)=>{const{config:h,handlers:k={},showConflictUI:g=!0,uiPosition:N="modal",autoOpenUI:R=!0,onConflictDetected:G,onConflictResolved:i,onResolutionFailed:l,renderConflictList:b,renderConflictItem:E,children:v}=n,d={...Fn,...h},[p,I]=e.useState([]),[B,q]=e.useState(!1),[z,Y]=e.useState(!1),K=e.useCallback(_=>k[_]||{},[k]),F=e.useCallback(_=>({pending:_.filter(M=>M.status==="pending").length,resolving:_.filter(M=>M.status==="resolving").length,resolved:_.filter(M=>M.status==="resolved").length,failed:_.filter(M=>M.status==="failed").length}),[]),W={conflicts:p,isResolving:B,counts:F(p)},j=e.useCallback(()=>{if(d.persistConflicts)try{const _=localStorage.getItem(d.storageKey);if(_){const L=JSON.parse(_).map(X=>({...X,createdAt:new Date(X.createdAt),resolvedAt:X.resolvedAt?new Date(X.resolvedAt):void 0,clientVersion:{...X.clientVersion,timestamp:new Date(X.clientVersion.timestamp)},serverVersion:{...X.serverVersion,timestamp:new Date(X.serverVersion.timestamp)},baseVersion:X.baseVersion?{...X.baseVersion,timestamp:new Date(X.baseVersion.timestamp)}:void 0}));I(L)}}catch(_){console.warn("Failed to load persisted conflicts:",_)}},[d.persistConflicts,d.storageKey]),U=e.useCallback(_=>{if(d.persistConflicts)try{const M=_.filter(L=>L.status==="pending"||L.status==="failed");localStorage.setItem(d.storageKey,JSON.stringify(M))}catch(M){console.warn("Failed to persist conflicts:",M)}},[d.persistConflicts,d.storageKey]);e.useEffect(()=>{j()},[j]),e.useEffect(()=>{U(p)},[p,U]);const D=e.useCallback((_,M,L,X,$)=>{const Z=K(_),J=Z.compare||qn,V=Z.hash||$n,Q=Z.getConflictingFields;if(J(L.data,X.data)||L.timestamp<X.timestamp&&$&&J(L.data,$.data))return null;const ee={id:Bn(),entityType:_,entityId:M,clientVersion:{...L,hash:V(L.data)},serverVersion:{...X,hash:V(X.data)},baseVersion:$?{...$,hash:V($.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:Q?Q(L.data,X.data):void 0};return P(ee),ee},[K]),P=e.useCallback(_=>{I(M=>{const L=M.findIndex($=>$.entityType===_.entityType&&$.entityId===_.entityId);let X;return L>=0?(X=[...M],X[L]=_):X=[...M,_],X.length>d.maxPendingConflicts&&(X=X.slice(-d.maxPendingConflicts)),X}),G==null||G(_),R&&g&&Y(!0),d.autoResolve&&d.defaultStrategy!=="manual"&&T(_.id,d.defaultStrategy)},[d.maxPendingConflicts,d.autoResolve,d.defaultStrategy,R,g,G]),T=e.useCallback(async(_,M,L)=>{var J;const X=p.findIndex(V=>V.id===_);if(X===-1)return;const $=p[X],Z=K($.entityType);q(!0),I(V=>{const Q=[...V];return Q[X]={...$,status:"resolving"},Q});try{let V;switch(M){case"client-wins":V=$.clientVersion.data;break;case"server-wins":V=$.serverVersion.data;break;case"latest-wins":V=$.clientVersion.timestamp>$.serverVersion.timestamp?$.clientVersion.data:$.serverVersion.data;break;case"merge":{V=await(Z.merge||Un)($.clientVersion.data,$.serverVersion.data,(J=$.baseVersion)==null?void 0:J.data);break}case"manual":if(L===void 0)throw new Error("Manual resolution requires merged data");V=L;break}const Q={...$,status:"resolved",resolvedVersion:{data:V,timestamp:new Date,source:M==="client-wins"?"client":"server"},resolvedWith:M,resolvedAt:new Date};I(ee=>{const te=[...ee];return te[X]=Q,te}),i==null||i(Q)}catch(V){const Q=V instanceof Error?V.message:"Resolution failed";I(ee=>{const te=[...ee];return te[X]={...$,status:"failed",error:Q},te}),l==null||l($,V instanceof Error?V:new Error(Q))}finally{q(!1)}},[p,K,i,l]),O=e.useCallback(async _=>{const M=p.filter(L=>L.status==="pending");for(const L of M)await T(L.id,_)},[p,T]),y=e.useCallback(_=>p.find(M=>M.id===_),[p]),s=e.useCallback((_,M)=>p.filter(L=>L.entityType===_&&(M===void 0||L.entityId===M)),[p]),r=e.useCallback(()=>p.filter(_=>_.status==="pending"),[p]),a=e.useCallback(_=>{I(M=>M.filter(L=>L.id!==_))},[]),c=e.useCallback(()=>{I(_=>_.filter(M=>M.status!=="resolved"))},[]),o=e.useCallback(()=>{I([])},[]),S=e.useCallback(()=>Y(!0),[]),A=e.useCallback(()=>Y(!1),[]);e.useImperativeHandle(f,()=>({getState:()=>W,detectConflict:D,addConflict:P,resolveConflict:T,resolveAll:O,getConflict:y,getConflictsByEntity:s,getPendingConflicts:r,dismissConflict:a,clearResolved:c,clearAll:o,openUI:S,closeUI:A}),[W,D,P,T,O,y,s,r,a,c,o,S,A]);const m={...W,detectConflict:D,addConflict:P,resolveConflict:T,resolveAll:O,getConflict:y,getConflictsByEntity:s,getPendingConflicts:r,dismissConflict:a,clearResolved:c,clearAll:o},w=r(),u=(_,M,L)=>{T(_,M,L)},C=_=>{a(_)},x=_=>E?E({conflict:_,onResolve:(M,L)=>u(_.id,M,L),onDismiss:()=>C(_.id)}):t.jsxs("div",{className:"nice-conflict-item",children:[t.jsxs("div",{className:"nice-conflict-item__header",children:[t.jsx("span",{className:"nice-conflict-item__type",children:_.entityType}),t.jsxs("span",{className:"nice-conflict-item__id",children:["ID: ",_.entityId]})]}),t.jsxs("div",{className:"nice-conflict-item__versions",children:[t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--client",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Your changes"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.clientVersion.timestamp.toLocaleString()})]}),t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--server",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Server version"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.serverVersion.timestamp.toLocaleString()})]})]}),_.conflictingFields&&_.conflictingFields.length>0&&t.jsxs("div",{className:"nice-conflict-item__fields",children:[t.jsx("span",{children:"Conflicting fields:"}),_.conflictingFields.map(M=>t.jsx("code",{children:M},M))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>u(_.id,"client-wins"),disabled:B,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>u(_.id,"server-wins"),disabled:B,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>u(_.id,"merge"),disabled:B,children:"Merge"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>C(_.id),disabled:B,children:"Dismiss"})]})]},_.id),H=()=>{if(!g||!z||w.length===0)return null;if(b)return b({conflicts:w,onResolve:u,onDismiss:C});const _=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsxs("h3",{children:["Sync Conflicts (",w.length,")"]}),t.jsx("button",{className:"nice-conflict-list__close",onClick:A,"aria-label":"Close",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-conflict-list__items",children:w.map(x)}),w.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>O("client-wins"),disabled:B,children:"Keep All Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>O("server-wins"),disabled:B,children:"Use All Server"})]})]});switch(N){case"modal":return t.jsx("div",{className:"nice-conflict-overlay",children:t.jsx("div",{className:"nice-conflict-modal",children:_})});case"drawer":return t.jsx("div",{className:"nice-conflict-drawer nice-conflict-drawer--open",children:_});case"toast":return t.jsx("div",{className:"nice-conflict-toast",children:_});case"inline":default:return _}};return t.jsxs(tt.Provider,{value:m,children:[v,H()]})}),{displayName:"NiceConflictResolution"}),st=nt;process.env.NODE_ENV!=="production"&&(st.displayName="NiceConflictResolutionProvider");const rt=e.createContext(null),at=()=>{const n=e.useContext(rt);if(!n)throw new Error("useIndexedDB must be used within NiceIndexedDBProvider");return n};function Vn(n){const f=at(),h=e.useCallback(d=>f.get(n,d),[f,n]),k=e.useCallback(d=>f.getAll(n,d),[f,n]),g=e.useCallback((d,p)=>f.add(n,d,p),[f,n]),N=e.useCallback((d,p)=>f.put(n,d,p),[f,n]),R=e.useCallback(d=>f.delete(n,d),[f,n]),G=e.useCallback(()=>f.clear(n),[f,n]),i=e.useCallback(d=>f.count(n,d),[f,n]),l=e.useCallback(d=>f.query(n,d),[f,n]),b=e.useCallback(d=>f.bulkAdd(n,d),[f,n]),E=e.useCallback(d=>f.bulkPut(n,d),[f,n]),v=e.useCallback(d=>f.bulkDelete(n,d),[f,n]);return{isOpen:f.isOpen,isLoading:f.isLoading,error:f.error,get:h,getAll:k,add:g,put:N,remove:R,clear:G,count:i,query:l,bulkAdd:b,bulkPut:E,bulkDelete:v}}const it=Object.assign(e.forwardRef((n,f)=>{const{config:h,autoOpen:k=!0,onOpen:g,onError:N,onClose:R,children:G}=n,i=e.useRef(null),[l,b]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),E=e.useCallback(async()=>{if(i.current)return i.current;if(!("indexedDB"in window))throw new Error("IndexedDB is not supported in this browser");return b(s=>({...s,isLoading:!0,error:void 0})),new Promise((s,r)=>{const a=indexedDB.open(h.dbName,h.version);a.onerror=()=>{var o;const c=new Error(((o=a.error)==null?void 0:o.message)||"Failed to open database");b(S=>({...S,isLoading:!1,error:c.message})),N==null||N(c),r(c)},a.onblocked=()=>{var c;(c=h.onBlocked)==null||c.call(h)},a.onupgradeneeded=c=>{var m;const o=a.result,S=c.oldVersion,A=c.newVersion;for(const w of h.stores)if(!o.objectStoreNames.contains(w.name)){const u=o.createObjectStore(w.name,{keyPath:w.keyPath,autoIncrement:w.autoIncrement});if(w.indexes)for(const C of w.indexes)u.createIndex(C.name,C.keyPath,C.options)}(m=h.onUpgrade)==null||m.call(h,o,S,A)},a.onsuccess=()=>{const c=a.result;i.current=c,c.onclose=()=>{i.current=null,b(o=>({...o,isOpen:!1,db:void 0})),R==null||R()},c.onerror=o=>{var A;const S=o.target;N==null||N(new Error(((A=S.error)==null?void 0:A.message)||"Database error"))},b({db:c,isOpen:!0,isLoading:!1,version:c.version,storeNames:Array.from(c.objectStoreNames)}),g==null||g(c),s(c)}})},[h,g,N,R]),v=e.useCallback(()=>{i.current&&(i.current.close(),i.current=null,b(s=>({...s,isOpen:!1,db:void 0})),R==null||R())},[R]),d=e.useCallback(async()=>(v(),new Promise((s,r)=>{const a=indexedDB.deleteDatabase(h.dbName);a.onerror=()=>{var c;r(new Error(((c=a.error)==null?void 0:c.message)||"Failed to delete database"))},a.onsuccess=()=>{b({isOpen:!1,isLoading:!1,storeNames:[]}),s()}})),[h.dbName,v]),p=e.useCallback(async()=>i.current?i.current:E(),[E]),I=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readonly").objectStore(s).get(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c(m.result)})},[p]),B=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const A=a.transaction(s,"readonly").objectStore(s),w=(r!=null&&r.index?A.index(r.index):A).getAll(r==null?void 0:r.range,r==null?void 0:r.limit);w.onerror=()=>{var u;return o(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>{let u=w.result;r!=null&&r.offset&&(u=u.slice(r.offset)),c(u)}})},[p]),q=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const A=a.transaction(s,"readonly").objectStore(s),w=(r!=null&&r.index?A.index(r.index):A).getAllKeys(r==null?void 0:r.range,r==null?void 0:r.limit);w.onerror=()=>{var u;return o(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>c(w.result)})},[p]),z=e.useCallback(async(s,r,a)=>{const c=await p();return new Promise((o,S)=>{const w=c.transaction(s,"readwrite").objectStore(s).add(r,a);w.onerror=()=>{var u;return S(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>o(w.result)})},[p]),Y=e.useCallback(async(s,r,a)=>{const c=await p();return new Promise((o,S)=>{const w=c.transaction(s,"readwrite").objectStore(s).put(r,a);w.onerror=()=>{var u;return S(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>o(w.result)})},[p]),K=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readwrite").objectStore(s).delete(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c()})},[p]),F=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const A=r.transaction(s,"readwrite").objectStore(s).clear();A.onerror=()=>{var m;return c(new Error((m=A.error)==null?void 0:m.message))},A.onsuccess=()=>a()})},[p]),W=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readonly").objectStore(s).count(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c(m.result)})},[p]),j=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const m=a.transaction(s,"readonly").objectStore(s),u=(r.index?m.index(r.index):m).openCursor(r.range,r.direction);let C=0,x=0;u.onerror=()=>{var H;return S(new Error((H=u.error)==null?void 0:H.message))},u.onsuccess=()=>{const H=u.result;if(H){if(r.offset&&C<r.offset){C++,H.continue();return}if(r.limit&&x>=r.limit){o(c);return}c.push(H.value),x++,H.continue()}else o(c)}})},[p]),U=e.useCallback(async(s,r)=>{const c=(await p()).transaction(s.stores,s.mode||"readwrite");return new Promise((o,S)=>{c.onerror=()=>{var A;return S(new Error((A=c.error)==null?void 0:A.message))},c.onabort=()=>S(new Error("Transaction aborted")),r(c).then(A=>{c.oncomplete=()=>o(A)}).catch(S)})},[p]),D=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const A=a.transaction(s,"readwrite"),m=A.objectStore(s);A.onerror=()=>{var w;return S(new Error((w=A.error)==null?void 0:w.message))},A.oncomplete=()=>o(c);for(const w of r){const u=m.add(w);u.onsuccess=()=>c.push(u.result)}})},[p]),P=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const A=a.transaction(s,"readwrite"),m=A.objectStore(s);A.onerror=()=>{var w;return S(new Error((w=A.error)==null?void 0:w.message))},A.oncomplete=()=>o(c);for(const w of r){const u=m.put(w);u.onsuccess=()=>c.push(u.result)}})},[p]),T=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const S=a.transaction(s,"readwrite"),A=S.objectStore(s);S.onerror=()=>{var m;return o(new Error((m=S.error)==null?void 0:m.message))},S.oncomplete=()=>c();for(const m of r)A.delete(m)})},[p]),O=e.useCallback(async()=>{const s=await p(),r=[];for(const a of s.objectStoreNames){const o=s.transaction(a,"readonly").objectStore(a);r.push({name:o.name,keyPath:o.keyPath,autoIncrement:o.autoIncrement,indexNames:Array.from(o.indexNames)})}return{name:s.name,version:s.version,stores:r}},[p]);e.useEffect(()=>(k&&E().catch(()=>{}),()=>{v()}),[k,E,v]),e.useImperativeHandle(f,()=>({getState:()=>l,open:E,close:v,deleteDatabase:d,get:I,getAll:B,getAllKeys:q,add:z,put:Y,delete:K,clear:F,count:W,query:j,transaction:U,bulkAdd:D,bulkPut:P,bulkDelete:T,getInfo:O}),[l,E,v,d,I,B,q,z,Y,K,F,W,j,U,D,P,T,O]);const y={...l,open:E,close:v,deleteDatabase:d,get:I,getAll:B,getAllKeys:q,add:z,put:Y,delete:K,clear:F,count:W,query:j,transaction:U,bulkAdd:D,bulkPut:P,bulkDelete:T};return t.jsx(rt.Provider,{value:y,children:G})}),{displayName:"NiceIndexedDB"}),ct=it;process.env.NODE_ENV!=="production"&&(ct.displayName="NiceIndexedDBProvider");const ot=e.createContext(null),lt=()=>{const n=e.useContext(ot);if(!n)throw new Error("useOfflineForms must be used within NiceOfflineFormsProvider");return n},Hn={dbName:"nice-offline-forms",autoSaveInterval:5e3,maxDraftsPerForm:50,autoSubmitOnline:!0,retryFailed:!0,maxRetryAttempts:3,retryDelay:5e3},Wn=()=>`draft-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ut=Object.assign(e.forwardRef((n,f)=>{const{config:h,submitHandlers:k={},onDraftSaved:g,onFormSubmitted:N,onSubmissionFailed:R,onSyncComplete:G,children:i}=n,l={...Hn,...h},b=e.useRef(null),E=e.useRef(k),[v,d]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),p=e.useCallback(async()=>b.current?b.current:new Promise((s,r)=>{const a=indexedDB.open(l.dbName,1);a.onerror=()=>r(a.error),a.onupgradeneeded=()=>{const c=a.result;if(!c.objectStoreNames.contains("drafts")){const o=c.createObjectStore("drafts",{keyPath:"id"});o.createIndex("formId","formId",{unique:!1}),o.createIndex("status","status",{unique:!1})}},a.onsuccess=()=>{b.current=a.result,s(a.result)}}),[l.dbName]),I=e.useCallback(async(s,r,a)=>{const c=await p(),o={id:Wn(),formId:s,data:r,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:a};return new Promise((S,A)=>{const u=c.transaction("drafts","readwrite").objectStore("drafts").add(o);u.onerror=()=>A(u.error),u.onsuccess=()=>{g==null||g(o),O(),S(o.id)}})},[p,g]),B=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const A=r.transaction("drafts","readonly").objectStore("drafts").get(s);A.onerror=()=>c(A.error),A.onsuccess=()=>{const m=A.result;m&&(m.createdAt=new Date(m.createdAt),m.modifiedAt=new Date(m.modifiedAt),m.syncedAt&&(m.syncedAt=new Date(m.syncedAt))),a(m)}})},[p]),q=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const m=r.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(s);m.onerror=()=>c(m.error),m.onsuccess=()=>{const w=m.result.map(u=>({...u,createdAt:new Date(u.createdAt),modifiedAt:new Date(u.modifiedAt),syncedAt:u.syncedAt?new Date(u.syncedAt):void 0}));a(w)}})},[p]),z=e.useCallback(async()=>{const s=await p();return new Promise((r,a)=>{const S=s.transaction("drafts","readonly").objectStore("drafts").getAll();S.onerror=()=>a(S.error),S.onsuccess=()=>{const A=S.result.filter(m=>m.status==="pending"||m.status==="failed").map(m=>({...m,createdAt:new Date(m.createdAt),modifiedAt:new Date(m.modifiedAt),syncedAt:m.syncedAt?new Date(m.syncedAt):void 0}));r(A)}})},[p]),Y=e.useCallback(async(s,r)=>{const a=await B(s);if(!a)return;const c=await p(),o={...a,data:{...a.data,...r},modifiedAt:new Date,version:a.version+1};return new Promise((S,A)=>{const u=c.transaction("drafts","readwrite").objectStore("drafts").put(o);u.onerror=()=>A(u.error),u.onsuccess=()=>{g==null||g(o),S()}})},[p,B,g]),K=e.useCallback(async(s,r,a)=>{const c=await B(s);if(!c)return;const o=await p(),S={...c,status:r,error:a,attempts:r==="syncing"?c.attempts+1:c.attempts,syncedAt:r==="synced"?new Date:c.syncedAt};return new Promise((A,m)=>{const C=o.transaction("drafts","readwrite").objectStore("drafts").put(S);C.onerror=()=>m(C.error),C.onsuccess=()=>{O(),A()}})},[p,B]),F=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const A=r.transaction("drafts","readwrite").objectStore("drafts").delete(s);A.onerror=()=>c(A.error),A.onsuccess=()=>{O(),a()}})},[p]),W=e.useCallback(async s=>{const r=await q(s),a=await p();return new Promise((c,o)=>{const S=a.transaction("drafts","readwrite"),A=S.objectStore("drafts");S.onerror=()=>o(S.error),S.oncomplete=()=>{O(),c()};for(const m of r)A.delete(m.id)})},[p,q]),j=e.useCallback(async s=>{const r=await B(s);if(!r)throw new Error("Draft not found");const a=E.current[r.formId];if(!a)throw new Error(`No handler registered for form: ${r.formId}`);if(!v.isOnline){await K(s,"pending");return}await K(s,"syncing"),d(c=>({...c,isSyncing:!0}));try{await a(r.data,r),await K(s,"synced"),N==null||N(r),await F(s)}catch(c){const o=c instanceof Error?c.message:"Submission failed";await K(s,"failed",o),R==null||R(r,c instanceof Error?c:new Error(o))}finally{d(c=>({...c,isSyncing:!1}))}},[B,v.isOnline,K,F,N,R]),U=e.useCallback(async(s,r)=>{const a=await I(s,r);await K(a,"pending"),await j(a)},[I,K,j]),D=e.useCallback(async()=>{const s=await z(),r={synced:0,failed:0};d(a=>({...a,isSyncing:!0}));for(const a of s)if(!(a.status==="failed"&&a.attempts>=l.maxRetryAttempts))try{await j(a.id),r.synced++}catch{r.failed++}return d(a=>({...a,isSyncing:!1,lastSyncAt:new Date})),G==null||G(r),r},[z,j,l.maxRetryAttempts,G]),P=e.useCallback(async()=>{const r=(await z()).filter(a=>a.status==="failed");for(const a of r)a.attempts<l.maxRetryAttempts&&await K(a.id,"pending");await D()},[z,l.maxRetryAttempts,K,D]),T=e.useCallback((s,r)=>{E.current[s]=r},[]),O=e.useCallback(async()=>{try{const c=(await p()).transaction("drafts","readonly").objectStore("drafts").getAll();c.onsuccess=()=>{const o=c.result,S={};for(const w of o)S[w.formId]=(S[w.formId]||0)+1;const A=o.filter(w=>w.status==="pending").length,m=o.filter(w=>w.status==="failed").length;d(w=>({...w,draftCounts:S,pendingCount:A,failedCount:m}))}}catch{}},[p]);e.useEffect(()=>{const s=()=>{d(a=>({...a,isOnline:!0})),l.autoSubmitOnline&&D()},r=()=>{d(a=>({...a,isOnline:!1}))};return window.addEventListener("online",s),window.addEventListener("offline",r),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",r)}},[l.autoSubmitOnline,D]),e.useEffect(()=>{p().then(()=>O())},[p,O]),e.useImperativeHandle(f,()=>({getState:()=>v,saveDraft:I,getDraft:B,getDrafts:q,getPendingDrafts:z,updateDraft:Y,deleteDraft:F,submitDraft:j,submitForm:U,syncPending:D,retryFailed:P,clearDrafts:W,registerHandler:T}),[v,I,B,q,z,Y,F,j,U,D,P,W,T]);const y={...v,saveDraft:I,getDraft:B,getDrafts:q,getPendingDrafts:z,updateDraft:Y,deleteDraft:F,submitDraft:j,submitForm:U,syncPending:D,retryFailed:P,clearDrafts:W,registerHandler:T};return t.jsx(ot.Provider,{value:y,children:i})}),{displayName:"NiceOfflineForms"}),dt=ut;process.env.NODE_ENV!=="production"&&(dt.displayName="NiceOfflineFormsProvider");function zn(n){const{formId:f,initialData:h={},autoSave:k=!0,autoSaveInterval:g=5e3,onSubmit:N}=n,R=lt(),[G,i]=e.useState(h),[l,b]=e.useState(),[E,v]=e.useState(!1),[d,p]=e.useState();e.useEffect(()=>{R.registerHandler(f,N)},[R,f,N]),e.useEffect(()=>{if(!k)return;const Y=setInterval(async()=>{if(Object.keys(G).length>0)if(l)await R.updateDraft(l,G);else{const K=await R.saveDraft(f,G);b(K)}},g);return()=>clearInterval(Y)},[k,g,G,l,f,R]);const I=e.useCallback(Y=>{const{name:K,value:F,type:W}=Y.target;i(j=>({...j,[K]:W==="checkbox"?Y.target.checked:F}))},[]),B=e.useCallback(async Y=>{Y==null||Y.preventDefault(),v(!0),p(void 0);try{await R.submitForm(f,G),i(h),b(void 0)}catch(K){p(K instanceof Error?K.message:"Submission failed")}finally{v(!1)}},[R,f,G,h]),q=e.useCallback(()=>{i(h),p(void 0),l&&(R.deleteDraft(l),b(void 0))},[h,l,R]),z=e.useCallback(async Y=>{const K=await R.getDraft(Y);K&&(i(K.data),b(Y))},[R]);return{data:G,setData:i,draftId:l,isSubmitting:E,error:d,isOnline:R.isOnline,isSyncing:R.isSyncing,pendingCount:R.pendingCount,handleChange:I,handleSubmit:B,reset:q,loadDraft:z}}const fe=()=>{const n=navigator;return n.connection?{type:n.connection.type,effectiveType:n.connection.effectiveType,downlink:n.connection.downlink,rtt:n.connection.rtt,saveData:n.connection.saveData}:{}},me=n=>{if(!n.effectiveType)return n.downlink?Math.min(100,n.downlink*10):50;switch(n.effectiveType){case"4g":return 100;case"3g":return 75;case"2g":return 50;case"slow-2g":return 25;default:return 50}},Gn=Object.assign(e.forwardRef((n,f)=>{const{mode:h="banner",position:k="top",showWhenOnline:g=!1,autoHideOnlineDelay:N=3e3,showSlowConnectionWarning:R=!0,slowConnectionThreshold:G=1,showReconnecting:i=!0,reconnectCheckInterval:l=5e3,offlineMessage:b="You're offline",onlineMessage:E="Back online",slowConnectionMessage:v="Slow connection",reconnectingMessage:d="Reconnecting...",showDetails:p=!1,animated:I=!0,pulseWhenOffline:B=!0,offlineIcon:q,onlineIcon:z,slowIcon:Y,renderContent:K,onStatusChange:F,onReconnect:W,className:j,style:U}=n,[D,P]=e.useState(()=>{const $=fe();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...$,quality:me($)}}),[T,O]=e.useState(!D.isOnline||g),[y,s]=e.useState(!1),[r,a]=e.useState(null),c=e.useCallback(()=>{const $=fe(),Z=navigator.onLine;P(J=>{const V={isOnline:Z,...$,quality:Z?me($):0,lastOnlineAt:Z?new Date:J.lastOnlineAt,offlineDuration:!Z&&r?Date.now()-r.getTime():void 0};return(J.isOnline!==V.isOnline||J.quality!==V.quality)&&(F==null||F(V)),V})},[r,F]),o=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const $=()=>{s(!1),a(null),c(),O(!0),W==null||W(),N>0&&setTimeout(()=>{O(g)},N)},Z=()=>{a(new Date),c(),O(!0),s(i)};window.addEventListener("online",$),window.addEventListener("offline",Z);const J=navigator;return J.connection&&J.connection.addEventListener("change",c),()=>{window.removeEventListener("online",$),window.removeEventListener("offline",Z),J.connection&&J.connection.removeEventListener("change",c)}},[c,N,g,i,W]),e.useEffect(()=>{if(!y||D.isOnline)return;const $=setInterval(async()=>{await o()&&window.dispatchEvent(new Event("online"))},l);return()=>clearInterval($)},[y,D.isOnline,l,o]),e.useEffect(()=>{if(D.isOnline||!r)return;const $=setInterval(()=>{P(Z=>({...Z,offlineDuration:Date.now()-r.getTime()}))},1e3);return()=>clearInterval($)},[D.isOnline,r]),e.useImperativeHandle(f,()=>({getConnectionInfo:()=>D,checkConnection:o,show:()=>O(!0),hide:()=>O(!1),toggle:()=>O($=>!$)}),[D,o]);const S=D.isOnline&&R&&D.downlink!==void 0&&D.downlink<G,m=D.isOnline?S?"slow":"online":y?"reconnecting":"offline",w=()=>{switch(m){case"offline":return b;case"reconnecting":return d;case"slow":return v;case"online":return E}},u=$=>({display:"inline-block",width:10,height:10,borderRadius:"50%",background:$}),C=()=>{switch(m){case"offline":case"reconnecting":return q||t.jsx("span",{style:u("var(--nice-color-error, #ef4444)")});case"slow":return Y||t.jsx("span",{style:u("var(--nice-color-warning, #f59e0b)")});case"online":return z||t.jsx("span",{style:u("var(--nice-color-success, #22c55e)")})}},x=$=>{const Z=Math.floor($/1e3);if(Z<60)return`${Z}s`;const J=Math.floor(Z/60);return J<60?`${J}m ${Z%60}s`:`${Math.floor(J/60)}h ${J%60}m`};if(!T||D.isOnline&&!g&&!S)return null;const H=["nice-offline-indicator",`nice-offline-indicator--${h}`,`nice-offline-indicator--${k}`,`nice-offline-indicator--${m}`,I&&"nice-offline-indicator--animated",B&&m==="offline"&&"nice-offline-indicator--pulse",j].filter(Boolean).join(" ");if(K)return t.jsx("div",{className:H,style:U,children:K(D)});const _=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:C()}),M=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:w()}),L=()=>p?t.jsxs("div",{className:"nice-offline-indicator__details",children:[D.offlineDuration!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__duration",children:["Offline for ",x(D.offlineDuration)]}),D.effectiveType&&t.jsx("span",{className:"nice-offline-indicator__type",children:D.effectiveType.toUpperCase()}),D.downlink!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__speed",children:[D.downlink.toFixed(1)," Mbps"]}),D.rtt!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__latency",children:[D.rtt,"ms"]})]}):null,X=()=>!p||!D.isOnline?null:t.jsx("div",{className:"nice-offline-indicator__quality",children:t.jsx("div",{className:"nice-offline-indicator__quality-bar",style:{width:`${D.quality}%`,backgroundColor:D.quality>=75?"var(--nice-color-success, #22c55e)":D.quality>=50?"var(--nice-color-warning, #eab308)":"var(--nice-color-error, #ef4444)"}})});switch(h){case"icon-only":return t.jsx("div",{className:H,style:U,title:w(),children:_()});case"minimal":return t.jsxs("div",{className:H,style:U,children:[_(),M()]});case"badge":return t.jsxs("div",{className:H,style:U,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:w()})]});case"toast":return t.jsx("div",{className:H,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[M(),L()]})]})});case"detailed":return t.jsx("div",{className:H,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[M(),L(),X()]})]})});case"banner":default:return t.jsx("div",{className:H,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[_(),M(),p&&t.jsxs(t.Fragment,{children:[L(),y&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}}),{displayName:"NiceOfflineIndicator"});function Yn(){const[n,f]=e.useState(()=>{const h=fe();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...h,quality:me(h)}});return e.useEffect(()=>{const h=()=>{const g=fe();f(N=>({...N,isOnline:navigator.onLine,...g,quality:navigator.onLine?me(g):0,lastOnlineAt:navigator.onLine?new Date:N.lastOnlineAt}))};window.addEventListener("online",h),window.addEventListener("offline",h);const k=navigator;return k.connection&&k.connection.addEventListener("change",h),()=>{window.removeEventListener("online",h),window.removeEventListener("offline",h),k.connection&&k.connection.removeEventListener("change",h)}},[]),n}const ft=e.createContext(null),mt=()=>{const n=e.useContext(ft);if(!n)throw new Error("useOfflineMedia must be used within NiceOfflineMediaProvider");return n},Xn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},Kn=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Qn=(n,f)=>{var g;const h=((g=n.split(".").pop())==null?void 0:g.toLowerCase())||"",k=(f==null?void 0:f.toLowerCase())||"";return k.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(h)?"image":k.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(h)?"video":k.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(h)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(h)?"document":"other"},Jn=n=>{try{return new URL(n).pathname.split("/").pop()||"unknown"}catch{return n.split("/").pop()||"unknown"}},ht=Object.assign(e.forwardRef((n,f)=>{const{config:h,onDownloadStart:k,onDownloadProgress:g,onDownloadComplete:N,onDownloadFailed:R,onMediaRemoved:G,children:i}=n,l={...Xn,...h},b=e.useRef(null),E=e.useRef(new Map),v=e.useRef(new Map),[d,p]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),I=e.useCallback(async()=>b.current?b.current:new Promise((C,x)=>{const H=indexedDB.open(l.dbName,1);H.onerror=()=>x(H.error),H.onupgradeneeded=()=>{const _=H.result;if(!_.objectStoreNames.contains("media")){const M=_.createObjectStore("media",{keyPath:"id"});M.createIndex("url","url",{unique:!0}),M.createIndex("type","type",{unique:!1}),M.createIndex("status","status",{unique:!1})}_.objectStoreNames.contains("blobs")||_.createObjectStore("blobs",{keyPath:"id"})},H.onsuccess=()=>{b.current=H.result,C(H.result)}}),[l.dbName]),B=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const X=x.transaction("media","readwrite").objectStore("media").put(C);X.onerror=()=>_(X.error),X.onsuccess=()=>H()})},[I]),q=e.useCallback(async(C,x)=>{const H=await I();return new Promise((_,M)=>{const $=H.transaction("blobs","readwrite").objectStore("blobs").put({id:C,blob:x});$.onerror=()=>M($.error),$.onsuccess=()=>_()})},[I]),z=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const X=x.transaction("blobs","readonly").objectStore("blobs").get(C);X.onerror=()=>_(X.error),X.onsuccess=()=>{var $;return H(($=X.result)==null?void 0:$.blob)}})},[I]),Y=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const X=x.transaction("media","readonly").objectStore("media").get(C);X.onerror=()=>_(X.error),X.onsuccess=()=>{const $=X.result;$&&($.cachedAt=$.cachedAt?new Date($.cachedAt):void 0,$.expiresAt=$.expiresAt?new Date($.expiresAt):void 0),H($)}})},[I]),K=e.useCallback(async()=>{const C=await I();return new Promise((x,H)=>{const L=C.transaction("media","readonly").objectStore("media").getAll();L.onerror=()=>H(L.error),L.onsuccess=()=>{x(L.result.map(X=>({...X,cachedAt:X.cachedAt?new Date(X.cachedAt):void 0,expiresAt:X.expiresAt?new Date(X.expiresAt):void 0})))}})},[I]),F=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const $=x.transaction("media","readonly").objectStore("media").index("type").getAll(C);$.onerror=()=>_($.error),$.onsuccess=()=>H($.result)})},[I]),W=e.useCallback(async C=>(await K()).filter(H=>{var _;return(_=H.tags)==null?void 0:_.includes(C)}),[K]),j=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const $=x.transaction("media","readonly").objectStore("media").index("url").get(C);$.onerror=()=>_($.error),$.onsuccess=()=>H($.result)})},[I]),U=e.useCallback(async C=>{const x=await j(C);return(x==null?void 0:x.status)==="completed"},[j]),D=e.useCallback(async C=>{const x=v.current.get(C);if(x)return x;const H=await z(C);if(!H)return;const _=URL.createObjectURL(H);return v.current.set(C,_),_},[z]),P=e.useCallback(async(C,x)=>{var X;const H=await j(C);if((H==null?void 0:H.status)==="completed")return H.id;const _=new AbortController,M=(H==null?void 0:H.id)||Kn(),L={id:M,url:C,type:(x==null?void 0:x.type)||"other",name:(x==null?void 0:x.name)||Jn(C),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:x==null?void 0:x.metadata,tags:x==null?void 0:x.tags,priority:x==null?void 0:x.priority};E.current.set(M,_),await B(L),k==null||k(L),p($=>({...$,queuedDownloads:$.queuedDownloads+1,isDownloading:!0}));try{L.status="downloading",await B(L),p(se=>({...se,activeDownloads:se.activeDownloads+1,queuedDownloads:se.queuedDownloads-1}));const $=await fetch(C,{signal:_.signal,headers:x==null?void 0:x.headers});if(!$.ok)throw new Error(`HTTP ${$.status}`);const Z=$.headers.get("content-length"),J=$.headers.get("content-type")||"",V=Z?parseInt(Z,10):0;L.size=V,L.mimeType=J,L.type=(x==null?void 0:x.type)||Qn(C,J);const Q=(X=$.body)==null?void 0:X.getReader();if(!Q)throw new Error("No response body");const ee=[];let te=0;for(;;){const{done:se,value:re}=await Q.read();if(se)break;ee.push(re),te+=re.length,L.downloadedBytes=te,L.progress=V>0?Math.round(te/V*100):0,await B(L),g==null||g(L)}const ne=new Blob(ee,{type:J});return await q(M,ne),L.status="completed",L.progress=100,L.size=ne.size,L.cachedAt=new Date,L.expiresAt=x!=null&&x.cacheDuration?new Date(Date.now()+x.cacheDuration):new Date(Date.now()+l.defaultCacheDuration),await B(L),N==null||N(L),M}catch($){throw $.name==="AbortError"?L.status="cancelled":(L.status="failed",L.error=$ instanceof Error?$.message:"Download failed",R==null||R(L,$ instanceof Error?$:new Error(String($)))),await B(L),$}finally{E.current.delete(M),p($=>({...$,activeDownloads:Math.max(0,$.activeDownloads-1),isDownloading:$.activeDownloads>1})),await w()}},[j,B,q,l.defaultCacheDuration,k,g,N,R]),T=e.useCallback(async C=>{const x=[];for(let H=0;H<C.length;H+=l.maxConcurrentDownloads){const _=C.slice(H,H+l.maxConcurrentDownloads),M=await Promise.allSettled(_.map(L=>P(L.url,L.options)));for(const L of M)L.status==="fulfilled"&&x.push(L.value)}return x},[P,l.maxConcurrentDownloads]),O=e.useCallback(C=>{const x=E.current.get(C);x&&x.abort()},[]),y=e.useCallback(async C=>{const x=await Y(C);x&&(x.status==="paused"||x.status==="failed")&&await P(x.url,{type:x.type,name:x.name,metadata:x.metadata,tags:x.tags})},[Y,P]),s=e.useCallback(C=>{O(C)},[O]),r=e.useCallback(()=>{for(const[C]of E.current)O(C)},[O]),a=e.useCallback(async()=>{const x=(await K()).filter(H=>H.status==="paused"||H.status==="failed");await T(x.map(H=>({url:H.url})))},[K,T]),c=e.useCallback(async C=>{const x=await I(),H=v.current.get(C);H&&(URL.revokeObjectURL(H),v.current.delete(C)),await new Promise((_,M)=>{const L=x.transaction(["media","blobs"],"readwrite");L.objectStore("media").delete(C),L.objectStore("blobs").delete(C),L.onerror=()=>M(L.error),L.oncomplete=()=>_()}),G==null||G(C),await w()},[I,G]),o=e.useCallback(async()=>{const C=await I();for(const[,x]of v.current)URL.revokeObjectURL(x);v.current.clear(),await new Promise((x,H)=>{const _=C.transaction(["media","blobs"],"readwrite");_.objectStore("media").clear(),_.objectStore("blobs").clear(),_.onerror=()=>H(_.error),_.oncomplete=()=>x()}),await w()},[I]),S=e.useCallback(async()=>{const C=await K(),x=Date.now();let H=0;for(const _ of C)_.expiresAt&&_.expiresAt.getTime()<x&&(await c(_.id),H++);return H},[K,c]),A=e.useCallback(async()=>{const x=(await K()).filter(M=>M.status==="completed"),H={image:{count:0,size:0},video:{count:0,size:0},audio:{count:0,size:0},document:{count:0,size:0},other:{count:0,size:0}};let _=0;for(const M of x)_+=M.size,H[M.type].count++,H[M.type].size+=M.size;return{totalSize:_,itemCount:x.length,byType:H}},[K]),m=e.useCallback(async C=>{await T(C.map(x=>({url:x,options:{priority:-1}})))},[T]),w=e.useCallback(async()=>{const C=await A();p(x=>({...x,cachedCount:C.itemCount,totalCacheSize:C.totalSize}))},[A]);e.useEffect(()=>{const C=()=>{p(H=>({...H,isOnline:!0})),l.autoResumeOnReconnect&&a()},x=()=>{p(H=>({...H,isOnline:!1})),r()};return window.addEventListener("online",C),window.addEventListener("offline",x),()=>{window.removeEventListener("online",C),window.removeEventListener("offline",x)}},[l.autoResumeOnReconnect,a,r]),e.useEffect(()=>{if(!l.autoCleanup)return;const C=setInterval(()=>{S()},l.cleanupInterval);return()=>clearInterval(C)},[l.autoCleanup,l.cleanupInterval,S]),e.useEffect(()=>{I().then(()=>w());const C=v.current;return()=>{for(const[,x]of C)URL.revokeObjectURL(x)}},[I,w]),e.useImperativeHandle(f,()=>({getState:()=>d,download:P,downloadMultiple:T,getCachedMedia:Y,getAllCachedMedia:K,getMediaByType:F,getMediaByTag:W,getBlobUrl:D,isCached:U,pauseDownload:O,resumeDownload:y,cancelDownload:s,pauseAll:r,resumeAll:a,removeMedia:c,clearCache:o,clearExpired:S,getCacheStats:A,preload:m}),[d,P,T,Y,K,F,W,D,U,O,y,s,r,a,c,o,S,A,m]);const u={...d,download:P,downloadMultiple:T,getCachedMedia:Y,getAllCachedMedia:K,getMediaByType:F,getMediaByTag:W,getBlobUrl:D,isCached:U,pauseDownload:O,resumeDownload:y,cancelDownload:s,removeMedia:c,clearCache:o,preload:m};return t.jsx(ft.Provider,{value:u,children:i})}),{displayName:"NiceOfflineMedia"}),gt=ht;process.env.NODE_ENV!=="production"&&(gt.displayName="NiceOfflineMediaProvider");function Zn(n){const f=mt(),[h,k]=e.useState(),[g,N]=e.useState(),[R,G]=e.useState(!1);return e.useEffect(()=>{n&&(G(!0),Promise.all([f.getCachedMedia(n),f.getBlobUrl(n)]).then(([i,l])=>{k(i),N(l)}).finally(()=>{G(!1)}))},[n,f]),{item:h,blobUrl:g,isLoading:R,isOnline:f.isOnline}}const pt=e.createContext(null),es=()=>{const n=e.useContext(pt);if(!n)throw new Error("useServiceWorker must be used within NiceServiceWorkerProvider");return n},ts={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},bt=Object.assign(e.forwardRef((n,f)=>{const{config:h,showUpdateNotification:k=!0,showOfflineIndicator:g=!0,renderUpdateNotification:N,renderOfflineIndicator:R,notificationPosition:G="bottom",autoDismissDelay:i=0,onRegistered:l,onUpdateAvailable:b,onActivated:E,onError:v,onOnlineStatusChange:d,children:p,className:I}=n,B={...ts,...h},{swPath:q,scope:z,updateCheckInterval:Y,autoUpdate:K,reloadOnActivation:F}=B,W=B.skipWaiting,j=e.useMemo(()=>({swPath:q,scope:z,updateCheckInterval:Y,autoUpdate:K,skipWaiting:W,reloadOnActivation:F}),[q,z,Y,K,W,F]),U=e.useRef({onRegistered:l,onUpdateAvailable:b,onActivated:E,onError:v});e.useEffect(()=>{U.current={onRegistered:l,onUpdateAvailable:b,onActivated:E,onError:v}});const[D,P]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[T,O]=e.useState(!1);e.useEffect(()=>{const _=()=>{P(L=>({...L,isOnline:!0})),d==null||d(!0)},M=()=>{P(L=>({...L,isOnline:!1})),d==null||d(!1)};return window.addEventListener("online",_),window.addEventListener("offline",M),()=>{window.removeEventListener("online",_),window.removeEventListener("offline",M)}},[d]);const y=e.useCallback(async()=>{if(!("caches"in window))return[];const _=await caches.keys(),M=[];for(const L of _){const X=await caches.open(L),$=await X.keys();let Z=0;for(const J of $){const V=await X.match(J);if(V){const Q=await V.clone().blob();Z+=Q.size}}M.push({name:L,size:Z,itemCount:$.length})}return P(L=>({...L,caches:M})),M},[]),s=e.useCallback(async _=>{if(!("caches"in window))return!1;const M=await caches.delete(_);return await y(),M},[y]),r=e.useCallback(async()=>{if(!("caches"in window))return;const _=await caches.keys();await Promise.all(_.map(M=>caches.delete(M))),P(M=>({...M,caches:[],cachedUrls:[]}))},[]),a=e.useCallback(async(_,M)=>{if(!("caches"in window))return;await(await caches.open(_)).addAll(M),await y()},[y]),c=e.useCallback(async(_,M)=>{if(!("caches"in window))return!1;const X=await(await caches.open(_)).delete(M);return await y(),X},[y]),o=e.useCallback(async _=>"caches"in window?(await(await caches.open(_)).keys()).map(X=>X.url):[],[]),S=e.useCallback(async()=>{var M,L,X,$,Z,J;if(!("serviceWorker"in navigator)){P(V=>({...V,status:"error",error:"Service Worker not supported"}));return}P(V=>({...V,status:"registering"}));const _=!!navigator.serviceWorker.controller;try{const V=await navigator.serviceWorker.register(j.swPath,{scope:j.scope});P(ee=>({...ee,status:"registered",registration:V})),(L=(M=U.current).onRegistered)==null||L.call(M,V),V.addEventListener("updatefound",()=>{const ee=V.installing;ee&&ee.addEventListener("statechange",()=>{var te,ne,se,re;switch(ee.state){case"installing":P(ae=>({...ae,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(P(ae=>({...ae,status:"installed",updateAvailable:!0,waitingWorker:!0})),O(!0),(ne=(te=U.current).onUpdateAvailable)==null||ne.call(te)):P(ae=>({...ae,status:"installed"}));break;case"activating":P(ae=>({...ae,status:"activating"}));break;case"activated":P(ae=>({...ae,status:"activated",updateAvailable:!1,waitingWorker:!1})),(re=(se=U.current).onActivated)==null||re.call(se),j.reloadOnActivation&&_&&window.location.reload();break;case"redundant":P(ae=>({...ae,status:"redundant"}));break}})}),V.waiting&&(P(ee=>({...ee,updateAvailable:!0,waitingWorker:!0})),O(!0),($=(X=U.current).onUpdateAvailable)==null||$.call(X));let Q=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!Q&&j.reloadOnActivation&&(Q=!0,window.location.reload())}),await y(),V}catch(V){const Q=V instanceof Error?V.message:"Registration failed";P(ee=>({...ee,status:"error",error:Q})),(J=(Z=U.current).onError)==null||J.call(Z,V instanceof Error?V:new Error(Q));return}},[j,y]),A=e.useCallback(async()=>{if(!D.registration)return!1;const _=await D.registration.unregister();return _&&P(M=>({...M,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),_},[D.registration]),m=e.useCallback(async()=>{D.registration&&await D.registration.update()},[D.registration]),w=e.useCallback(()=>{var _;(_=D.registration)!=null&&_.waiting&&D.registration.waiting.postMessage({type:"SKIP_WAITING"})},[D.registration]),u=e.useCallback(()=>{j.skipWaiting&&w(),O(!1)},[j.skipWaiting,w]),C=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{S()},[S]),e.useEffect(()=>{if(!j.updateCheckInterval||j.updateCheckInterval<=0)return;const _=setInterval(()=>{m()},j.updateCheckInterval);return()=>clearInterval(_)},[j.updateCheckInterval,m]),e.useEffect(()=>{if(!T||i<=0)return;const _=setTimeout(()=>{O(!1)},i);return()=>clearTimeout(_)},[T,i]),e.useImperativeHandle(f,()=>({getState:()=>D,register:S,unregister:A,checkForUpdates:m,applyUpdate:u,skipWaiting:w,getCachesInfo:y,clearCache:s,clearAllCaches:r,addToCache:a,removeFromCache:c,getCachedUrls:o,forceReload:C}),[D,S,A,m,u,w,y,s,r,a,c,o,C]);const x={...D,register:S,unregister:A,checkForUpdates:m,applyUpdate:u,skipWaiting:w,getCachesInfo:y,clearCache:s,clearAllCaches:r,addToCache:a,removeFromCache:c,getCachedUrls:o},H=`nice-sw-notification--${G}`;return t.jsx(pt.Provider,{value:x,children:t.jsxs("div",{className:`nice-service-worker ${I||""}`,children:[p,k&&T&&D.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${H}`,children:N?N({onUpdate:u,onDismiss:()=>O(!1)}):t.jsxs("div",{className:"nice-sw-notification__content",children:[t.jsxs("div",{className:"nice-sw-notification__text",children:[t.jsx("strong",{children:"Update Available"}),t.jsx("span",{children:"A new version is ready to install"})]}),t.jsxs("div",{className:"nice-sw-notification__actions",children:[t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--primary",onClick:u,children:"Update Now"}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>O(!1),children:"Later"})]})]})}),g&&!D.isOnline&&t.jsx("div",{className:`nice-sw-offline ${H}`,children:R?R({isOnline:D.isOnline}):t.jsx("div",{className:"nice-sw-offline__content",children:t.jsx("span",{children:"You are offline"})})})]})})}),{displayName:"NiceServiceWorker"}),ns=Object.assign(e.forwardRef((n,f)=>t.jsx(bt,{...n,ref:f})),{displayName:"NiceServiceWorkerProvider"});exports.NiceAutoStart=_e;exports.NiceAutoStartProvider=Ne;exports.NiceBackgroundSync=Xe;exports.NiceBackgroundSyncProvider=Ke;exports.NiceBarcodeScanner=cn;exports.NiceBatchScanner=hn;exports.NiceBatchScannerProvider=gn;exports.NiceCacheStrategies=Ze;exports.NiceCacheStrategiesProvider=et;exports.NiceConflictResolution=nt;exports.NiceConflictResolutionProvider=st;exports.NiceExternalDisplay=Ee;exports.NiceExternalDisplayProvider=De;exports.NiceHardwareBarcodeGenerator=Zt;exports.NiceHardwareQRGenerator=wn;exports.NiceIndexedDB=it;exports.NiceIndexedDBProvider=ct;exports.NiceKioskMode=Le;exports.NiceKioskModeProvider=Re;exports.NiceLowPowerMode=Te;exports.NiceLowPowerModeProvider=Me;exports.NiceOfflineForms=ut;exports.NiceOfflineFormsProvider=dt;exports.NiceOfflineIndicator=Gn;exports.NiceOfflineMedia=ht;exports.NiceOfflineMediaProvider=gt;exports.NiceOrientationLock=$e;exports.NiceOrientationLockProvider=qe;exports.NiceQRScanner=Nn;exports.NiceRemoteManagement=Ve;exports.NiceRemoteManagementProvider=He;exports.NiceScreenBurnPrevention=Bt;exports.NiceScreenSelector=Ae;exports.NiceServiceWorker=bt;exports.NiceServiceWorkerProvider=ns;exports.NiceSymbologyConfig=In;exports.NiceSymbologyProvider=En;exports.NiceTouchCalibration=Ut;exports.useAutoStart=vt;exports.useBackgroundSync=Dn;exports.useBatchScanner=ln;exports.useCacheStrategies=Je;exports.useCachedFetch=Tn;exports.useConflictResolution=Mn;exports.useConnectionStatus=Yn;exports.useExternalDisplay=Ie;exports.useIndexedDB=at;exports.useIndexedDBStore=Vn;exports.useKioskMode=jt;exports.useLowPowerMode=Et;exports.useOfflineForm=zn;exports.useOfflineForms=lt;exports.useOfflineMedia=mt;exports.useOfflineMediaItem=Zn;exports.useOrientationLock=Pt;exports.useRemoteManagement=Tt;exports.useServiceWorker=es;exports.useSymbology=jn;
|
|
11
|
+
</svg>`}catch{return null}},[w,a]),H=e.useCallback((z="qrcode",T="png")=>{const M=document.createElement("a");if(T==="svg"){const j=Y();if(!j)return;const S=new Blob([j],{type:"image/svg+xml"});M.href=URL.createObjectURL(S),M.download=`${z}.svg`}else{const j=$();if(!j)return;M.href=j,M.download=`${z}.png`}M.click()},[$,Y]),X=e.useCallback(()=>{B()},[B]);e.useImperativeHandle(g,()=>({toDataURL:$,toSVG:Y,download:H,regenerate:X}),[$,Y,H,X]);const O=["nice-qr-generator",G&&"nice-qr-generator--bordered",f&&"nice-qr-generator--error",C].filter(Boolean).join(" ");return t.jsxs("div",{className:O,children:[t.jsx("canvas",{ref:y,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),f&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:f})})]})}),{displayName:"NiceQRGenerator"}),Sn={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},Nn=s=>{var g,c,w;if(/^https?:\/\//i.test(s))return{type:"url",data:{url:s}};if(/^mailto:/i.test(s)){const N=s.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:N==null?void 0:N[1],params:N==null?void 0:N[2]}}}if(/^tel:/i.test(s))return{type:"tel",data:{phone:s.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(s)){const N=s.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:N==null?void 0:N[1],message:N==null?void 0:N[2]}}}if(/^geo:/i.test(s)){const N=s.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((N==null?void 0:N[1])||"0"),longitude:parseFloat((N==null?void 0:N[2])||"0"),altitude:N!=null&&N[3]?parseFloat(N[3]):void 0}}}if(/^BEGIN:VCARD/i.test(s))return{type:"vcard",data:{raw:s}};if(/^BEGIN:VEVENT/i.test(s))return{type:"vevent",data:{raw:s}};if(/^WIFI:/i.test(s)){const N=(g=s.match(/S:([^;]+)/))==null?void 0:g[1],x=(c=s.match(/P:([^;]+)/))==null?void 0:c[1],A=(w=s.match(/T:([^;]+)/))==null?void 0:w[1],G=s.includes("H:true");return{type:"wifi",data:{ssid:N,password:x,type:A,hidden:G}}}return{type:"text"}},_n=()=>{try{const s=new(window.AudioContext||window.webkitAudioContext),g=s.createOscillator(),c=s.createGain();g.connect(c),c.connect(s.destination),g.type="square",g.frequency.value=1200,c.gain.value=.1,g.start(),setTimeout(()=>{g.stop(),s.close()},80)}catch{}},In=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},jn=()=>typeof window<"u"&&"BarcodeDetector"in window,Dn=s=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[s],An=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,onScan:N,onError:x,onCameraReady:A,autoStart:G=!1,showScanFrame:C=!0,children:D,className:a}=s,y={...Sn,...w},E=e.useRef(null),f=e.useRef(null),m=e.useRef(null),I=e.useRef(null),F=e.useRef(null),B=e.useRef(null),[$,Y]=e.useState(!1),[H,X]=e.useState(!1),[O,z]=e.useState(null),[T,M]=e.useState(null),[j,S]=e.useState(null),[P,W]=e.useState(y.facingMode),[i,r]=e.useState(!1),[d,n]=e.useState(!1),[l,o]=e.useState(null),h=jn(),v=e.useCallback(async()=>{var J;if(!E.current)return;const Z=Dn(y.resolution),U={video:{facingMode:P,width:{ideal:Z.width},height:{ideal:Z.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(U);m.current=ee,E.current.srcObject=ee,await E.current.play();const ne=ee.getVideoTracks()[0],se=(J=ne.getCapabilities)==null?void 0:J.call(ne);r(!!(se!=null&&se.torch)),X(!0),S(!0),M(null),A==null||A()}catch(ee){const ne=ee instanceof Error?ee.message:c("qrScanner.failedToAccessCamera","Failed to access camera");M(ne),S(!1),x==null||x(new Error(ne))}},[y.resolution,P,A,x,c]),b=e.useCallback(()=>{m.current&&(m.current.getTracks().forEach(Z=>Z.stop()),m.current=null),E.current&&(E.current.srcObject=null),X(!1),n(!1)},[]),k=e.useCallback(async()=>{W(P==="user"?"environment":"user"),$&&b()},[P,$,b]),u=e.useCallback(async()=>{if(!m.current||!i)return;const Z=m.current.getVideoTracks()[0],U=!d;try{await Z.applyConstraints({advanced:[{torch:U}]}),n(U)}catch{}},[i,d]),p=e.useCallback(async()=>{if(h)try{const Z=window.BarcodeDetector;I.current=new Z({formats:["qr_code"]})}catch(Z){const U=Z instanceof Error?Z.message:c("qrScanner.failedToInitializeQrDetector","Failed to initialize QR detector");M(U),x==null||x(new Error(U))}},[h,x,c]),R=e.useCallback((Z,U)=>{const J={text:Z,boundingBox:U.boundingBox?{x:U.boundingBox.x,y:U.boundingBox.y,width:U.boundingBox.width,height:U.boundingBox.height}:void 0,cornerPoints:U.cornerPoints,timestamp:new Date};if(y.parseDataType){const ee=Nn(Z);J.dataType=ee.type,J.parsedData=ee.data}return J},[y.parseDataType]),K=e.useCallback(async()=>{if(!(!E.current||!I.current||!H))try{const U=await I.current.detect(E.current);if(U.length>0){const J=U[0];if(y.continuous&&J.rawValue===B.current)return;B.current=J.rawValue;const ee=R(J.rawValue,J);y.highlightDetected&&ee.boundingBox&&(o(ee.boundingBox),setTimeout(()=>o(null),500)),y.beepOnScan&&_n(),y.vibrateOnScan&&In(),z(ee),N==null||N(ee),setTimeout(()=>{B.current=null},1e3)}}catch{}},[H,y.continuous,y.highlightDetected,y.beepOnScan,y.vibrateOnScan,R,N]),_=e.useCallback(async()=>{Y(!0),M(null),await p(),await v()},[p,v]),L=e.useCallback(()=>{Y(!1),F.current&&(clearInterval(F.current),F.current=null),b()},[b]),q=e.useCallback(async()=>{$?L():await _()},[$,_,L]),V=e.useCallback(()=>{if(!E.current||!f.current)return null;const Z=f.current,U=E.current;Z.width=U.videoWidth,Z.height=U.videoHeight;const J=Z.getContext("2d");return J?(J.drawImage(U,0,0),Z.toDataURL("image/png")):null},[]),Q=e.useCallback(async Z=>!h||!I.current?null:new Promise(U=>{const J=new Image;J.onload=async()=>{try{const ne=await I.current.detect(J);if(ne.length>0){const se=R(ne[0].rawValue,ne[0]);U(se)}else U(null)}catch{U(null)}},J.onerror=()=>U(null),J.src=URL.createObjectURL(Z)}),[h,R]);e.useEffect(()=>($&&H&&y.continuous&&(F.current=setInterval(K,y.scanInterval)),()=>{F.current&&(clearInterval(F.current),F.current=null)}),[$,H,y.continuous,y.scanInterval,K]),e.useEffect(()=>(G&&_(),()=>{L()}),[]),e.useEffect(()=>{$&&!H&&v()},[P,$,H,v]),e.useImperativeHandle(g,()=>({getState:()=>({isScanning:$,isCameraReady:H,lastResult:O,error:T,isSupported:h,hasPermission:j,torchAvailable:i,torchOn:d}),start:_,stop:L,toggle:q,switchCamera:k,toggleTorch:u,takeSnapshot:V,scanImage:Q}),[$,H,O,T,h,j,i,d,_,L,q,k,u,V,Q]);const te=["nice-qr-scanner",$&&"nice-qr-scanner--scanning",H&&"nice-qr-scanner--ready",T&&"nice-qr-scanner--error",a].filter(Boolean).join(" ");return t.jsxs("div",{className:te,children:[t.jsx("video",{ref:E,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:f,className:"nice-qr-scanner__canvas"}),C&&$&&t.jsxs("div",{className:"nice-qr-scanner__frame",children:[t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--br"})]}),l&&E.current&&t.jsx("div",{className:"nice-qr-scanner__bounding-box",style:{left:`${l.x/E.current.videoWidth*100}%`,top:`${l.y/E.current.videoHeight*100}%`,width:`${l.width/E.current.videoWidth*100}%`,height:`${l.height/E.current.videoHeight*100}%`}}),T&&t.jsxs("div",{className:"nice-qr-scanner__error",children:[t.jsx("div",{className:"nice-qr-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-qr-scanner__error-text",children:T}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>_(),children:c("qrScanner.tryAgain","Try Again")})]}),!h&&t.jsx("div",{className:"nice-qr-scanner__unsupported",children:t.jsx("p",{children:c("qrScanner.qrScanningIsNotSupported","QR scanning is not supported in this browser.")})}),D&&t.jsx("div",{className:"nice-qr-scanner__overlay",children:D})]})}),{displayName:"NiceQRScanner"}),ve=e.createContext(null),En=()=>{const s=e.useContext(ve);if(!s)throw new Error("useSymbology must be used within NiceSymbologyConfigProvider");return s},ce=[{id:"code128",name:"Code 128",category:"linear",description:"High-density barcode for alphanumeric data. Auto-switches between subsets A/B/C.",charset:"ASCII 0-127",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Shipping labels","Inventory","General purpose"],standard:"ISO/IEC 15417",detectorFormat:"code_128"},{id:"code128a",name:"Code 128A",category:"linear",description:"Code 128 subset A: uppercase + control characters.",charset:"ASCII 0-95 (uppercase, digits, control chars)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Systems with control characters","Legacy integration"],standard:"ISO/IEC 15417"},{id:"code128b",name:"Code 128B",category:"linear",description:"Code 128 subset B: uppercase + lowercase.",charset:"ASCII 32-127 (upper/lowercase, digits, symbols)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Alphanumeric data","Mixed case text"],standard:"ISO/IEC 15417"},{id:"code128c",name:"Code 128C",category:"linear",description:"Code 128 subset C: double-density numeric only.",charset:"0-9 (pairs only)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Long numeric values","Compact encoding"],standard:"ISO/IEC 15417"},{id:"code39",name:"Code 39",category:"linear",description:"Self-checking barcode supporting uppercase and digits.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Military (LOGMARS)","Automotive (AIAG)","Healthcare"],standard:"ISO/IEC 16388",detectorFormat:"code_39"},{id:"code93",name:"Code 93",category:"linear",description:"Compact barcode, denser than Code 39.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Canadian postal","General logistics"],standard:"ANSI/AIM BC5",detectorFormat:"code_93"},{id:"codabar",name:"Codabar",category:"linear",description:"Numeric barcode used in libraries and blood banks.",charset:"0-9, -, $, :, /, ., +, A-D (start/stop)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Blood banks","Libraries","FedEx"],standard:"ANSI/AIM BC3",detectorFormat:"codabar"},{id:"ean13",name:"EAN-13",category:"linear",description:"European Article Numbering — worldwide retail standard.",charset:"0-9",minLength:12,maxLength:12,fixedLength:13,hasCheckDigit:!0,useCases:["Retail worldwide","ISBN","ISSN"],standard:"ISO/IEC 15420",detectorFormat:"ean_13"},{id:"ean8",name:"EAN-8",category:"linear",description:"Compact version of EAN-13 for small products.",charset:"0-9",minLength:7,maxLength:7,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Space-constrained packaging"],standard:"ISO/IEC 15420",detectorFormat:"ean_8"},{id:"ean5",name:"EAN-5 Supplement",category:"linear",description:"5-digit addon for periodicals and books.",charset:"0-9",minLength:5,maxLength:5,fixedLength:5,hasCheckDigit:!0,useCases:["Book pricing","Magazine issues"],standard:"ISO/IEC 15420"},{id:"ean2",name:"EAN-2 Supplement",category:"linear",description:"2-digit addon for periodicals.",charset:"0-9",minLength:2,maxLength:2,fixedLength:2,hasCheckDigit:!1,useCases:["Magazine issue numbers"],standard:"ISO/IEC 15420"},{id:"upc_a",name:"UPC-A",category:"linear",description:"Universal Product Code — North American retail standard.",charset:"0-9",minLength:11,maxLength:11,fixedLength:12,hasCheckDigit:!0,useCases:["US/Canada retail","Point of Sale"],standard:"ISO/IEC 15420",detectorFormat:"upc_a"},{id:"upc_e",name:"UPC-E",category:"linear",description:"Compressed UPC for small packages.",charset:"0-9",minLength:6,maxLength:6,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Compact packaging"],standard:"ISO/IEC 15420",detectorFormat:"upc_e"},{id:"itf",name:"Interleaved 2 of 5",category:"linear",description:"Numeric pairs encoded in interleaved format.",charset:"0-9 (even length)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Warehouse distribution","Packaging"],standard:"ISO/IEC 16390",detectorFormat:"itf"},{id:"itf14",name:"ITF-14",category:"linear",description:"GTIN-14 barcode for shipping containers.",charset:"0-9",minLength:13,maxLength:13,fixedLength:14,hasCheckDigit:!0,useCases:["Shipping containers","Outer packaging"],standard:"ISO/IEC 16390"},{id:"msi",name:"MSI (Modified Plessey)",category:"linear",description:"Numeric barcode used in inventory management.",charset:"0-9",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Retail shelves","Inventory"],standard:"Proprietary"},{id:"pharmacode",name:"Pharmacode",category:"linear",description:"Pharmaceutical packaging identification.",charset:"3-131070 (numeric value)",minLength:1,maxLength:6,fixedLength:null,hasCheckDigit:!1,useCases:["Pharmaceutical packaging","Drug identification"],standard:"Laetus"},{id:"plessey",name:"Plessey",category:"linear",description:"Legacy barcode used in UK libraries.",charset:"0-9, A-F",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Legacy systems"],standard:"Proprietary"},{id:"telepen",name:"Telepen",category:"linear",description:"Full ASCII barcode used in UK libraries.",charset:"Full ASCII",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Inventory"],standard:"AIM"},{id:"qr_code",name:"QR Code",category:"2d",description:"Quick Response code — high capacity 2D barcode.",charset:"Full Unicode",minLength:1,maxLength:7089,fixedLength:null,hasCheckDigit:!0,useCases:["Mobile scanning","URLs","vCards","Payments"],standard:"ISO/IEC 18004",detectorFormat:"qr_code"},{id:"data_matrix",name:"Data Matrix",category:"2d",description:"High-density 2D code for small items.",charset:"Full ASCII",minLength:1,maxLength:2335,fixedLength:null,hasCheckDigit:!0,useCases:["Electronics","PCB marking","Medical devices","Aerospace"],standard:"ISO/IEC 16022",detectorFormat:"data_matrix"},{id:"aztec",name:"Aztec Code",category:"2d",description:"Compact 2D code, no quiet zone required.",charset:"Full ASCII",minLength:1,maxLength:3832,fixedLength:null,hasCheckDigit:!0,useCases:["Transport tickets","Boarding passes","Government IDs"],standard:"ISO/IEC 24778",detectorFormat:"aztec"},{id:"pdf417",name:"PDF417",category:"2d",description:"Stacked linear barcode with high capacity.",charset:"Full ASCII",minLength:1,maxLength:1850,fixedLength:null,hasCheckDigit:!0,useCases:["ID cards","Driver's licenses","Airline boarding","Postage"],standard:"ISO/IEC 15438",detectorFormat:"pdf417"},{id:"maxicode",name:"MaxiCode",category:"2d",description:"Fixed-size 2D code used by UPS.",charset:"Full ASCII",minLength:1,maxLength:93,fixedLength:null,hasCheckDigit:!0,useCases:["UPS shipping","High-speed sorting"],standard:"ISO/IEC 16023"},{id:"gs1_128",name:"GS1-128",category:"gs1",description:"Application Identifier-based supply chain barcode.",charset:"Full ASCII (with AI prefixes)",minLength:1,maxLength:48,fixedLength:null,hasCheckDigit:!0,useCases:["Supply chain","Healthcare","Food traceability"],standard:"ISO/IEC 15417 + GS1 General Specifications"},{id:"gs1_databar",name:"GS1 DataBar",category:"gs1",description:"Compact GS1 barcode for fresh food and coupons.",charset:"0-9 (GTIN-based)",minLength:14,maxLength:74,fixedLength:null,hasCheckDigit:!0,useCases:["Fresh food","Pharmacy","Coupons","Variable weight"],standard:"ISO/IEC 24724"}],me=(s,g)=>{const c=ce.find(C=>C.id===g);if(!c)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const w=[],N=[],x=c.fixedLength&&c.hasCheckDigit?c.fixedLength-1:c.fixedLength,A=!!c.fixedLength&&c.hasCheckDigit&&s.length===c.fixedLength;switch(c.fixedLength?s.length!==x&&!A&&w.push(c.hasCheckDigit?`Expected ${x} digits, or ${c.fixedLength} with the check digit; got ${s.length}`:`Expected ${c.fixedLength} characters, got ${s.length}`):(s.length<c.minLength&&w.push(`Minimum ${c.minLength} characters required`),s.length>c.maxLength&&w.push(`Maximum ${c.maxLength} characters allowed`)),g){case"ean13":case"ean8":case"ean5":case"ean2":case"upc_a":case"upc_e":case"itf":case"itf14":case"msi":case"pharmacode":/^\d+$/.test(s)||w.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(s)||w.push("Only numeric digits allowed"),s.length%2!==0&&N.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(s.toUpperCase())||w.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(s.toUpperCase())||w.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(s)||w.push("Only hex characters (0-9, A-F) allowed");break}let G;if(c.hasCheckDigit&&w.length===0)switch(g){case"ean13":case"ean8":case"upc_a":case"itf14":{const C=(A?s.slice(0,-1):s).split("").map(Number);let D=0;for(let a=0;a<C.length;a++)D+=C[a]*((C.length-1-a)%2===0?3:1);G=String((10-D%10)%10),A&&s[s.length-1]!==G&&w.push(`Check digit should be ${G}, not ${s[s.length-1]}`);break}}return g==="itf"&&s.length%2!==0&&w.push("ITF requires even number of digits"),{valid:w.length===0,errors:w,warnings:N,checkDigit:G,formattedValue:G&&!A?s+G:s}},je={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},Ln=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{selected:w,onChange:N,category:x="all",multiSelect:A=!0,showDetails:G=!0,showValidation:C=!1,testValue:D="",readOnly:a=!1,className:y}=s,[E,f]=e.useState([]),[m,I]=e.useState(null),F=w??E,B=e.useMemo(()=>x==="all"?ce:ce.filter(i=>i.category===x),[x]),$=e.useMemo(()=>{const i={};for(const r of B)i[r.category]||(i[r.category]=[]),i[r.category].push(r);return i},[B]),Y=e.useCallback(i=>{w||f(i),N==null||N(i)},[w,N]),H=e.useCallback(i=>{A?F.includes(i)||Y([...F,i]):Y([i])},[F,A,Y]),X=e.useCallback(i=>{Y(F.filter(r=>r!==i))},[F,Y]),O=e.useCallback(i=>{a||(F.includes(i)?X(i):H(i))},[F,a,H,X]),z=e.useCallback(()=>{Y(B.map(i=>i.id))},[B,Y]),T=e.useCallback(()=>{Y([])},[Y]),M=e.useCallback(i=>ce.find(r=>r.id===i),[]),j=e.useMemo(()=>!C||!D||!m?null:me(D,m),[C,D,m]);e.useImperativeHandle(g,()=>({getSelected:()=>F,select:H,deselect:X,selectAll:z,clearSelection:T,validate:me,getInfo:M,getAll:()=>ce}),[F,H,X,z,T,M]);const S=e.useMemo(()=>({symbologies:ce,selected:F,validate:me,getInfo:M}),[F,M]),P=m?M(m):null,W=["nice-symbology-config",a&&"nice-symbology-config--readonly",y].filter(Boolean).join(" ");return t.jsx(ve.Provider,{value:S,children:t.jsxs("div",{className:W,children:[A&&!a&&t.jsxs("div",{className:"nice-symbology-config__toolbar",children:[t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:z,children:c("symbologyConfig.selectAll","Select All")}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:T,children:c("symbologyConfig.clear","Clear")}),t.jsx("span",{className:"nice-symbology-config__count",children:c("symbologyConfig.selected","{selected} / {filteredSymbologies} selected").replace("{selected}",String(F.length)).replace("{filteredSymbologies}",String(B.length))})]}),t.jsxs("div",{className:"nice-symbology-config__content",children:[t.jsx("div",{className:"nice-symbology-config__list",children:Object.entries($).map(([i,r])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:c(`symbologyConfig.categoryName.${i}`,je[i]||i)}),t.jsx("div",{className:"nice-symbology-config__grid",children:r.map(d=>{const n=F.includes(d.id),l=m===d.id;return t.jsxs("div",{className:["nice-symbology-config__item",n&&"nice-symbology-config__item--selected",l&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{O(d.id),I(d.id)},role:"option","aria-selected":n,tabIndex:0,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),O(d.id),I(d.id))},children:[A&&t.jsx("span",{className:`nice-symbology-config__checkbox ${n?"nice-symbology-config__checkbox--checked":""}`,children:n&&t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}})}),t.jsxs("div",{className:"nice-symbology-config__item-info",children:[t.jsx("span",{className:"nice-symbology-config__item-name",children:d.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:d.fixedLength?c("symbologyConfig.digits","{fixedLength} digits").replace("{fixedLength}",String(d.fixedLength)):c("symbologyConfig.chars","{minLength}-{maxLength} chars").replace("{minLength}",String(d.minLength)).replace("{maxLength}",String(d.maxLength))})]})]},d.id)})})]},i))}),G&&P&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:P.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:c(`symbologyConfig.symbology.${P.id}.description`,P.description)}),t.jsxs("div",{className:"nice-symbology-config__details-props",children:[t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.category","Category")}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:c(`symbologyConfig.categoryName.${P.category}`,je[P.category])})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.characterSet","Character Set")}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:P.charset})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.length","Length")}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:P.fixedLength?c("symbologyConfig.fixed","Fixed: {fixedLength}").replace("{fixedLength}",String(P.fixedLength)):`${P.minLength} – ${P.maxLength}`})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.checkDigit2","Check Digit")}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:P.hasCheckDigit?c("symbologyConfig.yes","Yes"):c("symbologyConfig.no","No")})]}),P.standard&&t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.standard","Standard")}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:P.standard})]})]}),t.jsxs("div",{className:"nice-symbology-config__use-cases",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.useCases","Use Cases")}),t.jsx("div",{className:"nice-symbology-config__tags",children:P.useCases.map((i,r)=>t.jsx("span",{className:"nice-symbology-config__tag",children:c(`symbologyConfig.symbology.${P.id}.useCase${r}`,i)},i))})]}),C&&j&&t.jsxs("div",{className:"nice-symbology-config__validation",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:c("symbologyConfig.validation","Validation")}),t.jsxs("div",{className:`nice-symbology-config__validation-result ${j.valid?"nice-symbology-config__validation-result--valid":"nice-symbology-config__validation-result--invalid"}`,children:[t.jsx("span",{children:j.valid?c("symbologyConfig.valid","Valid"):c("symbologyConfig.invalid","Invalid")}),j.checkDigit&&t.jsx("span",{children:c("symbologyConfig.checkDigit","Check digit: {checkDigit}").replace("{checkDigit}",String(j.checkDigit))})]}),j.errors.map((i,r)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:i},r)),j.warnings.map((i,r)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:i},r))]})]})]})]})})}),{displayName:"NiceSymbologyConfig"}),Pn=({children:s})=>{const g=e.useCallback(w=>ce.find(N=>N.id===w),[]),c={symbologies:ce,selected:[],validate:me,getInfo:g};return t.jsx(ve.Provider,{value:c,children:s})},Je=e.createContext(null),Rn=()=>{const s=e.useContext(Je);if(!s)throw new Error("useBackgroundSync must be used within NiceBackgroundSyncProvider");return s},On={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},Tn=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Mn=s=>new Promise(g=>setTimeout(g,s)),Ze=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,handlers:N,onSyncStart:x,onSyncComplete:A,onTaskSuccess:G,onTaskFailed:C,onOnlineChange:D,children:a}=s,y={...On,...w},E=e.useRef(null),f=e.useRef(!1),[m,I]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),F=e.useCallback(async()=>E.current?E.current:new Promise((n,l)=>{const o=indexedDB.open(y.dbName,1);o.onerror=()=>l(o.error),o.onupgradeneeded=()=>{const h=o.result;if(!h.objectStoreNames.contains(y.storeName)){const v=h.createObjectStore(y.storeName,{keyPath:"id"});v.createIndex("tag","tag",{unique:!1}),v.createIndex("status","status",{unique:!1}),v.createIndex("priority","priority",{unique:!1})}},o.onsuccess=()=>{E.current=o.result,n(o.result)}}),[y.dbName,y.storeName]),B=e.useCallback(async(n,l,o)=>{const h=await F(),v={id:Tn(),tag:n,data:l,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(o==null?void 0:o.maxAttempts)??y.defaultMaxAttempts,priority:(o==null?void 0:o.priority)??0};return new Promise((b,k)=>{const R=h.transaction(y.storeName,"readwrite").objectStore(y.storeName).add(v);R.onerror=()=>k(R.error),R.onsuccess=()=>{I(K=>({...K,pendingCount:K.pendingCount+1})),b(v.id)}})},[F,y.storeName,y.defaultMaxAttempts]),$=e.useCallback(async n=>{const l=await F();return new Promise((o,h)=>{const k=l.transaction(y.storeName,"readwrite").objectStore(y.storeName).delete(n);k.onerror=()=>h(k.error),k.onsuccess=()=>o(!0)})},[F,y.storeName]),Y=e.useCallback(async n=>{const l=await F();return new Promise((o,h)=>{const b=l.transaction(y.storeName,"readonly").objectStore(y.storeName),k=n?b.index("tag").getAll(n):b.getAll();k.onerror=()=>h(k.error),k.onsuccess=()=>o(k.result)})},[F,y.storeName]),H=e.useCallback(async n=>(await Y(n)).filter(o=>o.status==="pending"),[Y]),X=e.useCallback(async n=>(await Y(n)).filter(o=>o.status==="failed"),[Y]),O=e.useCallback(async n=>{const l=await F();return new Promise((o,h)=>{const k=l.transaction(y.storeName,"readwrite").objectStore(y.storeName).put(n);k.onerror=()=>h(k.error),k.onsuccess=()=>o()})},[F,y.storeName]),z=e.useCallback(async()=>{const n=await Y(),l=n.filter(h=>h.status==="pending").length,o=n.filter(h=>h.status==="failed").length;I(h=>({...h,pendingCount:l,failedCount:o}))},[Y]),T=e.useCallback(async n=>{const l=N[n.tag];if(!l)return console.warn(`No handler registered for tag: ${n.tag}`),!1;n.status="syncing",n.lastAttemptAt=new Date,n.attempts++,await O(n);try{return await l.handler(n),n.status="success",await O(n),G==null||G(n),await $(n.id),!0}catch(o){const h=o instanceof Error?o.message:c("backgroundSync.unknownError","Unknown error");return n.error=h,n.attempts>=n.maxAttempts?(n.status="failed",C==null||C(n,o instanceof Error?o:new Error(h))):n.status="pending",await O(n),!1}},[N,O,$,G,C,c]),M=e.useCallback(async n=>{if(m.isSyncing)return{success:0,failed:0};f.current=!1,I(o=>({...o,isSyncing:!0,syncProgress:0,error:void 0})),x==null||x();const l={success:0,failed:0};try{const o=await H(n);o.sort((v,b)=>b.priority-v.priority);const h=o.length;for(let v=0;v<o.length&&!f.current;v++){const b=o[v],k=await T(b);if(k?l.success++:b.attempts>=b.maxAttempts&&l.failed++,!k&&b.attempts<b.maxAttempts){const u=Math.min(y.retryDelay*Math.pow(y.backoffFactor,b.attempts-1),y.maxRetryDelay);await Mn(u)}I(u=>({...u,syncProgress:Math.round((v+1)/h*100)}))}}catch(o){const h=o instanceof Error?o.message:c("backgroundSync.syncFailed","Sync failed");I(v=>({...v,error:h}))}return await z(),I(o=>({...o,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),A==null||A(l),l},[m.isSyncing,H,T,y.retryDelay,y.backoffFactor,y.maxRetryDelay,z,x,A,c]),j=e.useCallback(()=>{f.current=!0},[]),S=e.useCallback(async n=>{const o=(await Y()).find(h=>h.id===n);o&&o.status==="failed"&&(o.status="pending",o.attempts=0,o.error=void 0,await O(o),await z())},[Y,O,z]),P=e.useCallback(async n=>{const l=await X(n);for(const o of l)o.status="pending",o.attempts=0,o.error=void 0,await O(o);await z()},[X,O,z]),W=e.useCallback(async n=>{const l=await F(),o=await Y(n);return new Promise((h,v)=>{const b=l.transaction(y.storeName,"readwrite"),k=b.objectStore(y.storeName);b.onerror=()=>v(b.error),b.oncomplete=async()=>{await z(),h()};for(const u of o)k.delete(u.id)})},[F,Y,y.storeName,z]),i=e.useCallback(async n=>{const l=await F(),o=await X(n);return new Promise((h,v)=>{const b=l.transaction(y.storeName,"readwrite"),k=b.objectStore(y.storeName);b.onerror=()=>v(b.error),b.oncomplete=async()=>{await z(),h()};for(const u of o)k.delete(u.id)})},[F,X,y.storeName,z]),r=e.useCallback(async n=>{if(!("serviceWorker"in navigator))return!1;try{const l=await navigator.serviceWorker.ready;if("sync"in l)return await l.sync.register(n),!0}catch(l){console.warn("Background Sync registration failed:",l)}return!1},[]);e.useEffect(()=>{const n=()=>{I(o=>({...o,isOnline:!0})),D==null||D(!0),y.autoSyncOnConnect&&M()},l=()=>{I(o=>({...o,isOnline:!1})),D==null||D(!1)};return window.addEventListener("online",n),window.addEventListener("offline",l),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",l)}},[y.autoSyncOnConnect,M,D]),e.useEffect(()=>{if(y.periodicSyncInterval<=0)return;const n=setInterval(()=>{m.isOnline&&!m.isSyncing&&M()},y.periodicSyncInterval);return()=>clearInterval(n)},[y.periodicSyncInterval,m.isOnline,m.isSyncing,M]),e.useEffect(()=>{z()},[z]),e.useImperativeHandle(g,()=>({getState:()=>m,addTask:B,removeTask:$,getTasks:Y,getPendingTasks:H,getFailedTasks:X,retryTask:S,retryAllFailed:P,clearTasks:W,clearFailed:i,syncNow:M,cancelSync:j,registerBackgroundSync:r}),[m,B,$,Y,H,X,S,P,W,i,M,j,r]);const d={...m,addTask:B,removeTask:$,getTasks:Y,getPendingTasks:H,getFailedTasks:X,retryTask:S,retryAllFailed:P,clearTasks:W,clearFailed:i,syncNow:M,cancelSync:j};return t.jsx(Je.Provider,{value:d,children:a})}),{displayName:"NiceBackgroundSync"}),et=Ze;process.env.NODE_ENV!=="production"&&(et.displayName="NiceBackgroundSyncProvider");const tt=e.createContext(null),nt=()=>{const s=e.useContext(tt);if(!s)throw new Error("useCacheStrategies must be used within NiceCacheStrategiesProvider");return s},Fn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class Bn{constructor(){ue(this,"dbName","nice-cache-db");ue(this,"storeName","cache-entries");ue(this,"db",null)}async init(){if(!this.db)return new Promise((g,c)=>{const w=indexedDB.open(this.dbName,1);w.onerror=()=>c(w.error),w.onupgradeneeded=()=>{const N=w.result;N.objectStoreNames.contains(this.storeName)||N.createObjectStore(this.storeName,{keyPath:"key"})},w.onsuccess=()=>{this.db=w.result,g()}})}async get(g){if(await this.init(),!!this.db)return new Promise((c,w)=>{const A=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(g);A.onerror=()=>w(A.error),A.onsuccess=()=>{const G=A.result;c(G?G.value:void 0)}})}async set(g,c){if(await this.init(),!!this.db)return new Promise((w,N)=>{const G=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:g,value:c});G.onerror=()=>N(G.error),G.onsuccess=()=>w()})}async delete(g){return await this.init(),this.db?new Promise((c,w)=>{const A=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(g);A.onerror=()=>w(A.error),A.onsuccess=()=>c(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((g,c)=>{const x=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();x.onerror=()=>c(x.error),x.onsuccess=()=>g(x.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((g,c)=>{const x=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();x.onerror=()=>c(x.error),x.onsuccess=()=>g()})}async getAll(){return await this.init(),this.db?new Promise((g,c)=>{const x=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();x.onerror=()=>c(x.error),x.onsuccess=()=>g(x.result)}):[]}}const st=Object.assign(e.forwardRef((s,g)=>{const{config:c,routeStrategies:w={},precacheUrls:N=[],onFetch:x,onCacheHit:A,onCacheMiss:G,onNetworkError:C,children:D}=s,a={...Fn,...c},y=e.useRef(new Bn),[E,f]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:a.defaultStrategy}),m=e.useCallback(i=>{for(const[r,d]of Object.entries(w))if(new RegExp(r).test(i))return d;return E.strategy},[w,E.strategy]),I=e.useCallback(i=>{f(r=>({...r,strategy:i}))},[]),F=e.useCallback(async i=>{const r=await y.current.get(i);if(!r)return;const d=Date.now(),n=r.expiresAt&&r.expiresAt<d,l=r.timestamp+a.staleThreshold<d;if(n&&!a.serveStale){await y.current.delete(i);return}return{data:r.data,timestamp:new Date(r.timestamp),expiresAt:r.expiresAt?new Date(r.expiresAt):void 0,etag:r.etag,key:i,isStale:l||!!n,source:"cache",url:r.url}},[a.staleThreshold,a.serveStale]),B=e.useCallback(async()=>{const i=await y.current.getAll();let r=0,d,n;for(const l of i){const o=JSON.stringify(l.value.data).length;r+=o,(!d||l.value.timestamp<d)&&(d=l.value.timestamp),(!n||l.value.timestamp>n)&&(n=l.value.timestamp)}return{size:r,entryCount:i.length,oldestEntry:d?new Date(d):void 0,newestEntry:n?new Date(n):void 0}},[]),$=e.useCallback(async()=>{const i=await B();f(r=>({...r,entryCount:i.entryCount,totalSize:i.size}))},[B]),Y=e.useCallback(async(i,r,d)=>{const n=Date.now(),l={data:r,timestamp:n,expiresAt:d?n+d:n+a.defaultTTL};if(await y.current.set(i,l),(await y.current.keys()).length>a.maxEntries){const h=await y.current.getAll();h.sort((b,k)=>b.value.timestamp-k.value.timestamp);const v=h.slice(0,h.length-a.maxEntries);for(const b of v)await y.current.delete(b.key)}await $()},[a.defaultTTL,a.maxEntries,$]),H=e.useCallback(async i=>{const r=await y.current.delete(i);return await $(),r},[$]),X=e.useCallback(async()=>{await y.current.clear(),f(i=>({...i,entryCount:0,totalSize:0}))},[]),O=e.useCallback(async()=>y.current.keys(),[]),z=e.useCallback(async i=>await F(i)!==void 0,[F]),T=e.useCallback(async i=>{const r=await y.current.keys();let d=0;for(const n of r)i.test(n)&&(await y.current.delete(n),d++);return await $(),d},[$]),M=e.useCallback(async(i,r,d)=>{const n=new AbortController,l=setTimeout(()=>n.abort(),d);try{const o=await fetch(i,{...r,signal:n.signal});return clearTimeout(l),o}catch(o){throw clearTimeout(l),o}},[]),j=e.useCallback(async(i,r={})=>{const{strategy:d=m(i),ttl:n,cacheKey:l=i,forceRefresh:o=!1,timeout:h=a.networkTimeout,...v}=r;f(k=>({...k,isFetching:!0}));const b=async()=>{try{const k=await M(i,v,h);if(!k.ok)throw new Error(`HTTP ${k.status}`);const u=await k.json(),p=k.headers.get("etag")||void 0;await Y(l,u,n);const R={data:u,timestamp:new Date,etag:p,key:l,isStale:!1,source:"network",url:i};return f(K=>({...K,isFetching:!1})),x==null||x(R),R}catch(k){throw C==null||C(k instanceof Error?k:new Error(String(k)),i),k}};try{switch(d){case"cache-only":{const k=await F(l);if(k)return f(u=>({...u,isFetching:!1,hits:u.hits+1})),A==null||A(k),k;throw f(u=>({...u,isFetching:!1,misses:u.misses+1})),G==null||G(i),new Error("No cache entry found")}case"network-only":return f(k=>({...k,misses:k.misses+1})),await b();case"cache-first":{if(!o){const k=await F(l);if(k&&!k.isStale)return f(u=>({...u,isFetching:!1,hits:u.hits+1})),A==null||A(k),k}return f(k=>({...k,misses:k.misses+1})),await b()}case"network-first":try{return f(k=>({...k,misses:k.misses+1})),await b()}catch(k){const u=await F(l);if(u)return f(p=>({...p,isFetching:!1,hits:p.hits+1})),A==null||A(u),u;throw k}case"stale-while-revalidate":default:{const k=await F(l);return k&&!o?(f(u=>({...u,hits:u.hits+1})),A==null||A(k),k.isStale&&b().catch(()=>{}),f(u=>({...u,isFetching:!1})),k):(f(u=>({...u,misses:u.misses+1})),await b())}}}catch(k){throw f(u=>({...u,isFetching:!1})),k}},[m,a.networkTimeout,M,F,Y,x,A,G,C]),S=e.useCallback(async(i,r)=>(await j(i,r)).data,[j]),P=e.useCallback(async(i,r)=>{await Promise.all(i.map(d=>j(d,{...r,strategy:"network-first"}).catch(()=>{})))},[j]);e.useEffect(()=>{N.length>0&&P(N)},[N,P]),e.useEffect(()=>{(async()=>{await y.current.init();const r=await B();f(d=>({...d,totalSize:r.size,entryCount:r.entryCount}))})()},[B]),e.useImperativeHandle(g,()=>({getState:()=>E,fetch:j,fetchJSON:S,getFromCache:F,addToCache:Y,removeFromCache:H,clearCache:X,getCacheKeys:O,getCacheStats:B,prefetch:P,isCached:z,invalidateByPattern:T,setStrategy:I,getStrategyForUrl:m}),[E,j,S,F,Y,H,X,O,B,P,z,T,I,m]);const W={...E,fetch:j,fetchJSON:S,getFromCache:F,addToCache:Y,removeFromCache:H,clearCache:X,getCacheKeys:O,prefetch:P,isCached:z,setStrategy:I,getStrategyForUrl:m};return t.jsx(tt.Provider,{value:W,children:D})}),{displayName:"NiceCacheStrategies"}),rt=st;process.env.NODE_ENV!=="production"&&(rt.displayName="NiceCacheStrategiesProvider");function $n(s,g){const c=nt(),[w,N]=e.useState(void 0),[x,A]=e.useState(!1),[G,C]=e.useState(void 0),D=e.useCallback(async()=>{if(s){A(!0),C(void 0);try{const a=await c.fetchJSON(s,g);N(a)}catch(a){C(a instanceof Error?a:new Error(String(a)))}finally{A(!1)}}},[s,g,c]);return e.useEffect(()=>{D()},[D]),{data:w,isLoading:x,error:G,refetch:D}}const at=e.createContext(null),qn=()=>{const s=e.useContext(at);if(!s)throw new Error("useConflictResolution must be used within NiceConflictResolutionProvider");return s},Un={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},Vn=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Wn=s=>JSON.stringify(s),Hn=(s,g)=>JSON.stringify(s)===JSON.stringify(g),zn=(s,g,c)=>({...s,...g}),ot=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,handlers:N={},showConflictUI:x=!0,uiPosition:A="modal",autoOpenUI:G=!0,onConflictDetected:C,onConflictResolved:D,onResolutionFailed:a,renderConflictList:y,renderConflictItem:E,children:f}=s,m={...Un,...w},[I,F]=e.useState([]),[B,$]=e.useState(!1),[Y,H]=e.useState(!1),X=e.useCallback(_=>N[_]||{},[N]),O=e.useCallback(_=>({pending:_.filter(L=>L.status==="pending").length,resolving:_.filter(L=>L.status==="resolving").length,resolved:_.filter(L=>L.status==="resolved").length,failed:_.filter(L=>L.status==="failed").length}),[]),z=e.useMemo(()=>({conflicts:I,isResolving:B,counts:O(I)}),[I,B,O]),T=e.useCallback(()=>{if(m.persistConflicts)try{const _=localStorage.getItem(m.storageKey);if(_){const q=JSON.parse(_).map(V=>({...V,createdAt:new Date(V.createdAt),resolvedAt:V.resolvedAt?new Date(V.resolvedAt):void 0,clientVersion:{...V.clientVersion,timestamp:new Date(V.clientVersion.timestamp)},serverVersion:{...V.serverVersion,timestamp:new Date(V.serverVersion.timestamp)},baseVersion:V.baseVersion?{...V.baseVersion,timestamp:new Date(V.baseVersion.timestamp)}:void 0}));F(q)}}catch(_){console.warn("Failed to load persisted conflicts:",_)}},[m.persistConflicts,m.storageKey]),M=e.useCallback(_=>{if(m.persistConflicts)try{const L=_.filter(q=>q.status==="pending"||q.status==="failed");localStorage.setItem(m.storageKey,JSON.stringify(L))}catch(L){console.warn("Failed to persist conflicts:",L)}},[m.persistConflicts,m.storageKey]);e.useEffect(()=>{T()},[T]),e.useEffect(()=>{M(I)},[I,M]);const j=e.useCallback(_=>{F(L=>{const q=L.findIndex(Q=>Q.entityType===_.entityType&&Q.entityId===_.entityId);let V;return q>=0?(V=[...L],V[q]=_):V=[...L,_],V.length>m.maxPendingConflicts&&(V=V.slice(-m.maxPendingConflicts)),V}),C==null||C(_),G&&x&&H(!0)},[m.maxPendingConflicts,G,x,C]),S=e.useCallback((_,L,q,V,Q)=>{const te=X(_),Z=te.compare||Hn,U=te.hash||Wn,J=te.getConflictingFields;if(Z(q.data,V.data)||q.timestamp<V.timestamp&&Q&&Z(q.data,Q.data))return null;const ee={id:Vn(),entityType:_,entityId:L,clientVersion:{...q,hash:U(q.data)},serverVersion:{...V,hash:U(V.data)},baseVersion:Q?{...Q,hash:U(Q.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:J?J(q.data,V.data):void 0};return j(ee),ee},[X,j]),P=e.useCallback(async(_,L,q)=>{var Z;const V=I.findIndex(U=>U.id===_);if(V===-1)return;const Q=I[V],te=X(Q.entityType);$(!0),F(U=>{const J=[...U];return J[V]={...Q,status:"resolving"},J});try{let U;switch(L){case"client-wins":U=Q.clientVersion.data;break;case"server-wins":U=Q.serverVersion.data;break;case"latest-wins":U=Q.clientVersion.timestamp>Q.serverVersion.timestamp?Q.clientVersion.data:Q.serverVersion.data;break;case"merge":{U=await(te.merge||zn)(Q.clientVersion.data,Q.serverVersion.data,(Z=Q.baseVersion)==null?void 0:Z.data);break}case"manual":if(q===void 0)throw new Error("Manual resolution requires merged data");U=q;break}const J={...Q,status:"resolved",resolvedVersion:{data:U,timestamp:new Date,source:L==="client-wins"?"client":"server"},resolvedWith:L,resolvedAt:new Date};F(ee=>{const ne=[...ee];return ne[V]=J,ne}),D==null||D(J)}catch(U){const J=U instanceof Error?U.message:c("conflictResolution.resolutionFailed","Resolution failed");F(ee=>{const ne=[...ee];return ne[V]={...Q,status:"failed",error:J},ne}),a==null||a(Q,U instanceof Error?U:new Error(J))}finally{$(!1)}},[I,X,D,a,c]);e.useEffect(()=>{if(!(!m.autoResolve||m.defaultStrategy==="manual"))for(const _ of I)_.status==="pending"&&P(_.id,m.defaultStrategy)},[I,m.autoResolve,m.defaultStrategy,P]);const W=e.useCallback(async _=>{const L=I.filter(q=>q.status==="pending");for(const q of L)await P(q.id,_)},[I,P]),i=e.useCallback(_=>I.find(L=>L.id===_),[I]),r=e.useCallback((_,L)=>I.filter(q=>q.entityType===_&&(L===void 0||q.entityId===L)),[I]),d=e.useCallback(()=>I.filter(_=>_.status==="pending"),[I]),n=e.useCallback(_=>{F(L=>L.filter(q=>q.id!==_))},[]),l=e.useCallback(()=>{F(_=>_.filter(L=>L.status!=="resolved"))},[]),o=e.useCallback(()=>{F([])},[]),h=e.useCallback(()=>H(!0),[]),v=e.useCallback(()=>H(!1),[]);e.useImperativeHandle(g,()=>({getState:()=>z,detectConflict:S,addConflict:j,resolveConflict:P,resolveAll:W,getConflict:i,getConflictsByEntity:r,getPendingConflicts:d,dismissConflict:n,clearResolved:l,clearAll:o,openUI:h,closeUI:v}),[z,S,j,P,W,i,r,d,n,l,o,h,v]);const b={...z,detectConflict:S,addConflict:j,resolveConflict:P,resolveAll:W,getConflict:i,getConflictsByEntity:r,getPendingConflicts:d,dismissConflict:n,clearResolved:l,clearAll:o},k=d(),u=(_,L,q)=>{P(_,L,q)},p=_=>{n(_)},R=_=>E?E({conflict:_,onResolve:(L,q)=>u(_.id,L,q),onDismiss:()=>p(_.id)}):t.jsxs("div",{className:"nice-conflict-item",children:[t.jsxs("div",{className:"nice-conflict-item__header",children:[t.jsx("span",{className:"nice-conflict-item__type",children:_.entityType}),t.jsx("span",{className:"nice-conflict-item__id",children:c("conflictResolution.id","ID: {entityId}").replace("{entityId}",String(_.entityId))})]}),t.jsxs("div",{className:"nice-conflict-item__versions",children:[t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--client",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:c("conflictResolution.yourChanges","Your changes")}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.clientVersion.timestamp.toLocaleString()})]}),t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--server",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:c("conflictResolution.serverVersion","Server version")}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.serverVersion.timestamp.toLocaleString()})]})]}),_.conflictingFields&&_.conflictingFields.length>0&&t.jsxs("div",{className:"nice-conflict-item__fields",children:[t.jsx("span",{children:c("conflictResolution.conflictingFields","Conflicting fields:")}),_.conflictingFields.map(L=>t.jsx("code",{children:L},L))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>u(_.id,"client-wins"),disabled:B,children:c("conflictResolution.keepMine","Keep Mine")}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>u(_.id,"server-wins"),disabled:B,children:c("conflictResolution.useServer","Use Server")}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>u(_.id,"merge"),disabled:B,children:c("conflictResolution.merge","Merge")}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>p(_.id),disabled:B,children:c("conflictResolution.dismiss","Dismiss")})]})]},_.id),K=()=>{if(!x||!Y||k.length===0)return null;if(y)return y({conflicts:k,onResolve:u,onDismiss:p});const _=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsx("h3",{children:c("conflictResolution.syncConflicts","Sync Conflicts ({pendingConflicts})").replace("{pendingConflicts}",String(k.length))}),t.jsx("button",{className:"nice-conflict-list__close",onClick:v,"aria-label":c("conflictResolution.close","Close"),children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-conflict-list__items",children:k.map(R)}),k.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>W("client-wins"),disabled:B,children:c("conflictResolution.keepAllMine","Keep All Mine")}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>W("server-wins"),disabled:B,children:c("conflictResolution.useAllServer","Use All Server")})]})]});switch(A){case"modal":return t.jsx("div",{className:"nice-conflict-overlay",children:t.jsx("div",{className:"nice-conflict-modal",children:_})});case"drawer":return t.jsx("div",{className:"nice-conflict-drawer nice-conflict-drawer--open",children:_});case"toast":return t.jsx("div",{className:"nice-conflict-toast",children:_});case"inline":default:return _}};return t.jsxs(at.Provider,{value:b,children:[f,K()]})}),{displayName:"NiceConflictResolution"}),it=ot;process.env.NODE_ENV!=="production"&&(it.displayName="NiceConflictResolutionProvider");const ct=e.createContext(null),lt=()=>{const s=e.useContext(ct);if(!s)throw new Error("useIndexedDB must be used within NiceIndexedDBProvider");return s};function Gn(s){const g=lt(),c=e.useCallback(f=>g.get(s,f),[g,s]),w=e.useCallback(f=>g.getAll(s,f),[g,s]),N=e.useCallback((f,m)=>g.add(s,f,m),[g,s]),x=e.useCallback((f,m)=>g.put(s,f,m),[g,s]),A=e.useCallback(f=>g.delete(s,f),[g,s]),G=e.useCallback(()=>g.clear(s),[g,s]),C=e.useCallback(f=>g.count(s,f),[g,s]),D=e.useCallback(f=>g.query(s,f),[g,s]),a=e.useCallback(f=>g.bulkAdd(s,f),[g,s]),y=e.useCallback(f=>g.bulkPut(s,f),[g,s]),E=e.useCallback(f=>g.bulkDelete(s,f),[g,s]);return{isOpen:g.isOpen,isLoading:g.isLoading,error:g.error,get:c,getAll:w,add:N,put:x,remove:A,clear:G,count:C,query:D,bulkAdd:a,bulkPut:y,bulkDelete:E}}const ut=Object.assign(e.forwardRef((s,g)=>{const{config:c,autoOpen:w=!0,onOpen:N,onError:x,onClose:A,children:G}=s,C=e.useRef(null),[D,a]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),y=e.useCallback(async()=>{if(C.current)return C.current;if(!("indexedDB"in window))throw new Error("IndexedDB is not supported in this browser");return a(i=>({...i,isLoading:!0,error:void 0})),new Promise((i,r)=>{const d=indexedDB.open(c.dbName,c.version);d.onerror=()=>{var l;const n=new Error(((l=d.error)==null?void 0:l.message)||"Failed to open database");a(o=>({...o,isLoading:!1,error:n.message})),x==null||x(n),r(n)},d.onblocked=()=>{var n;(n=c.onBlocked)==null||n.call(c)},d.onupgradeneeded=n=>{var v;const l=d.result,o=n.oldVersion,h=n.newVersion;for(const b of c.stores)if(!l.objectStoreNames.contains(b.name)){const k=l.createObjectStore(b.name,{keyPath:b.keyPath,autoIncrement:b.autoIncrement});if(b.indexes)for(const u of b.indexes)k.createIndex(u.name,u.keyPath,u.options)}(v=c.onUpgrade)==null||v.call(c,l,o,h)},d.onsuccess=()=>{const n=d.result;C.current=n,n.onclose=()=>{C.current=null,a(l=>({...l,isOpen:!1,db:void 0})),A==null||A()},n.onerror=l=>{var h;const o=l.target;x==null||x(new Error(((h=o.error)==null?void 0:h.message)||"Database error"))},a({db:n,isOpen:!0,isLoading:!1,version:n.version,storeNames:Array.from(n.objectStoreNames)}),N==null||N(n),i(n)}})},[c,N,x,A]),E=e.useCallback(()=>{C.current&&(C.current.close(),C.current=null,a(i=>({...i,isOpen:!1,db:void 0})),A==null||A())},[A]),f=e.useCallback(async()=>(E(),new Promise((i,r)=>{const d=indexedDB.deleteDatabase(c.dbName);d.onerror=()=>{var n;r(new Error(((n=d.error)==null?void 0:n.message)||"Failed to delete database"))},d.onsuccess=()=>{a({isOpen:!1,isLoading:!1,storeNames:[]}),i()}})),[c.dbName,E]),m=e.useCallback(async()=>C.current?C.current:y(),[y]),I=e.useCallback(async(i,r)=>{const d=await m();return new Promise((n,l)=>{const v=d.transaction(i,"readonly").objectStore(i).get(r);v.onerror=()=>{var b;return l(new Error((b=v.error)==null?void 0:b.message))},v.onsuccess=()=>n(v.result)})},[m]),F=e.useCallback(async(i,r)=>{const d=await m();return new Promise((n,l)=>{const h=d.transaction(i,"readonly").objectStore(i),b=(r!=null&&r.index?h.index(r.index):h).getAll(r==null?void 0:r.range,r==null?void 0:r.limit);b.onerror=()=>{var k;return l(new Error((k=b.error)==null?void 0:k.message))},b.onsuccess=()=>{let k=b.result;r!=null&&r.offset&&(k=k.slice(r.offset)),n(k)}})},[m]),B=e.useCallback(async(i,r)=>{const d=await m();return new Promise((n,l)=>{const h=d.transaction(i,"readonly").objectStore(i),b=(r!=null&&r.index?h.index(r.index):h).getAllKeys(r==null?void 0:r.range,r==null?void 0:r.limit);b.onerror=()=>{var k;return l(new Error((k=b.error)==null?void 0:k.message))},b.onsuccess=()=>n(b.result)})},[m]),$=e.useCallback(async(i,r,d)=>{const n=await m();return new Promise((l,o)=>{const b=n.transaction(i,"readwrite").objectStore(i).add(r,d);b.onerror=()=>{var k;return o(new Error((k=b.error)==null?void 0:k.message))},b.onsuccess=()=>l(b.result)})},[m]),Y=e.useCallback(async(i,r,d)=>{const n=await m();return new Promise((l,o)=>{const b=n.transaction(i,"readwrite").objectStore(i).put(r,d);b.onerror=()=>{var k;return o(new Error((k=b.error)==null?void 0:k.message))},b.onsuccess=()=>l(b.result)})},[m]),H=e.useCallback(async(i,r)=>{const d=await m();return new Promise((n,l)=>{const v=d.transaction(i,"readwrite").objectStore(i).delete(r);v.onerror=()=>{var b;return l(new Error((b=v.error)==null?void 0:b.message))},v.onsuccess=()=>n()})},[m]),X=e.useCallback(async i=>{const r=await m();return new Promise((d,n)=>{const h=r.transaction(i,"readwrite").objectStore(i).clear();h.onerror=()=>{var v;return n(new Error((v=h.error)==null?void 0:v.message))},h.onsuccess=()=>d()})},[m]),O=e.useCallback(async(i,r)=>{const d=await m();return new Promise((n,l)=>{const v=d.transaction(i,"readonly").objectStore(i).count(r);v.onerror=()=>{var b;return l(new Error((b=v.error)==null?void 0:b.message))},v.onsuccess=()=>n(v.result)})},[m]),z=e.useCallback(async(i,r)=>{const d=await m(),n=[];return new Promise((l,o)=>{const v=d.transaction(i,"readonly").objectStore(i),k=(r.index?v.index(r.index):v).openCursor(r.range,r.direction);let u=0,p=0;k.onerror=()=>{var R;return o(new Error((R=k.error)==null?void 0:R.message))},k.onsuccess=()=>{const R=k.result;if(R){if(r.offset&&u<r.offset){u++,R.continue();return}if(r.limit&&p>=r.limit){l(n);return}n.push(R.value),p++,R.continue()}else l(n)}})},[m]),T=e.useCallback(async(i,r)=>{const n=(await m()).transaction(i.stores,i.mode||"readwrite");return new Promise((l,o)=>{n.onerror=()=>{var h;return o(new Error((h=n.error)==null?void 0:h.message))},n.onabort=()=>o(new Error("Transaction aborted")),r(n).then(h=>{n.oncomplete=()=>l(h)}).catch(o)})},[m]),M=e.useCallback(async(i,r)=>{const d=await m(),n=[];return new Promise((l,o)=>{const h=d.transaction(i,"readwrite"),v=h.objectStore(i);h.onerror=()=>{var b;return o(new Error((b=h.error)==null?void 0:b.message))},h.oncomplete=()=>l(n);for(const b of r){const k=v.add(b);k.onsuccess=()=>n.push(k.result)}})},[m]),j=e.useCallback(async(i,r)=>{const d=await m(),n=[];return new Promise((l,o)=>{const h=d.transaction(i,"readwrite"),v=h.objectStore(i);h.onerror=()=>{var b;return o(new Error((b=h.error)==null?void 0:b.message))},h.oncomplete=()=>l(n);for(const b of r){const k=v.put(b);k.onsuccess=()=>n.push(k.result)}})},[m]),S=e.useCallback(async(i,r)=>{const d=await m();return new Promise((n,l)=>{const o=d.transaction(i,"readwrite"),h=o.objectStore(i);o.onerror=()=>{var v;return l(new Error((v=o.error)==null?void 0:v.message))},o.oncomplete=()=>n();for(const v of r)h.delete(v)})},[m]),P=e.useCallback(async()=>{const i=await m(),r=[];for(const d of i.objectStoreNames){const l=i.transaction(d,"readonly").objectStore(d);r.push({name:l.name,keyPath:l.keyPath,autoIncrement:l.autoIncrement,indexNames:Array.from(l.indexNames)})}return{name:i.name,version:i.version,stores:r}},[m]);e.useEffect(()=>(w&&y().catch(()=>{}),()=>{E()}),[w,y,E]),e.useImperativeHandle(g,()=>({getState:()=>D,open:y,close:E,deleteDatabase:f,get:I,getAll:F,getAllKeys:B,add:$,put:Y,delete:H,clear:X,count:O,query:z,transaction:T,bulkAdd:M,bulkPut:j,bulkDelete:S,getInfo:P}),[D,y,E,f,I,F,B,$,Y,H,X,O,z,T,M,j,S,P]);const W={...D,open:y,close:E,deleteDatabase:f,get:I,getAll:F,getAllKeys:B,add:$,put:Y,delete:H,clear:X,count:O,query:z,transaction:T,bulkAdd:M,bulkPut:j,bulkDelete:S};return t.jsx(ct.Provider,{value:W,children:G})}),{displayName:"NiceIndexedDB"}),dt=ut;process.env.NODE_ENV!=="production"&&(dt.displayName="NiceIndexedDBProvider");const ft=e.createContext(null),mt=()=>{const s=e.useContext(ft);if(!s)throw new Error("useOfflineForms must be used within NiceOfflineFormsProvider");return s},Yn={dbName:"nice-offline-forms",autoSaveInterval:5e3,maxDraftsPerForm:50,autoSubmitOnline:!0,retryFailed:!0,maxRetryAttempts:3,retryDelay:5e3},Xn=()=>`draft-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ht=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,submitHandlers:N={},onDraftSaved:x,onFormSubmitted:A,onSubmissionFailed:G,onSyncComplete:C,children:D}=s,a={...Yn,...w},y=e.useRef(null),E=e.useRef(N),[f,m]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),I=e.useCallback(async()=>y.current?y.current:new Promise((r,d)=>{const n=indexedDB.open(a.dbName,1);n.onerror=()=>d(n.error),n.onupgradeneeded=()=>{const l=n.result;if(!l.objectStoreNames.contains("drafts")){const o=l.createObjectStore("drafts",{keyPath:"id"});o.createIndex("formId","formId",{unique:!1}),o.createIndex("status","status",{unique:!1})}},n.onsuccess=()=>{y.current=n.result,r(n.result)}}),[a.dbName]),F=e.useCallback(async()=>{try{const l=(await I()).transaction("drafts","readonly").objectStore("drafts").getAll();l.onsuccess=()=>{const o=l.result,h={};for(const k of o)h[k.formId]=(h[k.formId]||0)+1;const v=o.filter(k=>k.status==="pending").length,b=o.filter(k=>k.status==="failed").length;m(k=>({...k,draftCounts:h,pendingCount:v,failedCount:b}))}}catch{}},[I]),B=e.useCallback(async(r,d,n)=>{const l=await I(),o={id:Xn(),formId:r,data:d,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:n};return new Promise((h,v)=>{const u=l.transaction("drafts","readwrite").objectStore("drafts").add(o);u.onerror=()=>v(u.error),u.onsuccess=()=>{x==null||x(o),F(),h(o.id)}})},[I,x,F]),$=e.useCallback(async r=>{const d=await I();return new Promise((n,l)=>{const v=d.transaction("drafts","readonly").objectStore("drafts").get(r);v.onerror=()=>l(v.error),v.onsuccess=()=>{const b=v.result;b&&(b.createdAt=new Date(b.createdAt),b.modifiedAt=new Date(b.modifiedAt),b.syncedAt&&(b.syncedAt=new Date(b.syncedAt))),n(b)}})},[I]),Y=e.useCallback(async r=>{const d=await I();return new Promise((n,l)=>{const b=d.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(r);b.onerror=()=>l(b.error),b.onsuccess=()=>{const k=b.result.map(u=>({...u,createdAt:new Date(u.createdAt),modifiedAt:new Date(u.modifiedAt),syncedAt:u.syncedAt?new Date(u.syncedAt):void 0}));n(k)}})},[I]),H=e.useCallback(async()=>{const r=await I();return new Promise((d,n)=>{const h=r.transaction("drafts","readonly").objectStore("drafts").getAll();h.onerror=()=>n(h.error),h.onsuccess=()=>{const v=h.result.filter(b=>b.status==="pending"||b.status==="failed").map(b=>({...b,createdAt:new Date(b.createdAt),modifiedAt:new Date(b.modifiedAt),syncedAt:b.syncedAt?new Date(b.syncedAt):void 0}));d(v)}})},[I]),X=e.useCallback(async(r,d)=>{const n=await $(r);if(!n)return;const l=await I(),o={...n,data:{...n.data,...d},modifiedAt:new Date,version:n.version+1};return new Promise((h,v)=>{const u=l.transaction("drafts","readwrite").objectStore("drafts").put(o);u.onerror=()=>v(u.error),u.onsuccess=()=>{x==null||x(o),h()}})},[I,$,x]),O=e.useCallback(async(r,d,n)=>{const l=await $(r);if(!l)return;const o=await I(),h={...l,status:d,error:n,attempts:d==="syncing"?l.attempts+1:l.attempts,syncedAt:d==="synced"?new Date:l.syncedAt};return new Promise((v,b)=>{const p=o.transaction("drafts","readwrite").objectStore("drafts").put(h);p.onerror=()=>b(p.error),p.onsuccess=()=>{F(),v()}})},[I,$,F]),z=e.useCallback(async r=>{const d=await I();return new Promise((n,l)=>{const v=d.transaction("drafts","readwrite").objectStore("drafts").delete(r);v.onerror=()=>l(v.error),v.onsuccess=()=>{F(),n()}})},[I,F]),T=e.useCallback(async r=>{const d=await Y(r),n=await I();return new Promise((l,o)=>{const h=n.transaction("drafts","readwrite"),v=h.objectStore("drafts");h.onerror=()=>o(h.error),h.oncomplete=()=>{F(),l()};for(const b of d)v.delete(b.id)})},[I,Y,F]),M=e.useCallback(async r=>{const d=await $(r);if(!d)throw new Error("Draft not found");const n=E.current[d.formId];if(!n)throw new Error(`No handler registered for form: ${d.formId}`);if(!f.isOnline){await O(r,"pending");return}await O(r,"syncing"),m(l=>({...l,isSyncing:!0}));try{await n(d.data,d),await O(r,"synced"),A==null||A(d),await z(r)}catch(l){const o=l instanceof Error?l.message:c("offlineForms.submissionFailed","Submission failed");await O(r,"failed",o),G==null||G(d,l instanceof Error?l:new Error(o))}finally{m(l=>({...l,isSyncing:!1}))}},[$,f.isOnline,O,z,A,G,c]),j=e.useCallback(async(r,d)=>{const n=await B(r,d);await O(n,"pending"),await M(n)},[B,O,M]),S=e.useCallback(async()=>{const r=await H(),d={synced:0,failed:0};m(n=>({...n,isSyncing:!0}));for(const n of r)if(!(n.status==="failed"&&n.attempts>=a.maxRetryAttempts))try{await M(n.id),d.synced++}catch{d.failed++}return m(n=>({...n,isSyncing:!1,lastSyncAt:new Date})),C==null||C(d),d},[H,M,a.maxRetryAttempts,C]),P=e.useCallback(async()=>{const d=(await H()).filter(n=>n.status==="failed");for(const n of d)n.attempts<a.maxRetryAttempts&&await O(n.id,"pending");await S()},[H,a.maxRetryAttempts,O,S]),W=e.useCallback((r,d)=>{E.current[r]=d},[]);e.useEffect(()=>{const r=()=>{m(n=>({...n,isOnline:!0})),a.autoSubmitOnline&&S()},d=()=>{m(n=>({...n,isOnline:!1}))};return window.addEventListener("online",r),window.addEventListener("offline",d),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",d)}},[a.autoSubmitOnline,S]),e.useEffect(()=>{I().then(()=>F())},[I,F]),e.useImperativeHandle(g,()=>({getState:()=>f,saveDraft:B,getDraft:$,getDrafts:Y,getPendingDrafts:H,updateDraft:X,deleteDraft:z,submitDraft:M,submitForm:j,syncPending:S,retryFailed:P,clearDrafts:T,registerHandler:W}),[f,B,$,Y,H,X,z,M,j,S,P,T,W]);const i={...f,saveDraft:B,getDraft:$,getDrafts:Y,getPendingDrafts:H,updateDraft:X,deleteDraft:z,submitDraft:M,submitForm:j,syncPending:S,retryFailed:P,clearDrafts:T,registerHandler:W};return t.jsx(ft.Provider,{value:i,children:D})}),{displayName:"NiceOfflineForms"}),gt=ht;process.env.NODE_ENV!=="production"&&(gt.displayName="NiceOfflineFormsProvider");function Kn(s){const{t:g}=ae.useNiceTranslation(),{formId:c,initialData:w={},autoSave:N=!0,autoSaveInterval:x=5e3,onSubmit:A}=s,G=mt(),[C,D]=e.useState(w),[a,y]=e.useState(),[E,f]=e.useState(!1),[m,I]=e.useState();e.useEffect(()=>{G.registerHandler(c,A)},[G,c,A]),e.useEffect(()=>{if(!N)return;const H=setInterval(async()=>{if(Object.keys(C).length>0)if(a)await G.updateDraft(a,C);else{const X=await G.saveDraft(c,C);y(X)}},x);return()=>clearInterval(H)},[N,x,C,a,c,G]);const F=e.useCallback(H=>{const{name:X,value:O,type:z}=H.target;D(T=>({...T,[X]:z==="checkbox"?H.target.checked:O}))},[]),B=e.useCallback(async H=>{H==null||H.preventDefault(),f(!0),I(void 0);try{await G.submitForm(c,C),D(w),y(void 0)}catch(X){I(X instanceof Error?X.message:g("offlineForms.submissionFailed","Submission failed"))}finally{f(!1)}},[G,c,C,w,g]),$=e.useCallback(()=>{D(w),I(void 0),a&&(G.deleteDraft(a),y(void 0))},[w,a,G]),Y=e.useCallback(async H=>{const X=await G.getDraft(H);X&&(D(X.data),y(H))},[G]);return{data:C,setData:D,draftId:a,isSubmitting:E,error:m,isOnline:G.isOnline,isSyncing:G.isSyncing,pendingCount:G.pendingCount,handleChange:F,handleSubmit:B,reset:$,loadDraft:Y}}const ge=()=>{const s=navigator;return s.connection?{type:s.connection.type,effectiveType:s.connection.effectiveType,downlink:s.connection.downlink,rtt:s.connection.rtt,saveData:s.connection.saveData}:{}},pe=s=>{if(!s.effectiveType)return s.downlink?Math.min(100,s.downlink*10):50;switch(s.effectiveType){case"4g":return 100;case"3g":return 75;case"2g":return 50;case"slow-2g":return 25;default:return 50}},Qn=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{mode:w="banner",position:N="top",showWhenOnline:x=!1,autoHideOnlineDelay:A=3e3,showSlowConnectionWarning:G=!0,slowConnectionThreshold:C=1,showReconnecting:D=!0,reconnectCheckInterval:a=5e3,offlineMessage:y=c("offlineIndicator.youreOffline","You're offline"),onlineMessage:E=c("offlineIndicator.backOnline","Back online"),slowConnectionMessage:f=c("offlineIndicator.slowConnection","Slow connection"),reconnectingMessage:m=c("offlineIndicator.reconnecting","Reconnecting..."),showDetails:I=!1,animated:F=!0,pulseWhenOffline:B=!0,offlineIcon:$,onlineIcon:Y,slowIcon:H,renderContent:X,onStatusChange:O,onReconnect:z,className:T,style:M}=s,[j,S]=e.useState(()=>{const Q=ge();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...Q,quality:pe(Q)}}),[P,W]=e.useState(!j.isOnline||x),[i,r]=e.useState(!1),[d,n]=e.useState(null),l=e.useCallback(()=>{const Q=ge(),te=navigator.onLine;S(Z=>{const U={isOnline:te,...Q,quality:te?pe(Q):0,lastOnlineAt:te?new Date:Z.lastOnlineAt,offlineDuration:!te&&d?Date.now()-d.getTime():void 0};return(Z.isOnline!==U.isOnline||Z.quality!==U.quality)&&(O==null||O(U)),U})},[d,O]),o=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const Q=()=>{r(!1),n(null),l(),W(!0),z==null||z(),A>0&&setTimeout(()=>{W(x)},A)},te=()=>{n(new Date),l(),W(!0),r(D)};window.addEventListener("online",Q),window.addEventListener("offline",te);const Z=navigator;return Z.connection&&Z.connection.addEventListener("change",l),()=>{window.removeEventListener("online",Q),window.removeEventListener("offline",te),Z.connection&&Z.connection.removeEventListener("change",l)}},[l,A,x,D,z]),e.useEffect(()=>{if(!i||j.isOnline)return;const Q=setInterval(async()=>{await o()&&window.dispatchEvent(new Event("online"))},a);return()=>clearInterval(Q)},[i,j.isOnline,a,o]),e.useEffect(()=>{if(j.isOnline||!d)return;const Q=setInterval(()=>{S(te=>({...te,offlineDuration:Date.now()-d.getTime()}))},1e3);return()=>clearInterval(Q)},[j.isOnline,d]),e.useImperativeHandle(g,()=>({getConnectionInfo:()=>j,checkConnection:o,show:()=>W(!0),hide:()=>W(!1),toggle:()=>W(Q=>!Q)}),[j,o]);const h=j.isOnline&&G&&j.downlink!==void 0&&j.downlink<C,b=j.isOnline?h?"slow":"online":i?"reconnecting":"offline",k=()=>{switch(b){case"offline":return y;case"reconnecting":return m;case"slow":return f;case"online":return E}},u=Q=>({display:"inline-block",width:10,height:10,borderRadius:"50%",background:Q}),p=()=>{switch(b){case"offline":case"reconnecting":return $||t.jsx("span",{style:u("var(--nice-color-error, #ef4444)")});case"slow":return H||t.jsx("span",{style:u("var(--nice-color-warning, #f59e0b)")});case"online":return Y||t.jsx("span",{style:u("var(--nice-color-success, #22c55e)")})}},R=Q=>{const te=Math.floor(Q/1e3);if(te<60)return`${te}s`;const Z=Math.floor(te/60);return Z<60?`${Z}m ${te%60}s`:`${Math.floor(Z/60)}h ${Z%60}m`};if(!P||j.isOnline&&!x&&!h)return null;const K=["nice-offline-indicator",`nice-offline-indicator--${w}`,`nice-offline-indicator--${N}`,`nice-offline-indicator--${b}`,F&&"nice-offline-indicator--animated",B&&b==="offline"&&"nice-offline-indicator--pulse",T].filter(Boolean).join(" ");if(X)return t.jsx("div",{className:K,style:M,children:X(j)});const _=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:p()}),L=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:k()}),q=()=>I?t.jsxs("div",{className:"nice-offline-indicator__details",children:[j.offlineDuration!==void 0&&t.jsx("span",{className:"nice-offline-indicator__duration",children:c("offlineIndicator.offlineFor","Offline for {offlineDuration}").replace("{offlineDuration}",String(R(j.offlineDuration)))}),j.effectiveType&&t.jsx("span",{className:"nice-offline-indicator__type",children:j.effectiveType.toUpperCase()}),j.downlink!==void 0&&t.jsx("span",{className:"nice-offline-indicator__speed",children:c("offlineIndicator.mbps","{downlink} Mbps").replace("{downlink}",String(j.downlink.toFixed(1)))}),j.rtt!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__latency",children:[j.rtt,"ms"]})]}):null,V=()=>!I||!j.isOnline?null:t.jsx("div",{className:"nice-offline-indicator__quality",children:t.jsx("div",{className:"nice-offline-indicator__quality-bar",style:{width:`${j.quality}%`,backgroundColor:j.quality>=75?"var(--nice-color-success, #22c55e)":j.quality>=50?"var(--nice-color-warning, #eab308)":"var(--nice-color-error, #ef4444)"}})});switch(w){case"icon-only":return t.jsx("div",{className:K,style:M,title:k(),children:_()});case"minimal":return t.jsxs("div",{className:K,style:M,children:[_(),L()]});case"badge":return t.jsxs("div",{className:K,style:M,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:k()})]});case"toast":return t.jsx("div",{className:K,style:M,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[L(),q()]})]})});case"detailed":return t.jsx("div",{className:K,style:M,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[L(),q(),V()]})]})});case"banner":default:return t.jsx("div",{className:K,style:M,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[_(),L(),I&&t.jsxs(t.Fragment,{children:[q(),i&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}}),{displayName:"NiceOfflineIndicator"});function Jn(){const[s,g]=e.useState(()=>{const c=ge();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...c,quality:pe(c)}});return e.useEffect(()=>{const c=()=>{const N=ge();g(x=>({...x,isOnline:navigator.onLine,...N,quality:navigator.onLine?pe(N):0,lastOnlineAt:navigator.onLine?new Date:x.lastOnlineAt}))};window.addEventListener("online",c),window.addEventListener("offline",c);const w=navigator;return w.connection&&w.connection.addEventListener("change",c),()=>{window.removeEventListener("online",c),window.removeEventListener("offline",c),w.connection&&w.connection.removeEventListener("change",c)}},[]),s}const pt=e.createContext(null),yt=()=>{const s=e.useContext(pt);if(!s)throw new Error("useOfflineMedia must be used within NiceOfflineMediaProvider");return s},Zn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},es=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ts=(s,g)=>{var N;const c=((N=s.split(".").pop())==null?void 0:N.toLowerCase())||"",w=(g==null?void 0:g.toLowerCase())||"";return w.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(c)?"image":w.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(c)?"video":w.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(c)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(c)?"document":"other"},ns=s=>{try{return new URL(s).pathname.split("/").pop()||"unknown"}catch{return s.split("/").pop()||"unknown"}},bt=Object.assign(e.forwardRef((s,g)=>{const{config:c,onDownloadStart:w,onDownloadProgress:N,onDownloadComplete:x,onDownloadFailed:A,onMediaRemoved:G,children:C}=s,D={...Zn,...c},a=e.useRef(null),y=e.useRef(new Map),E=e.useRef(new Map),[f,m]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),I=e.useCallback(async()=>a.current?a.current:new Promise((u,p)=>{const R=indexedDB.open(D.dbName,1);R.onerror=()=>p(R.error),R.onupgradeneeded=()=>{const K=R.result;if(!K.objectStoreNames.contains("media")){const _=K.createObjectStore("media",{keyPath:"id"});_.createIndex("url","url",{unique:!0}),_.createIndex("type","type",{unique:!1}),_.createIndex("status","status",{unique:!1})}K.objectStoreNames.contains("blobs")||K.createObjectStore("blobs",{keyPath:"id"})},R.onsuccess=()=>{a.current=R.result,u(R.result)}}),[D.dbName]),F=e.useCallback(async u=>{const p=await I();return new Promise((R,K)=>{const q=p.transaction("media","readwrite").objectStore("media").put(u);q.onerror=()=>K(q.error),q.onsuccess=()=>R()})},[I]),B=e.useCallback(async(u,p)=>{const R=await I();return new Promise((K,_)=>{const V=R.transaction("blobs","readwrite").objectStore("blobs").put({id:u,blob:p});V.onerror=()=>_(V.error),V.onsuccess=()=>K()})},[I]),$=e.useCallback(async u=>{const p=await I();return new Promise((R,K)=>{const q=p.transaction("blobs","readonly").objectStore("blobs").get(u);q.onerror=()=>K(q.error),q.onsuccess=()=>{var V;return R((V=q.result)==null?void 0:V.blob)}})},[I]),Y=e.useCallback(async u=>{const p=await I();return new Promise((R,K)=>{const q=p.transaction("media","readonly").objectStore("media").get(u);q.onerror=()=>K(q.error),q.onsuccess=()=>{const V=q.result;V&&(V.cachedAt=V.cachedAt?new Date(V.cachedAt):void 0,V.expiresAt=V.expiresAt?new Date(V.expiresAt):void 0),R(V)}})},[I]),H=e.useCallback(async()=>{const u=await I();return new Promise((p,R)=>{const L=u.transaction("media","readonly").objectStore("media").getAll();L.onerror=()=>R(L.error),L.onsuccess=()=>{p(L.result.map(q=>({...q,cachedAt:q.cachedAt?new Date(q.cachedAt):void 0,expiresAt:q.expiresAt?new Date(q.expiresAt):void 0})))}})},[I]),X=e.useCallback(async u=>{const p=await I();return new Promise((R,K)=>{const V=p.transaction("media","readonly").objectStore("media").index("type").getAll(u);V.onerror=()=>K(V.error),V.onsuccess=()=>R(V.result)})},[I]),O=e.useCallback(async u=>(await H()).filter(R=>{var K;return(K=R.tags)==null?void 0:K.includes(u)}),[H]),z=e.useCallback(async u=>{const p=await I();return new Promise((R,K)=>{const V=p.transaction("media","readonly").objectStore("media").index("url").get(u);V.onerror=()=>K(V.error),V.onsuccess=()=>R(V.result)})},[I]),T=e.useCallback(async u=>{const p=await z(u);return(p==null?void 0:p.status)==="completed"},[z]),M=e.useCallback(async u=>{const p=E.current.get(u);if(p)return p;const R=await $(u);if(!R)return;const K=URL.createObjectURL(R);return E.current.set(u,K),K},[$]),j=e.useCallback(async()=>{const p=(await H()).filter(_=>_.status==="completed"),R={image:{count:0,size:0},video:{count:0,size:0},audio:{count:0,size:0},document:{count:0,size:0},other:{count:0,size:0}};let K=0;for(const _ of p)K+=_.size,R[_.type].count++,R[_.type].size+=_.size;return{totalSize:K,itemCount:p.length,byType:R}},[H]),S=e.useCallback(async()=>{const u=await j();m(p=>({...p,cachedCount:u.itemCount,totalCacheSize:u.totalSize}))},[j]),P=e.useCallback(async(u,p)=>{var q;const R=await z(u);if((R==null?void 0:R.status)==="completed")return R.id;const K=new AbortController,_=(R==null?void 0:R.id)||es(),L={id:_,url:u,type:(p==null?void 0:p.type)||"other",name:(p==null?void 0:p.name)||ns(u),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:p==null?void 0:p.metadata,tags:p==null?void 0:p.tags,priority:p==null?void 0:p.priority};y.current.set(_,K),await F(L),w==null||w(L),m(V=>({...V,queuedDownloads:V.queuedDownloads+1,isDownloading:!0}));try{L.status="downloading",await F(L),m(se=>({...se,activeDownloads:se.activeDownloads+1,queuedDownloads:se.queuedDownloads-1}));const V=await fetch(u,{signal:K.signal,headers:p==null?void 0:p.headers});if(!V.ok)throw new Error(`HTTP ${V.status}`);const Q=V.headers.get("content-length"),te=V.headers.get("content-type")||"",Z=Q?parseInt(Q,10):0;L.size=Z,L.mimeType=te,L.type=(p==null?void 0:p.type)||ts(u,te);const U=(q=V.body)==null?void 0:q.getReader();if(!U)throw new Error("No response body");const J=[];let ee=0;for(;;){const{done:se,value:re}=await U.read();if(se)break;J.push(re),ee+=re.length,L.downloadedBytes=ee,L.progress=Z>0?Math.round(ee/Z*100):0,await F(L),N==null||N(L)}const ne=new Blob(J,{type:te});return await B(_,ne),L.status="completed",L.progress=100,L.size=ne.size,L.cachedAt=new Date,L.expiresAt=p!=null&&p.cacheDuration?new Date(Date.now()+p.cacheDuration):new Date(Date.now()+D.defaultCacheDuration),await F(L),x==null||x(L),_}catch(V){throw V.name==="AbortError"?L.status="cancelled":(L.status="failed",L.error=V instanceof Error?V.message:"Download failed",A==null||A(L,V instanceof Error?V:new Error(String(V)))),await F(L),V}finally{y.current.delete(_),m(V=>({...V,activeDownloads:Math.max(0,V.activeDownloads-1),isDownloading:V.activeDownloads>1})),await S()}},[z,F,B,D.defaultCacheDuration,w,N,x,A,S]),W=e.useCallback(async u=>{const p=[];for(let R=0;R<u.length;R+=D.maxConcurrentDownloads){const K=u.slice(R,R+D.maxConcurrentDownloads),_=await Promise.allSettled(K.map(L=>P(L.url,L.options)));for(const L of _)L.status==="fulfilled"&&p.push(L.value)}return p},[P,D.maxConcurrentDownloads]),i=e.useCallback(u=>{const p=y.current.get(u);p&&p.abort()},[]),r=e.useCallback(async u=>{const p=await Y(u);p&&(p.status==="paused"||p.status==="failed")&&await P(p.url,{type:p.type,name:p.name,metadata:p.metadata,tags:p.tags})},[Y,P]),d=e.useCallback(u=>{i(u)},[i]),n=e.useCallback(()=>{for(const[u]of y.current)i(u)},[i]),l=e.useCallback(async()=>{const p=(await H()).filter(R=>R.status==="paused"||R.status==="failed");await W(p.map(R=>({url:R.url})))},[H,W]),o=e.useCallback(async u=>{const p=await I(),R=E.current.get(u);R&&(URL.revokeObjectURL(R),E.current.delete(u)),await new Promise((K,_)=>{const L=p.transaction(["media","blobs"],"readwrite");L.objectStore("media").delete(u),L.objectStore("blobs").delete(u),L.onerror=()=>_(L.error),L.oncomplete=()=>K()}),G==null||G(u),await S()},[I,G,S]),h=e.useCallback(async()=>{const u=await I();for(const[,p]of E.current)URL.revokeObjectURL(p);E.current.clear(),await new Promise((p,R)=>{const K=u.transaction(["media","blobs"],"readwrite");K.objectStore("media").clear(),K.objectStore("blobs").clear(),K.onerror=()=>R(K.error),K.oncomplete=()=>p()}),await S()},[I,S]),v=e.useCallback(async()=>{const u=await H(),p=Date.now();let R=0;for(const K of u)K.expiresAt&&K.expiresAt.getTime()<p&&(await o(K.id),R++);return R},[H,o]),b=e.useCallback(async u=>{await W(u.map(p=>({url:p,options:{priority:-1}})))},[W]);e.useEffect(()=>{const u=()=>{m(R=>({...R,isOnline:!0})),D.autoResumeOnReconnect&&l()},p=()=>{m(R=>({...R,isOnline:!1})),n()};return window.addEventListener("online",u),window.addEventListener("offline",p),()=>{window.removeEventListener("online",u),window.removeEventListener("offline",p)}},[D.autoResumeOnReconnect,l,n]),e.useEffect(()=>{if(!D.autoCleanup)return;const u=setInterval(()=>{v()},D.cleanupInterval);return()=>clearInterval(u)},[D.autoCleanup,D.cleanupInterval,v]),e.useEffect(()=>{I().then(()=>S());const u=E.current;return()=>{for(const[,p]of u)URL.revokeObjectURL(p)}},[I,S]),e.useImperativeHandle(g,()=>({getState:()=>f,download:P,downloadMultiple:W,getCachedMedia:Y,getAllCachedMedia:H,getMediaByType:X,getMediaByTag:O,getBlobUrl:M,isCached:T,pauseDownload:i,resumeDownload:r,cancelDownload:d,pauseAll:n,resumeAll:l,removeMedia:o,clearCache:h,clearExpired:v,getCacheStats:j,preload:b}),[f,P,W,Y,H,X,O,M,T,i,r,d,n,l,o,h,v,j,b]);const k={...f,download:P,downloadMultiple:W,getCachedMedia:Y,getAllCachedMedia:H,getMediaByType:X,getMediaByTag:O,getBlobUrl:M,isCached:T,pauseDownload:i,resumeDownload:r,cancelDownload:d,removeMedia:o,clearCache:h,preload:b};return t.jsx(pt.Provider,{value:k,children:C})}),{displayName:"NiceOfflineMedia"}),vt=bt;process.env.NODE_ENV!=="production"&&(vt.displayName="NiceOfflineMediaProvider");function ss(s){const g=yt(),[c,w]=e.useState(),[N,x]=e.useState(),[A,G]=e.useState(!1);return e.useEffect(()=>{s&&(G(!0),Promise.all([g.getCachedMedia(s),g.getBlobUrl(s)]).then(([C,D])=>{w(C),x(D)}).finally(()=>{G(!1)}))},[s,g]),{item:c,blobUrl:N,isLoading:A,isOnline:g.isOnline}}const wt=e.createContext(null),rs=()=>{const s=e.useContext(wt);if(!s)throw new Error("useServiceWorker must be used within NiceServiceWorkerProvider");return s},as={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},xt=Object.assign(e.forwardRef((s,g)=>{const{t:c}=ae.useNiceTranslation(),{config:w,showUpdateNotification:N=!0,showOfflineIndicator:x=!0,renderUpdateNotification:A,renderOfflineIndicator:G,notificationPosition:C="bottom",autoDismissDelay:D=0,onRegistered:a,onUpdateAvailable:y,onActivated:E,onError:f,onOnlineStatusChange:m,children:I,className:F}=s,B={...as,...w},{swPath:$,scope:Y,updateCheckInterval:H,autoUpdate:X,reloadOnActivation:O}=B,z=B.skipWaiting,T=e.useMemo(()=>({swPath:$,scope:Y,updateCheckInterval:H,autoUpdate:X,skipWaiting:z,reloadOnActivation:O}),[$,Y,H,X,z,O]),M=e.useRef({onRegistered:a,onUpdateAvailable:y,onActivated:E,onError:f});e.useEffect(()=>{M.current={onRegistered:a,onUpdateAvailable:y,onActivated:E,onError:f}});const[j,S]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[P,W]=e.useState(!1);e.useEffect(()=>{const _=()=>{S(q=>({...q,isOnline:!0})),m==null||m(!0)},L=()=>{S(q=>({...q,isOnline:!1})),m==null||m(!1)};return window.addEventListener("online",_),window.addEventListener("offline",L),()=>{window.removeEventListener("online",_),window.removeEventListener("offline",L)}},[m]);const i=e.useCallback(async()=>{if(!("caches"in window))return[];const _=await caches.keys(),L=[];for(const q of _){const V=await caches.open(q),Q=await V.keys();let te=0;for(const Z of Q){const U=await V.match(Z);if(U){const J=await U.clone().blob();te+=J.size}}L.push({name:q,size:te,itemCount:Q.length})}return S(q=>({...q,caches:L})),L},[]),r=e.useCallback(async _=>{if(!("caches"in window))return!1;const L=await caches.delete(_);return await i(),L},[i]),d=e.useCallback(async()=>{if(!("caches"in window))return;const _=await caches.keys();await Promise.all(_.map(L=>caches.delete(L))),S(L=>({...L,caches:[],cachedUrls:[]}))},[]),n=e.useCallback(async(_,L)=>{if(!("caches"in window))return;await(await caches.open(_)).addAll(L),await i()},[i]),l=e.useCallback(async(_,L)=>{if(!("caches"in window))return!1;const V=await(await caches.open(_)).delete(L);return await i(),V},[i]),o=e.useCallback(async _=>"caches"in window?(await(await caches.open(_)).keys()).map(V=>V.url):[],[]),h=e.useCallback(async()=>{var L,q,V,Q,te,Z;if(!("serviceWorker"in navigator)){S(U=>({...U,status:"error",error:"Service Worker not supported"}));return}S(U=>({...U,status:"registering"}));const _=!!navigator.serviceWorker.controller;try{const U=await navigator.serviceWorker.register(T.swPath,{scope:T.scope});S(ee=>({...ee,status:"registered",registration:U})),(q=(L=M.current).onRegistered)==null||q.call(L,U),U.addEventListener("updatefound",()=>{const ee=U.installing;ee&&ee.addEventListener("statechange",()=>{var ne,se,re,oe;switch(ee.state){case"installing":S(ie=>({...ie,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(S(ie=>({...ie,status:"installed",updateAvailable:!0,waitingWorker:!0})),W(!0),(se=(ne=M.current).onUpdateAvailable)==null||se.call(ne)):S(ie=>({...ie,status:"installed"}));break;case"activating":S(ie=>({...ie,status:"activating"}));break;case"activated":S(ie=>({...ie,status:"activated",updateAvailable:!1,waitingWorker:!1})),(oe=(re=M.current).onActivated)==null||oe.call(re),T.reloadOnActivation&&_&&window.location.reload();break;case"redundant":S(ie=>({...ie,status:"redundant"}));break}})}),U.waiting&&(S(ee=>({...ee,updateAvailable:!0,waitingWorker:!0})),W(!0),(Q=(V=M.current).onUpdateAvailable)==null||Q.call(V));let J=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!J&&T.reloadOnActivation&&(J=!0,window.location.reload())}),await i(),U}catch(U){const J=U instanceof Error?U.message:c("serviceWorker.registrationFailed","Registration failed");S(ee=>({...ee,status:"error",error:J})),(Z=(te=M.current).onError)==null||Z.call(te,U instanceof Error?U:new Error(J));return}},[T,i,c]),v=e.useCallback(async()=>{if(!j.registration)return!1;const _=await j.registration.unregister();return _&&S(L=>({...L,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),_},[j.registration]),b=e.useCallback(async()=>{j.registration&&await j.registration.update()},[j.registration]),k=e.useCallback(()=>{var _;(_=j.registration)!=null&&_.waiting&&j.registration.waiting.postMessage({type:"SKIP_WAITING"})},[j.registration]),u=e.useCallback(()=>{T.skipWaiting&&k(),W(!1)},[T.skipWaiting,k]),p=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{h()},[h]),e.useEffect(()=>{if(!T.updateCheckInterval||T.updateCheckInterval<=0)return;const _=setInterval(()=>{b()},T.updateCheckInterval);return()=>clearInterval(_)},[T.updateCheckInterval,b]),e.useEffect(()=>{if(!P||D<=0)return;const _=setTimeout(()=>{W(!1)},D);return()=>clearTimeout(_)},[P,D]),e.useImperativeHandle(g,()=>({getState:()=>j,register:h,unregister:v,checkForUpdates:b,applyUpdate:u,skipWaiting:k,getCachesInfo:i,clearCache:r,clearAllCaches:d,addToCache:n,removeFromCache:l,getCachedUrls:o,forceReload:p}),[j,h,v,b,u,k,i,r,d,n,l,o,p]);const R={...j,register:h,unregister:v,checkForUpdates:b,applyUpdate:u,skipWaiting:k,getCachesInfo:i,clearCache:r,clearAllCaches:d,addToCache:n,removeFromCache:l,getCachedUrls:o},K=`nice-sw-notification--${C}`;return t.jsx(wt.Provider,{value:R,children:t.jsxs("div",{className:`nice-service-worker ${F||""}`,children:[I,N&&P&&j.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${K}`,children:A?A({onUpdate:u,onDismiss:()=>W(!1)}):t.jsxs("div",{className:"nice-sw-notification__content",children:[t.jsxs("div",{className:"nice-sw-notification__text",children:[t.jsx("strong",{children:c("serviceWorker.updateAvailable","Update Available")}),t.jsx("span",{children:c("serviceWorker.aNewVersionIsReady","A new version is ready to install")})]}),t.jsxs("div",{className:"nice-sw-notification__actions",children:[t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--primary",onClick:u,children:c("serviceWorker.updateNow","Update Now")}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>W(!1),children:c("serviceWorker.later","Later")})]})]})}),x&&!j.isOnline&&t.jsx("div",{className:`nice-sw-offline ${K}`,children:G?G({isOnline:j.isOnline}):t.jsx("div",{className:"nice-sw-offline__content",children:t.jsx("span",{children:c("serviceWorker.youAreOffline","You are offline")})})})]})})}),{displayName:"NiceServiceWorker"}),os=Object.assign(e.forwardRef((s,g)=>t.jsx(xt,{...s,ref:g})),{displayName:"NiceServiceWorkerProvider"});exports.NiceAutoStart=De;exports.NiceAutoStartProvider=Ae;exports.NiceBackgroundSync=Ze;exports.NiceBackgroundSyncProvider=et;exports.NiceBarcodeScanner=dn;exports.NiceBatchScanner=bn;exports.NiceBatchScannerProvider=vn;exports.NiceCacheStrategies=st;exports.NiceCacheStrategiesProvider=rt;exports.NiceConflictResolution=ot;exports.NiceConflictResolutionProvider=it;exports.NiceExternalDisplay=Pe;exports.NiceExternalDisplayProvider=Re;exports.NiceHardwareBarcodeGenerator=sn;exports.NiceHardwareQRGenerator=kn;exports.NiceIndexedDB=ut;exports.NiceIndexedDBProvider=dt;exports.NiceKioskMode=Me;exports.NiceKioskModeProvider=Fe;exports.NiceLowPowerMode=$e;exports.NiceLowPowerModeProvider=qe;exports.NiceOfflineForms=ht;exports.NiceOfflineFormsProvider=gt;exports.NiceOfflineIndicator=Qn;exports.NiceOfflineMedia=bt;exports.NiceOfflineMediaProvider=vt;exports.NiceOrientationLock=We;exports.NiceOrientationLockProvider=He;exports.NiceQRScanner=An;exports.NiceRemoteManagement=Ge;exports.NiceRemoteManagementProvider=Ye;exports.NiceScreenBurnPrevention=Vt;exports.NiceScreenSelector=Oe;exports.NiceServiceWorker=xt;exports.NiceServiceWorkerProvider=os;exports.NiceSymbologyConfig=Ln;exports.NiceSymbologyProvider=Pn;exports.NiceTouchCalibration=zt;exports.useAutoStart=St;exports.useBackgroundSync=Rn;exports.useBatchScanner=mn;exports.useCacheStrategies=nt;exports.useCachedFetch=$n;exports.useConflictResolution=qn;exports.useConnectionStatus=Jn;exports.useExternalDisplay=Le;exports.useIndexedDB=lt;exports.useIndexedDBStore=Gn;exports.useKioskMode=Et;exports.useLowPowerMode=Pt;exports.useOfflineForm=Kn;exports.useOfflineForms=mt;exports.useOfflineMedia=yt;exports.useOfflineMediaItem=ss;exports.useOrientationLock=Tt;exports.useRemoteManagement=$t;exports.useServiceWorker=rs;exports.useSymbology=En;
|